From stygian at tesco.net Tue Feb 1 00:01:39 2005 From: stygian at tesco.net (Glen) Date: Tue Feb 1 00:01:32 2005 Subject: [Tutor] Newbie struggling with Tkinter/canvas tags In-Reply-To: <41FE9DF8.7030606@tds.net> References: <Pine.LNX.4.44.0501311242390.11027-100000@hkn.eecs.berkeley.edu> <41FE9DF8.7030606@tds.net> Message-ID: <1107212499.4944.5.camel@localhost> > > Have you tried the addtag_withtag() method? It looks like it should be > > able to do what you're thinking of. The documentation here: > > > > http://tkinter.unpythonic.net/pydoc/Tkinter.Canvas.html > > > > should talk about addtag_withtag(). > > itemconfig() also looks promising. > > http://www.pythonware.com/library/tkinter/introduction/x2017-concepts.htm > Thanks Danny and Kent, I see it now. With so many options on offer it's easy to miss the obvious. All of this new information should keep me occupied for quite some time. Thanks again. Glen From mlaberge at labergedaylight.com Tue Feb 1 00:27:24 2005 From: mlaberge at labergedaylight.com (Michiyo LaBerge) Date: Tue Feb 1 00:27:30 2005 Subject: [Tutor] Comparing files, Counting Value Message-ID: <A9D56CBC-73DF-11D9-BAA2-0003934C30CA@labergedaylight.com> Hello all, I'm very new to Python and have been trying to write a script to compare data from 2 files and getting a total. One of the two files contains x, y positions of pixels and a color value(z) of each, so it has three columns in the file. The other file has two columns; x1, y1. I'd like to get only x, y positions which match to x1, y1 of the second file and then look up the z value. If the z value is greater than a certain number, it counts 1, otherwise it moves on the next x, y position. Finally, I'm able to get total count of the pixels that are over the threshold. The script I'm using is below step by step, however, I haven't been able to figure out the error massage "IndexError: list index out of range" on z value. Any comments would be appreciated! Regards, Michiyo file 1: file 2: 299 189 8.543e-02 260 168 300 189 0.000e+00 270 180 301 189 0.000e+00 299 189 302 189 0.000e+00 300 170 0 188 5.095e-02 301 189 1 188 5.108e-02 . . . . . . . . . . . . #!usr/local/bin/python import sys i=open("file 1") #value data o=open("file 2") #look-up file l=open("result", 'w')#result results={} line=i.readline() line=o.readline() while line: fields=line.split() x1=fields[0, 1] in i #x,y position in file 1 z=fields[2] in i #value data in file 1 x2=fields[0, 1] in o #x,y position in file 2 if x1 == x2: read(z) if z >= 5.000e-02: z=1 count(n=0) print>>l, count(1) i.close() o.close() l.close() From apple_py at biz-experts.net Tue Feb 1 01:01:59 2005 From: apple_py at biz-experts.net (Victor Rex) Date: Tue Feb 1 01:02:02 2005 Subject: [Tutor] carriage return on windows In-Reply-To: <41FC558A.7090402@gmail.com> References: <41FC40C8.1050308@fastmail.fm><166443577941.20050129211823@columbus.rr.com> <8b67b003454f617189945135968facfc@yahoo.fr> <001b01c50675$0a2f00c0$275328cf@JSLAPTOP> <0943e4bba36230c65951716acb5f1241@yahoo.fr> <000601c5067b$ca454ad0$d25428cf@JSLAPTOP> <41FC558A.7090402@gmail.com> Message-ID: <41FEC6F7.3050301@biz-experts.net> Orri Ganel wrote: > Jacob S. wrote: > >> Thanks Kent and Max!!!!! >> >> Wow, I didn't know it did that. I'm too dumb to figure it out on my >> own I guess... >> Oh well! I found a cool new thing to play with at least! >> >> Thanks, >> Jacob >> >> >> >>> >>> On Jan 30, 2005, at 02:40, Jacob S. wrote: >>> >>>> I don't think that's what he wants. I think he wants to *overwrite* >>>> what's in the shell with new output. >>>> For example. >>>> >>>> >>>> so that the whole line is overwritten. In my experience, this is >>>> not possible and if anyone can show me how to do it, >>>> I would be grateful. >>>> >>>> HTH, >>>> Jacob >>> >>> >>> >>> It *is* possible, that's exactly what my code does (well, as long as >>> you don't run it on Mac OS 9). The carriage return (\r, as opposed >>> to the linefeed \n) moves the cursor to the beginning of the >>> *current* line. >>> >>> -- Max >>> maxnoel_fr at yahoo dot fr -- ICQ #85274019 >>> "Look at you hacker... A pathetic creature of meat and bone, panting >>> and sweating as you run through my corridors... How can you >>> challenge a perfect, immortal machine?" >>> >>> >>> >> >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> > Just a note: This does not work on IDLE, so for those who try this and > are frustrated when it fails, try it in the dos-box (command prompt). > I played around with this output issue and I love the way it works. Now, how do you do this in *nix? I tried the same approach and I get a blank line for 5 seconds (or whatever number of cycles you have on your example) and the a final line with the last value of the iterable. Do you happen to know how this in done? Thanks. Victor worked around this problem and I love the solution. From bill.mill at gmail.com Tue Feb 1 01:13:27 2005 From: bill.mill at gmail.com (Bill Mill) Date: Tue Feb 1 01:13:30 2005 Subject: [Tutor] Comparing files, Counting Value In-Reply-To: <A9D56CBC-73DF-11D9-BAA2-0003934C30CA@labergedaylight.com> References: <A9D56CBC-73DF-11D9-BAA2-0003934C30CA@labergedaylight.com> Message-ID: <797fe3d405013116132a19ea99@mail.gmail.com> Michiyo, When you ask a question to the list, you should be more careful to highlight your problem so that it doesn't seem like you're asking people to write a script for you. I don't think that's what you were doing, but just try to reduce your problem to a minimal example in the future. I don't know what your script is doing; array[0, 2] is not legal as far as I know in python (it is legal on numarray.array types, but not on regular python lists AFAIK). I also don't know what that "in i" stuff you're doing means. When I run your code, I get a "TypeError: list indices must be integers" on the fields[0, 1] line. You should try to write your code in small bites to make it easier to debug. That said, I dig doing this sort of text processing, so I wrote my own script to do it. Perhaps it'll help clear up some ideas for you; if you have any questions, feel free to ask me about them: ==========begin file testprocess.py===================== one = open('one') two = open('two') out = open('out', 'w') THRESHOLD = .05 #build dict of {(x,y): z} from 'one' pts = {} for line in one: x, y, z = [float(i) for i in line.split()] #convert strings to floats pts[(x,y)] = z #insert point into dictionary #now check to find each pixel in 'two' in the pts dictionary bigpixels = 0 for line in two: x, y = [float(i) for i in line.split()] #convert strings to floats if (x,y) in pts and pts[(x,y)] > THRESHOLD: bigpixels += 1 print "%d pixels over %f" % (bigpixels, THRESHOLD) ============end file============================== Peace Bill Mill bill.mill at gmail.com On Mon, 31 Jan 2005 15:27:24 -0800, Michiyo LaBerge <mlaberge@labergedaylight.com> wrote: > Hello all, > > I'm very new to Python and have been trying to write a script to > compare data from 2 files and getting a total. One of the two files > contains x, y positions of pixels and a color value(z) of each, so it > has three columns in the file. The other file has two columns; x1, y1. > I'd like to get only x, y positions which match to x1, y1 of the second > file and then look up the z value. If the z value is greater than a > certain number, it counts 1, otherwise it moves on the next x, y > position. Finally, I'm able to get total count of the pixels that are > over the threshold. The script I'm using is below step by step, > however, I haven't been able to figure out the error massage > "IndexError: list index out of range" on z value. Any comments would be > appreciated! > > Regards, > Michiyo > > file 1: file 2: > 299 189 8.543e-02 260 168 > 300 189 0.000e+00 270 180 > 301 189 0.000e+00 299 189 > 302 189 0.000e+00 300 170 > 0 188 5.095e-02 301 189 > 1 188 5.108e-02 . . > . . . . . > . . . . . > > #!usr/local/bin/python > > import sys > > i=open("file 1") #value data > o=open("file 2") #look-up file > l=open("result", 'w')#result > > results={} > > line=i.readline() > line=o.readline() > > while line: > fields=line.split() > x1=fields[0, 1] in i #x,y position in file 1 > z=fields[2] in i #value data in file 1 > x2=fields[0, 1] in o #x,y position in file 2 > > if x1 == x2: > read(z) > > if z >= 5.000e-02: > z=1 > count(n=0) > print>>l, count(1) > > i.close() > o.close() > l.close() > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From guillermo.fernandez.castellanos at gmail.com Tue Feb 1 01:15:51 2005 From: guillermo.fernandez.castellanos at gmail.com (Guillermo Fernandez Castellanos) Date: Tue Feb 1 01:15:53 2005 Subject: [Tutor] Traffic Network simulator In-Reply-To: <20050131225034.38172.qmail@web53810.mail.yahoo.com> References: <20050131225034.38172.qmail@web53810.mail.yahoo.com> Message-ID: <7d7029e7050131161569621a77@mail.gmail.com> Hi, Don't know if there's any network simulator. But I know about SimPy: http://simpy.sourceforge.net/ Looks well documented. Check the examples, it seems you can do pretty robust things with not toomuch code. I readed about it in the charming python section of IBM developers works: http://www-106.ibm.com/developerworks/linux/library/l-simpy.html?dwzone=linux Check also the SimPy Wiki: http://www.mcs.vuw.ac.nz/cgi-bin/wiki/SimPy?SimPy Enjoy, Guille On Mon, 31 Jan 2005 14:50:34 -0800 (PST), Shitiz Bansal <shitizb@yahoo.com> wrote: > Hi, > > I need a traffic network simulator(for roads) for my > project work.I would prefer the simulator to be in > python so that i can reprogram/modify it according to > my needs. > does anyone know where i can find something of the > sort or are there any special modules available which > can help me build one? > > Shitiz > > > __________________________________ > Do you Yahoo!? > All your favorites on one personal page ? Try My Yahoo! > http://my.yahoo.com > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Tue Feb 1 01:18:28 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Feb 1 01:18:35 2005 Subject: [Tutor] carriage return on windows In-Reply-To: <41FEC6F7.3050301@biz-experts.net> References: <41FC40C8.1050308@fastmail.fm><166443577941.20050129211823@columbus.rr.com> <8b67b003454f617189945135968facfc@yahoo.fr> <001b01c50675$0a2f00c0$275328cf@JSLAPTOP> <0943e4bba36230c65951716acb5f1241@yahoo.fr> <000601c5067b$ca454ad0$d25428cf@JSLAPTOP> <41FC558A.7090402@gmail.com> <41FEC6F7.3050301@biz-experts.net> Message-ID: <41FECAD4.5010702@tds.net> Victor Rex wrote: > I played around with this output issue and I love the way it works. > Now, how do you do this in *nix? I tried the same approach and I get a > blank line for 5 seconds (or whatever number of cycles you have on your > example) and the a final line with the last value of the iterable. It sounds like the '\r' is erasing the line, not just moving the cursor. Try putting the '\r' at the beginning of the output rather than the end: for i in range(10): print '\r', 'i is', i time.sleep(1) Kent From dyoo at hkn.eecs.berkeley.edu Tue Feb 1 01:21:53 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Feb 1 01:22:03 2005 Subject: [Tutor] Comparing files, Counting Value In-Reply-To: <A9D56CBC-73DF-11D9-BAA2-0003934C30CA@labergedaylight.com> Message-ID: <Pine.LNX.4.44.0501311535550.24680-100000@hkn.eecs.berkeley.edu> Hi Michiyo, Ok, let's take a look at the code. > i=open("file 1") #value data > o=open("file 2") #look-up file > l=open("result", 'w')#result We strongly recommend renaming these names to ones that aren't single characters. It's difficult to tell here what 'i', 'o', and 'l' mean, outside of the context of the assignments. The letters 'i' and 'o' often stand for the words "input" and "output". The way that you're using these as variable names for input files will break the expectation of people who read the code. Futhermore, 'l' can easily be misread as 'i'. In short, those names should be changed to something readable. This is a pure style issue, but I think it's important as programmers to make the code easy for humans to understand. > results={} > > line=i.readline() > line=o.readline() This looks problematic. The 'line' name here, by the end of these two statements, is bound to the value of the look-up file's line. I believe you need to keep those values distinct. > while line: > fields=line.split() > x1=fields[0, 1] in i #x,y position in file 1 > z=fields[2] in i #value data in file 1 > x2=fields[0, 1] in o #x,y position in file 2 There are several fundamental issues with this. Conventionally, a file-loop has the following structure: ### for line in inputFile: # ... do something with that line ### and anything that tries to iterate across a file in a different way should be looked at with some care. The way that your code is trying to iterate across the file won't work. We strongly recommend you read through a tutorial like: http://www.freenetpages.co.uk/hp/alan.gauld/tutfiles.htm which has examples of how to write programs that work with files. The way the program's structured also seems a bit monolithic. I'd recommend breaking down the problem into some phases: Phase 1: read the value-data file into some data structure. Phase 2: taking that data structure, read in the lookup file and identify which positions are matching, and record matches in the output file. This partitioning of the problem should allow you to work on either phase of the program without having to get it correct all at once. The phases can be decoupled because we can easily feed in some kind of hardcoded data structure into Phase 2, just to check that the lookup-file matching is doing something reasonable. For example: ### hardcodedDataStructure = { (299, 189) : 8.543e-02, (300, 189) : 0.000e+00, (301, 189) : 0.000e+00, (1, 188) : 5.108e-02 } ### is a very small subset of the information that your value data contains. We can then take this hardcodedDataStructure and work on the second part of the program using 'hardcodedDataStructure'. Later on, when we do get Phase 1 working ok, we can use the result of Phase 1 instead of the hardcodedDataStructure, and it should just fit into place. Does this make sense? Don't try writing the program all at once and then start trying to make it all work. But instead, try building small simple programs that do work, and then put those together. The statements: > fields=line.split() > x1=fields[0, 1] in i #x,y position in file 1 won't work. 'fields[0, 1]' does not represent the first and second elements of 'fields': it means something else, but you should get errors from it anyway. For example: ### >>> values = ["hello", "world", "testing"] >>> values[0, 1] Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: list indices must be integers ### So you should have already seen TypeErrors by this point of the program. What you probably meant to write was: ### fields = line.split() x1 = (fields[0], fields[1]) ### Alternatively: ### fields = line.split() x1 = fields[0:1] ### The significance of accidentely using the comma there won't make too much sense until you learn about tuples and dictionaries, so I won't press on this too much. I'd recommend that you read through one of the Python tutorials before trying to finishing the program. Some of the things that your program contains are... well, truthfully, a little wacky. There are several good tutorials linked here: http://www.python.org/moin/BeginnersGuide/NonProgrammers If you have more questions, please feel free to ask! From dyoo at hkn.eecs.berkeley.edu Tue Feb 1 02:27:15 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Feb 1 02:27:19 2005 Subject: [Tutor] Better structure? In-Reply-To: <000301c507a3$f3828c90$7d5428cf@JSLAPTOP> Message-ID: <Pine.LNX.4.44.0501311447390.24680-100000@hkn.eecs.berkeley.edu> On Mon, 31 Jan 2005, Jacob S. wrote: > I think this thing is screaming for better structure, but previous attempts > at using oop for it have failed. Hi Jacob, Ok, I see one big refactoring that should help things quite a bit. There's a large case-analysis off if/elif/elif statements that involves 'y'. Let me just grep for the lines here: > if y == 'clear': > elif y == 'quit': > elif y == 'remove lines': > elif y == 'return lines': > elif y.startswith('gatl'): > elif y.startswith('ganl'): > elif y.startswith('gotl'): > elif y.startswith('gonl'): > elif y.startswith('getpt'): > elif y == 'regraph': The structure can be improves by using that dispatch-table method we talked about a few days ago. We can't directly apply the dispatch technique, because there's a little bit of nonuniformity. Some of the statements compare y by equality, while others use 'startswith' checks. But I think we can handle it by making everything a little bit more uniform: we can make everything an 'equality' check against the first word on the line. Here's some pseudocode for the proposed fix: ### Pseudocode commandDispatchTable = {'clear' : clearCommand 'quit' : quitCommand 'remove' : removeCommand 'return' : returnCommand 'gatl' : gatlCommand 'ganl' : ganlCommand 'gotl' : gotlCommand 'gonl' : gonlCommand 'getpt' : getplCommand 'regraph': regraphCommand def evaluate(line): """Evaluates the line.""" pieces = line.split() cmd, rest = pieces[0], pieces[1:] if cmd in commandDispatchTable: dispatchTable[cmd](rest) elif isAssignment(line): ... else: ... ### The evaluate() function tries to handle the common-case stuff with a dispatch-table method, and otherwise follows up with special-case stuff to handle the rest of the case analysis. One other neat feature of this is that, because we split() against the whole line, we've broken down the line into 'cmd' and the 'rest' of the arguments to that command. This might also help clean up some of the logic that grabbing the argument on the rest of the line, step2 = float(y.lstrip("gatl ")) x = float(y.lstrip('gotl ')) x = float(y.lstrip('gonl ')) y = y.lstrip("getpt ") You can avoid doing so many lstrip()s by using the 'rest' argument list. Best of wishes to you! From p.hartley at spitech.com Tue Feb 1 17:35:41 2005 From: p.hartley at spitech.com (Paul Hartley) Date: Tue Feb 1 03:33:43 2005 Subject: [Tutor] Presentation Message-ID: <003f01c5087c$117cb6c0$012118ac@SP1179> I am trying to get Python established here in the Philippines. Currently I am in charge of operations at a business based in Manila and I have asked my IT staff to start using Python (with some success). A local university has now asked that I give a talk to their IT people on Python - so here is an opportunity to spread the word and get some more converts and maybe introduce python into their computer science courses. Any help I can get would be much appreciated - such as language comparisons, companies and systems that use python, debates about what python is good for (almost everything), examples of elegant code.. When I was a member of the Forth Interest Group in the USA we learned that Forth was used on the buggy that went to mars, that it started life controlling huge radio telescopes which only had 4k (yes 4k) of memory for both language and application. Anything like the above concerning python would be useful. Any other suggestions would help also, the audience will have computers, so a demonstration of small workshop would also be good - the presentation/session is for 4 hours on the 10th February. Paul -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050201/1e0e22d0/attachment.html From maxnoel_fr at yahoo.fr Tue Feb 1 03:43:32 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Tue Feb 1 03:43:38 2005 Subject: [Tutor] Presentation In-Reply-To: <003f01c5087c$117cb6c0$012118ac@SP1179> References: <003f01c5087c$117cb6c0$012118ac@SP1179> Message-ID: <61684d94f666d2cb496f617cf83f4582@yahoo.fr> On Feb 1, 2005, at 16:35, Paul Hartley wrote: > When I was a member of the Forth Interest Group in the USA we learned > that Forth was used on the buggy that went to mars, that it started > life controlling huge radio telescopes which only had 4k (yes 4k) of > memory for both language and application. > ? > Anything like the above concerning python would be useful. Well, that's probably not as awe-inspiring, but BitTorrent is written entirely in Python (with the wxPython graphical toolkit for the Windows and X11 versions, and PyObjC for the Mac OS X version). Google also use the language extensively, although I don't exactly know why, thanks to their obsession with secrecy. You could point out that Python's greatest strength (aside from its extreme readability -- unlike most people, The Whitespace Thing always struck me as an excellent design decision, although had I been Guido, I'd have forced the use of either tabs or spaces but not allowed both) is the fact that it's multi-paradigm. You can work procedurally, object-orientedly, and even in some cases functionally. And you can mix-and-match those 3 paradigms depending on your needs. This can be very useful. Oh, and make sure you mention iterators and list comprehensions at some point. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From carroll at tjc.com Tue Feb 1 04:18:58 2005 From: carroll at tjc.com (Terry Carroll) Date: Tue Feb 1 04:19:01 2005 Subject: [Tutor] Presentation In-Reply-To: <003f01c5087c$117cb6c0$012118ac@SP1179> Message-ID: <Pine.LNX.4.44.0501311911010.23935-100000@violet.rahul.net> On Tue, 1 Feb 2005, Paul Hartley wrote: > When I was a member of the Forth Interest Group in the USA we learned > that Forth was used on the buggy that went to mars, that it started life > controlling huge radio telescopes which only had 4k (yes 4k) of memory > for both language and application. > > Anything like the above concerning python would be useful. I just did a google on "Pyton success stories," and found this page, which you may find useful. http://www.pythonology.com/success See also the two O'Reilley links on that page. Since you mentioned use in space exploration, always a sexy example, I search for "Nasa Python" also turned up these: NASA Ames Processing in Python: http://home.badc.rl.ac.uk/astephens/software/nappy/ Space shuttle engineers use Python to streamline mission design: http://builder.com.com/5100-6401-1045764.html ... and others. From keridee at jayco.net Tue Feb 1 05:34:09 2005 From: keridee at jayco.net (Jacob S.) Date: Tue Feb 1 05:34:55 2005 Subject: [Tutor] Better structure? References: <000301c507a3$f3828c90$7d5428cf@JSLAPTOP> <00af01c507c5$f06ec470$d1b48651@xp> Message-ID: <001701c50817$6f454d90$6d5428cf@JSLAPTOP> >> def start(): > .... lots of lines... >> global xaxis >> global yaxis > > Its traditional to put global statements at the top of the function. > Also you only need one line to list all of the global variables > >> global radiusaxis >> global radiusaxis2 What, like global radiusaxis, radiusaxis2 > Similarly here., and again you can put all four in one place. > >> radiusaxis2.visible = 0 > And since there is no input parameter and no return statement > and you only call start() once... Not true. If y == 'clear', then start is called to "redraw" the window. Very important part. >> def graphit(type,f,range2,step): >> li = curve(color=color.blue) >> if type in ['y','x']: >> x = -15 >> radiusaxis.visible = 0 >> radiusaxis2.visible = 0 >> while -15 <= x <= 15: >> if eval(range2): >> try: >> a = f(x) >> if -15 <= a <= 15: >> if type == 'y': >> li.append(pos=(x,a,0)) >> elif type == 'x': >> li.append(pos=(a,x,0)) >> else: >> li = curve(color=color.blue) >> except: >> pass > > This is iffy. If *anthing* happens you ignore it. > Now suppose due to a bug you go into an infinite > loop and you try to stop using CTRL-C - it won't work! > > If you must use a catch-all except then do something > with it - print a message at least! I think I'll do that, but of course I'll have to add ValueError -- because of math domain errors on my function. That's what the try except block is for. Otherwise I wouldn't need it. > I got a sore head after that... I'll leave the rest for > others to remark upon. :-) > > Alan G. I'd send some Advil or something, but it doesn't work too well through email. ;-) Thanks for the help, Jacob Schmidt From keridee at jayco.net Tue Feb 1 05:38:03 2005 From: keridee at jayco.net (Jacob S.) Date: Tue Feb 1 05:38:17 2005 Subject: [Tutor] Better structure? References: <Pine.LNX.4.44.0501311447390.24680-100000@hkn.eecs.berkeley.edu> Message-ID: <001b01c50817$d6846cc0$6d5428cf@JSLAPTOP> Ah, I like. BTW, it was a few months ago, not days... but the thought still counts. At least you remember. I was getting stumped by the difference in comparing y The check for seeing what the first word is made me slamp my forehead... Thanks! Jacob Schmidt > > > On Mon, 31 Jan 2005, Jacob S. wrote: > >> I think this thing is screaming for better structure, but previous >> attempts >> at using oop for it have failed. > > > Hi Jacob, > > > Ok, I see one big refactoring that should help things quite a bit. > There's a large case-analysis off if/elif/elif statements that involves > 'y'. Let me just grep for the lines here: > >> if y == 'clear': >> elif y == 'quit': >> elif y == 'remove lines': >> elif y == 'return lines': >> elif y.startswith('gatl'): >> elif y.startswith('ganl'): >> elif y.startswith('gotl'): >> elif y.startswith('gonl'): >> elif y.startswith('getpt'): >> elif y == 'regraph': > > > The structure can be improves by using that dispatch-table method we > talked about a few days ago. > > > We can't directly apply the dispatch technique, because there's a little > bit of nonuniformity. Some of the statements compare y by equality, while > others use 'startswith' checks. But I think we can handle it by making > everything a little bit more uniform: we can make everything an 'equality' > check against the first word on the line. Here's some pseudocode for the > proposed fix: > > > ### Pseudocode > commandDispatchTable = {'clear' : clearCommand > 'quit' : quitCommand > 'remove' : removeCommand > 'return' : returnCommand > 'gatl' : gatlCommand > 'ganl' : ganlCommand > 'gotl' : gotlCommand > 'gonl' : gonlCommand > 'getpt' : getplCommand > 'regraph': regraphCommand > > def evaluate(line): > """Evaluates the line.""" > pieces = line.split() > cmd, rest = pieces[0], pieces[1:] > if cmd in commandDispatchTable: > dispatchTable[cmd](rest) > elif isAssignment(line): > ... > else: > ... > ### > > The evaluate() function tries to handle the common-case stuff with a > dispatch-table method, and otherwise follows up with special-case stuff to > handle the rest of the case analysis. > > > One other neat feature of this is that, because we split() against the > whole line, we've broken down the line into 'cmd' and the 'rest' of the > arguments to that command. This might also help clean up some of the > logic that grabbing the argument on the rest of the line, > > step2 = float(y.lstrip("gatl ")) > x = float(y.lstrip('gotl ')) > x = float(y.lstrip('gonl ')) > y = y.lstrip("getpt ") > > You can avoid doing so many lstrip()s by using the 'rest' argument list. > > > > Best of wishes to you! > > > From alan.gauld at freenet.co.uk Tue Feb 1 05:39:00 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Feb 1 05:38:50 2005 Subject: [Tutor] Traffic Network simulator References: <20050131225034.38172.qmail@web53810.mail.yahoo.com> Message-ID: <004e01c50817$f39e6040$68b78851@xp> > I need a traffic network simulator(for roads) for my > project work.I would prefer the simulator to be in > python so that i can reprogram/modify it according to > my needs. I don't jnow of anything ready made. But a Google search may find someting somewhere... > does anyone know where i can find something of the > sort or are there any special modules available which > can help me build one? These kinds of simulators usually entail a set of interacting queues. There might be python modules around for building queues. You might also find a math book or web site on queuing theory useful... Also you will certainly want to use the random module for this. Alan G. From andrewm at object-craft.com.au Tue Feb 1 08:01:41 2005 From: andrewm at object-craft.com.au (Andrew McNamara) Date: Tue Feb 1 08:01:43 2005 Subject: [Tutor] Traffic Network simulator In-Reply-To: <004e01c50817$f39e6040$68b78851@xp> References: <20050131225034.38172.qmail@web53810.mail.yahoo.com> <004e01c50817$f39e6040$68b78851@xp> Message-ID: <20050201070141.897863C889@coffee.object-craft.com.au> > I need a traffic network simulator(for roads) for my > project work.I would prefer the simulator to be in > python so that i can reprogram/modify it according to > my needs. Have you looked at SimPy: http://simpy.sourceforge.net/ -- Andrew McNamara, Senior Developer, Object Craft http://www.object-craft.com.au/ From kraus at hagen-partner.de Tue Feb 1 09:15:53 2005 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Tue Feb 1 09:16:02 2005 Subject: [Tutor] Re: Presentation In-Reply-To: <003f01c5087c$117cb6c0$012118ac@SP1179> References: <003f01c5087c$117cb6c0$012118ac@SP1179> Message-ID: <ctndr4$h6s$1@sea.gmane.org> Paul Hartley wrote: [...] > When I was a member of the Forth Interest Group in the USA we learned > that Forth was used on the buggy that went to mars, that it started > life controlling huge radio telescopes which only had 4k (yes 4k) of > memory for both language and application. Well, the rover used Forth, but the rover-website is Plone powered: http://plone.org/newsitems/mars-rover Plone is a CMS built on top of Zope, which itself is Python powered. For more sites running plone see: http://plone.org/about/sites/ HTH, Wolfram From dyoo at hkn.eecs.berkeley.edu Tue Feb 1 10:21:29 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Feb 1 10:21:33 2005 Subject: [Tutor] Better structure? In-Reply-To: <001b01c50817$d6846cc0$6d5428cf@JSLAPTOP> Message-ID: <Pine.LNX.4.44.0502010026540.16528-100000@hkn.eecs.berkeley.edu> On Mon, 31 Jan 2005, Jacob S. wrote: > BTW, it was a few months ago, not days... but the thought still counts. > At least you remember. Hi Jacob, Wait, was it really a few months ago? Let me check the archive... http://mail.python.org/pipermail/tutor/2004-December/033728.html You're right. Wow, I'm getting that much more senile by the minute. > I was getting stumped by the difference in comparing y The check for > seeing what the first word is made me slamp my forehead... I'm glad that you enjoyed one of those "ah ha!" moments. *grin* If you ever get the chance, you may want to take a look at a book called Programming Pearls: http://www.cs.bell-labs.com/cm/cs/pearls/ for a few more examples of "ah ha!" moments of enlightenment. As a side note: it's possible to do the same sort of thing that we did in the last post --- with class instances --- but it's slightly more heavyweight compared to using first-class function values. Let's see what that looks like, just for comparison. The following variant will probably feel more comfortable to Java programmers: here's a sketch of how we can do this dispatch technique with classes instead of first-class functions: ###### class Command(object): def execute(self, args): raise NotImplementedError class ClearCommand(Command): def execute(self, args): ... class QuitCommand(Command): def execute(self, args): ... ... commandDispatchTable = { 'clear' : ClearCommand(), 'quit' : QuitCommand(), ... } def evaluate(line): """Evaluates the line.""" pieces = line.split() cmd, rest = pieces[0], pieces[1:] if cmd in commandDispatchTable: dispatchTable[cmd].execute(rest) elif isAssignment(line): ... else: ... ###### It's the same general idea. But just more typing. *grin* An advantage of using the class approach is that it is easy to extend the commands to respond to different methods besides direct execution. For example, we might want to add a "help()" Command that provides a functionality similar to the one provided by the builtin Python help() function. If each of the Commands implements a help() method, then we can do something like: ### class Command(object): def execute(self, args): raise NotImplementedError def help(self): return self.__doc__ class HelpCommand(Command): """Displays help for a command. Syntax: help [command name]. Example Usage: help clear """ def getHelpString(self, commandName): if commandName in dispatchTable: return dispatchTable[commandName].help() else: return "Unknown command." def execute(self, args): if not args: commandName = 'help' else: commandName = args[0] print "help on %r: %s" % (commandName, self.getHelpString(commandName)) ### We can get more complicated from here. I'm not sure if this help() Command is a good idea, but it's an option. And perhaps not coincidently, if we look at your program's structure again now, we might notice that it's gradually looking more and more like an interpreter. *grin* Best of wishes to you! From kent37 at tds.net Tue Feb 1 11:49:13 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Feb 1 11:49:16 2005 Subject: [Tutor] Presentation In-Reply-To: <003f01c5087c$117cb6c0$012118ac@SP1179> References: <003f01c5087c$117cb6c0$012118ac@SP1179> Message-ID: <41FF5EA9.3090000@tds.net> Eric Raymond's "Why Python?" essay is a classic: http://pythonology.org/success&story=esr Bruce Eckel's "Why I love Python" presentation is here: http://64.78.49.204/pub/eckel/LovePython.zip This page has lots of links you might be interested in: http://www.ferg.org/python_presentations/index.html This page has links to language comparisons: http://www.python.org/moin/LanguageComparisons Good luck! Kent Paul Hartley wrote: > I am trying to get Python established here in the Philippines. Currently > I am in charge of operations at a business based in Manila and I have > asked my IT staff to start using Python (with some success). > > A local university has now asked that I give a talk to their IT people > on Python - so here is an opportunity to spread the word and get some > more converts and maybe introduce python into their computer science > courses. > > Any help I can get would be much appreciated - such as language > comparisons, companies and systems that use python, debates about what > python is good for (almost everything), examples of elegant code.. > > When I was a member of the Forth Interest Group in the USA we learned > that Forth was used on the buggy that went to mars, that it started life > controlling huge radio telescopes which only had 4k (yes 4k) of memory > for both language and application. > > Anything like the above concerning python would be useful. > > Any other suggestions would help also, the audience will have computers, > so a demonstration of small workshop would also be good - the > presentation/session is for 4 hours on the 10th February. > > Paul > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Tue Feb 1 11:57:06 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Feb 1 11:57:11 2005 Subject: [Tutor] Better structure? In-Reply-To: <Pine.LNX.4.44.0501311447390.24680-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0501311447390.24680-100000@hkn.eecs.berkeley.edu> Message-ID: <41FF6082.70005@tds.net> Danny Yoo wrote: > > On Mon, 31 Jan 2005, Jacob S. wrote: > ### Pseudocode > commandDispatchTable = {'clear' : clearCommand > 'quit' : quitCommand > 'remove' : removeCommand > 'return' : returnCommand > 'gatl' : gatlCommand > 'ganl' : ganlCommand > 'gotl' : gotlCommand > 'gonl' : gonlCommand > 'getpt' : getplCommand > 'regraph': regraphCommand > > def evaluate(line): > """Evaluates the line.""" > pieces = line.split() > cmd, rest = pieces[0], pieces[1:] > if cmd in commandDispatchTable: > dispatchTable[cmd](rest) > elif isAssignment(line): > ... > else: > ... > ### > > The evaluate() function tries to handle the common-case stuff with a > dispatch-table method, and otherwise follows up with special-case stuff to > handle the rest of the case analysis. Jacob, if you like this you might want to look into the cmd module, it supports dispatching on the first word of a command with support for help, etc. > step2 = float(y.lstrip("gatl ")) > x = float(y.lstrip('gotl ')) > x = float(y.lstrip('gonl ')) > y = y.lstrip("getpt ") This code is broken. lstrip('gonl ') will remove *all* leading g, o, n, l and space, in any order: >>> s='go long on log buddy!' >>> s.lstrip('gonl ') 'buddy!' Instead of y.lstrip('gonl ') you should use y[5:] or maybe y[len('gonl '):] Kent From polatel at gmail.com Tue Feb 1 12:08:39 2005 From: polatel at gmail.com (Ali Polatel) Date: Tue Feb 1 12:09:11 2005 Subject: [Tutor] Programming Challenge C++ and Python Message-ID: <3c51d5180502010308149302c2@mail.gmail.com> I need a favor.I play chess at a chess server with the name ICC(www.chessclub.com). I want to write a plugin for their interface using Python. I don't have any idea about how to write a plugin but I found out that the server administrator has written a Plugin Development Kit in C++ for those who wish to write plugins for the interface.I don't know C++ so I cannot convert this kit into python scripts.Can anyone do this for me? or can anyone examine those scripts and tell me a way how to write those with python?The development kit is avaliable at the site ftp://ftp.chessclub.com/pub/icc/interface/blitzin2/plugins/ under the name PluginDevkit.zip Any kind of help is appreciated. Regards, Ali Polatel From cyresse at gmail.com Tue Feb 1 12:37:50 2005 From: cyresse at gmail.com (Liam Clarke) Date: Tue Feb 1 12:37:54 2005 Subject: [Tutor] Better structure? In-Reply-To: <Pine.LNX.4.44.0502010026540.16528-100000@hkn.eecs.berkeley.edu> References: <001b01c50817$d6846cc0$6d5428cf@JSLAPTOP> <Pine.LNX.4.44.0502010026540.16528-100000@hkn.eecs.berkeley.edu> Message-ID: <f2ff2d05020103374ecea410@mail.gmail.com> > http://www.cs.bell-labs.com/cm/cs/pearls/ That link seems to be dead. Pity. My whole programming experience is comprised of Ah-Ha's followed by Um's... -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From godoy at ieee.org Tue Feb 1 13:14:21 2005 From: godoy at ieee.org (Jorge Luiz Godoy Filho) Date: Tue Feb 1 13:16:01 2005 Subject: [Tutor] Re: Better structure? References: <001b01c50817$d6846cc0$6d5428cf@JSLAPTOP> <Pine.LNX.4.44.0502010026540.16528-100000@hkn.eecs.berkeley.edu> <f2ff2d05020103374ecea410@mail.gmail.com> Message-ID: <1289640.DAVN76bQ42@jupiter.g2ctech> Liam Clarke wrote: >> http://www.cs.bell-labs.com/cm/cs/pearls/ > That link seems to be dead. Pity. My whole programming experience is > comprised of Ah-Ha's followed by Um's... It worked here. -- Godoy. <godoy@ieee.org> From mi.janssen at gmail.com Tue Feb 1 13:40:36 2005 From: mi.janssen at gmail.com (Michael Janssen) Date: Tue Feb 1 13:40:41 2005 Subject: [Tutor] How does import work? In-Reply-To: <41FA7925.80109@freenet.de> References: <41FA7925.80109@freenet.de> Message-ID: <1ff2dfbf05020104407bd21929@mail.gmail.com> On Fri, 28 Jan 2005 18:40:53 +0100, Johan Nilsson <johan.nilsson@freenet.de> wrote: > >>> from scipy.signal.signaltools import * > > /Traceback (most recent call last): > File "<pyshell#0>", line 1, in -toplevel- > from scipy.signal.signaltools import * > ImportError: No module named signaltools/ > > So I try the methodic way and this works, giving me access to the > functions I need > > >>> from scipy import * > >>> from scipy.signal import * > >>> from scipy.signal.signaltools import * seems like overkill (and I don't understand why it works better than the above, but that's more an issue about my understanding and not about python ;-). Try from scipy.signal import signaltools # don't import everything from signal and go on using functions from signaltools like this: signaltools.function > Now what confuses me is that when I put the above three lines in a file > (of course without the >>>) and execute them I get a long error message. perhaps different python versions? > / Traceback (most recent call last): > File "/home/johan/pyton/import_test.py", line 5, in -toplevel- > from scipy.signal import * note that the error occours while importing everything from scipy.signal . The chance are well that this error goes away when using a reduced import statement. [snip long traceback talking about scipy and Numerics imports] > import lapack_lite > ImportError: > /usr/local/lib/python2.3/site-packages/Numeric/lapack_lite.so: undefined > symbol: dgesdd_/ given the fact that I'm no c-programmer this seems to me like a broken c module. I would try to reinstall Numeric/ scipy (After hunting the problem down to a specific import). The most obvious reason why the import in idle works is that idle uses another version of python (ask sys.version) regards Michael From mi.janssen at gmail.com Tue Feb 1 14:30:37 2005 From: mi.janssen at gmail.com (Michael Janssen) Date: Tue Feb 1 14:30:41 2005 Subject: [Tutor] carriage return on windows In-Reply-To: <41FEC6F7.3050301@biz-experts.net> References: <41FC40C8.1050308@fastmail.fm> <166443577941.20050129211823@columbus.rr.com> <8b67b003454f617189945135968facfc@yahoo.fr> <001b01c50675$0a2f00c0$275328cf@JSLAPTOP> <0943e4bba36230c65951716acb5f1241@yahoo.fr> <000601c5067b$ca454ad0$d25428cf@JSLAPTOP> <41FC558A.7090402@gmail.com> <41FEC6F7.3050301@biz-experts.net> Message-ID: <1ff2dfbf05020105307f2ee5d2@mail.gmail.com> On Mon, 31 Jan 2005 18:01:59 -0600, Victor Rex <apple_py@biz-experts.net> wrote: > I played around with this output issue and I love the way it works. > Now, how do you do this in *nix? I tried the same approach and I get a > blank line for 5 seconds (or whatever number of cycles you have on your > example) and the a final line with the last value of the iterable. > > Do you happen to know how this in done? you might want to flush stdout after printing to it. "print" will cares for this only when not using that trailing comma. "flush" means to write immedatly instead to wait for a fair amount of data. import sys,time for i in range(8): sys.stdout.write( "step: %s\r" % i) # or: print "step: %s\r" % i, sys.stdout.flush() time.sleep(.5) There's still another possibilty using ansi control sequences. The dirty way is to print (without trailing comma) and go back to previous line: import time for i in range(8): print "step: %s\033[A" % i # print subsystem has done stdout.flush time.sleep(.5) It's dirty cause the next line was already entered and thus is written (as an empty line) and content of older "steps" will stay an screen, when subsequents lines aren't long enough to overwrite them. Which also applies to \r: import sys,time for i in range(8,0,-1): # printing 8**8, ..., 0**0 on line. Forget to overwrite sys.stdout.write( "step: %s\r" % (i**i)) sys.stdout.flush() time.sleep(.5) Fixes are to add whitespace to the line. Stepping back with \033[D fixes the empty newline issue (which is most often not worth the effort): import sys,time for i in range(8,0,-1): # fixing output length to 30 output = "%-30s" % "step: %s" % (i**i) length = len(output) sys.stdout.write(output) # "print output," would be different, because of implizit spaces sys.stdout.write("\033[D"* (length)) sys.stdout.flush() time.sleep(.5) regards Michael From mark.brown at rogers.com Tue Feb 1 15:40:06 2005 From: mark.brown at rogers.com (Mark Brown) Date: Tue Feb 1 15:40:10 2005 Subject: [Tutor] Test Message-ID: <41FF94C6.2070709@rogers.com> Test, please disregard. From apple_py at biz-experts.net Tue Feb 1 17:28:31 2005 From: apple_py at biz-experts.net (Victor Rex) Date: Tue Feb 1 17:28:34 2005 Subject: [Tutor] carriage return on windows In-Reply-To: <1ff2dfbf05020105307f2ee5d2@mail.gmail.com> References: <41FC40C8.1050308@fastmail.fm> <166443577941.20050129211823@columbus.rr.com> <8b67b003454f617189945135968facfc@yahoo.fr> <001b01c50675$0a2f00c0$275328cf@JSLAPTOP> <0943e4bba36230c65951716acb5f1241@yahoo.fr> <000601c5067b$ca454ad0$d25428cf@JSLAPTOP> <41FC558A.7090402@gmail.com> <41FEC6F7.3050301@biz-experts.net> <1ff2dfbf05020105307f2ee5d2@mail.gmail.com> Message-ID: <41FFAE2F.80500@biz-experts.net> Michael Janssen wrote: >On Mon, 31 Jan 2005 18:01:59 -0600, Victor Rex <apple_py@biz-experts.net> wrote: > > > >>I played around with this output issue and I love the way it works. >>Now, how do you do this in *nix? I tried the same approach and I get a >>blank line for 5 seconds (or whatever number of cycles you have on your >>example) and the a final line with the last value of the iterable. >> >>Do you happen to know how this in done? >> >> > >you might want to flush stdout after printing to it. "print" will >cares for this only when not using that trailing comma. "flush" means >to write immedatly instead to wait for a fair amount of data. > >import sys,time >for i in range(8): > sys.stdout.write( "step: %s\r" % i) > # or: print "step: %s\r" % i, > sys.stdout.flush() > time.sleep(.5) > > >There's still another possibilty using ansi control sequences. The >dirty way is to print (without trailing comma) and go back to previous >line: > >import time >for i in range(8): > print "step: %s\033[A" % i > # print subsystem has done stdout.flush > time.sleep(.5) > >It's dirty cause the next line was already entered and thus is written >(as an empty line) and content of older "steps" will stay an screen, >when subsequents lines aren't long enough to overwrite them. Which >also applies to \r: > >import sys,time >for i in range(8,0,-1): > # printing 8**8, ..., 0**0 on line. Forget to overwrite > sys.stdout.write( "step: %s\r" % (i**i)) > sys.stdout.flush() > time.sleep(.5) > >Fixes are to add whitespace to the line. Stepping back with \033[D >fixes the empty newline issue (which is most often not worth the >effort): > >import sys,time >for i in range(8,0,-1): > # fixing output length to 30 > output = "%-30s" % "step: %s" % (i**i) > length = len(output) > sys.stdout.write(output) > # "print output," would be different, because of implizit spaces > sys.stdout.write("\033[D"* (length)) > sys.stdout.flush() > time.sleep(.5) > > >regards >Michael > > > > Excellent. Thanks Kent and Michael. Great tutorial ;-) You're right Michael. This last one works nicely but it is probably not worth the effort. I likes the previous one but adding fixed formatting to the number output, something like "step: %9s\r" instead of just "step: %s\r". Thanks again. Victor From jsmith at medplus.com Tue Feb 1 17:40:18 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Tue Feb 1 17:40:23 2005 Subject: [Tutor] Matching with beginning of the line in the character set Message-ID: <C4C644CF4ADA9448904C3E8BACC4B97C02E67186@medexch1.medplus.com> I want to match a string which is preceeded by a space or occurs at the beginning of the line. I also don't want to catch the preceeding character as a group. I have found both of the following to work re.compile('(?:^|\s)string') re.compile('(?:\A|\s)string') But would prefer to use the more concise [] notation. However re.compile('[^\s]string') Does not work and re.compile('[\A\s]string') throws an exception: Traceback (most recent call last): File "<interactive input>", line 1, in ? File "C:\Python24\Lib\sre.py", line 180, in compile return _compile(pattern, flags) File "C:\Python24\Lib\sre.py", line 227, in _compile raise error, v # invalid expression error: internal: unsupported set operator Why don't either of these work (particularly the latter)? Jeff From mark.kels at gmail.com Tue Feb 1 18:08:41 2005 From: mark.kels at gmail.com (Mark Kels) Date: Tue Feb 1 19:08:50 2005 Subject: [Tutor] Tkinter questions Message-ID: <c225925305020109087a9d7b6e@mail.gmail.com> Hello, I got some Tkinter questions that I need the answer for to complete a little project of mine: 1. How can I make the program to open in a X*Y sized window ? 2. How can I open another window from the first one (without closing it) ? 3. How can I add a file browser for my app (like the one you get when you press "Save as..." in windows apps) ? 4. How do I configure the font size on the Text widget (its realy huge, and I would like to change it to somthing like 12). 5. [OT] Do you know any web-sites that I can store my project at (like sourceforge and others) ? This is all for now :) Thanks in advence . -- 1. The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners. 2. Unix is user friendly - it's just picky about it's friends. 3. Documentation is like sex: when it is good, it is very, very good. And when it is bad, it is better than nothing. - Dick Brandon From kent37 at tds.net Tue Feb 1 19:15:18 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Feb 1 19:15:27 2005 Subject: [Tutor] Matching with beginning of the line in the character set In-Reply-To: <C4C644CF4ADA9448904C3E8BACC4B97C02E67186@medexch1.medplus.com> References: <C4C644CF4ADA9448904C3E8BACC4B97C02E67186@medexch1.medplus.com> Message-ID: <41FFC736.1090106@tds.net> Smith, Jeff wrote: > I want to match a string which is preceeded by a space or occurs at the > beginning of the line. I also don't want to catch the preceeding > character as a group. > > I have found both of the following to work > re.compile('(?:^|\s)string') > re.compile('(?:\A|\s)string') How about r'\bstring' ? It doesn't mean quite the same as \sstring but it might work for you. > > But would prefer to use the more concise [] notation. However > re.compile('[^\s]string') As the first character in [], ^ means 'not'. > Does not work and > re.compile('[\A\s]string') I guess \A doesn't count as a 'character class'? Or do you need to be using raw strings? Kent From jsmith at medplus.com Tue Feb 1 19:30:44 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Tue Feb 1 19:30:47 2005 Subject: [Tutor] Matching with beginning of the line in the character set Message-ID: <C4C644CF4ADA9448904C3E8BACC4B97C02E671A5@medexch1.medplus.com> Kent, I think \b will work for me since I was really looking for [\A\W] anyway. That still doesn't answer the generalized question about something like [\A\d] for instance. Thanks, Jeff BTW, I was using raw strings although I forgot to put that in. -----Original Message----- From: Kent Johnson [mailto:kent37@tds.net] Sent: Tuesday, February 01, 2005 1:15 PM Cc: Tutor@python.org Subject: Re: [Tutor] Matching with beginning of the line in the character set Smith, Jeff wrote: > I want to match a string which is preceeded by a space or occurs at > the beginning of the line. I also don't want to catch the preceeding > character as a group. > > I have found both of the following to work > re.compile('(?:^|\s)string') > re.compile('(?:\A|\s)string') How about r'\bstring' ? It doesn't mean quite the same as \sstring but it might work for you. > > But would prefer to use the more concise [] notation. However > re.compile('[^\s]string') As the first character in [], ^ means 'not'. > Does not work and > re.compile('[\A\s]string') I guess \A doesn't count as a 'character class'? Or do you need to be using raw strings? Kent _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Tue Feb 1 19:49:20 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Feb 1 19:49:30 2005 Subject: [Tutor] Matching with beginning of the line in the character set In-Reply-To: <C4C644CF4ADA9448904C3E8BACC4B97C02E671A5@medexch1.medplus.com> References: <C4C644CF4ADA9448904C3E8BACC4B97C02E671A5@medexch1.medplus.com> Message-ID: <41FFCF30.2090504@tds.net> Smith, Jeff wrote: > Kent, > > I think \b will work for me since I was really looking for [\A\W] > anyway. > > That still doesn't answer the generalized question about something like > [\A\d] for instance. I know :-) The docs say [] is "Used to indicate a set of characters." So it kind of makes sense that it works for \w and \s, which are just shortcuts for sets of characters themselves, but not for \A which is something different. Kent > > Thanks, > Jeff > > BTW, I was using raw strings although I forgot to put that in. > > -----Original Message----- > From: Kent Johnson [mailto:kent37@tds.net] > Sent: Tuesday, February 01, 2005 1:15 PM > Cc: Tutor@python.org > Subject: Re: [Tutor] Matching with beginning of the line in the > character set > > > > > Smith, Jeff wrote: > >>I want to match a string which is preceeded by a space or occurs at >>the beginning of the line. I also don't want to catch the preceeding >>character as a group. >> >>I have found both of the following to work >> re.compile('(?:^|\s)string') >> re.compile('(?:\A|\s)string') > > > How about r'\bstring' ? It doesn't mean quite the same as \sstring but > it might work for you. > > >>But would prefer to use the more concise [] notation. However >> re.compile('[^\s]string') > > > As the first character in [], ^ means 'not'. > > >>Does not work and >> re.compile('[\A\s]string') > > > I guess \A doesn't count as a 'character class'? Or do you need to be > using raw strings? > > Kent > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From ternary at gmail.com Tue Feb 1 19:58:49 2005 From: ternary at gmail.com (Mike Bell) Date: Tue Feb 1 19:58:52 2005 Subject: [Tutor] Matching with beginning of the line in the character set In-Reply-To: <C4C644CF4ADA9448904C3E8BACC4B97C02E671A5@medexch1.medplus.com> References: <C4C644CF4ADA9448904C3E8BACC4B97C02E671A5@medexch1.medplus.com> Message-ID: <82975b0c05020110581244f840@mail.gmail.com> Alternatively, you could .split() your string and not invoke the mechanisms dealing with regular expressions. Is this considered stylistically sloppy in the event that the split results in a very long array? Sloppier than REs are to begin with? I think that the problem with [\A\d] is that \A is zero-length, which doesn't make sense in the context of []. Brackets aren't shorthand for "'or' a bunch of small things together" but rather "'or' a bunch of these single-character matches together" mike On Tue, 1 Feb 2005 13:30:44 -0500, Smith, Jeff <jsmith@medplus.com> wrote: > Kent, > > I think \b will work for me since I was really looking for [\A\W] > anyway. > > That still doesn't answer the generalized question about something like > [\A\d] for instance. > > Thanks, > Jeff > > BTW, I was using raw strings although I forgot to put that in. > > -----Original Message----- > From: Kent Johnson [mailto:kent37@tds.net] > Sent: Tuesday, February 01, 2005 1:15 PM > Cc: Tutor@python.org > Subject: Re: [Tutor] Matching with beginning of the line in the > character set > > Smith, Jeff wrote: > > I want to match a string which is preceeded by a space or occurs at > > the beginning of the line. I also don't want to catch the preceeding > > character as a group. > > > > I have found both of the following to work > > re.compile('(?:^|\s)string') > > re.compile('(?:\A|\s)string') > > How about r'\bstring' ? It doesn't mean quite the same as \sstring but > it might work for you. > > > > > But would prefer to use the more concise [] notation. However > > re.compile('[^\s]string') > > As the first character in [], ^ means 'not'. > > > Does not work and > > re.compile('[\A\s]string') > > I guess \A doesn't count as a 'character class'? Or do you need to be > using raw strings? > > Kent > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From ps_python at yahoo.com Tue Feb 1 20:14:21 2005 From: ps_python at yahoo.com (kumar s) Date: Tue Feb 1 20:14:25 2005 Subject: [Tutor] Append function In-Reply-To: <Pine.LNX.4.44.0501302348270.13470-100000@hkn.eecs.berkeley.edu> Message-ID: <20050201191421.7520.qmail@web53702.mail.yahoo.com> Hi Danny: I have ~50 files in this format: File1: 680:209 3006.3 266:123 250.5 62:393 117.3 547:429 161.5 341:311 546.5 132:419 163.3 98:471 306.3 File 2: 266:123 168.0 62:393 119.3 547:429 131.0 341:311 162.3 132:419 149.5 98:471 85.0 289:215 207.0 75:553 517.0 I am generating these files using this module: f1 = open("test2_cor.txt","r") ana = f1.read().split('\n') ana = ana[:-1] pbs = [] for line in ana: cols = line.split('\t') pb = cols[0] pbs.append(pb) ##########CEL Files section ######## files = glob.glob("c:\files\*.cel") def parSer(file): f1 = open(file,'r') celf = f1.read().split('\n') celfile = celf[24:409624] my_vals = celParser(celfile,pbs) f2 = open(file+'.txt','w') for line in my_vals: f2.write(line+'\t') f2.write('\n') f2.close() def main(): for each in files: parSer(each) main() Because, I asked to write a file with the name of the file as output, it is generating 50 output files for 50 input files. What I am interested in is to append the output to one single file but with tab delimmitation. For example: for each file there are 2 columns. Cor and val file 1 file 2 file 3 file 4 cor val cor val cor val cor val x:x 1345 x:x 5434 x:x 4454 x:x 4462 x:y 3463 x:y 3435 x:y 3435 x:y 3435 Could you suggest a way. Thank you. __________________________________ Do you Yahoo!? The all-new My Yahoo! - What will yours do? http://my.yahoo.com From alan.gauld at freenet.co.uk Tue Feb 1 22:12:09 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Feb 1 22:11:53 2005 Subject: [Tutor] Better structure? References: <000301c507a3$f3828c90$7d5428cf@JSLAPTOP> <00af01c507c5$f06ec470$d1b48651@xp> <001701c50817$6f454d90$6d5428cf@JSLAPTOP> Message-ID: <005f01c508a2$b14ec1e0$68b78851@xp> > What, like > global radiusaxis, radiusaxis2 exactly. > > And since there is no input parameter and no return statement > > and you only call start() once... > > Not true. If y == 'clear', then start is called to "redraw" the window. > Very important part. OK, I missed that, but its still better to hide the call to start inside an if name== main clause since otherwise you can't ever import your file without drawing the screen. > I think I'll do that, but of course I'll have to add ValueError -- because > of math domain errors on my function. That's what the try except block is for. In that case just put the ValueError clause in and leave other erors to raise an error stack - that way you get to see the source of the problem. Then wrap your call to start in a try/except to catch the errors and print a message at the outer level. That way its easy to turn error reporting on/off Alan G. From alan.gauld at freenet.co.uk Tue Feb 1 22:23:24 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Feb 1 22:25:13 2005 Subject: [Tutor] Presentation References: <003f01c5087c$117cb6c0$012118ac@SP1179> Message-ID: <008f01c508a4$43947a30$68b78851@xp> > Any help I can get would be much appreciated - such as > language comparisons, companies and systems that use python, > debates about what python is good for Most of that can be found under the General FAQ on the python web site. And links to other similar material. Alan G From ps_python at yahoo.com Tue Feb 1 22:36:32 2005 From: ps_python at yahoo.com (kumar s) Date: Tue Feb 1 22:36:35 2005 Subject: [Tutor] Append function In-Reply-To: <41FD6E9B.6030200@tds.net> Message-ID: <20050201213632.46115.qmail@web53710.mail.yahoo.com> Hi Kent, Thank you for your suggestion. I keep getting IOError permission denied every time I try the tips that you provided. I tried to lookup on this error and did not get reasonable answer. Is this error something to do with Windows OS? Any suggestions. Thank you K >>> allColumns = [readColumns("C:\Documents and Settings\myfiles")for filePath in file_list] Traceback (most recent call last): File "<pyshell#167>", line 1, in -toplevel- allColumns = [readColumns("C:\Documents and Settings\myfiles")for filePath in file_list] File "<pyshell#159>", line 2, in readColumns rows = [line.split() for line in open(filePath)] IOError: [Errno 13] Permission denied: 'C:\\Documents and Settings\\myfiles' >>> > def readColumns(filePath): > rows = [ line.split() for line in > open(filePath) ] > return zip(*rows) > > # list of all the files to read > allFiles = [ 'f1.txt', 'f2.txt' ] > > # both columns from all files > allColumns = [ readColumns(filePath) for filePath in > allFiles ] > > # just the second column from all files > allSecondColumns = [ cols[1] for cols in allColumns > ] > > # a representative first column > col1 = allColumns[0][0] > > # zip it up into rows > allRows = zip(col1, *allSecondColumns) > > for row in allRows: > print '\t'.join(row) > > > Kent __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From alan.gauld at freenet.co.uk Tue Feb 1 22:37:34 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Feb 1 22:37:24 2005 Subject: [Tutor] Better structure? References: <Pine.LNX.4.44.0502010026540.16528-100000@hkn.eecs.berkeley.edu> Message-ID: <00ad01c508a6$3e727910$68b78851@xp> > ever get the chance, you may want to take a look at a book called > Programming Pearls: > > http://www.cs.bell-labs.com/cm/cs/pearls/ > I'll second that. Personally I try to read both books (I have the original 2 volume version!) every couple of years - they are that valuable. Most newbie programmers can learn a lot from Bentley's book(s) - especially about programming for performance. But loads of other tricks too. Alan G. From alan.gauld at freenet.co.uk Tue Feb 1 22:40:31 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Feb 1 22:40:09 2005 Subject: [Tutor] Programming Challenge C++ and Python References: <3c51d5180502010308149302c2@mail.gmail.com> Message-ID: <00c601c508a6$a7bf4290$68b78851@xp> > I don't have any idea about how to write a plugin but I found out > that the server administrator has written a Plugin Development Kit in > C++ for those who wish to write plugins for the interface.I don't know > C++ so I cannot convert this kit into python scripts. Caveat: I've never done this so don't know how easy it is but... There is a tool called SWIG which is for creating Python(or Perl or Tcl etc) wrappers around C/C++ APIs. So SWIG might be able to wrap your plug-in API for you. But I've no idea how easy that is! Alan G. From jhomme at libcom.com Tue Feb 1 23:15:33 2005 From: jhomme at libcom.com (jhomme) Date: Tue Feb 1 23:17:32 2005 Subject: [Tutor] Introductory Links Message-ID: <9a8eb73ba1935359202338cfbb407fba@libcom.com> -----Original message----- From: "Alan Gauld" alan.gauld@freenet.co.uk Date: Tue, 1 Feb 2005 16:15:14 -0500 To: "jhomme" jhomme@libcom.com Subject: Re: [Tutor] Dictionary Nesting > > Um, thanks for reminding me about the prompt. > > ....work my way through some other stuff before wasting people's > time. > > It was your own time I was thinking of. Its much quicker to > experiment briefly if you think you might know the answer > than to compose an email, send it and then wait for replies! > > Then if you do send a mail you can be much more specific too, > because you know what doesn't work! :-) > > Alan G. > Hi, Is it possible to get a copy of the message sent to us when we first join? I want to follow the links in it so I can learn how to do the research and ask questions on the list. Thanks. Jim From kent37 at tds.net Wed Feb 2 00:00:45 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Feb 2 00:00:52 2005 Subject: [Tutor] Append function In-Reply-To: <20050201213632.46115.qmail@web53710.mail.yahoo.com> References: <20050201213632.46115.qmail@web53710.mail.yahoo.com> Message-ID: <42000A1D.9090005@tds.net> You seem to be giving a path to a directory rather than a single file. Also you are putting it in the wrong place, you should edit the allFiles list. Kent kumar s wrote: > Hi Kent, > Thank you for your suggestion. I keep getting > IOError permission denied every time I try the tips > that you provided. I tried to lookup on this error and > did not get reasonable answer. Is this error something > to do with Windows OS? > > Any suggestions. > > Thank you > K > > >>>>allColumns = [readColumns("C:\Documents and > > Settings\myfiles")for filePath in file_list] > > Traceback (most recent call last): > File "<pyshell#167>", line 1, in -toplevel- > allColumns = [readColumns("C:\Documents and > Settings\myfiles")for filePath in file_list] > File "<pyshell#159>", line 2, in readColumns > rows = [line.split() for line in open(filePath)] > IOError: [Errno 13] Permission denied: 'C:\\Documents > and Settings\\myfiles' > > > > >>def readColumns(filePath): >> rows = [ line.split() for line in >>open(filePath) ] >> return zip(*rows) >> >># list of all the files to read >>allFiles = [ 'f1.txt', 'f2.txt' ] >> >># both columns from all files >>allColumns = [ readColumns(filePath) for filePath in >>allFiles ] >> >># just the second column from all files >>allSecondColumns = [ cols[1] for cols in allColumns >>] >> >># a representative first column >>col1 = allColumns[0][0] >> >># zip it up into rows >>allRows = zip(col1, *allSecondColumns) >> >>for row in allRows: >> print '\t'.join(row) >> >> >>Kent > > > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > From bvande at po-box.mcgill.ca Wed Feb 2 00:09:01 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed Feb 2 00:09:17 2005 Subject: [Tutor] Introductory Links In-Reply-To: <9a8eb73ba1935359202338cfbb407fba@libcom.com> References: <9a8eb73ba1935359202338cfbb407fba@libcom.com> Message-ID: <42000C0C.9030003@po-box.mcgill.ca> jhomme said unto the world upon 2005-02-01 17:15: <SNIP> > Hi, Is it possible to get a copy of the message sent to us when we > first join? I want to follow the links in it so I can learn how to > do the research and ask questions on the list. > > Thanks. > > Jim Hi Jim, I don't still have a copy of my Welcome msg. But the following links all are good places to look: <http://www.python.org/moin/BeginnersGuide> The Python wwiki's beginner's page <http://groups.google.ca/groups?hl=en&lr=&ie=UTF-8&group=comp.lang.python> Search com.lang.python <http://www.python.org/cgi-bin/moinmoin/RecentChanges> The Python Wiki page -- not the front, but the recent changes which is how I like to enter it. <http://starship.python.net/crew/mhammond/mozilla/pythonpanel.xul> The Python Sidebar for Mozilla -- works for FireFox, too. A useful tool if you're using the right [ambiguity intended ;-)] browser. <http://catb.org/~esr/faqs/smart-questions.html> How To Ask Questions The Smart Way by Eric Raymond. The Tutor list won't bite you if you don't follow any of the advice in that essay. But it is a very useful thing to read to learn how best to frame your questions so as to get maximum return from everyone's effort (your and those who answer you both). HTH, Brian vdB From alan.gauld at freenet.co.uk Wed Feb 2 00:11:00 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Feb 2 00:10:50 2005 Subject: [Tutor] Introductory Links References: <9a8eb73ba1935359202338cfbb407fba@libcom.com> Message-ID: <012701c508b3$546a0690$68b78851@xp> > > Then if you do send a mail you can be much more specific too, > > because you know what doesn't work! :-) > > > Is it possible to get a copy of the message sent to us when we first join? >I want to follow the links in it so I can learn how to do the research > and ask questions on the list. I'm not sure which message you mean, but assuming its the one you get when you start a new thread on tutor then I guess thats a question for the list admin team. It sounds emminently sensible to send a welcome message with some kind of set of intro links in it. Its so long sice I joined I can't recall what happened!! Danny? Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From ismaelgf at adinet.com.uy Wed Feb 2 00:08:19 2005 From: ismaelgf at adinet.com.uy (Ismael Garrido) Date: Wed Feb 2 00:28:38 2005 Subject: [Tutor] Classes Message-ID: <42000BE3.60309@adinet.com.uy> Hello. I was just wondering, what magic can you do with classes? I mean, things like "class Name(Exception)" or "class Name(threading.Thread), which other classes are interesting to subclass? I've seen Object too, but I don't understand what it does. Thanks Ismael From maxnoel_fr at yahoo.fr Wed Feb 2 00:44:28 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Wed Feb 2 00:44:35 2005 Subject: [Tutor] Classes In-Reply-To: <42000BE3.60309@adinet.com.uy> References: <42000BE3.60309@adinet.com.uy> Message-ID: <6c4daf2ca96450b2a6b0606bfb4313af@yahoo.fr> On Feb 1, 2005, at 23:08, Ismael Garrido wrote: > Hello. > > I was just wondering, what magic can you do with classes? I mean, > things like "class Name(Exception)" or "class Name(threading.Thread), > which other classes are interesting to subclass? I've seen Object too, > but I don't understand what it does. Basically, Object is the class all your classes should be deriving from (when you do that, you're using "new-style classes"). It's the root in the class hierarchy of Python. This gives you access to a lot of nifty features for free, such as properties. Oh, and the best classes are those you create yourself, of course :D -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From kp8 at mac.com Wed Feb 2 00:53:13 2005 From: kp8 at mac.com (kevin parks) Date: Wed Feb 2 00:53:18 2005 Subject: [Tutor] permutations, patterns, and probability In-Reply-To: <20050113181855.9CBEC1E4014@bag.python.org> References: <20050113181855.9CBEC1E4014@bag.python.org> Message-ID: <80a3c832a484b4eeb57c06111afbb931@mac.com> Greetings, I am working on a program to produce patterns. What would like is for it to exhaustively produce all possible permutations of a sequence of items but for each permutation produce variations, and also a sort of stutter based on probability / weighted randomess. Let us say we have tiles of four primary colors: ['Red', 'Blue', 'Green', 'Yellow']. Now we also have 4 alternatives or substitutes for each color ['Maroon', 'Navy_Blue', 'Forest_Green', 'Dark_Brown'] We pick a unique permutation, say: ['Red', 'Blue', 'Yellow', 'Green'] Now I would like to pick the primary colors substitute (say 30% chance for each element) so instead of our plain ['Red', 'Blue', 'Yellow', 'Green'] we might end up with: ['Red', 'Navy_Blue', 'Yellow', 'Forest_Green'] or ['Maroon', 'Navy_Blue', 'Yellow', 'Green'] Whatever... The main point is that sometimes the original color is retained and sometimes the dark color is substituted. Now I want to take this list and sometimes stutter an element so that there is, let us say a 50% chance for each element, that it is stuttered, and it may be repeated 1 (34%), 2(66%), or 3(33%) times. So that we could get: ['Maroon','Maroon','Navy_Blue', 'Yellow','Yellow','Yellow','Yellow', 'Green'] The program would quit when all 24 (in the case of 4 elements) was exhausted. I have code that makes weighted randomness. I have code that makes permutations, but I am having trouble putting this all together... While i work on it though that i might ask for help... I'd like for the code to be reusable and am building a library of functions for patterns. cheers, kevin ### This is not mine, it is from a python book... I believe the Lutz book def permute(list): if not list: # shuffle any sequence return [list] # empty sequence else: res = [] for i in range(len(list)): rest = list[:i] + list[i+1:] # delete current node for x in permute(rest): # permute the others res.append(list[i:i+1] + x) # add node at front return res mport random ### This this is mine, but seems to work anyway hee hee def windex(lst): '''an attempt to make a random.choose() function that makes weighted choices accepts a list of tuples with the item and probability as a pair like: >>> x = [('one', 0.25), ('two', 0.25), ('three', 0.5)] >>> y=windex(x)''' n = random.uniform(0, 1) for item, weight in lst: if n < weight: break n = n - weight return item From apple_py at biz-experts.net Wed Feb 2 02:32:50 2005 From: apple_py at biz-experts.net (Victor Rex) Date: Wed Feb 2 02:33:00 2005 Subject: [Tutor] Presentation In-Reply-To: <41FF5EA9.3090000@tds.net> References: <003f01c5087c$117cb6c0$012118ac@SP1179> <41FF5EA9.3090000@tds.net> Message-ID: <42002DC2.1030202@biz-experts.net> This is a great series of links. I found the following on Pythology too: Python Spotting http://pythonology.org/spotting Best of luck. Kent Johnson wrote: > Eric Raymond's "Why Python?" essay is a classic: > http://pythonology.org/success&story=esr > > Bruce Eckel's "Why I love Python" presentation is here: > http://64.78.49.204/pub/eckel/LovePython.zip > > This page has lots of links you might be interested in: > http://www.ferg.org/python_presentations/index.html > > This page has links to language comparisons: > http://www.python.org/moin/LanguageComparisons > > Good luck! > Kent > > Paul Hartley wrote: > >> I am trying to get Python established here in the Philippines. >> Currently I am in charge of operations at a business based in Manila >> and I have asked my IT staff to start using Python (with some success). >> >> A local university has now asked that I give a talk to their IT >> people on Python - so here is an opportunity to spread the word and >> get some more converts and maybe introduce python into their computer >> science courses. >> >> Any help I can get would be much appreciated - such as language >> comparisons, companies and systems that use python, debates about >> what python is good for (almost everything), examples of elegant code.. >> >> When I was a member of the Forth Interest Group in the USA we learned >> that Forth was used on the buggy that went to mars, that it started >> life controlling huge radio telescopes which only had 4k (yes 4k) of >> memory for both language and application. >> >> Anything like the above concerning python would be useful. >> >> Any other suggestions would help also, the audience will have >> computers, so a demonstration of small workshop would also be good - >> the presentation/session is for 4 hours on the 10th February. >> >> Paul >> >> >> >> ------------------------------------------------------------------------ >> >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Wed Feb 2 02:43:52 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Feb 2 02:43:56 2005 Subject: [Tutor] permutations, patterns, and probability In-Reply-To: <80a3c832a484b4eeb57c06111afbb931@mac.com> References: <20050113181855.9CBEC1E4014@bag.python.org> <80a3c832a484b4eeb57c06111afbb931@mac.com> Message-ID: <42003058.6040502@tds.net> kevin parks wrote: > Greetings, > > I am working on a program to produce patterns. What would like is for it > to exhaustively produce all possible permutations of a sequence of > items but for each permutation produce variations, and also a sort of > stutter based on probability / weighted randomess. > > Let us say we have tiles of four primary colors: ['Red', 'Blue', > 'Green', 'Yellow']. Now we also have 4 alternatives or substitutes for > each color ['Maroon', 'Navy_Blue', 'Forest_Green', 'Dark_Brown'] > > We pick a unique permutation, say: ['Red', 'Blue', 'Yellow', 'Green'] > > Now I would like to pick the primary colors substitute (say 30% chance > for each element) so instead of our plain > > ['Red', 'Blue', 'Yellow', 'Green'] > > we might end up with: > > ['Red', 'Navy_Blue', 'Yellow', 'Forest_Green'] > > or > > ['Maroon', 'Navy_Blue', 'Yellow', 'Green'] > > Whatever... The main point is that sometimes the original color is > retained and sometimes the dark color is substituted. > > Now I want to take this list and sometimes stutter an element so that > there is, let us say a 50% chance for each element, that it is > stuttered, and it may be repeated 1 (34%), 2(66%), or 3(33%) times. So > that we could get: > > ['Maroon','Maroon','Navy_Blue', 'Yellow','Yellow','Yellow','Yellow', > 'Green'] > > The program would quit when all 24 (in the case of 4 elements) was > exhausted. > > I have code that makes weighted randomness. I have code that makes > permutations, but I am having trouble putting this all together... While > i work on it though that i might ask for help... I'd like for the code > to be reusable and am building a library of functions for patterns. If you had a randomizeList function and a stutterList function then your top-level function would look like this: permutations = permute(['Red', 'Blue', 'Yellow', 'Green']) permutations = [ randomizeList(list) for list in permutations ] permutations = [ stutterList(list) for list in permutations ] In other words you start with the basic permutations, then apply the randomize function to each permutation, then apply the stutter function. The randomizeList function should walk through the list, find the right randomize list for that list element (a dict could help with that - look up the list element and get the randomize list), and build a new list with the randomized values. The stutterList function walks through the list building a new list with possibly repeated elements. HTH, Kent > > cheers, > kevin > > > ### This is not mine, it is from a python book... I believe the Lutz book > > def permute(list): > if not list: # shuffle any > sequence > return [list] # empty sequence > else: > res = [] > for i in range(len(list)): > rest = list[:i] + list[i+1:] # delete current > node > for x in permute(rest): # permute the > others > res.append(list[i:i+1] + x) # add node at front > return res > > mport random > > ### This this is mine, but seems to work anyway hee hee > > def windex(lst): > '''an attempt to make a random.choose() function that makes > weighted choices > > accepts a list of tuples with the item and probability as a pair > like: >>> x = [('one', 0.25), ('two', 0.25), ('three', 0.5)] > >>> y=windex(x)''' > n = random.uniform(0, 1) > for item, weight in lst: > if n < weight: > break > n = n - weight > return item > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at freenet.co.uk Tue Feb 1 05:42:12 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Feb 2 02:58:07 2005 Subject: [Tutor] carriage return on windows References: <41FC40C8.1050308@fastmail.fm><166443577941.20050129211823@columbus.rr.com> <8b67b003454f617189945135968facfc@yahoo.fr> <001b01c50675$0a2f00c0$275328cf@JSLAPTOP> <0943e4bba36230c65951716acb5f1241@yahoo.fr> <000601c5067b$ca454ad0$d25428cf@JSLAPTOP><41FC558A.7090402@gmail.com> <41FEC6F7.3050301@biz-experts.net> Message-ID: <005301c50818$6620f380$68b78851@xp> > I played around with this output issue and I love the way it works. > Now, how do you do this in *nix? I tried the same approach and I get a > blank line for 5 seconds (or whatever number of cycles you have on your > example) and the a final line with the last value of the iterable. On Unix it is easiest to use the curses library. There are so many different terminals in use on Unix that no single set of control codes can be guaranteed to work. Curses provides an abstract terminal that you can control by positioning the cursor at x,y coordinates etc. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From keridee at jayco.net Tue Feb 1 16:20:28 2005 From: keridee at jayco.net (Jacob S.) Date: Wed Feb 2 03:02:46 2005 Subject: [Tutor] Better structure? References: <Pine.LNX.4.44.0501311447390.24680-100000@hkn.eecs.berkeley.edu> <41FF6082.70005@tds.net> Message-ID: <000001c508cb$5a67e9f0$3b5428cf@JSLAPTOP> I don't know who's going crazy here... but I checked that straight from the python 2.4 interpreter... Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> a = "go on long buddy" >>> a.lstrip("gonl") ' on long buddy' >>> a = "go long on log buddy!" >>> a.lstrip('gonl') ' long on log buddy!' >>> In both cases, lstrip just removed the first word... I don't see how this code is broken. Hope we figure it out. Jacob > This code is broken. lstrip('gonl ') will remove *all* leading g, o, n, l > and space, in any order: > >>> s='go long on log buddy!' > >>> s.lstrip('gonl ') > 'buddy!' > > Instead of y.lstrip('gonl ') you should use y[5:] or maybe y[len('gonl > '):] > > Kent > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From keridee at jayco.net Wed Feb 2 03:12:00 2005 From: keridee at jayco.net (Jacob S.) Date: Wed Feb 2 03:11:54 2005 Subject: [Tutor] Tkinter questions References: <c225925305020109087a9d7b6e@mail.gmail.com> Message-ID: <001d01c508cc$9e02ee70$3b5428cf@JSLAPTOP> I suggest looking at Introduction to Tkinter. http://www.pythonware.com/library/tkinter/introduction/index.htm HTH, Jacob > Hello, > I got some Tkinter questions that I need the answer for to complete a > little project of mine: > 1. How can I make the program to open in a X*Y sized window ? > 2. How can I open another window from the first one (without closing it) ? > 3. How can I add a file browser for my app (like the one you get when > you press "Save as..." in windows apps) ? > 4. How do I configure the font size on the Text widget (its realy > huge, and I would like to change it to somthing like 12). > 5. [OT] Do you know any web-sites that I can store my project at (like > sourceforge and others) ? > > This is all for now :) > Thanks in advence . > > -- > 1. The day Microsoft makes something that doesn't suck is probably the > day they start making vacuum cleaners. > 2. Unix is user friendly - it's just picky about it's friends. > 3. Documentation is like sex: when it is good, it is very, very good. > And when it is bad, it is better than nothing. - Dick Brandon > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From jeff at ccvcorp.com Wed Feb 2 03:14:10 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed Feb 2 03:13:23 2005 Subject: [Tutor] Better structure? In-Reply-To: <000001c508cb$5a67e9f0$3b5428cf@JSLAPTOP> References: <Pine.LNX.4.44.0501311447390.24680-100000@hkn.eecs.berkeley.edu> <41FF6082.70005@tds.net> <000001c508cb$5a67e9f0$3b5428cf@JSLAPTOP> Message-ID: <42003772.4010808@ccvcorp.com> Jacob S. wrote: > I don't know who's going crazy here... but I checked that straight from > the python 2.4 interpreter... >>> a = "go on long buddy" >>> a.lstrip('gonl') ' on long buddy' >>> a.lstrip('gonl ') 'buddy' >>> Note that in the second case, I've included a space in the lstrip() parameter. lstrip() is essentially saying "remove all leading characters until you find a character that's not in this sequence" -- a space counts as a character. (Took me trying it out before I saw this, so don't feel bad. ;) ) Jeff Shannon Technician/Programmer Credit International From keridee at jayco.net Wed Feb 2 03:23:10 2005 From: keridee at jayco.net (Jacob S.) Date: Wed Feb 2 03:22:54 2005 Subject: [Tutor] Better structure? References: <Pine.LNX.4.44.0501311447390.24680-100000@hkn.eecs.berkeley.edu> <41FF6082.70005@tds.net><000001c508cb$5a67e9f0$3b5428cf@JSLAPTOP> <42003772.4010808@ccvcorp.com> Message-ID: <002501c508ce$294e4e10$3b5428cf@JSLAPTOP> So, how would one go about this in a non broken code way? Don't they have something like what I'm requesting. It seems to me that a few things are flawed in the standard distribution. Little things like the overlooking of adding a method or function to decimal for returning an instance with x places right of the decimal. I know of quantize, but that's junk and not simple. Also why shouldn't string methods include stuff like lstrip which do precisely what I request? Maybe because they don't want to bother putting def mylstrip(string,stripstring): return string[len(stripstring):] as a method or something? Messy, just plain messy. Jacob Schmidt > Jacob S. wrote: > >> I don't know who's going crazy here... but I checked that straight from >> the python 2.4 interpreter... > > >>> a = "go on long buddy" > >>> a.lstrip('gonl') > ' on long buddy' > >>> a.lstrip('gonl ') > 'buddy' > >>> > > Note that in the second case, I've included a space in the lstrip() > parameter. lstrip() is essentially saying "remove all leading characters > until you find a character that's not in this sequence" -- > a space counts as a character. (Took me trying it out before I saw this, > so don't feel bad. ;) ) > > Jeff Shannon > Technician/Programmer > Credit International > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From jeff at ccvcorp.com Wed Feb 2 03:37:00 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed Feb 2 03:36:12 2005 Subject: [Tutor] Better structure? In-Reply-To: <002501c508ce$294e4e10$3b5428cf@JSLAPTOP> References: <Pine.LNX.4.44.0501311447390.24680-100000@hkn.eecs.berkeley.edu> <41FF6082.70005@tds.net><000001c508cb$5a67e9f0$3b5428cf@JSLAPTOP> <42003772.4010808@ccvcorp.com> <002501c508ce$294e4e10$3b5428cf@JSLAPTOP> Message-ID: <42003CCC.5060300@ccvcorp.com> Jacob S. wrote: > So, how would one go about this in a non broken code way? Don't they > have something like what I'm requesting. No, but it's pretty easy to do: def exact_lstrip(astring, stripstring): if astring.startswith(stripstring): astring = astring[len(stripstring):] return astring > [...] Also why > shouldn't string methods include stuff like lstrip which do precisely > what I request? Maybe it's because other people would have different expectations? The current implementation of strip() (including lstrip() and rstrip()) seems to work well for the most common case, and I'm not sure that your expectation is necessarily more generally useful than the current behavior. Especially given that your behavior is the one that's easier to hand-code if it's desired. Jeff Shannon Technician/Programmer Credit International From kp8 at mac.com Wed Feb 2 03:42:13 2005 From: kp8 at mac.com (kevin parks) Date: Wed Feb 2 03:42:19 2005 Subject: [Tutor] permutations, patterns, and probability In-Reply-To: <20050202015810.47F641E4004@bag.python.org> References: <20050202015810.47F641E4004@bag.python.org> Message-ID: <f7af922f6e5af5a124268c186347d71a@mac.com> Tremendously helpful!!!! One question though. How can i pluck a unique item from my exhaustive list of permutations without repeats making sure that each one is used once? Like filling a bag, shaking it, and then picking from the bag and removing that item from the bag so it isn't used again.... -k On Feb 1, 2005, at 8:58 PM, tutor-request@python.org wrote: > f you had a randomizeList function and a stutterList function then > your top-level function would > look like this: > > permutations = permute(['Red', 'Blue', 'Yellow', 'Green']) > permutations = [ randomizeList(list) for list in permutations ] > permutations = [ stutterList(list) for list in permutations ] > > In other words you start with the basic permutations, then apply the > randomize function to each > permutation, then apply the stutter function. > > The randomizeList function should walk through the list, find the > right randomize list for that list > element (a dict could help with that - look up the list element and > get the randomize list), and > build a new list with the randomized values. > > The stutterList function walks through the list building a new list > with possibly repeated elements. > > HTH, > Kent From p.hartley at spitech.com Wed Feb 2 17:57:57 2005 From: p.hartley at spitech.com (Paul Hartley) Date: Wed Feb 2 03:55:58 2005 Subject: [Tutor] Presentation References: <003f01c5087c$117cb6c0$012118ac@SP1179> Message-ID: <016a01c50948$5877aae0$012118ac@SP1179> Thank you for all your feedback on this - powerpoint presentations and all!! Not only is the language amazing but the community is fantastic!! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050202/1411e8ec/attachment.html From carroll at tjc.com Wed Feb 2 04:04:01 2005 From: carroll at tjc.com (Terry Carroll) Date: Wed Feb 2 04:04:07 2005 Subject: [Tutor] Presentation In-Reply-To: <016a01c50948$5877aae0$012118ac@SP1179> Message-ID: <Pine.LNX.4.44.0502011902500.4638-100000@violet.rahul.net> On Wed, 2 Feb 2005, Paul Hartley wrote: > Not only is the language amazing but the community is fantastic!! The community is one of the things I particularly like about Python. I always hated asking a question in the Perl newsgroups; although you usually got an answer, you were almost certain to be told you're stupid for not already knowing it. From kent37 at tds.net Wed Feb 2 04:38:49 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Feb 2 04:38:54 2005 Subject: [Tutor] permutations, patterns, and probability In-Reply-To: <f7af922f6e5af5a124268c186347d71a@mac.com> References: <20050202015810.47F641E4004@bag.python.org> <f7af922f6e5af5a124268c186347d71a@mac.com> Message-ID: <42004B49.4070004@tds.net> kevin parks wrote: > Tremendously helpful!!!! One question though. How can i pluck a unique > item from my exhaustive list of permutations without repeats making sure > that each one is used once? Like filling a bag, shaking it, and then > picking from the bag and removing that item from the bag so it isn't > used again.... Use random.shuffle() to 'shake' the list. Then use pop() to remove an item: >>> import random >>> l=range(10) >>> random.shuffle(l) >>> l [4, 5, 0, 8, 9, 6, 2, 1, 7, 3] >>> l.pop() 3 >>> l.pop() 7 >>> l.pop() 1 >>> l [4, 5, 0, 8, 9, 6, 2] Kent From nbbalane at gmail.com Wed Feb 2 08:10:36 2005 From: nbbalane at gmail.com (jrlen balane) Date: Wed Feb 2 08:10:39 2005 Subject: [Tutor] how to separate hexadecimal Message-ID: <2cad209005020123107fb43105@mail.gmail.com> i have a 4 digit hex number (2 bytes) and i want to separate it into 2 digit hex (1 byte each) meaning i want to get the upper byte and the lower byte since i am going to add this two. how am i going to do this? should i treat it just like a normal string? please help, thanks. ex. hexa = '0x87BE" # what i want to do is: a = 0x87, b = 0xBE # so that i could do this: c = a + b #which should be equal to 0x145 From kraus at hagen-partner.de Wed Feb 2 09:12:55 2005 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Wed Feb 2 09:12:26 2005 Subject: [Tutor] Re: how to separate hexadecimal In-Reply-To: <2cad209005020123107fb43105@mail.gmail.com> References: <2cad209005020123107fb43105@mail.gmail.com> Message-ID: <ctq1um$gp7$1@sea.gmane.org> jrlen balane wrote: > i have a 4 digit hex number (2 bytes) and i want to separate it into 2 > digit hex (1 byte each) meaning i want to get the upper byte and the > lower byte since i am going to add this two. > how am i going to do this? > should i treat it just like a normal string? > please help, thanks. > > ex. hexa = '0x87BE" # what i want to do is: > a = 0x87, b = 0xBE # so that i could do this: > c = a + b #which should be equal to 0x145 Not sure where you get hexa from, but given your example you can use int(x, base) with base = 16 to convert your string to an integer and then use the %x formatstring: >>> hexa = '0x87BE' >>> upper = int(hexa[2:4], 16) >>> lower = int(hexa[4:6], 16) >>> print '0x%x + 0x%x = 0x%x' % (upper, lower, upper+lower) 0x87 + 0xbe = 0x145 HTH, Wolfram From alan.gauld at freenet.co.uk Wed Feb 2 09:32:59 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Feb 2 09:32:27 2005 Subject: [Tutor] Classes References: <42000BE3.60309@adinet.com.uy> Message-ID: <014d01c50901$cde680e0$68b78851@xp> > I was just wondering, what magic can you do with classes? You can define your own types. Thats what classes are for. Those types can be as 'magic' as your imagination (and programming skills!) allow. > other classes are interesting to subclass? I've seen Object too, but I > don't understand what it does. It's 'object' - lowercase o - and that is the way to tell Python to use "new-style" classes, which are not very new now! Essentially all the basic types in Python are descended from object and the object class provides access to some special features that won't be available if you don't subclass object (as in classic style classes) OTOH subclsassing object does add overhead to your class and so makes it a bit slower. You can also subclass any other Python type, thus class bigfloat(float): .... would provide a special type of floating point number - maybe with unlimited precision, provided you wrote the code to allow that... Finally classes are themselves objects and can be used as a way of monitoring and controlling a collection of objects. This is often called meta-programming and if you want to twist your head in knots read the paper that Guido wrote on meta programming in Python :-) Read the OOP topic in my tutorial for more about using classes. (but not about meta programming!! :-) Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Wed Feb 2 09:35:47 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Feb 2 09:35:26 2005 Subject: [Tutor] Better structure? References: <Pine.LNX.4.44.0501311447390.24680-100000@hkn.eecs.berkeley.edu><41FF6082.70005@tds.net> <000001c508cb$5a67e9f0$3b5428cf@JSLAPTOP> Message-ID: <016101c50902$323efae0$68b78851@xp> > I don't know who's going crazy here... but I checked that straight from the > python 2.4 interpreter... > > Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> a = "go on long buddy" > >>> a.lstrip("gonl") > ' on long buddy' > >>> a = "go long on log buddy!" > >>> a.lstrip('gonl') > ' long on log buddy!' > >>> > > In both cases, lstrip just removed the first word... I don't see how this > code is broken. It removed all the g,o,n & l's up till it found a character that wasn't in your list - a space. Thats what you told it to do. If you want the space stripped add one to your list... Alan G. From dyoo at hkn.eecs.berkeley.edu Wed Feb 2 09:40:56 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Feb 2 09:41:05 2005 Subject: [Tutor] Better structure? In-Reply-To: <002501c508ce$294e4e10$3b5428cf@JSLAPTOP> Message-ID: <Pine.LNX.4.44.0502020019070.29444-100000@hkn.eecs.berkeley.edu> On Tue, 1 Feb 2005, Jacob S. wrote: > Also why shouldn't string methods include stuff like lstrip which do > precisely what I request? Hi Jacob, I think the confusion here is that, in Python, strings can be considered a concrete single thing, but they can also be considered an ordered collection of characters. And we might not even care about order. As a concrete example, we might write a function that sees if something is a vowel: ### >>> def isvowel(letter): ... return len(letter) == 1 and letter in "aeiou" ... ### Here, we're using a string simply as a collection of characters, but our definition doesn't really depend on the order of the vowels. So some functions will use strings merely because they're good containers of letters. lstrip() (and rstrip()) are designed so that they consider their arguments a collection of characters to strip off, but it doesn't care about the order of the characters. Admittedly, the documentation of lstrip() doesn't really spell this out with perfect clarity: """ lstrip([chars]) Return a copy of the string with leading characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the beginning of the string this method is called on. """ So this can definitely be improved. The documentation of lstrip() should emphasize that 'chars' here is used to define the set of characters that it'll toss out, to keep people aware that it doesn't care about the sequence-y nature of its input string. > Maybe because they don't want to bother putting > > def mylstrip(string,stripstring): > return string[len(stripstring):] The implementation of rstrip() (the cousin of lstrip()) does come in really handy when we're dealing with line terminators, since we can "chomp()" a line by doing: ### def chomp(line): return line.rstrip('\r\n') ### It is debatable what lstrip() and rstrip() should consider as the common case. The library designers decided the behavior they felt would help people the most, but that may not handle all the ways we might like to use it. But, then, that's why we have 'def'. *grin* Best of wishes to you! From alan.gauld at freenet.co.uk Wed Feb 2 09:52:20 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Feb 2 09:51:54 2005 Subject: [Tutor] Better structure? References: <Pine.LNX.4.44.0501311447390.24680-100000@hkn.eecs.berkeley.edu> <41FF6082.70005@tds.net><000001c508cb$5a67e9f0$3b5428cf@JSLAPTOP><42003772.4010808@ccvcorp.com> <002501c508ce$294e4e10$3b5428cf@JSLAPTOP> Message-ID: <016a01c50904$81e75db0$68b78851@xp> Jacob, Writing library code is a difficult and unrewarding task - I've been there so I sympathise, however... > So, how would one go about this in a non broken code way? Don't they have > something like what I'm requesting. Its not broken, its just different to what you want. What you want is much simpler than what lstrip does so you can easily code your requirements. Try writing the code to do what lstrip actually does - its much harder. So the library includes the more difficult function and lets you code the easy ones. > It seems to me that a few things are flawed in the standard distribution. No library is perfect - you should try using C! But the Python library isually has good reasons for its apparent limitations. > Little things like the overlooking of adding a method or function to decimal > for returning an instance with x places right of the decimal. But there is very little need to do that. Usually you only want to do that in presentation - ie printing. Thus the mechanism for doing that is in the string formatting code - where it makes sense. Why would limiting the precision of the internal number representation be something you'd want to do? Very occassionally maybe, but in those cases its easy to fake (and it is a fake because the number is in binary and not true decimal so its always an approximation - in any language!) > quantize, but that's junk and not simple. You mean it does a complex job and not the one youd like it to do? :-) > Also why shouldn't string methods include stuff like > lstrip which do precisely what I request? strings do include lstrip() but as I said they couldn't predict what you thought it shjould do, so they built it to do what they thought would be the most generally useful function. Stripping off a string literal is such a trivial programming task that you can easily write that yourself. You can even subclass string and make it a method if you like. > Maybe because they don't want to bother putting > > def mylstrip(string,stripstring): > return string[len(stripstring):] > > as a method or something? > Messy, just plain messy. Such a method would indeed be plain messy. Do you really want code like this: >>> s = "Here is a longish string" >>> s.mylstrip('foo') >>> print s e is a longish string >>> s.mylstrip('supercalifragilisticexpalidocious') >>> print s >>> I suspect your function should probably be: def mylstrip(str,stripstring): if str.startswith(stripstring) and len(stripstring) < len(str): return str[len(stripstring):] But thats just my guess at what *you* really want... And finally remember that Python is built by volunteers mostly. You should be pleased the *bothered* to write any of it! Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld > > Jacob Schmidt > > > > Jacob S. wrote: > > > >> I don't know who's going crazy here... but I checked that straight from > >> the python 2.4 interpreter... > > > > >>> a = "go on long buddy" > > >>> a.lstrip('gonl') > > ' on long buddy' > > >>> a.lstrip('gonl ') > > 'buddy' > > >>> > > > > Note that in the second case, I've included a space in the lstrip() > > parameter. lstrip() is essentially saying "remove all leading characters > > until you find a character that's not in this sequence" -- > > a space counts as a character. (Took me trying it out before I saw this, > > so don't feel bad. ;) ) > > > > Jeff Shannon > > Technician/Programmer > > Credit International > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > From dyoo at hkn.eecs.berkeley.edu Wed Feb 2 09:59:44 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Feb 2 09:59:50 2005 Subject: [Tutor] Presentation In-Reply-To: <Pine.LNX.4.44.0502011902500.4638-100000@violet.rahul.net> Message-ID: <Pine.LNX.4.44.0502020041470.29444-100000@hkn.eecs.berkeley.edu> > The community is one of the things I particularly like about Python. I > always hated asking a question in the Perl newsgroups; although you > usually got an answer, you were almost certain to be told you're stupid > for not already knowing it. Hi Terry, Just to act as Devil's advocate: the programming language communities are large enough to support subcultures. So the experiences you have had in the seedy corners of comp.lang.perl are probably not representative of the Perl community as a whole. Some newsgroups are notoriously noisy, and even comp.lang.python can get a little hairy at times. The mailing list communities tend to be a bit more civilized because they have a strong topical focus. For people who do want to learn Perl, the web site: http://learn.perl.org/ and Casey West's 'beginners' Perl mailing list: http://www.nntp.perl.org/group/perl.beginners/ appear to be excellent resources. So the Perl community there is also doing what they can to help folks learn Perl. We, as Python programmers, should do one step better: we should help folks learn programming as well as Python. *grin* Best of wishes to you! From alan.gauld at freenet.co.uk Wed Feb 2 10:07:32 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Feb 2 10:07:36 2005 Subject: [Tutor] Re: how to separate hexadecimal References: <2cad209005020123107fb43105@mail.gmail.com> <ctq1um$gp7$1@sea.gmane.org> Message-ID: <018101c50906$a14d5220$68b78851@xp> > >>> hexa = '0x87BE' > >>> upper = int(hexa[2:4], 16) > >>> lower = int(hexa[4:6], 16) FWIW : You don't need to strip the '0x' from the front, int() is smart enough to do that automatically for base 16 conversions... Alan G. From cyresse at gmail.com Wed Feb 2 10:12:07 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed Feb 2 10:12:11 2005 Subject: [Tutor] Presentation In-Reply-To: <Pine.LNX.4.44.0502020041470.29444-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0502011902500.4638-100000@violet.rahul.net> <Pine.LNX.4.44.0502020041470.29444-100000@hkn.eecs.berkeley.edu> Message-ID: <f2ff2d0502020112118554dc@mail.gmail.com> Hi Danny, I think that learning Python naturally leads to learning programming. It's like learning to fly, you learn to fly in a Cessna or Piper Cherokee. Simple, elegant, easy to operate. You can then focus on the art of flying, not on how exactly you lower the flaps. Then, once you're good at flying, you move to the Pitt's Special. (Actually could you imagine a plane built by Perl enthusiasts... How do I lower the flaps? Well, you can push this button, or pull that lever, or lean to the right, or you could install this cool module that lowers them when you wink your left eye twice in 5 seconds. Remember, there's more than one way to do it!) Regards, Liam Clarke On Wed, 2 Feb 2005 00:59:44 -0800 (PST), Danny Yoo <dyoo@hkn.eecs.berkeley.edu> wrote: > > > > The community is one of the things I particularly like about Python. I > > always hated asking a question in the Perl newsgroups; although you > > usually got an answer, you were almost certain to be told you're stupid > > for not already knowing it. > > Hi Terry, > > Just to act as Devil's advocate: the programming language communities are > large enough to support subcultures. So the experiences you have had in > the seedy corners of comp.lang.perl are probably not representative of the > Perl community as a whole. > > Some newsgroups are notoriously noisy, and even comp.lang.python can get a > little hairy at times. The mailing list communities tend to be a bit more > civilized because they have a strong topical focus. > > For people who do want to learn Perl, the web site: > > http://learn.perl.org/ > > and Casey West's 'beginners' Perl mailing list: > > http://www.nntp.perl.org/group/perl.beginners/ > > appear to be excellent resources. So the Perl community there is also > doing what they can to help folks learn Perl. > > We, as Python programmers, should do one step better: we should help folks > learn programming as well as Python. *grin* > > Best of wishes to you! > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cyresse at gmail.com Wed Feb 2 10:58:47 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed Feb 2 10:58:51 2005 Subject: [Tutor] Better structure? In-Reply-To: <016a01c50904$81e75db0$68b78851@xp> References: <Pine.LNX.4.44.0501311447390.24680-100000@hkn.eecs.berkeley.edu> <41FF6082.70005@tds.net> <000001c508cb$5a67e9f0$3b5428cf@JSLAPTOP> <42003772.4010808@ccvcorp.com> <002501c508ce$294e4e10$3b5428cf@JSLAPTOP> <016a01c50904$81e75db0$68b78851@xp> Message-ID: <f2ff2d05020201584192a2e@mail.gmail.com> Hello all, > > So, how would one go about this in a non broken code way? Don't they > have > > something like what I'm requesting. If not,it's a challenge you can implement yourself! Ever use QBasic? Had a command - a$ = inkey$(1) Which would return a key press as a$. Very handy for 'press any key. It's next to the space bar. Honest' dialogues. Anyway, I come to Python, I want inkey$ damnit! So, I examine, and build it - import msvcrt def inkey(): print "Press any key. It's next to the space bar. Honest." while not msvcrt.kbhit(): pass return Save it, and et voila. Anytime I want my inkey, I import a file called pause, and call pause.inkey(). Now, how many other peoples would need that? I use string.lstrip() in the same way you do - to strip prefixes. What Kent has mentioned is a caveat on using it, that's all. > > And finally remember that Python is built by volunteers mostly. > You should be pleased the *bothered* to write any of it! > Exactly. You shouldn't complain that something free doesn't have the precise features you require. If you installed Linux and you can't play your DirectX capable games, should Linux support DirectX just for you, or should you install Windows? Don't mean to sound too censorious, but the Python library is fantastic, and it's free. It's got some twists, but it's mostly documented and usually works. Not bad for $0.00 eh? Regards, Liam Clarke On Wed, 2 Feb 2005 08:52:20 -0000, Alan Gauld <alan.gauld@freenet.co.uk> wrote: > Jacob, > > Writing library code is a difficult and unrewarding task > - I've been there so I sympathise, however... > > > So, how would one go about this in a non broken code way? Don't they > have > > something like what I'm requesting. > > Its not broken, its just different to what you want. > What you want is much simpler than what lstrip does > so you can easily code your requirements. > Try writing the code to do what lstrip actually does > - its much harder. So the library includes the more > difficult function and lets you code the easy ones. > > > It seems to me that a few things are flawed in the standard > distribution. > > No library is perfect - you should try using C! > > But the Python library isually has good reasons for its > apparent limitations. > > > Little things like the overlooking of adding a method or function to > decimal > > for returning an instance with x places right of the decimal. > > But there is very little need to do that. Usually you only want > to do that in presentation - ie printing. Thus the mechanism > for doing that is in the string formatting code - where it > makes sense. Why would limiting the precision of the internal > number representation be something you'd want to do? Very > occassionally maybe, but in those cases its easy to fake > (and it is a fake because the number is in binary and not > true decimal so its always an approximation - in any language!) > > > quantize, but that's junk and not simple. > > You mean it does a complex job and not the one youd like it to do? :-) > > > Also why shouldn't string methods include stuff like > > lstrip which do precisely what I request? > > strings do include lstrip() but as I said they couldn't predict > what you thought it shjould do, so they built it to do what > they thought would be the most generally useful function. > Stripping off a string literal is such a trivial programming > task that you can easily write that yourself. You can even > subclass string and make it a method if you like. > > > Maybe because they don't want to bother putting > > > > def mylstrip(string,stripstring): > > return string[len(stripstring):] > > > > as a method or something? > > Messy, just plain messy. > > Such a method would indeed be plain messy. > Do you really want code like this: > > >>> s = "Here is a longish string" > >>> s.mylstrip('foo') > >>> print s > e is a longish string > >>> s.mylstrip('supercalifragilisticexpalidocious') > >>> print s > > >>> > > I suspect your function should probably be: > > def mylstrip(str,stripstring): > if str.startswith(stripstring) and > len(stripstring) < len(str): > return str[len(stripstring):] > > But thats just my guess at what *you* really want... > > And finally remember that Python is built by volunteers mostly. > You should be pleased the *bothered* to write any of it! > > Alan G > Author of the Learn to Program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > > > > > Jacob Schmidt > > > > > > > Jacob S. wrote: > > > > > >> I don't know who's going crazy here... but I checked that > straight from > > >> the python 2.4 interpreter... > > > > > > >>> a = "go on long buddy" > > > >>> a.lstrip('gonl') > > > ' on long buddy' > > > >>> a.lstrip('gonl ') > > > 'buddy' > > > >>> > > > > > > Note that in the second case, I've included a space in the > lstrip() > > > parameter. lstrip() is essentially saying "remove all leading > characters > > > until you find a character that's not in this sequence" -- > > > a space counts as a character. (Took me trying it out before I > saw this, > > > so don't feel bad. ;) ) > > > > > > Jeff Shannon > > > Technician/Programmer > > > Credit International > > > > > > > > > _______________________________________________ > > > Tutor maillist - Tutor@python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From ewald.ertl at hartter.com Wed Feb 2 11:19:45 2005 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Wed Feb 2 11:19:51 2005 Subject: [Tutor] how to separate hexadecimal In-Reply-To: <2cad209005020123107fb43105@mail.gmail.com> References: <2cad209005020123107fb43105@mail.gmail.com> Message-ID: <20050202111945.000025cf@sunray2.hartter.com> Hi! Using binary operations: >>> a='0x87BE' >>> str(hex(int(a,16) & 0xFF)) '0xbe' >>> str(hex((int(a,16) & 0xFF00) / 0xFF)) '0x87' >>> HTH Ewald on Wed, 2 Feb 2005 15:10:36 +0800 jrlen balane <nbbalane@gmail.com> wrote : --------------------------------------------------------------------------------------------- jrlen balane > i have a 4 digit hex number (2 bytes) and i want to separate it into 2 jrlen balane > digit hex (1 byte each) meaning i want to get the upper byte and the jrlen balane > lower byte since i am going to add this two. jrlen balane > how am i going to do this? jrlen balane > should i treat it just like a normal string? jrlen balane > please help, thanks. jrlen balane > jrlen balane > ex. hexa = '0x87BE" # what i want to do is: jrlen balane > a = 0x87, b = 0xBE # so that i could do this: jrlen balane > c = a + b #which should be equal to 0x145 jrlen balane > _______________________________________________ jrlen balane > Tutor maillist - Tutor@python.org jrlen balane > http://mail.python.org/mailman/listinfo/tutor jrlen balane > ------------------- end ---------------------- From kent37 at tds.net Wed Feb 2 12:05:39 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Feb 2 12:05:43 2005 Subject: [Tutor] How to sum rows and columns of a matrix? In-Reply-To: <f2ff2d050131103945e2d83a@mail.gmail.com> References: <41FE7477.4020403@aon.at> <f2ff2d050131103945e2d83a@mail.gmail.com> Message-ID: <4200B403.4020606@tds.net> Liam Clarke wrote: > There's a specific package for arrays > > http://www.stsci.edu/resources/software_hardware/numarray > > that implements array mathematics. I use it for pixel map manipulation > in pygame, so it's relatively fast. Here is one way to do what you want using numarray: >>> import numarray Create a 4x4 array: >>> m=numarray.array(range(16),shape=(4,4)) >>> m array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) Row access: >>> m[1] array([4, 5, 6, 7]) Column access: >>> m[:,1] array([ 1, 5, 9, 13]) Sum all the rows: >>> [sum(m[i]) for i in range(4)] [6, 22, 38, 54] Sum all the columns: >>> [sum(m[:,i]) for i in range(4)] [24, 28, 32, 36] Kent > > > On Mon, 31 Jan 2005 19:09:59 +0100, Gregor Lingl <glingl@aon.at> wrote: > >>Hi all of you, >> >>I'm representing a 4x4 matrix as a 16-element list, e.g. >> >>m=range(16) >> >>first 4 elements first row, second four elements second row etc. >>I want to sum rows and columns like >> >>i-th row: >> >>sum(m[4*i:4*i+4]) >> >>and ith column: >> >>sum(m[i::4]) >> >>This seems to be slow because of the formation of the slices. >>I wonder if there is a way using generators or generator-expressions >>(which I didn't study yet) to compute these sums without copying >>parts of the matrix to a new list. (I'd guess that there should exist >>some canonical generator for sequences, which produces their elements >>..., maybe also for slices ?) >> >>All comments, hints, solutions are welcome. >> >>Regards, >>Gregor >> >>-- >>Gregor Lingl >>Reisnerstrasse 3/19 >>A-1030 Wien >> >>Telefon: +43 1 713 33 98 >>Mobil: +43 664 140 35 27 >> >>Autor von "Python f?r Kids" >>Website: python4kids.net >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> > > > From maxnoel_fr at yahoo.fr Wed Feb 2 12:31:09 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Wed Feb 2 12:31:14 2005 Subject: [Tutor] how to separate hexadecimal In-Reply-To: <20050202111945.000025cf@sunray2.hartter.com> References: <2cad209005020123107fb43105@mail.gmail.com> <20050202111945.000025cf@sunray2.hartter.com> Message-ID: <2a4c96c64aaa6372bae40254aa02805a@yahoo.fr> On Feb 2, 2005, at 10:19, Ewald Ertl wrote: > Hi! > > Using binary operations: > >>>> a='0x87BE' >>>> str(hex(int(a,16) & 0xFF)) > '0xbe' >>>> str(hex((int(a,16) & 0xFF00) / 0xFF)) > '0x87' >>>> > > HTH Ewald Actually, the int conversions aren't even necessary. >>> hex(0x87BE & 0xFF) '0xbe' >>> hex((0x87BE & 0xFF00) / 0xFF) '0x87' -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From kent37 at tds.net Wed Feb 2 13:54:53 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Feb 2 13:54:57 2005 Subject: [Tutor] How to sum rows and columns of a matrix? In-Reply-To: <4200B403.4020606@tds.net> References: <41FE7477.4020403@aon.at> <f2ff2d050131103945e2d83a@mail.gmail.com> <4200B403.4020606@tds.net> Message-ID: <4200CD9D.5010000@tds.net> Kent Johnson wrote: > Liam Clarke wrote: > >> There's a specific package for arrays >> http://www.stsci.edu/resources/software_hardware/numarray >> >> that implements array mathematics. I use it for pixel map manipulation >> in pygame, so it's relatively fast. > > > Here is one way to do what you want using numarray: Here is another way, probably more idiomatic and faster. (I'm just doodling with numarray so there may still be a better way to do this...) >>> import numarray >>> m=numarray.array(range(16),shape=(4,4)) >>> numarray.add.reduce(m) array([24, 28, 32, 36]) >>> numarray.add.reduce(m, axis=1) array([ 6, 22, 38, 54]) Kent > > >>> import numarray > > Create a 4x4 array: > >>> m=numarray.array(range(16),shape=(4,4)) > >>> m > array([[ 0, 1, 2, 3], > [ 4, 5, 6, 7], > [ 8, 9, 10, 11], > [12, 13, 14, 15]]) > > Row access: > >>> m[1] > array([4, 5, 6, 7]) > > Column access: > >>> m[:,1] > array([ 1, 5, 9, 13]) > > Sum all the rows: > >>> [sum(m[i]) for i in range(4)] > [6, 22, 38, 54] > > Sum all the columns: > >>> [sum(m[:,i]) for i in range(4)] > [24, 28, 32, 36] > > Kent > >> >> >> On Mon, 31 Jan 2005 19:09:59 +0100, Gregor Lingl <glingl@aon.at> wrote: >> >>> Hi all of you, >>> >>> I'm representing a 4x4 matrix as a 16-element list, e.g. >>> >>> m=range(16) >>> >>> first 4 elements first row, second four elements second row etc. >>> I want to sum rows and columns like >>> >>> i-th row: >>> >>> sum(m[4*i:4*i+4]) >>> >>> and ith column: >>> >>> sum(m[i::4]) >>> >>> This seems to be slow because of the formation of the slices. >>> I wonder if there is a way using generators or generator-expressions >>> (which I didn't study yet) to compute these sums without copying >>> parts of the matrix to a new list. (I'd guess that there should exist >>> some canonical generator for sequences, which produces their elements >>> ..., maybe also for slices ?) >>> >>> All comments, hints, solutions are welcome. >>> >>> Regards, >>> Gregor >>> >>> -- >>> Gregor Lingl >>> Reisnerstrasse 3/19 >>> A-1030 Wien >>> >>> Telefon: +43 1 713 33 98 >>> Mobil: +43 664 140 35 27 >>> >>> Autor von "Python f?r Kids" >>> Website: python4kids.net >>> _______________________________________________ >>> Tutor maillist - Tutor@python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >> >> >> > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From pierre.barbier at cirad.fr Wed Feb 2 14:09:04 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Wed Feb 2 14:06:57 2005 Subject: [Tutor] How to sum rows and columns of a matrix? In-Reply-To: <4200CD9D.5010000@tds.net> References: <41FE7477.4020403@aon.at> <f2ff2d050131103945e2d83a@mail.gmail.com> <4200B403.4020606@tds.net> <4200CD9D.5010000@tds.net> Message-ID: <4200D0F0.4010703@cirad.fr> Even better : >>> import numarray >>> m = numarray.arange(16,shape=(4,4)) >>> numarray.sum(m) array([24, 28, 32, 36]) >>> numarray.sum(axis=1) array([ 6, 22, 38, 54]) Pierre Kent Johnson a ?crit : > Kent Johnson wrote: > >> Liam Clarke wrote: >> >>> There's a specific package for arrays >>> http://www.stsci.edu/resources/software_hardware/numarray >>> >>> that implements array mathematics. I use it for pixel map manipulation >>> in pygame, so it's relatively fast. >> >> >> >> Here is one way to do what you want using numarray: > > > Here is another way, probably more idiomatic and faster. (I'm just > doodling with numarray so there may still be a better way to do this...) > > >>> import numarray > >>> m=numarray.array(range(16),shape=(4,4)) > > >>> numarray.add.reduce(m) > array([24, 28, 32, 36]) > > >>> numarray.add.reduce(m, axis=1) > array([ 6, 22, 38, 54]) > > Kent > >> -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 From klappnase at freenet.de Wed Feb 2 16:40:52 2005 From: klappnase at freenet.de (Michael Lange) Date: Wed Feb 2 16:38:33 2005 Subject: [Tutor] Tkinter questions In-Reply-To: <c225925305020109087a9d7b6e@mail.gmail.com> References: <c225925305020109087a9d7b6e@mail.gmail.com> Message-ID: <20050202164052.086a4441.klappnase@freenet.de> On Tue, 1 Feb 2005 19:08:41 +0200 Mark Kels <mark.kels@gmail.com> wrote: Hi Mark, > Hello, > I got some Tkinter questions that I need the answer for to complete a > little project of mine: > 1. How can I make the program to open in a X*Y sized window ? from Tkinter import * root = Tk() root.geometry('600x400+0+0') This makes a window of 600x400 pixels placed in the upper left corner of the screen (+0+0 is the x- and y- offset; both of the window size and the offset may be omitted, so you can use '600x400' or '+0+0' as arguments for geometry() as well). > 2. How can I open another window from the first one (without closing it) ? Use instances of Toplevel() to create new windows as children of the root (Tk()) window. > 3. How can I add a file browser for my app (like the one you get when > you press "Save as..." in windows apps) ? import tkFileDialog filename = tkFileDialog.asksaveasfilename() if filename: # save the file...; if the user presses the 'Cancel' button, filename should be set to an empty string. > 4. How do I configure the font size on the Text widget (its realy > huge, and I would like to change it to somthing like 12). text = Text(parent, font=('helvetica', '-12', 'normal'))# "negative" size -> pixel size or: text.configure(font=('helvetica', '12', 'normal'))# "positive" size -> point size You can use any 3-tuple of the form (family, size, weight) as font descriptor; if the requested font is not found, the widget should fall back to some (probably ugly) default; tk guarantees that at least 'times', 'helvetica' and 'courier' font families are available, the availability of other fonts depends on your system. I hope this helps Michael From stygian at tesco.net Wed Feb 2 22:44:24 2005 From: stygian at tesco.net (Glen) Date: Wed Feb 2 22:44:06 2005 Subject: [Tutor] Python 2.4 with Mandrake 10.0 query Message-ID: <1107380664.2964.0.camel@localhost> My setup is Mandrake 10.0 which came with python 2.3 and a standard Python 2.4 build/install. I always start Idle from an icon on my taskbar, when I click the icon, Idle starts after a second but a small rotating timer appears over the taskbar for 30 seconds and then disappears. If I close Idle immediatly, the timer still remains for the 30 seconds. Idle/Python has always seemed to run perfectly so I have ignored the timer until I recently thought to run Idle from a console. Idle/Python still works great but this output appears in the console... [glen@localhost glen]$ idle set([34, 36, 38, 39]) Failed to load extension 'CodeContext' Traceback (most recent call last): File "/usr/local/lib/python2.4/idlelib/EditorWindow.py", line 737, in load_standard_extensions self.load_extension(name) File "/usr/local/lib/python2.4/idlelib/EditorWindow.py", line 747, in load_extension mod = __import__(name, globals(), locals(), []) File "/usr/local/lib/python2.4/idlelib/CodeContext.py", line 15, in ? from sets import Set ImportError: cannot import name Set [glen@localhost glen]$ I have only just discovered the set command in python, and it seems a bit of a coincedence that some of the console output lines... set([34, 36, 38, 39]) from sets import Set ImportError: cannot import name Set ...appear connected to code I was playing with a few days ago. I have looked at CodeContext.py, and line 15 is 'from sets import Set' which Python 2.4 doesn't like, as set is already built in. I have rebuilt/installed Python 2.4, but it made no difference. Can anyone give me a clue as to what may be going on? Glen From dyoo at hkn.eecs.berkeley.edu Wed Feb 2 23:02:55 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Feb 2 23:03:01 2005 Subject: [Tutor] Python 2.4 with Mandrake 10.0 query In-Reply-To: <1107380664.2964.0.camel@localhost> Message-ID: <Pine.LNX.4.44.0502021357390.12128-100000@hkn.eecs.berkeley.edu> On Wed, 2 Feb 2005, Glen wrote: > [glen@localhost glen]$ idle > set([34, 36, 38, 39]) > Failed to load extension 'CodeContext' > Traceback (most recent call last): > File "/usr/local/lib/python2.4/idlelib/EditorWindow.py", line 737, in > load_standard_extensions > self.load_extension(name) > File "/usr/local/lib/python2.4/idlelib/EditorWindow.py", line 747, in > load_extension > mod = __import__(name, globals(), locals(), []) > File "/usr/local/lib/python2.4/idlelib/CodeContext.py", line 15, in ? > from sets import Set > ImportError: cannot import name Set Hi Glen, Ah! Check to see if there's a "sets.py" program somewhere in your current working directory. It's very likely that Python is picking that up, instead of the 'sets' standard library module. This is one thing that does bite people every so often, because it's all too easy to accidently write a program uses the same name as a standard library module. I wrote a small module a while back as a proposed solution to the issue: http://hkn.eecs.berkeley.edu/~dyoo/python/__std__/ but I don't think it's really being used. Best of wishes to you! From kent37 at tds.net Wed Feb 2 23:07:22 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Feb 2 23:07:27 2005 Subject: [Tutor] Better structure? In-Reply-To: <000301c507a3$f3828c90$7d5428cf@JSLAPTOP> References: <000301c507a3$f3828c90$7d5428cf@JSLAPTOP> Message-ID: <42014F1A.2010005@tds.net> I would at least introduce some functions. For example each case of your command handling loop could be broken out into a separate function. If there is a lot of shared state between the functions then make them all class methods and put the shared state in the class. Maybe all the drawing commands should be in a class with xaxis, yaxis, radiusaxis, radiusaxis2 at least as member fields. Kent Jacob S. wrote: > I think this thing is screaming for better structure, but previous > attempts at using oop for it have failed. > I think Derintegral is okay, I'm focusing on FunctionGrapher5.py--but > you can comment on both. > (To Johan Nilsson: I haven't had time to implement Simpson's rule > instead of Reimann's sum yet... but I have gotten it to work faster > anyway.) > I will probably expand the code yet... Add extra things like find area > between curve and x axis in interval [a,b]... > Any suggestions are greatly appreciated. If you want the code to work on > your machine, you'll need to have my Derintegral.py sys.path, obviously. > > #### Start of FunctionGrapher5.py ################### > from __future__ import division > from visual import * > import Derintegral > import os, random > from math import * > ja = 0 > > scenexdefault = 375 > > def start(): > for objects in scene.objects: > objects.visible = 0 > scene.title = "Function Grapher by Jacob, Inc." > scene.x = scenexdefault > scene.visible=1 > scene.exit=0 > scene.userspin = 0 > scene.range=(10,10,1) > scene.background=(1,1,1) > global xaxis > global yaxis > xaxis = curve(pos=[(100,0,0),(-100,0,0)],color=color.black) > yaxis = curve(pos=[(0,100,0),(0,-100,0)],color=color.black) > global radiusaxis > global radiusaxis2 > radiusaxis = curve(pos=[(-100,-100),(100,100)],color=color.black) > radiusaxis2 = curve(pos=[(-100,100),(100,-100)],color=color.black) > radiusaxis.visible = 0 > radiusaxis2.visible = 0 > > start() > d = 1 > print """\ > List of Commands: > clear > quit > remove lines > return lines > gotl # (Graph One Tangent Line) w/optional x coordinate > gatl # (Graph All Tangent Lines) w/optional step > gonl # (Graph One Normal Line) w/optional x coordinate > ganl # (Graph All Normal Lines) w/optional step > > Function Syntax: > [y,x,or r] = function [range] ["s" followed by float for step] > Brackets mean that it's not required. > So, in effect, you don't have to type a function > """ > > def graphit(type,f,range2,step): > li = curve(color=color.blue) > if type in ['y','x']: > x = -15 > radiusaxis.visible = 0 > radiusaxis2.visible = 0 > while -15 <= x <= 15: > if eval(range2): > try: > a = f(x) > if -15 <= a <= 15: > if type == 'y': > li.append(pos=(x,a,0)) > elif type == 'x': > li.append(pos=(a,x,0)) > else: > li = curve(color=color.blue) > except: > pass > else: > li = curve(color=color.blue) > x = x+step > elif type == 'r': > exec "def m(t): return f(t)*cos(t)" > exec "def n(t): return f(t)*sin(t)" > t = 0 > while 0 <= t <= 10*pi: > if eval(range2): > try: > li.append(pos=(m(t),n(t),0)) > except: > li = curve(color=color.blue) > t = t+step > > > print 'Please type in functions in below. ' > while 1: > lists=[] > y = raw_input(">") > if y == 'clear': > scene.visible=0 > start() > print "-"*36 > continue > elif y == 'quit': > scene.visible = 0 > del scene > break > elif y == 'remove lines': > a = [radiusaxis,radiusaxis2,xaxis,yaxis] > for x in a: > x.visible = 0 > d = 0 > continue > elif y == 'return lines': > a = [radiusaxis,radiusaxis2,xaxis,yaxis] > for x in a: > x.visible = 1 > d = 1 > continue > elif y.startswith('gatl'): > try: > step2 = float(y.lstrip("gatl ")) > except: > step2 = 0.5 > x = -20 > while -20 <=x<= 20: > try: > der = Derintegral.diffatpt(f,x) > if abs(der)<=25: > if type == 'y': > > curve(pos=[(-15,eval("der*(-15-x)+f(x)")),(15,eval("der*(15-x)+f(x)"))],color=color.red) > > else: > > curve(pos=[(eval("der*(-15-x)+f(x)"),-15),(eval("der*(15-x)+f(x)"),15)],color=color.red) > > except: > pass > x = x + step2 > continue > elif y.startswith('ganl'): > try: > step2 = float(y.lstrip("ganl ")) > except: > step2 = 0.5 > x = -20 > while -20 <=x<= 20: > try: > der = Derintegral.diffatpt(f,x) > if abs(der)<=25: > if type == 'y': > > curve(pos=[(-15,eval("(-1/der)*(-15-x)+f(x)")),(15,eval("(-1/der)*(15-x)+f(x)"))],color > = color.red) > else: > > curve(pos=[(eval("(-1/der)*(-15-x)+f(x)"),-15),(eval("(-1/der)*(15-x)+f(x)"),15)],color > = color.red) > except: > pass > x = x + step2 > continue > elif y.startswith('gotl'): > try: > x = float(y.lstrip('gotl ')) > except: > x = float(raw_input('What x coordinate do you want the > tangent line at? ')) > der = Derintegral.diffatpt(f,x) > try: > if abs(der)<= 25: > if type == 'y': > > curve(pos=[(-15,eval("der*(-15-x)+f(x)")),(15,eval("der*(15-x)+f(x)"))],color=color.red) > > else: > > curve(pos=[(eval("der*(-15-x)+f(x)"),-15),(eval("der*(15-x)+f(x)"),15)],color=color.red) > > except: > pass > continue > elif y.startswith('gonl'): > try: > x = float(y.lstrip('gonl ')) > except: > x = float(raw_input('What x coordinate do you want the > tangent line at? ')) > der = Derintegral.diffatpt(f,x) > try: > if abs(der)<= 25: > if type == 'y': > > curve(pos=[(-15,eval("(-1/der)*(-15-x)+f(x)")),(15,eval("(-1/der)*(15-x)+f(x)"))],color=color.red) > > else: > > curve(pos=[(eval("(-1/der)*(-15-x)+f(x)"),-15),(eval("(-1/der)*(15-x)+f(x)"),15)],color=color.red) > > except: > pass > continue > elif y.startswith('getpt'): > y = y.lstrip("getpt ") > if y: > m = float(eval(y)) > else: > m = float(eval(raw_input("f(?) "))) > try: > print f(m) > except ValueError: > print "Math Domain Error" > continue > elif y == 'regraph': > graphit(type,f,range2,step) > continue > if y.count(" = ") == 1: > y = y.split(" = ") > type = y[0].lower() > y = y[1] > y = y.replace("y","x") > if type == 'r': > defaultrange = '0<=t<=5*pi' > y = y.replace('x','t') > if d == 1: > radiusaxis.visible = 1 > radiusaxis2.visible = 1 > else: > defaultrange = '-15<=x<=15' > else: > type = 'y' > defaultrange = '-15<=x<=15' > y = y.split(" ",1) > tempfunct = y.pop(0) > if y: > y = y[0] > if y.count('st'): > if y.startswith('st'): > y = y.lstrip('st') > step = float(y) > else: > y = y.split(" ") > step = float(y.pop().lstrip('st')) > y = " ".join(y) > range2 = defaultrange > else: > range2 = y > step = 0.005 > else: > range2 = defaultrange > step = 0.005 > y = tempfunct > range2 = range2.replace('and','or') > range2 = range2.replace(',','<=x<=') > try: > exec "def f(x): return %s" % y > except: > continue > graphit(type,f,range2,step) > ###### End of FunctionGrapher5.py ########### > > #### Start of Derintegral.py ########## > from __future__ import division > import psyco > psyco.full() > from math import * > > > def diffatpt(funct,pt): > """Return the derivative of a function at a specific point. """ > sminc = 1e-10 > x = pt+sminc > y2 = funct(x) > x2 = x > x = pt-sminc > y1 = funct(x) > x1 = x > slope = (y2-y1)/(x2-x1) > return slope > > def defintegral(fofx,x,max1): > total = 0 > step = 1e-5 > exec "def f(x): return %s" % fofx > while x <= max1: > try: > total = total+f(x) > except: > pass > x = x+step > return abs(total*step) > ######End of Derintegral.py ########## > > > Like I said, any comments appreciated. > Jacob Schmidt > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From cyresse at gmail.com Thu Feb 3 00:18:00 2005 From: cyresse at gmail.com (Liam Clarke) Date: Thu Feb 3 00:18:42 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: <f2ff2d0502021518547f14c0@mail.gmail.com> Hi, Had the *ahem* joy of learning Perl last night. Egad. Wrote the script in Python to get it right, and then 'translated' it to Perl. Does the style of coding Python engenders suit the Perl environment in anyone's experienc? AFAI can see there is no real 'style' to Perl, apart from white noise of non alphanumeric characters. Just wondering if I should bite the bullet and code from scratch in Perl, or if my Python - Perl is Ok. Two codes are here - Python http://www.rafb.net/paste/results/BVaym940.html Perl http://www.rafb.net/paste/results/LromA876.html [OT begins] By the way, I'm only learning Perl because I need to script some routine HTML maintenance, and I can't be bothered applying to head office IT for an install of Python, as the justification involved is ludicrous, especially considering that my role as defined does not include scripting. First impressions of Perl - 1) I'll use Perl for the regex stuff from now on, Perl is obviously built for this. 2 ) There's More Than One Way To Do It makes debugging hard - i.e. close INFILE; & close (INFILE); are both valid. I like one syntax, cos it's easier to remember. 3) Some stuff is counter-intuitive - $lenOfModList = @moddirList is the Perl equivalent of lenofModList = len(moddirList) @someArray = (@someArray, $newValue) is the same as someArray.append(newValue) I couldn't figure this one out until I read that Perl automatically flattens lists. Also, why doesn't if ( not $d eq "a" && not $d eq "c") evaluate to true for $d = "b" when if (not $d eq "a") evals to true and if ($d ne "a" && $d ne "c") evals true also? What's with that? 4) WHAT IS WITH THE STUPID SYMBOLS EVERYWHERE LARRY??!! I'm not referring to the $ & @, I can see how they could be useful, although with a list - @dude = (1, 2, 3), to obtain the 2nd value I would expect $d = @dude[1], not $d = $dude[1], that's counterintuitive also. Oh, no, what I'm referring to is stuff like @_, and @!, and @indexFile = <INFILE> to read a whole file, and this - I hate Perl for this - open OUTFILE, ">c:/python23/j/index.htm" What's the difference between open OUTFILE, "c:/python23/j/index.htm" and open OUTFILE, ">c:/python23/j/index.htm" ? The first will open index.htm with the handle OUTFILE, to read... The second will open index.htm with the handle OUTFILE to write!. Of course, the documentation I had didn't mention that. It just said to open it and use print FILEHANDLE $value; to write. Oh no, I had to find a CGI Perl tutorial, which mentioned using &lst; to open and &gst; to write (or something), which I guessed as lesser/greater than. Why is the read/write modifier part of the filename??? Why is it a > ? In my opinion, there's only one place a > sign should be, in an inequality test. So, Perl in my opinion - great for regexes obviously based around *nix conventions. Big hodge-podge, oozing with inconsistency. I'd hate to work collaboratively on a Perl project. Two steps up from Brainf**k in parts. Obviously in need of a benevolent dictator a la Guido. But then, I've been spoilt by clean, smooth (usually) Python. Lovely, usually consistent Python. Aah, Pythonnnn.... *dreamy look* [end OT rant] -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From johnp at milwaukielumber.com Thu Feb 3 00:24:32 2005 From: johnp at milwaukielumber.com (John Purser) Date: Thu Feb 3 00:24:38 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <f2ff2d0502021518547f14c0@mail.gmail.com> Message-ID: <200502022324.j12NOWjV027813@mail.morseintranet.com> Glad someone else thinks so. I tried getting into Perl. The rational made perfect sense and I had picked up several languages by then. Tried. Hated it. Bounced off it. It's like reading alphabet soup. IMHO they took what was wrong with Shell scripting, AWK, Sed and a few other languages and rolled them into one. That's when I came across Python. Never looked back. John Purser -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of Liam Clarke Sent: Wednesday, February 02, 2005 15:18 To: Tutor Tutor Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Hi, Had the *ahem* joy of learning Perl last night. Egad. Wrote the script in Python to get it right, and then 'translated' it to Perl. Does the style of coding Python engenders suit the Perl environment in anyone's experienc? AFAI can see there is no real 'style' to Perl, apart from white noise of non alphanumeric characters. Just wondering if I should bite the bullet and code from scratch in Perl, or if my Python - Perl is Ok. Two codes are here - Python http://www.rafb.net/paste/results/BVaym940.html Perl http://www.rafb.net/paste/results/LromA876.html [OT begins] By the way, I'm only learning Perl because I need to script some routine HTML maintenance, and I can't be bothered applying to head office IT for an install of Python, as the justification involved is ludicrous, especially considering that my role as defined does not include scripting. First impressions of Perl - 1) I'll use Perl for the regex stuff from now on, Perl is obviously built for this. 2 ) There's More Than One Way To Do It makes debugging hard - i.e. close INFILE; & close (INFILE); are both valid. I like one syntax, cos it's easier to remember. 3) Some stuff is counter-intuitive - $lenOfModList = @moddirList is the Perl equivalent of lenofModList = len(moddirList) @someArray = (@someArray, $newValue) is the same as someArray.append(newValue) I couldn't figure this one out until I read that Perl automatically flattens lists. Also, why doesn't if ( not $d eq "a" && not $d eq "c") evaluate to true for $d = "b" when if (not $d eq "a") evals to true and if ($d ne "a" && $d ne "c") evals true also? What's with that? 4) WHAT IS WITH THE STUPID SYMBOLS EVERYWHERE LARRY??!! I'm not referring to the $ & @, I can see how they could be useful, although with a list - @dude = (1, 2, 3), to obtain the 2nd value I would expect $d = @dude[1], not $d = $dude[1], that's counterintuitive also. Oh, no, what I'm referring to is stuff like @_, and @!, and @indexFile = <INFILE> to read a whole file, and this - I hate Perl for this - open OUTFILE, ">c:/python23/j/index.htm" What's the difference between open OUTFILE, "c:/python23/j/index.htm" and open OUTFILE, ">c:/python23/j/index.htm" ? The first will open index.htm with the handle OUTFILE, to read... The second will open index.htm with the handle OUTFILE to write!. Of course, the documentation I had didn't mention that. It just said to open it and use print FILEHANDLE $value; to write. Oh no, I had to find a CGI Perl tutorial, which mentioned using &lst; to open and &gst; to write (or something), which I guessed as lesser/greater than. Why is the read/write modifier part of the filename??? Why is it a > ? In my opinion, there's only one place a > sign should be, in an inequality test. So, Perl in my opinion - great for regexes obviously based around *nix conventions. Big hodge-podge, oozing with inconsistency. I'd hate to work collaboratively on a Perl project. Two steps up from Brainf**k in parts. Obviously in need of a benevolent dictator a la Guido. But then, I've been spoilt by clean, smooth (usually) Python. Lovely, usually consistent Python. Aah, Pythonnnn.... *dreamy look* [end OT rant] -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From carroll at tjc.com Thu Feb 3 00:25:10 2005 From: carroll at tjc.com (Terry Carroll) Date: Thu Feb 3 00:25:18 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <f2ff2d0502021518547f14c0@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0502021524350.15232-100000@violet.rahul.net> I got nothing on your Perl rant, but in response to the subject line... http://www.snopes.com/legal/arizona.htm From maxnoel_fr at yahoo.fr Thu Feb 3 00:33:44 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu Feb 3 00:33:48 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <f2ff2d0502021518547f14c0@mail.gmail.com> References: <f2ff2d0502021518547f14c0@mail.gmail.com> Message-ID: <86626245450c1bfcf3190400baffe178@yahoo.fr> On Feb 2, 2005, at 23:18, Liam Clarke wrote: > 1) I'll use Perl for the regex stuff from now on, Perl is obviously > built for this. Actually IIRC Perl *invented* regexes as we know them. The "standard" regex syntax is known as "Perl regex syntax". > 2 ) There's More Than One Way To Do It makes debugging hard - i.e. > close INFILE; & close (INFILE); are both valid. I like one syntax, cos > it's easier to remember. I don't find it that bad. Ruby does it as well, and it's perfectly readable. It's more or less equivalent as if condition: and if(condition): both being valid in Python. > 3) Some stuff is counter-intuitive - > $lenOfModList = @moddirList is the Perl equivalent of lenofModList = > len(moddirList) You sure of that? I was under the impression that len(moddirList) in Perl was $moddirList (@moddirList is the list itself). > Also, why doesn't if ( not $d eq "a" && not $d eq "c") evaluate to > true for $d = "b" when > if (not $d eq "a") evals to true and if ($d ne "a" && $d ne "c") evals > true also? What's with that? This probably has to do with operator precedence. It's been lifted from C, so chances are that && has a higher precedence than eq. Use parentheses. > 4) WHAT IS WITH THE STUPID SYMBOLS EVERYWHERE LARRY??!! > > I'm not referring to the $ & @, I can see how they could be useful, > although with a list - > > @dude = (1, 2, 3), to obtain the 2nd value I would expect $d = > @dude[1], > not $d = $dude[1], that's counterintuitive also. This will be fixed in Perl 6. Then again, Perl 6 is supposed to be pure heaven, as the Parrot virtual machine can theoretically be used with any language and is heavily optimized. Python and Ruby with the speed of Perl, and the possibility to interface your code with CPAN modules. That's really cool. Once Perl 6 is released, of course. > Why is the read/write modifier part of the filename??? Why is it a > ? > In my opinion, there's only one place a > sign should be, in an > inequality test. This is consistent with UNIX redirection. ./foo > bar.txt executes the command foo, and redirects its STDOUT to the file bar.txt. ./foo >> bar.txt does the same, but appends to bar.txt instead f overwriting it. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From maxnoel_fr at yahoo.fr Thu Feb 3 00:39:32 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu Feb 3 00:39:40 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <86626245450c1bfcf3190400baffe178@yahoo.fr> References: <f2ff2d0502021518547f14c0@mail.gmail.com> <86626245450c1bfcf3190400baffe178@yahoo.fr> Message-ID: <9bb26ab5f9c3d8166f27d39464b9c750@yahoo.fr> (damn, forgot to add the main part of my argumentation) I learnt Perl as well, a few years ago. It was the first scripting language I came across (all I knew before that were C, Turbo Pascal, and a few calculator programming languages), so I immediately fell in love with its string manipulation capabilities. I came across PHP a little while after, and while it had some things which I liked (PHP.net being the main one), I preferred Perl. However, I never got the opportunity to really use it, and after a while the inconsistency of the syntax grew on me, and the language itself kept eluding me. I was never able to grok it, and thus systematically reverted to C every time I had to code something. Fast forward to last summer. In the span of 1 week, I discovered both Python and Ruby. Fell in love with both and immediately ditched Perl. I never looked back, even though I know Perl is still the fastest scripting language around. I value debugging time more than CPU time these days. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From stygian at tesco.net Thu Feb 3 00:53:29 2005 From: stygian at tesco.net (Glen) Date: Thu Feb 3 00:53:13 2005 Subject: [Tutor] Python 2.4 with Mandrake 10.0 query In-Reply-To: <Pine.LNX.4.44.0502021357390.12128-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0502021357390.12128-100000@hkn.eecs.berkeley.edu> Message-ID: <1107388409.3726.6.camel@localhost> On Wed, 2005-02-02 at 22:02, Danny Yoo wrote: > On Wed, 2 Feb 2005, Glen wrote: > > > [glen@localhost glen]$ idle > > set([34, 36, 38, 39]) > > Failed to load extension 'CodeContext' > > Traceback (most recent call last): > > File "/usr/local/lib/python2.4/idlelib/EditorWindow.py", line 737, in > > load_standard_extensions > > self.load_extension(name) > > File "/usr/local/lib/python2.4/idlelib/EditorWindow.py", line 747, in > > load_extension > > mod = __import__(name, globals(), locals(), []) > > File "/usr/local/lib/python2.4/idlelib/CodeContext.py", line 15, in ? > > from sets import Set > > ImportError: cannot import name Set > > Hi Glen, > > > Ah! Check to see if there's a "sets.py" program somewhere in your current > working directory. It's very likely that Python is picking that up, > instead of the 'sets' standard library module. > > This is one thing that does bite people every so often, because it's all > too easy to accidently write a program uses the same name as a standard > library module. > > I wrote a small module a while back as a proposed solution to the issue: > > http://hkn.eecs.berkeley.edu/~dyoo/python/__std__/ > > but I don't think it's really being used. > > Best of wishes to you! > You're a genius! That's exactly what I'd done. It also explains the odd results I was getting when I did import the sets module. Thanks, I'll have a look at your module. Glen From cyresse at gmail.com Thu Feb 3 01:42:10 2005 From: cyresse at gmail.com (Liam Clarke) Date: Thu Feb 3 01:42:14 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <9bb26ab5f9c3d8166f27d39464b9c750@yahoo.fr> References: <f2ff2d0502021518547f14c0@mail.gmail.com> <86626245450c1bfcf3190400baffe178@yahoo.fr> <9bb26ab5f9c3d8166f27d39464b9c750@yahoo.fr> Message-ID: <f2ff2d0502021642627b77ee@mail.gmail.com> > I don't find it that bad. Ruby does it as well, and it's perfectly readable. It's more or less equivalent as if condition: and if(condition): both being valid in Python. Yeah, but you'd never call a function foo like this- x = foo in Python. It's just good to be able to say that a function always has <some rule here>. That improves readability (imao). >You sure of that? I was under the impression that len(moddirList) in Perl was $moddirList (@moddirList is the list itself). Well, my one's correct, but I think yours is also. And this is what gets me. @mod = (1,2,3) $mod = 3 $mod[0] = 1 Is inconsistent. Or at least, the logic behind this is not immediately apparent to me. I'm always open to illumination on these things however. >> if ( not $d eq "a" && not $d eq "c") = False for $d = "b" >> if ($d ne "a" && $d ne "c") = True >This probably has to do with operator precedence. It's been lifted from C, so chances are that && has a higher precedence than eq. Use parentheses. Ah... Ironic, I got misled by TMTOWTDI. I figured that if not x=="a" and not x == "c" evaled as True in Python, and "if (not $d eq "a")" evaled as True in Perl, that if ( not $d eq "a" && not $d eq "c") would also eval as true. Of course, what's even weirder to me is that if ($d ne "a" && $d ne "c") does eval as True, as far as I can see, '$d ne "a"' is the same as d != "a" in Python, which is the same as 'if not d == "a"', which, logically, would mean that $d ne "a" is the same as 'if(not $d eq "a") in which case both tests should handle the addition of an AND the same. Once again, illumination is welcomed, as I have a finally that some subtlety of Boolean logic is eluding me, and a 'x != a' test is different to 'if not x == a' in a small but significant way. Max - the foo > std.txt thing explains it, but what about @dude = <FILE>, where do the brackets originate from? This is another issue I'm having with Perl as opposed to Python - Perl is very much written by *nix users for *nix users, it's implementation of *nix conventions shows, including the `` things. Whereas (correct me if I'm wrong), but Python was written by *nix users for everyone. Python seems very non-OS-denominational in it's current incarnation, it may have been very *nix orientated prior. So here comes me, the guy who installed Linux once, failed to see the big deal and uninstalled it. Up until 3 months ago, my comp was used for gaming, pure and simple, me being a certified Day of Defeat freak, and so Windows has always best served my purpose. Now, I want to programme, so I have to learn Unix conventions to use a crossplatform language! It's like asking *nix users to sign a Microsoft EULA!! (Well, not as bad, but still as anathemic.) >Fast forward to last summer. In the span of 1 week, I discovered both Python and Ruby. Fell in love with both and immediately ditched Perl. How's Ruby? I bookmarked the homepage, but never got around to looking at it. Oh, and I will say this - Perl > Java (and that's an inequality test, not a redirection of output) Cheers, Liam Clarke -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From lumbricus at gmx.net Thu Feb 3 01:52:50 2005 From: lumbricus at gmx.net (lumbricus@gmx.net) Date: Thu Feb 3 01:52:54 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <86626245450c1bfcf3190400baffe178@yahoo.fr> Message-ID: <32746.1107391970@www54.gmx.net> Hello! > Actually IIRC Perl *invented* regexes as we know them. The "standard" > regex syntax is known as "Perl regex syntax". Regex are way older than Perl. The roots are in the Fourties(!). They were first used in the editor qed, then ed, then sed and eventually grep. Then awk, emacs, vi lex and finally Perl. "http://en.wikipedia.org/wiki/Regular_expressions#History" > -- Max HTH and Greetings, J"o! -- Wir sind jetzt ein Imperium und wir schaffen uns unsere eigene Realit?t. Wir sind die Akteure der Geschichte, und Ihnen, Ihnen allen bleibt nichts, als die Realit?t zu studieren, die wir geschaffen haben. -- Karl Rove zu Ron Suskind (NYT) Sparen beginnt mit GMX DSL: http://www.gmx.net/de/go/dsl From dyoo at hkn.eecs.berkeley.edu Thu Feb 3 02:46:28 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Feb 3 02:46:34 2005 Subject: [Tutor] Python 2.4 with Mandrake 10.0 query In-Reply-To: <1107388409.3726.6.camel@localhost> Message-ID: <Pine.LNX.4.44.0502021735510.24738-100000@hkn.eecs.berkeley.edu> > > Ah! Check to see if there's a "sets.py" program somewhere in your > > current working directory. It's very likely that Python is picking > > that up, instead of the 'sets' standard library module. > > You're a genius! That's exactly what I'd done. Hi Glen, I'd attribute it not to genius, but more to pattern matching: I've seen that particular problem a lot. *sigh* But I'm very glad that the problem's identified and fixed. > > I wrote a small module a while back as a proposed solution to the issue: > > > > http://hkn.eecs.berkeley.edu/~dyoo/python/__std__/ > > > > but I don't think it's really being used. > > > It also explains the odd results I was getting when I did import the > sets module. Thanks, I'll have a look at your module. You probably won't need it; PEP 328 is supposed to handle this issue properly: http://www.python.org/peps/pep-0328.html My __std__ package is a kludge, and I know it's a kludge. *grin* I noticed that someone else had run into limitations using it: http://www.gossamer-threads.com/lists/python/python/348985 so it's not as useful as I had first thought. Best of wishes to you! From maxnoel_fr at yahoo.fr Thu Feb 3 02:49:22 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu Feb 3 02:49:27 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <f2ff2d0502021642627b77ee@mail.gmail.com> References: <f2ff2d0502021518547f14c0@mail.gmail.com> <86626245450c1bfcf3190400baffe178@yahoo.fr> <9bb26ab5f9c3d8166f27d39464b9c750@yahoo.fr> <f2ff2d0502021642627b77ee@mail.gmail.com> Message-ID: <56abcbca5acfdc78d0b13c480c1af850@yahoo.fr> On Feb 3, 2005, at 00:42, Liam Clarke wrote: >> I don't find it that bad. Ruby does it as well, and it's perfectly > readable. It's more or less equivalent as if condition: and > if(condition): both being valid in Python. > > Yeah, but you'd never call a function foo like this- > > x = foo > > in Python. It's just good to be able to say that a function always has > <some rule here>. > That improves readability (imao). Yes. That, and the fact that you can use function pointers very easily that way. For example, x = foo x() will call foo. Which is cool. I do prefer the Python style as well. Just like variable naming conventions should tell you something about their nature, function calls should have something that explicitly gives them away as such. MyClass MY_CONSTANT myVariable myFunctionCall() > @mod = (1,2,3) > $mod = 3 > $mod[0] = 1 > > Is inconsistent. Or at least, the logic behind this is not immediately > apparent to me. I'm always open to illumination on these things > however. Yeah. As with most things in Perl, there is no way to guess it. This is actually what I hate the most about that language, and what makes it write-only. >>> if ( not $d eq "a" && not $d eq "c") = False for $d = "b" >>> if ($d ne "a" && $d ne "c") = True > >> This probably has to do with operator precedence. It's been lifted > from C, so chances are that && has a higher precedence than eq. Use > parentheses. > > Ah... Ironic, I got misled by TMTOWTDI. I figured that if not x=="a" > and not x == "c" evaled as True in Python, and "if (not $d eq "a")" > evaled as True in Perl, that > if ( not $d eq "a" && not $d eq "c") would also eval as true. > Of course, what's even weirder to me is that > if ($d ne "a" && $d ne "c") does eval as True, as far as I can see, > > '$d ne "a"' is the same as d != "a" in Python, which is the same as > 'if not d == "a"', which, logically, would mean that $d ne "a" is the > same as 'if(not $d eq "a") in which case both tests should handle the > addition of an AND the same. Again, no, because IIRC (it's been a while since I last used Perl) eq and ne are the Perl operators with the lowest precedence. In effect, your last statement is evaluated as if((not $d) eq "a"). Use == and !=, they work on strings as well. Or (and?) use parens. Also, don't forget that Perl, like Python, uses lazy evaluation. > Once again, illumination is welcomed, as I have a finally that some > subtlety of Boolean logic is eluding me, and a 'x != a' test is > different to 'if not x == a' in a small but significant way. > > Max - the foo > std.txt thing explains it, but what about @dude = > <FILE>, where do the brackets originate from? I have no idea. Somehow I think it makes sense. It's one of the few things that I think make sense in Perl. Couldn't tell you why I think so, though :p > This is another issue I'm having with Perl as opposed to Python - Perl > is very much written by *nix users for *nix users, it's implementation > of *nix conventions shows, including the > `` things. Whereas (correct me if I'm wrong), but Python was written > by *nix users for everyone. Python seems very non-OS-denominational in > it's current incarnation, it may have been very *nix orientated prior. Not really. The thing is, Python in itself does very little. You have to import modules whenever you want to do something that involves the system (aside from file operations). That's an advantage IMO, since the default modules are quite good and allow for some nice cross-platform capabilities. However, if the redirection operators and pipes are what make you think that way, you should know that MS-DOS (and WinNT's DOS shell) does handle pipes and redirection. Perhaps not as powerfully as *NIX, but it does. (however, I would appreciate it if the Python standard distribution came with a "real" XML parser, 'cause DOM and SAX just plain suck -- by the way, thanks guys, I tried dom4j on my Java project and it changed my life) > So here comes me, the guy who installed Linux once, failed to see the > big deal and uninstalled it. Up until 3 months ago, my comp was used > for gaming, pure and simple, me being a certified Day of Defeat freak, > and so Windows has always best served my purpose. > > Now, I want to programme, so I have to learn Unix conventions to use a > crossplatform language! It's like asking *nix users to sign a > Microsoft EULA!! (Well, not as bad, but still as anathemic.) Well, in Perl's defense, Windows does implement a fairly large part of the POSIX standard. And believe me. I'm a UNIX user (Mac OS X is my primary OS, but I also use Windows and Linux on a fairly regular basis). Perl doesn't make any more sense to me than when I was still a Windows-only guy. > How's Ruby? I bookmarked the homepage, but never got around to looking > at it. Very, very nice. Cleanest object-orientedness I ever saw in a language (not that I have that much experience -- people like Alan would probably be better judges than me on this). I find it more elegant than Python, however I end up using Python anyway because Ruby has a huge flaw: it's Japanese (AFAIK it's also the only "Made in Japan" programming language, apart from stuff like ASM 68K), and so is a large part of its community. As such, English language documentation is flaky at best. And as far as I know there is no tutor@ruby-lang.org. Which, as you will probably agree, sucks. > Oh, and I will say this - Perl > Java (and that's an inequality test, > not a redirection of output) I'll have to disagree with you there, unless vi/emacs is the only IDE you have access to (did I ever tell you about Eclipse?), and perhaps even then. From what I remember, if you're programming in an object-oriented style (which I now tend do by default unless there is a painfully obvious and optimal solution in procedural style), Perl is the ugliest thing ever created since Visual Basic. Last time I checked, its OOness was frighteningly ugly. Java was built as an OO language from the ground up, if you except the presence of the basic C types. As such, it is very clean, although it clearly lacks the elegance of Python (then again, what to say of Perl?). Java code always makes sense when you read it (and in the worst-case, when you have access to the API documentation, which is available as long as you have Internet access). Sure, it requires a lot of typing (in both meanings of the word), but it's rarely -- if ever -- ambiguous. Also, Java has the added advantage of being very easy to learn: I learned it in 1 week 4 months ago (doesn't beat Python's record, though: I was doing useful stuff with it within 24 hours of learning about its existence), and now feel confident enough with it to do just about anything. Of course, my C/C++ programming experience probably helped me a lot with this. In my opinion, Java has only 2 big flaws: 1) The Java Virtual Machine is a horrible resource hog. Sure, your program runs quite fast, but unless you've got multiple CPUs the responsiveness of your machine goes *down* (especially noticeable on machines with slow CPUs such as the G4 867 with which I'm typing this right now). 2) Sun didn't ever encourage anyone to write [insert language here]?compilers that compiled to JVM bytecode. The JVM was supposed to run Java code and nothing else. That's stupid. Microsoft got it right with .NET; Sun should have thought of it at least 5 years ago. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From dyoo at hkn.eecs.berkeley.edu Thu Feb 3 03:19:26 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Feb 3 03:19:29 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <f2ff2d0502021518547f14c0@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0502021747440.24738-100000@hkn.eecs.berkeley.edu> On Thu, 3 Feb 2005, Liam Clarke wrote: > Had the *ahem* joy of learning Perl last night. Egad. Wrote the script > in Python to get it right, and then 'translated' it to Perl. Hi Liam, I strongly recommend sending the Perl code to that Perl-beginners mailing list referenced earlier. I'm sure that there are some Perl idioms that can simplify the code there. For example: ### Perl ### $wrkDir = "c:/python23/j/j2"; opendir( TGTDIR, $wrkDir); @dirList = readdir(TGTDIR); @moddirList=(); foreach $fileName (@dirList) { if ($fileName ne ".." && $fileName ne ".") { @moddirList = (@moddirList, $fileName); } } ###### can be greatly improved by Perl's globbing operator instead of readdir(): ###### $wrkDir = "c:/python23/j/j2"; @dirList = <$wrkDir/*>; ###### This has a fairly close Python equivalent in the glob.glob() function: ### wrkDir = "s:/toolkit/retain/sustainableEmployment" dirList = glob.glob(wrkDir + "/*") ### > @someArray = (@someArray, $newValue) is the same as someArray.append(newValue) This is actually doing much more work than a list append. The list-adding code that you had earlier is equivalent to: ### Python ### someList = someList + [newValue] ###### which is just bad. *grin* More idiomatic Perl is: ### Perl ### push @someArray, $newValue; ###### which should have the same performance as a list append(). > Of course, the documentation I had didn't mention that. It just said to > open it and use print FILEHANDLE $value; to write. Perl's documentation system 'perldoc' command is one of the really nice things about Perl. In some cases, I think it might be even more comprehensive than 'pydoc', since perldoc also directly links to tutorial material. Try: ### $ perldoc perl ### I guess I'm trying to say: language idioms take time to learn, and unlike syntax errors, weird idioms aren't really detectable by the runtime system. *grin* If you continue to learn Perl, talk with the beginners's group there, so that the community there can help. And if the Perl programs that you're writing seem suboptimal, get it vetted by someone who knows Perl well; you may be pleasantly surprised. Best of wishes to you! From keridee at jayco.net Thu Feb 3 03:47:55 2005 From: keridee at jayco.net (Jacob S.) Date: Thu Feb 3 03:48:23 2005 Subject: [Tutor] Better structure? References: <Pine.LNX.4.44.0501311447390.24680-100000@hkn.eecs.berkeley.edu> <41FF6082.70005@tds.net><000001c508cb$5a67e9f0$3b5428cf@JSLAPTOP><42003772.4010808@ccvcorp.com> <002501c508ce$294e4e10$3b5428cf@JSLAPTOP> <016a01c50904$81e75db0$68b78851@xp> Message-ID: <001301c5099a$df6c7dd0$145428cf@JSLAPTOP> Interesting topic. > Jacob, > > Writing library code is a difficult and unrewarding task > - I've been there so I sympathise, however... I wouldn't say that... >> So, how would one go about this in a non broken code way? Don't they > have >> something like what I'm requesting. > > Its not broken, its just different to what you want. > What you want is much simpler than what lstrip does > so you can easily code your requirements. > Try writing the code to do what lstrip actually does > - its much harder. So the library includes the more > difficult function and lets you code the easy ones. def lstrip(string,chars=' ') string = list(string) t = 0 for x in string: if x in chars: string.remove(t) else: break t = t+1 Okay, so it's not that difficult, but I get your point. Since all of these are not too hard to write, my library structure is probably what's flawed. I have so many miscellaneous functions that I am copying and pasting (oh no!) that I finally decided to move them to a different module. Unfortunately, they are quite random and I will have to find someway of seperating them. >> It seems to me that a few things are flawed in the standard > distribution. > > No library is perfect - you should try using C! > > But the Python library isually has good reasons for its > apparent limitations. > >> Little things like the overlooking of adding a method or function to > decimal >> for returning an instance with x places right of the decimal. > > But there is very little need to do that. Usually you only want > to do that in presentation - ie printing. Thus the mechanism > for doing that is in the string formatting code - where it > makes sense. Uck. True usually in printing. String formatting doesn't cut it for a type that's not a string. Especially something not builtin. >Why would limiting the precision of the internal > number representation be something you'd want to do? Very > occassionally maybe, but in those cases its easy to fake > (and it is a fake because the number is in binary and not > true decimal so its always an approximation - in any language!) > >> quantize, but that's junk and not simple. > > You mean it does a complex job and not the one youd like it to do? :-) It does precisely what I would like it to do. I guess I just looked at it and said, they are making it too difficult. quantize -- a method of class Decimal in module decimal arguments -- exp - a Decimal instance that has the required amount of places to the right of the decimal pt. So, it seems to me that one could possibly add to the decimal module. userprec = 10 ## A default def q(decinst): ## simple name -- unfortunately might conflict -- decinst stands for decimal instance return decinst.quantize(Decimal("0.%s" % ('0'*userprec))) ## Creates a Decimal instance w/userprec places right of #### decimal pt. then uses the given argument decinst method quantize to return decinst w/ userprec places right of the decimal. Which, of course, I did. >You can even subclass string and make it a method if you like. Ooooh! How do I do that? > I suspect your function should probably be: > > def mylstrip(str,stripstring): > if str.startswith(stripstring) and > len(stripstring) < len(str): > return str[len(stripstring):] > > But thats just my guess at what *you* really want... Well yeah. I didn't think it through that far. But that also contributes to my probably poor library structure. Where would I put such a function? > And finally remember that Python is built by volunteers mostly. > You should be pleased the *bothered* to write any of it! Excuse me... I didn't mean to offend those volunteers in any way. I'm beautifully happy with python! Just little quirks here and there... Maybe someday I'll become one of those volunteers. Jacob Schmidt From kent37 at tds.net Thu Feb 3 05:11:06 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Feb 3 05:11:10 2005 Subject: [Tutor] Better structure? In-Reply-To: <001301c5099a$df6c7dd0$145428cf@JSLAPTOP> References: <Pine.LNX.4.44.0501311447390.24680-100000@hkn.eecs.berkeley.edu> <41FF6082.70005@tds.net><000001c508cb$5a67e9f0$3b5428cf@JSLAPTOP><42003772.4010808@ccvcorp.com> <002501c508ce$294e4e10$3b5428cf@JSLAPTOP> <016a01c50904$81e75db0$68b78851@xp> <001301c5099a$df6c7dd0$145428cf@JSLAPTOP> Message-ID: <4201A45A.2060205@tds.net> Jacob S. wrote: >> Try writing the code to do what lstrip actually does >> - its much harder. So the library includes the more >> difficult function and lets you code the easy ones. > > > def lstrip(string,chars=' ') > string = list(string) > t = 0 > for x in string: > if x in chars: > string.remove(t) > else: > break > t = t+1 > > > Okay, so it's not that difficult, Well, after fixing the obvious syntax error I tried print lstrip('abcd', 'abcd') and got Traceback (most recent call last): File "D:\Personal\Tutor\LStrip.py", line 11, in ? print lstrip('abcd', 'abcd') File "D:\Personal\Tutor\LStrip.py", line 6, in lstrip string.remove(t) ValueError: list.remove(x): x not in list so maybe it's not that easy either. Don't forget the unit tests! :-) Kent From singingxduck at gmail.com Thu Feb 3 05:23:03 2005 From: singingxduck at gmail.com (Orri Ganel) Date: Thu Feb 3 05:23:20 2005 Subject: [Tutor] Better structure? In-Reply-To: <4201A45A.2060205@tds.net> References: <Pine.LNX.4.44.0501311447390.24680-100000@hkn.eecs.berkeley.edu> <41FF6082.70005@tds.net><000001c508cb$5a67e9f0$3b5428cf@JSLAPTOP><42003772.4010808@ccvcorp.com> <002501c508ce$294e4e10$3b5428cf@JSLAPTOP> <016a01c50904$81e75db0$68b78851@xp> <001301c5099a$df6c7dd0$145428cf@JSLAPTOP> <4201A45A.2060205@tds.net> Message-ID: <4201A727.1040206@gmail.com> Kent Johnson wrote: > Jacob S. wrote: > >>> Try writing the code to do what lstrip actually does >>> - its much harder. So the library includes the more >>> difficult function and lets you code the easy ones. >> >> >> >> def lstrip(string,chars=' ') >> string = list(string) >> t = 0 >> for x in string: >> if x in chars: >> string.remove(t) >> else: >> break >> t = t+1 >> >> >> Okay, so it's not that difficult, > > > Well, after fixing the obvious syntax error I tried > print lstrip('abcd', 'abcd') > > and got > Traceback (most recent call last): > File "D:\Personal\Tutor\LStrip.py", line 11, in ? > print lstrip('abcd', 'abcd') > File "D:\Personal\Tutor\LStrip.py", line 6, in lstrip > string.remove(t) > ValueError: list.remove(x): x not in list > > so maybe it's not that easy either. Don't forget the unit tests! :-) > > Kent > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > Actually, its not all that difficult. Instead of removing characters from the list, just replace them with an empty string and return ''.join(string): >>> def lstrip(string,chars=' '): string = list(string) i = 0 for x in string: if x in chars: string[i] = '' else: break i+=1 return ''.join(string) >>> lstrip('abcd','abcd') '' >>> 'abcd'.lstrip('abcd') '' >>> 'go on long log buddy'.lstrip('gonl ') 'buddy' >>> lstrip('go on long log buddy', 'gonl ') 'buddy' >>> 'go on long log buddy'.lstrip('gonl') ' on long log buddy' >>> lstrip('go on long log buddy', 'gonl') ' on long log buddy' So its not a brute force thing so much as a change in how you look at it that makes it difficult. -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From singingxduck at gmail.com Thu Feb 3 05:28:04 2005 From: singingxduck at gmail.com (Orri Ganel) Date: Thu Feb 3 05:28:18 2005 Subject: [Tutor] Better structure? In-Reply-To: <4201A727.1040206@gmail.com> References: <Pine.LNX.4.44.0501311447390.24680-100000@hkn.eecs.berkeley.edu> <41FF6082.70005@tds.net><000001c508cb$5a67e9f0$3b5428cf@JSLAPTOP><42003772.4010808@ccvcorp.com> <002501c508ce$294e4e10$3b5428cf@JSLAPTOP> <016a01c50904$81e75db0$68b78851@xp> <001301c5099a$df6c7dd0$145428cf@JSLAPTOP> <4201A45A.2060205@tds.net> <4201A727.1040206@gmail.com> Message-ID: <4201A854.8000103@gmail.com> Orri Ganel wrote: > Kent Johnson wrote: > >> Jacob S. wrote: >> >>>> Try writing the code to do what lstrip actually does >>>> - its much harder. So the library includes the more >>>> difficult function and lets you code the easy ones. >>> >>> >>> >>> >>> def lstrip(string,chars=' ') >>> string = list(string) >>> t = 0 >>> for x in string: >>> if x in chars: >>> string.remove(t) >>> else: >>> break >>> t = t+1 >>> >>> >>> Okay, so it's not that difficult, >> >> >> >> Well, after fixing the obvious syntax error I tried >> print lstrip('abcd', 'abcd') >> >> and got >> Traceback (most recent call last): >> File "D:\Personal\Tutor\LStrip.py", line 11, in ? >> print lstrip('abcd', 'abcd') >> File "D:\Personal\Tutor\LStrip.py", line 6, in lstrip >> string.remove(t) >> ValueError: list.remove(x): x not in list >> >> so maybe it's not that easy either. Don't forget the unit tests! :-) >> >> Kent >> >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> > Actually, its not all that difficult. Instead of removing characters > from the list, just replace them with an empty string and return > ''.join(string): > > >>> def lstrip(string,chars=' '): > string = list(string) > i = 0 > for x in string: > if x in chars: > string[i] = '' > else: > break > i+=1 > return ''.join(string) > > >>> lstrip('abcd','abcd') > '' > >>> 'abcd'.lstrip('abcd') > '' > >>> 'go on long log buddy'.lstrip('gonl ') > 'buddy' > >>> lstrip('go on long log buddy', 'gonl ') > 'buddy' > >>> 'go on long log buddy'.lstrip('gonl') > ' on long log buddy' > >>> lstrip('go on long log buddy', 'gonl') > ' on long log buddy' > > So its not a brute force thing so much as a change in how you look at > it that makes it difficult. > By the same token, to do rstrip just [::-1] - ify string when you make it into a list and when you join it to be returned: >>> def rstrip(string,chars=' '): string = list(string)[::-1] i = 0 for x in string: if x in chars: string[i] = '' else: break i+=1 return ''.join(string)[::-1] >>> 'abcde'.rstrip('cde') 'ab' >>> 'abcde'.rstrip('ecd') 'ab' >>> rstrip('abcde','cde') 'ab' >>> rstrip('abcde','ecd') 'ab' -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From sandip at lug-delhi.org Thu Feb 3 05:51:50 2005 From: sandip at lug-delhi.org (Sandip Bhattacharya) Date: Thu Feb 3 05:52:12 2005 Subject: [Tutor] Better structure? In-Reply-To: <4201A854.8000103@gmail.com> References: <Pine.LNX.4.44.0501311447390.24680-100000@hkn.eecs.berkeley.edu> <41FF6082.70005@tds.net><000001c508cb$5a67e9f0$3b5428cf@JSLAPTOP><42003772.4010808@ccvcorp.com> <002501c508ce$294e4e10$3b5428cf@JSLAPTOP> <016a01c50904$81e75db0$68b78851@xp> <001301c5099a$df6c7dd0$145428cf@JSLAPTOP> <4201A45A.2060205@tds.net> <4201A727.1040206@gmail.com> <4201A854.8000103@gmail.com> Message-ID: <4201ADE6.1040908@lug-delhi.org> > for x in string: > if x in chars: > string[i] = '' I just have a hangover from other languages, but I really wanted to know how Python handles iteration over a variable which is being changed within the loop itself. Is the "for" condition evaluated in every loop? - Sandip From shaleh at speakeasy.net Thu Feb 3 06:01:09 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Thu Feb 3 06:01:29 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <f2ff2d0502021518547f14c0@mail.gmail.com> References: <f2ff2d0502021518547f14c0@mail.gmail.com> Message-ID: <4201B015.7030001@speakeasy.net> Liam Clarke wrote: > 4) WHAT IS WITH THE STUPID SYMBOLS EVERYWHERE LARRY??!! > > I'm not referring to the $ & @, I can see how they could be useful, > although with a list - > > @dude = (1, 2, 3), to obtain the 2nd value I would expect $d = @dude[1], > not $d = $dude[1], that's counterintuitive also. > (I am an ex-perler gone clean. Been straight for 5 years now with only the occasional work forced binges.) Perl was designed by a linguist. He wanted it to act like human language -- which is not very consistent. That said, perhaps I can shed some light on the symbols. Ever learned a Romance language? latin, spanish, french, etc? The dollars and at signs can be thought of in relation to plural endings. $foo --> dog @dog --> a group of dogs $dog[0] --> a dog in the group So when you mean "the whole group" use the plural spelling and when you want to refer to a member use the singular spelling. Likewise with other parts of the language. Personally, the thing that keeps me away from Perl is nested datastructures. Python: my_list = [....] a_dict = {.....} b_dict = {.....} my_list.append(a_dict) my_list.append(b_dict) if my_list[0].has_key("foo"): print "Yes" easy. Try that in Perl. my @my_list; # remember those semicolons my %a_dict, %b_dict; push @my_list, %a_dict; push @my_list, %b_dict; if (exists $my_list->[0], "foo") print "Yes\n"; # yes, references required, in Perl ick. From singingxduck at gmail.com Thu Feb 3 06:05:24 2005 From: singingxduck at gmail.com (Orri Ganel) Date: Thu Feb 3 06:05:58 2005 Subject: [Tutor] Better structure? In-Reply-To: <4201ADE6.1040908@lug-delhi.org> References: <Pine.LNX.4.44.0501311447390.24680-100000@hkn.eecs.berkeley.edu> <41FF6082.70005@tds.net><000001c508cb$5a67e9f0$3b5428cf@JSLAPTOP><42003772.4010808@ccvcorp.com> <002501c508ce$294e4e10$3b5428cf@JSLAPTOP> <016a01c50904$81e75db0$68b78851@xp> <001301c5099a$df6c7dd0$145428cf@JSLAPTOP> <4201A45A.2060205@tds.net> <4201A727.1040206@gmail.com> <4201A854.8000103@gmail.com> <4201ADE6.1040908@lug-delhi.org> Message-ID: <4201B114.7040108@gmail.com> Sandip Bhattacharya wrote: >> for x in string: >> if x in chars: >> string[i] = '' > > > I just have a hangover from other languages, but I really wanted to > know how Python handles iteration over a variable which is being > changed within the loop itself. Is the "for" condition evaluated in > every loop? > > - Sandip > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > AFAIK, the for condition in this case *is* evaluated at the beginning of every iteration, but this is misleading. For example: >>> string=list('banana') >>> for x in string: string.remove(x) print string Does not print ['a', 'n', 'a', 'n', 'a'] ['n', 'a', 'n', 'a'] ['a', 'n', 'a'] ['n', 'a'] ['a'] [] But rather: ['a', 'n', 'a', 'n', 'a'] ['a', 'a', 'n', 'a'] ['a', 'a', 'a'] Let's figure this out. First, string is ['b','a','n','a','n','a']. So x == 'b'. 'b' is removed, and string printed: ['a', 'n', 'a', 'n', 'a']. Then, the for loop grabs the second character in string (which has changed) because it has already used the first one. So x == 'n'. 'n' is removed and string printed, etc. In general, it is A Good Idea to not change the length of sequences as you loop over them. If you use a for i in range(len(string)): style, you will get an IndexError because in this case Python does *not* check len(string) every iteration. If you use a different style, you will just get weird results. HTH, Orri -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From alan.gauld at freenet.co.uk Thu Feb 3 09:41:22 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Feb 3 09:41:44 2005 Subject: [Tutor] Better structure? References: <Pine.LNX.4.44.0501311447390.24680-100000@hkn.eecs.berkeley.edu> <41FF6082.70005@tds.net><000001c508cb$5a67e9f0$3b5428cf@JSLAPTOP><42003772.4010808@ccvcorp.com> <002501c508ce$294e4e10$3b5428cf@JSLAPTOP> <016a01c50904$81e75db0$68b78851@xp> <001301c5099a$df6c7dd0$145428cf@JSLAPTOP> Message-ID: <01e601c509cc$240f2d80$68b78851@xp> > > Try writing the code to do what lstrip actually does > > - its much harder. So the library includes the more > > difficult function and lets you code the easy ones. > > def lstrip(string,chars=' ') > string = list(string) > t = 0 > for x in string: > if x in chars: > string.remove(t) > else: > break > t = t+1 > > > Okay, so it's not that difficult, but I get your point. I assume you didn't try testing that. It doesn't work. Its close but there are some extra wrinkles you need to consider. And its the wrinkles that makes writing library code hard! But even this is more complex than the simple front slicing that you were looking for. [As an aside, estimates vary, but it is reckoned to take between 5-10 times as much effort to write generic reusable code as it does to write specific code. One of the things proponents of the argument that "reuse is cheap" often forget! Its only cheap if someone else develops what you reuse!] > to a different module. Unfortunately, they are quite random and I will have > to find someway of seperating them. And another hard part of designing any library is figuring out the best logical structure, which module has which bits. > Uck. True usually in printing. String formatting doesn't cut it for a type > that's not a string. Especially something not builtin. It does if you override the __Str__ method of your newly defined type. Then you can print it using %s... Although you did trigger the interesting thought: I wonder if there is a way of hooking the formatting characters to tailor the representation, hmmm, some research required... > >You can even subclass string and make it a method if you like. > > Ooooh! How do I do that? class MyString(string): # your methods go here, and don't forget __init__... HTH, Alan G. From alan.gauld at freenet.co.uk Thu Feb 3 09:59:28 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Feb 3 09:58:45 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <f2ff2d0502021518547f14c0@mail.gmail.com> Message-ID: <01f701c509ce$ab5933b0$68b78851@xp> > Just wondering if I should bite the bullet and code from scratch in > Perl, or if my Python - Perl is Ok. Its nearly always a bad idea to just translate code structures from one language to another. It will usually be sub optimal and non idiomatic - thus harder for the 'native' programmers to understand/debug. Bjarne Stroustrup made the same observation when C++ first came out and lots of Smalltalkers tried to use it like Smalltalk. He said "C++ is not Smalltalk, if you want to write Smalltalk use smalltalk" > 1) I'll use Perl for the regex stuff from now on, Perl is obviously > built for this. Yes, or PHP. Both have RE baked in. > 2 ) There's More Than One Way To Do It makes debugging hard - i.e. > close INFILE; & close (INFILE); are both valid. I like one syntax, cos > it's easier to remember. I can cope with that - BASIC does the same kind of thing - but its the zillion ways to handle errors that bug me! do thing until die do thing or die die unless do thing etc.... > 3) Some stuff is counter-intuitive - A huge understatement! :-) > Also, why doesn't if ( not $d eq "a" && not $d eq "c") evaluate to I don;t know but in cases like these I use parentheses like amaniac: if ( ((not $d) eq "a") && ((not $d) eq "c") ) Or did you mean if ( (not ($d eq "a")) && (not ($d eq "c")) ) Or was it if ( (not $d) eq ("a" && not ($d eq "c") ) # OK thats a bit unlikely... > 4) WHAT IS WITH THE STUPID SYMBOLS EVERYWHERE LARRY??!! Clever abbreviations apparently! I don't even like the $ and @... one reason I can never quite feel happy with Ruby. It has fewer of them but still more than I like. > In my opinion, there's only one place a > sign should be, in an > inequality test. Nope, I'm quite happy for it to be used in file indirection and even for right/left bit-shifting. But I don;t like it being part of the filename - I agree with that! > great for regexes > obviously based around *nix conventions. > Big hodge-podge, oozing with inconsistency. I'd hate to work > collaboratively on a Perl project. > Two steps up from Brainf**k in parts. > Obviously in need of a benevolent dictator a la Guido. Good summary! Perl reflects the fact that its inventor is a natural-language student not a computer scientist. It tries to incorporate the "richness of expression" of natural spech. But when dealing with machines that's a flaw IMHO! Alan G. From kraus at hagen-partner.de Thu Feb 3 10:09:26 2005 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Thu Feb 3 10:10:53 2005 Subject: [Tutor] Re: Are you allowed to shoot camels? [kinda OT] In-Reply-To: <01f701c509ce$ab5933b0$68b78851@xp> References: <f2ff2d0502021518547f14c0@mail.gmail.com> <01f701c509ce$ab5933b0$68b78851@xp> Message-ID: <ctspmt$5ug$1@sea.gmane.org> Alan Gauld wrote: [...] >>1) I'll use Perl for the regex stuff from now on, Perl is obviously >>built for this. > > > Yes, or PHP. Both have RE baked in. > Beware! Overcome the temptation! Try this: http://kodos.sourceforge.net/ HTH ;-) Wolfram From pathall at gmail.com Thu Feb 3 10:24:06 2005 From: pathall at gmail.com (Patrick Hall) Date: Thu Feb 3 10:24:09 2005 Subject: [Tutor] Re: Are you allowed to shoot camels? [kinda OT] In-Reply-To: <ctspmt$5ug$1@sea.gmane.org> References: <f2ff2d0502021518547f14c0@mail.gmail.com> <01f701c509ce$ab5933b0$68b78851@xp> <ctspmt$5ug$1@sea.gmane.org> Message-ID: <6465924d050203012479ff6970@mail.gmail.com> > Beware! Overcome the temptation! > Try this: http://kodos.sourceforge.net/ While I have no problem personally with Perl or PHP, I'll second the recommendation for kodos -- it's very useful for learning to use regexes in Python. From alan.gauld at freenet.co.uk Thu Feb 3 10:48:38 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Feb 3 10:48:17 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <f2ff2d0502021518547f14c0@mail.gmail.com><86626245450c1bfcf3190400baffe178@yahoo.fr><9bb26ab5f9c3d8166f27d39464b9c750@yahoo.fr><f2ff2d0502021642627b77ee@mail.gmail.com> <56abcbca5acfdc78d0b13c480c1af850@yahoo.fr> Message-ID: <021301c509d5$89daa960$68b78851@xp> > > How's Ruby? I bookmarked the homepage, but never got around to looking > > at it. > > Very, very nice. Cleanest object-orientedness I ever saw in a language > (not that I have that much experience -- people like Alan would > probably be better judges than me on this). You knew I couldn't resist! :-) Ruby OOP is OK although I don;t like the @ stuiff for members, theres simply no need for it! ONe thing I really like about Ruby is its implementation of iterators and generators - much better than Pythons IMHO. And their anonymous code blocks (aka lambdas) show how it can bve done. Pythons lambda feature is a bare minimum (and Guido wants to remove it!). > anyway because Ruby has a huge flaw: it's Japanese (AFAIK it's also the > only "Made in Japan" programming language, apart from stuff like ASM Yes the Japanese thing is an issue. THere are a few English books now, and the original one by Thomas and Hunt is free on the web. > And as far as I know there is no tutor@ruby-lang.org. No English one at least. > From what I remember, if you're programming in an object-oriented > style (which I now tend do by default unless there is a painfully > obvious and optimal solution in procedural style), Perl is the ugliest > thing ever created since Visual Basic. VB is a thing of beauty compared to Perl for OO! In fact I actually don't mind VB OOP at all, especially in its .NET variant which includes inheritance and polymorphism. But Perl OOP is a hideous bodge. > was frighteningly ugly. Java was built as an OO language from the > ground up, if you except the presence of the basic C types. But unfortunately built very badly as an OOP environment. Its more accurate to call it a class based language since its perfectly possible to build a Java program with no objecs but lots of classes! I'd go so far as to say that if you followed Java's lead on OOP you would pick up some very bad OO habits and write code that was not really very OOP at all! Thats not to say you can't write good OO code in Java just that Java does little to encourage it. You need to read a good OO book, like BRuce Eckels Thinking IN... series) to see how to do it properly! > ...Sure, it requires a lot of typing > (in both meanings of the word), :-) 1) The Java Virtual Machine is a horrible resource hog. Most virtual machines are, especially those that try to be the OS as opposed to simply wrap the OS... The old UCSD Pascal virtual machine was the same, it ran great on a mainframe but the little Mini computers we had in the labs were woeful! > 2) Sun didn't ever encourage anyone to write [insert language > here] compilers that compiled to JVM bytecode. I don't think they discouraged it, there are JVM compilers for Python, Smalltalk, Lisp, Tcl and Perl at least... And whats worse is that there are few native code compilers for Java. The JVM thing is a big hype factor IMHO. We've been writing C/C++ programs for years that ran on Windows/Unix and IBM boxes with only minor #ifdefs inserted. The performance (and hence costs for servers!) differences are huge! Its no coincidence that 2 of the biggest supporters of Java (IBM and Sun) are hardware vendors! A slightly cynical Alan G. From kent37 at tds.net Thu Feb 3 11:50:32 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Feb 3 11:50:37 2005 Subject: [Tutor] Re: Are you allowed to shoot camels? [kinda OT] In-Reply-To: <6465924d050203012479ff6970@mail.gmail.com> References: <f2ff2d0502021518547f14c0@mail.gmail.com> <01f701c509ce$ab5933b0$68b78851@xp> <ctspmt$5ug$1@sea.gmane.org> <6465924d050203012479ff6970@mail.gmail.com> Message-ID: <420201F8.1000408@tds.net> Patrick Hall wrote: >>Beware! Overcome the temptation! >>Try this: http://kodos.sourceforge.net/ > > > While I have no problem personally with Perl or PHP, I'll second the > recommendation for kodos -- it's very useful for learning to use > regexes in Python. Or, if you don't have Qt available, use the regular expression tester that comes with Python - it's at C:\Python24\Tools\Scripts\redemo.py (or whatever the *nix equivalent is). Kent > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From maxnoel_fr at yahoo.fr Thu Feb 3 14:00:02 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu Feb 3 14:00:10 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <021301c509d5$89daa960$68b78851@xp> References: <f2ff2d0502021518547f14c0@mail.gmail.com><86626245450c1bfcf3190400baffe178@yahoo.fr><9bb26ab5f9c3d8166f27d39464b9c750@yahoo.fr><f2ff2d0502021642627b77ee@mail.gmail.com> <56abcbca5acfdc78d0b13c480c1af850@yahoo.fr> <021301c509d5$89daa960$68b78851@xp> Message-ID: <93fef199885ae5cf5b466c6e0e724ae5@yahoo.fr> On Feb 3, 2005, at 09:48, Alan Gauld wrote: > Pythons lambda feature is a bare minimum (and Guido wants to remove > it!). Does he? Damn, just when I was learning functional programming! (in Haskell, if you're curious ^^) > Yes the Japanese thing is an issue. > THere are a few English books now, and the original one by Thomas > and Hunt is free on the web. A little bit outdated, however. Ruby lacks a proper series of O'Reilly books; last time I checked the only one available was "Ruby in a Nutshell", which is a few years old and covers Ruby 1.6 (2 versions behind the current one). What Matz needs to do IMO is to gather a couple of the l33test Ruby hackers in the world in a nice house in the Japanese countryside, pick a cool-looking animal (what about an eastern dragon?), and sit down with them to write a thousand-page "Programming Ruby". > is a thing of beauty compared to Perl for OO! > In fact I actually don't mind VB OOP at all, especially in > its .NET variant which includes inheritance and polymorphism. > But Perl OOP is a hideous bodge. I haven't tried VB.NET (and don't intend to, I don't like BASIC-style languages), so I can't comment on this. > But unfortunately built very badly as an OOP environment. Its > more accurate to call it a class based language since its > perfectly possible to build a Java program with no objecs > but lots of classes! I'd go so far as to say that if you > followed Java's lead on OOP you would pick up some very > bad OO habits and write code that was not really very OOP > at all! > > Thats not to say you can't write good OO code in Java just > that Java does little to encourage it. You need to read a > good OO book, like BRuce Eckels Thinking IN... series) to > see how to do it properly! Well, of course, it all depends on how you're learning it. I'm sure there are some C tutorials out there that teach you (and encourage you) to use GOTO statements. :-D Me? I learnt Java by reading Eckel's "Thinking in Java" (and then followed with Wigglesworth/McMillan's "Java Programming: Advanced Topics"). I agree with you: it's an excellent book, that encourages good coding style and proper OOP. > And whats worse is that there are few native code compilers > for Java. The JVM thing is a big hype factor IMHO. We've been > writing C/C++ programs for years that ran on Windows/Unix and > IBM boxes with only minor #ifdefs inserted. The performance > (and hence costs for servers!) differences are huge! Its no > coincidence that 2 of the biggest supporters of Java > (IBM and Sun) are hardware vendors! Agreed. I'm no compiler programmer, but it seems to me that they could just have written a nice cross-platform API and then platform-specific compilers, while keeping the specification of the language intact (i.e. platform-independent endian-ness, type sizes, etc.). The reasoning behind the JVM is that you don't need to recompile your code to run it on a different platform. But most existing Java projects have platform-specific versions, if only to make the GUI (try to) look native. You can spot a Java app from a hundred meters away. (then again, the same critic could be made of Python's and Perl's "standard" GUI toolkits) -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From amonroe at columbus.rr.com Thu Feb 3 14:29:41 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Thu Feb 3 14:30:16 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <93fef199885ae5cf5b466c6e0e724ae5@yahoo.fr> References: <f2ff2d0502021518547f14c0@mail.gmail.com> <86626245450c1bfcf3190400baffe178@yahoo.fr> <9bb26ab5f9c3d8166f27d39464b9c750@yahoo.fr> <f2ff2d0502021642627b77ee@mail.gmail.com> <56abcbca5acfdc78d0b13c480c1af850@yahoo.fr> <021301c509d5$89daa960$68b78851@xp> <93fef199885ae5cf5b466c6e0e724ae5@yahoo.fr> Message-ID: <25317573686.20050203082941@columbus.rr.com> > code to run it on a different platform. But most existing Java projects > have platform-specific versions, if only to make the GUI (try to) look > native. You can spot a Java app from a hundred meters away. > (then again, the same critic could be made of Python's and Perl's > "standard" GUI toolkits) Amen. This drives me absolutely bonkers! Alan From Nicholas.Montpetit at deluxe.com Thu Feb 3 14:43:01 2005 From: Nicholas.Montpetit at deluxe.com (Nicholas.Montpetit@deluxe.com) Date: Thu Feb 3 14:43:16 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: <OF52033BE6.BCF7E85A-ON86256F9D.004B425A-86256F9D.004B39D7@deluxe.com> Well, here's my $0.02. I would recommend caution regarding the trashing of Perl. One thing I've been very impressed with on this list (and other segments of the Python community) is the _fairly_ cordial relationship between the supporters of the two languages. Contrast that to a lot of PHP literature I've seen, which doesn't even acknowledge that Perl exists. My theory is that many who use PHP got kicked around by trying to learn Perl, and bitterness set in. But that's a digression... Anyway, I'm on the fence as to whether I want to learn Python (not exactly a "core competency" for statisticians, but I do line the numerical computation capabilities which look _much_ better than those of Perl), and I wouldn't want this negativity to push me (or others) away. I'll try to speak to a few of the points below, from my limited experience: > Had the *ahem* joy of learning Perl last night. Egad. Wrote the script > in Python to get it right, and then 'translated' it to Perl. Does the > style of coding Python engenders suit the Perl environment in anyone's > experienc? AFAI can see there is no real 'style' to Perl, apart from > white noise of non alphanumeric characters. Actually, because there is "more than one way to do it", you can impose any style you want on your code, and (in my opinion) the onus _should_ be on the user to use "proper" style, however you want to define that. As Larry Wall says in the excellent "Natural Language Principals in Perl", "It's officially okay in the Perl realm to program in the subset of Perl corresponding to sed, or awk, or C, or shell, or BASIC, or Lisp or Python". > 1) I'll use Perl for the regex stuff from now on, Perl is obviously > built for this. No tool is better than Perl for that, IMO. > 2 ) There's More Than One Way To Do It makes debugging hard - i.e. > close INFILE; & close (INFILE); are both valid. I like one syntax, cos > it's easier to remember. Many people see "there's more than one way to do it" as a good thing. > 3) Some stuff is counter-intuitive - > $lenOfModList = @moddirList is the Perl equivalent of lenofModList = > len(moddirList) > @someArray = (@someArray, $newValue) is the same as someArray.append(newValue) It's only counter-intuitive if you don't know the language. Once you know the language, it's very intuitive. One could say that the theory of relativity is counter-intuitive, but to a physicist (or even anyone else who's thought about it for a while) it _is_ intuitive. It's all about context and perspective. Speaking of context, once you understand the concept of "context" in Perl, the statements above are very intuitive -- and elegant -- in my opinion. > Also, why doesn't if ( not $d eq "a" && not $d eq "c") evaluate to > true for $d = "b" when > if (not $d eq "a") evals to true and if ($d ne "a" && $d ne "c") evals > true also? What's with that? Must be an order-of-operations or logic thing, and I can assure you -- without even looking at it much -- that the problem isn't Perl's. > 4) WHAT IS WITH THE STUPID SYMBOLS EVERYWHERE LARRY??!! > > I'm not referring to the $ & @, I can see how they could be useful, > although with a list - > > @dude = (1, 2, 3), to obtain the 2nd value I would expect $d = @dude[1], > not $d = $dude[1], that's counterintuitive also. The definition of "counterintuitive" is based on context. That stuff is very intuitive when you understand the language. > Oh, no, what I'm referring to is stuff like @_, and @!, and @indexFile > = <INFILE> to read a whole file, and this - I hate Perl for this - > open OUTFILE, ">c:/python23/j/index.htm" > What's the difference between > open OUTFILE, "c:/python23/j/index.htm" and > open OUTFILE, ">c:/python23/j/index.htm" ? > > The first will open index.htm with the handle OUTFILE, to read... > The second will open index.htm with the handle OUTFILE to write!. So? That's the syntax of the language. I don't know why that would be bothersome... > Of course, the documentation I had didn't mention that. It just said > to open it and use > print FILEHANDLE $value; to write. Oh no, I had to find a CGI Perl > tutorial, which mentioned using &lst; to open and &gst; to write (or > something), which I guessed as lesser/greater than. > > Why is the read/write modifier part of the filename??? Why is it a > ? > In my opinion, there's only one place a > sign should be, in an > inequality test. Nicholas Montpetit Deluxe Business Services 651-787-1008 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050203/b4e44d35/attachment.htm From scilamed at yahoo.com Thu Feb 3 14:53:31 2005 From: scilamed at yahoo.com (alieks laouhe) Date: Thu Feb 3 14:53:36 2005 Subject: [Tutor] i have a question??? Message-ID: <20050203135332.67940.qmail@web41007.mail.yahoo.com> This is from a tutorial "EXERCISE 3.9 Use the math library to write a program to print out the sin and cos of numbers from 0 to 2pi in intervals of pi/6. You will need to use the range() function." Range won't let me use pi/6 as an incremator is there some other way i can accomplish this task im new to programming so all the help i can get is greatly appreciated. NI! alex __________________________________ Do you Yahoo!? The all-new My Yahoo! - What will yours do? http://my.yahoo.com From Nicholas.Montpetit at deluxe.com Thu Feb 3 15:03:27 2005 From: Nicholas.Montpetit at deluxe.com (Nicholas.Montpetit@deluxe.com) Date: Thu Feb 3 15:03:33 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <4201B015.7030001@speakeasy.net> Message-ID: <OF33792B19.FC9F0C7A-ON86256F9D.004B751A-86256F9D.004D18D9@deluxe.com> > (I am an ex-perler gone clean. Been straight for 5 years now with only > the occasional work forced binges.) > > Perl was designed by a linguist. He wanted it to act like human language > -- which is not very consistent. And from what I gather, quite effective. :-) > Personally, the thing that keeps me away from Perl is nested datastructures. > > Python: > > my_list = [....] > a_dict = {.....} > b_dict = {.....} > my_list.append(a_dict) > my_list.append(b_dict) > > if my_list[0].has_key("foo"): print "Yes" > > easy. Try that in Perl. OK, sounds like fun: my %a_dict = (...); my %b_dict = (...); my @my_list = (\%a_dict, \%b_dict); if (exists $my_list->[0]{foo}) print "Yes\n"; And if you want to do it another way: my @my_list = ( (...), (...) ); #define hashes in the (...)'s print "Yes\n" if (exists $my_list->[0]{foo}); Btw, I'm skeptical that the code below does what you want it to do. :-) > my @my_list; # remember those semicolons > my %a_dict, %b_dict; > push @my_list, %a_dict; > push @my_list, %b_dict; > if (exists $my_list->[0], "foo") print "Yes\n"; > # yes, references required, in Perl ick. > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050203/a3f24801/attachment.html From mi.janssen at gmail.com Thu Feb 3 15:26:31 2005 From: mi.janssen at gmail.com (Michael Janssen) Date: Thu Feb 3 15:26:34 2005 Subject: [Tutor] i have a question??? In-Reply-To: <20050203135332.67940.qmail@web41007.mail.yahoo.com> References: <20050203135332.67940.qmail@web41007.mail.yahoo.com> Message-ID: <1ff2dfbf0502030626f78d954@mail.gmail.com> On Thu, 3 Feb 2005 05:53:31 -0800 (PST), alieks laouhe <scilamed@yahoo.com> wrote: > This is from a tutorial > > "EXERCISE 3.9 > Use the math library to write a program to print out > the sin and cos of numbers from 0 to 2pi in intervals > of pi/6. You will need to use the range() function." > > Range won't let me use pi/6 as an incremator correct. The range is for integers only. You _can_ do the exercise with the range function but it would be easier without (eg. with a while-loop). Hint-no-solution: You will need a certain number of intervals, which (the number of intervalls) is plain integer. Then translate from current-intervall-number to pi'ish (sorry for that, my english ;-) value. regards Michael From pierre.barbier at cirad.fr Thu Feb 3 15:32:38 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Thu Feb 3 15:30:34 2005 Subject: [Tutor] i have a question??? In-Reply-To: <1ff2dfbf0502030626f78d954@mail.gmail.com> References: <20050203135332.67940.qmail@web41007.mail.yahoo.com> <1ff2dfbf0502030626f78d954@mail.gmail.com> Message-ID: <42023606.9000200@cirad.fr> Michael Janssen a ?crit : > On Thu, 3 Feb 2005 05:53:31 -0800 (PST), alieks laouhe > <scilamed@yahoo.com> wrote: > >>This is from a tutorial >> >>"EXERCISE 3.9 >>Use the math library to write a program to print out >>the sin and cos of numbers from 0 to 2pi in intervals >>of pi/6. You will need to use the range() function." >> >> Range won't let me use pi/6 as an incremator > > > correct. The range is for integers only. You _can_ do the exercise > with the range function but it would be easier without (eg. with a > while-loop). I disagree ... :P And your next remark makes it clear range (or even better : xrange) is exactly what's needed for that problem ! > > Hint-no-solution: You will need a certain number of intervals, which > (the number of intervalls) is plain integer. Then translate from > current-intervall-number to pi'ish (sorry for that, my english ;-) > value. > > regards > Michael -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 From jsmith at medplus.com Thu Feb 3 15:45:30 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Thu Feb 3 15:45:34 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: <C4C644CF4ADA9448904C3E8BACC4B97C02E672F6@medexch1.medplus.com> Nicholas, Well put. I come from a physics FORTRAN background and when I decided to learn C and start using it I heard the same arguments: it's too hard to read. It's a silly argument to use against a language. It's like an English-only speaker claiming he won't learn Greek because he doesn't understand it :-) I've been programming Perl for about 10 years and Python about 6 months. Most of what Python programmers find counter-intuitive about Perl seem perfectly reasonable to me and I find something in Python quite counter-intuitive although I understand the rationale. For the non-Perl people here, let me defend Perl by saying it is VERY good at what it was built for and not so good (but passable) at what it was not built for. What it is good at: Very rapid development of small scripts Replacing sed/awk/ksh/etc for scripting Manipulating strings System administration tasks What it is only passable at Large scale team development OOP Most of what Python developmers complain about in Perl are aimed at the rapid development thing. Perl is very terse which allows you do quickly script up small filters and data miners. I still use Perl for this and don't think that will ever change. Someone also complained about the "many way to exit" issue. Personally, I love that and use it to clarify my code. On a normal if statement I will put the test first: (test) && (stuff-to-do); whereas if the test will affect code flow in a more major way I use the inversion, as with: return if (test); It allows me to quickly re-read my older scripts and understand the code flow faster. Having said all that, I'm also a big fan of Python which I can see will be very good at the two things Perl isn't so good at. However (and I know most here will disagree) there's still things I don't like about Python. My top two are: 1. Lack of closure on flow statements. I've already been bitten by: if test: do this do that where "do that" should have been out-dented. For a non-Python programmer, this "feature" can lead to some very non-intuitive coding should someone be so perverse as to write it :-) 2. Lack of "use strict" semantics. I know that pychecker can supposedly do this but I still believe it belongs in the language. Don't try to defend them. I've read all the arguments but I just don't agree with the design choice. Jeff -----Original Message----- From: Nicholas.Montpetit@deluxe.com [mailto:Nicholas.Montpetit@deluxe.com] Sent: Thursday, February 03, 2005 8:43 AM To: tutor@python.org Subject: Re: [Tutor] Are you allowed to shoot camels? [kinda OT] Well, here's my $0.02. I would recommend caution regarding the trashing of Perl. One thing I've been very impressed with on this list (and other segments of the Python community) is the _fairly_ cordial relationship between the supporters of the two languages. Contrast that to a lot of PHP literature I've seen, which doesn't even acknowledge that Perl exists. My theory is that many who use PHP got kicked around by trying to learn Perl, and bitterness set in. But that's a digression... Anyway, I'm on the fence as to whether I want to learn Python (not exactly a "core competency" for statisticians, but I do line the numerical computation capabilities which look _much_ better than those of Perl), and I wouldn't want this negativity to push me (or others) away. >... Nicholas Montpetit Deluxe Business Services 651-787-1008 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050203/9c911ecf/attachment.html From Nicholas.Montpetit at deluxe.com Thu Feb 3 16:11:47 2005 From: Nicholas.Montpetit at deluxe.com (Nicholas.Montpetit@deluxe.com) Date: Thu Feb 3 16:11:55 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <C4C644CF4ADA9448904C3E8BACC4B97C02E672F6@medexch1.medplus.com> Message-ID: <OFF55EC37B.D4DBA228-ON86256F9D.005243A8-86256F9D.00535A47@deluxe.com> Hi Jeff, > Well put. I come from a physics FORTRAN background and when I > decided to learn C and start using it I heard the same arguments: > it's too hard to read. > > It's a silly argument to use against a language. It's like an > English-only speaker claiming he won't learn Greek because he > doesn't understand it :-) Now that's well put. > I've been programming Perl for about 10 years and Python about 6 > months. Most of what Python programmers find counter-intuitive > about Perl seem perfectly reasonable to me and I find something in > Python quite counter-intuitive although I understand the rationale. > > For the non-Perl people here, let me defend Perl by saying it is > VERY good at what it was built for and not so good (but passable) at > what it was not built for. > > What it is good at: > Very rapid development of small scripts > Replacing sed/awk/ksh/etc for scripting > Manipulating strings > System administration tasks > > What it is only passable at > Large scale team development > OOP I'll second your thoughts on Perl's shortcomings. What brought me to Python was the shortcomings in Perl that you've mentioned, along with Python's better numerical computation and GUI creation capabilities. If people on the list are to criticize Perl, I wish they would stick to the things that are Perl shortcomings for people who understand Perl. I'm OK with that, but I can't stand by and let people criticize something just because they don't understand it. I don't know anything about Python, so I'll reserve judgement until I do. I am confident that I will learn to like Python as much (or maybe even more :-) ) than I like Perl, and then I'll be able to choose the best tool for the task at hand. > Most of what Python developmers complain about in Perl are aimed at > the rapid development thing. Perl is very terse which allows you do > quickly script up small filters and data miners. I still use Perl > for this and don't think that will ever change. > > Someone also complained about the "many way to exit" issue. > Personally, I love that and use it to clarify my code. On a normal > if statement I will put the test first: I like the "there's more than one way to do it" thing as well. Your example below is very illustrative of that concept. > (test) && (stuff-to-do); > > whereas if the test will affect code flow in a more major way I use > the inversion, as with: > > return if (test); > > It allows me to quickly re-read my older scripts and understand the > code flow faster. One thing I really like about Python is the community: you folks are very friendly and helpful. I look forward to learning as much as I can about Python from this list! Thanks, -Nick -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050203/27cc5a1f/attachment.htm From mi.janssen at gmail.com Thu Feb 3 16:49:13 2005 From: mi.janssen at gmail.com (Michael Janssen) Date: Thu Feb 3 16:49:17 2005 Subject: [Tutor] i have a question??? In-Reply-To: <42023606.9000200@cirad.fr> References: <20050203135332.67940.qmail@web41007.mail.yahoo.com> <1ff2dfbf0502030626f78d954@mail.gmail.com> <42023606.9000200@cirad.fr> Message-ID: <1ff2dfbf05020307494d7a11a3@mail.gmail.com> [the problem provided by alieks] > >>"EXERCISE 3.9 > >>Use the math library to write a program to print out > >>the sin and cos of numbers from 0 to 2pi in intervals > >>of pi/6. You will need to use the range() function." [Michael] > > You _can_ do the exercise > > with the range function but it would be easier without (eg. with a > > while-loop). [Pierre] > I disagree ... :P And your next remark makes it clear range (or even > better : xrange) is exactly what's needed for that problem ! [Michael's next remark] > > Hint-no-solution: You will need a certain number of intervals, which > > (the number of intervalls) is plain integer. Then translate from > > current-intervall-number to pi'ish (sorry for that, my english ;-) > > value. You're right, I've described the range-solution. But what makes you think, that the range-solution is actually the best/ simplest/ easiest? Within a while-loop you would increment your variable each time by pi/6 and test if still lower-equal than 2*pi (need care for float comparision) . With range you need to compute the "certain number of intervals", then for-loop through the range-generated list and compute the "pi'ish" value. There's a loop one way or another ;-) Unless one want to add some extra exercises like list comprehension and the map function. With the while-loop, you don't need to know certainly which number of intervals are needed, you just check if the upper boundary is reached. Don't know, perhaps I should post examples but alieks might still be working on the exercise and I don't want to spoil anybodies joy for my own one ;-) So, please alieks, post your results to us! regards Michael From marilyn at deliberate.com Thu Feb 3 18:33:06 2005 From: marilyn at deliberate.com (Marilyn Davis) Date: Thu Feb 3 18:37:55 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <01f701c509ce$ab5933b0$68b78851@xp> Message-ID: <Pine.LNX.4.44.0502030931260.6017-100000@Kuna> I once heard that Larry Wall said, "Perl is worse than Python because people needed it worse". And I've heard it said that "Perl is the Write-Only language" Marilyn From scilamed at yahoo.com Thu Feb 3 19:17:55 2005 From: scilamed at yahoo.com (alieks laouhe) Date: Thu Feb 3 19:17:59 2005 Subject: [Tutor] got it In-Reply-To: <20050203154947.52E491E4004@bag.python.org> Message-ID: <20050203181755.10592.qmail@web41015.mail.yahoo.com> i came up with z=0 while z<= 2*pi: z=z+pi/6 print z z=z+pi/6 "while" makes alot more sense than using range i still don't know if its the most efficient way to do it this is day two with python, im pushing 30hrs straight lots of coffee and ciggarettes! So far I really like python...alot. it's so intuitive I started trying to learn c but it's lack of intuitive string handling made me shudder... so, i tried perl and it was a breath of fresh air after c. then i stumbled upon python. it's the most intuitive yet. anybody here have any experiance writing scripts for processing audio data? so, im glad python has alot of learning resources. thanks for your help alex __________________________________ Do you Yahoo!? The all-new My Yahoo! - What will yours do? http://my.yahoo.com From kent37 at tds.net Thu Feb 3 19:24:53 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Feb 3 19:24:56 2005 Subject: [Tutor] got it In-Reply-To: <20050203181755.10592.qmail@web41015.mail.yahoo.com> References: <20050203181755.10592.qmail@web41015.mail.yahoo.com> Message-ID: <42026C75.3000309@tds.net> alieks laouhe wrote: > i came up with > > z=0 > while z<= 2*pi: > z=z+pi/6 > print z > z=z+pi/6 I don't think you're quite there. You are incrementing by pi/6 twice in the loop, so the printed values will differ by pi/3. And the first value printed will be pi/6, not 0. Where are you getting the value of pi? You can import it from the math module with from math import pi Kent > > "while" makes alot more sense than using range > i still don't know if its the most efficient way > to do it this is day two with python, im pushing 30hrs > straight lots of coffee and ciggarettes! > So far I really like python...alot. it's so intuitive > I started trying to learn c but it's lack of intuitive > string handling made me shudder... so, i tried perl > and it was a breath of fresh air after c. > then i stumbled upon python. it's the most intuitive > yet. > anybody here have any experiance writing scripts for > processing audio data? > so, im glad python has alot of learning resources. > thanks for your help > alex > > > > __________________________________ > Do you Yahoo!? > The all-new My Yahoo! - What will yours do? > http://my.yahoo.com > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From scilamed at yahoo.com Thu Feb 3 19:26:02 2005 From: scilamed at yahoo.com (alieks laouhe) Date: Thu Feb 3 19:26:06 2005 Subject: [Tutor] oops. Message-ID: <20050203182603.40505.qmail@web41008.mail.yahoo.com> sorry way off heh... i think i'll sleep and try later. __________________________________ Do you Yahoo!? Yahoo! Mail - Easier than ever with enhanced search. Learn more. http://info.mail.yahoo.com/mail_250 From alan.gauld at freenet.co.uk Thu Feb 3 19:36:34 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Feb 3 19:35:38 2005 Subject: [Tutor] Better structure? References: <Pine.LNX.4.44.0501311447390.24680-100000@hkn.eecs.berkeley.edu> <41FF6082.70005@tds.net><000001c508cb$5a67e9f0$3b5428cf@JSLAPTOP><42003772.4010808@ccvcorp.com> <002501c508ce$294e4e10$3b5428cf@JSLAPTOP> <016a01c50904$81e75db0$68b78851@xp> <001301c5099a$df6c7dd0$145428cf@JSLAPTOP> <4201A45A.2060205@tds.net><4201A727.1040206@gmail.com> <4201A854.8000103@gmail.com> <4201ADE6.1040908@lug-delhi.org> Message-ID: <024e01c50a1f$4a4ab0c0$68b78851@xp> > > for x in string: > > if x in chars: > > string[i] = '' > > I just have a hangover from other languages, but I really wanted to know > how Python handles iteration over a variable which is being changed > within the loop itself. Is the "for" condition evaluated in every loop? Its bad practice to delete a member in the collection being iterated but Python copes OK if you just change the current item. Alan G. From scilamed at yahoo.com Thu Feb 3 19:37:20 2005 From: scilamed at yahoo.com (alieks laouhe) Date: Thu Feb 3 19:37:36 2005 Subject: [Tutor] v.00001 Message-ID: <20050203183721.32772.qmail@web41011.mail.yahoo.com> from math import * z=0 while z<=2*pi: print cos(z) z=z+(pi/6) ok i think this is right... __________________________________ Do you Yahoo!? Yahoo! Mail - You care about security. So do we. http://promotions.yahoo.com/new_mail From maxnoel_fr at yahoo.fr Thu Feb 3 19:40:53 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu Feb 3 19:40:56 2005 Subject: [Tutor] got it In-Reply-To: <20050203181755.10592.qmail@web41015.mail.yahoo.com> References: <20050203181755.10592.qmail@web41015.mail.yahoo.com> Message-ID: <c239ef280967eb0a8e0c91279699a890@yahoo.fr> On Feb 3, 2005, at 18:17, alieks laouhe wrote: > So far I really like python...alot. it's so intuitive > I started trying to learn c but it's lack of intuitive > string handling made me shudder... so, i tried perl > and it was a breath of fresh air after c. > then i stumbled upon python. it's the most intuitive > yet. C is very good for a number of things (chief among those: speed). But string manipulation is definitely not one of them. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From dyoo at hkn.eecs.berkeley.edu Thu Feb 3 19:52:09 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Feb 3 19:52:22 2005 Subject: [Tutor] In-place changes on loops In-Reply-To: <4201ADE6.1040908@lug-delhi.org> Message-ID: <Pine.LNX.4.44.0502031040130.18322-100000@hkn.eecs.berkeley.edu> On Thu, 3 Feb 2005, Sandip Bhattacharya wrote: > > for x in string: > > if x in chars: > > string[i] = '' > > I just have a hangover from other languages, but I really wanted to know > how Python handles iteration over a variable which is being changed > within the loop itself. Is the "for" condition evaluated in every loop? Hi Sandip, Strings are immutable, so the above code won't work. *grin* But let's change it to what I think you were thinking of: ### def lstrip(string, chars): scratchspace = list(string) ## get a mutable list of characters for x in scratchspace: if x in chars: scratchspace[i] = '' return ''.join(scratchspace) ### This works fine. In-place list changes that don't modify list structure will do ok. When we do structural changes to a list that we're iterating across, then we do have to be careful. The Reference Manual does mention caution near the bottom of: http://www.python.org/doc/ref/for.html When we have an statement of the form: ### Pseudocode ### for <var> in <some expresssion>: <body> ###### then Python does evaluate <some expression> just once. However, what it gets back is an "iterator", an object that marches across a sequence. For example: ### >>> message = list("this is a test") >>> iterator = iter(message) >>> iterator.next() 't' >>> iterator.next() 'h' >>> iterator.next() 'i' >>> iterator.next() 's' ### In effect, the for loop repeatedly calls next() on an iterator until it exhausts itself. The iterator doesn't try to be smart, so if we start mutating the list that backs the iterator, we do risk skipping elements. Let's try an experiment: ### >>> message = list("testing") >>> iterator = iter(message) >>> iterator.next() 't' >>> iterator.next() 'e' >>> message.insert(0, "x") >>> iterator.next() 'e' >>> iterator.next() 's' ### The 'insert()' shoves all the elements one place right. But, blissfully ignorant, the iterator doesn't shift itself, but instead stays in place. So the next call to next() revisits that 'e' character. Does this make sense? Please feel free to ask more questions about this. From dyoo at hkn.eecs.berkeley.edu Thu Feb 3 20:18:36 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Feb 3 20:18:41 2005 Subject: [Tutor] In-place changes on loops In-Reply-To: <Pine.LNX.4.44.0502031040130.18322-100000@hkn.eecs.berkeley.edu> Message-ID: <Pine.LNX.4.44.0502031101060.18322-100000@hkn.eecs.berkeley.edu> > But let's change it to what I think you were thinking of: > > ### > def lstrip(string, chars): > scratchspace = list(string) ## get a mutable list of characters > for x in scratchspace: > if x in chars: > scratchspace[i] = '' > return ''.join(scratchspace) > ### > > This works fine. Hi Sandip, Doh. I hate people who make blanket assertions like that without even doing a minimal test. Even if it is myself. *grin* The code above is just broken, since there is no index 'i'. Let me try to fix it. ### def lstrip(string, chars): scratchspace = list(string) ## get a mutable list of characters for (i, x) in enumerate(scratchspace): if x in chars: scratchspace[i] = '' return ''.join(scratchspace) ### I'm not going to make the same mistake twice: we're going to test this sucker. *grin* ### >>> lstrip("hello world", "he") 'llo world' >>> lstrip("hello world", "eh") 'llo world' ### Everything looks peachy... except: ### >>> lstrip("hello world", "aeiou") 'hll wrld' ### Ah! That's not right either! Ok, one more time: ### def lstrip(string, chars): scratchspace = list(string) ## get a mutable list of characters for (i, x) in enumerate(scratchspace): if x in chars: scratchspace[i] = '' else: break return ''.join(scratchspace) ### Quick sanity check: ### >>> lstrip("hello world", "eh") 'llo world' >>> lstrip("hello world", "he") 'llo world' >>> lstrip("hello world", "aeiou") 'hello world' ### Finally. *grin* Anyway, I wanted to apologize; I should have tested my code. From dyoo at hkn.eecs.berkeley.edu Thu Feb 3 20:29:56 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Feb 3 20:30:00 2005 Subject: [Tutor] v.00001 In-Reply-To: <20050203183721.32772.qmail@web41011.mail.yahoo.com> Message-ID: <Pine.LNX.4.44.0502031056040.18322-100000@hkn.eecs.berkeley.edu> On Thu, 3 Feb 2005, alieks laouhe wrote: > from math import * > z=0 > while z<=2*pi: > print cos(z) > z=z+(pi/6) > > ok i think this is right... Hi Alieks, This looks ok, and is probably the most straightforward way to do this. For safety's sake, you may want to modify the top import statement from: ### from math import * ### to something a little more limited: ### from math import pi, cos ### The reason is because the other form, the one with the '*', pulls everything into the current namespace, and that can be problematic in larger programs. There's a note about it here: http://www.python.org/doc/tut/node8.html#SECTION008410000000000000000 There are some cute things we can do with some advanced Python. You don't have to understand this yet, but here's a variation of your program: ### >>> def stepper(start, end, step): ... i = start ... while i <= end: ... yield i ... i = i + step ... >>> from math import pi, cos >>> for z in stepper(0, 2*pi, pi/6): ... print z, cos(z) ... 0 1.0 0.523598775598 0.866025403784 1.0471975512 0.5 1.57079632679 6.12303176911e-17 2.09439510239 -0.5 2.61799387799 -0.866025403784 3.14159265359 -1.0 3.66519142919 -0.866025403784 4.18879020479 -0.5 4.71238898038 -1.83690953073e-16 5.23598775598 0.5 5.75958653158 0.866025403784 ### stepper() acts like the range() function, but it can work on floating point numbers. range (and xrange) only work on integers: http://www.python.org/doc/lib/built-in-funcs.html#l2h-56 If we want to do some stepping across a range with floats, we can use the stepper() definition above. Best of wishes to you! From shaleh at speakeasy.net Thu Feb 3 20:42:32 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Thu Feb 3 20:42:56 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <OF33792B19.FC9F0C7A-ON86256F9D.004B751A-86256F9D.004D18D9@deluxe.com> References: <OF33792B19.FC9F0C7A-ON86256F9D.004B751A-86256F9D.004D18D9@deluxe.com> Message-ID: <42027EA8.4020603@speakeasy.net> Nicholas.Montpetit@deluxe.com wrote: > > > Btw, I'm skeptical that the code below does what you want it to do. :-) > that was kind of my point. In python I just type the obvious and it works. In Perl I have to muck with references, slashes, arrows and the like. Every time I have had to write a nested datastructure I have spent my time debugging that structure. From bill.mill at gmail.com Thu Feb 3 21:27:32 2005 From: bill.mill at gmail.com (Bill Mill) Date: Thu Feb 3 21:28:24 2005 Subject: [Tutor] Re: Are you allowed to shoot camels? [kinda OT] In-Reply-To: <6465924d050203012479ff6970@mail.gmail.com> References: <f2ff2d0502021518547f14c0@mail.gmail.com> <01f701c509ce$ab5933b0$68b78851@xp> <ctspmt$5ug$1@sea.gmane.org> <6465924d050203012479ff6970@mail.gmail.com> Message-ID: <797fe3d40502031227485be921@mail.gmail.com> On Thu, 3 Feb 2005 04:24:06 -0500, Patrick Hall <pathall@gmail.com> wrote: > > Beware! Overcome the temptation! > > Try this: http://kodos.sourceforge.net/ > > While I have no problem personally with Perl or PHP, I'll second the > recommendation for kodos -- it's very useful for learning to use > regexes in Python. Ok, I have to ask: why? Whenever I write and debug regexes (as I had to do this morning for the first time in a while - I try to avoid them) I always create a function in the interpreter that looks like: def test(regex, line): print re.compile(regex).match(line).groups() and then test my regexes incrementally: >>>l = '8 this is my line to test' >>> test('^\s*(\d)+', l) until I have it right. How is using this tool easier than that? Peace Bill Mill bill.mill at gmail.com > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From Nicholas.Montpetit at deluxe.com Thu Feb 3 21:30:53 2005 From: Nicholas.Montpetit at deluxe.com (Nicholas.Montpetit@deluxe.com) Date: Thu Feb 3 21:30:59 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <42027EA8.4020603@speakeasy.net> Message-ID: <OFE01B2208.7A4F96B9-ON86256F9D.00706470-86256F9D.00709147@deluxe.com> > Nicholas.Montpetit@deluxe.com wrote: > > > > > > Btw, I'm skeptical that the code below does what you want it to do. :-) > > > > that was kind of my point. In python I just type the obvious and it > works. In Perl I have to muck with references, slashes, arrows and the > like. Every time I have had to write a nested datastructure I have spent > my time debugging that structure. Same here, Sean: whenever I work with nested data structures, I end up doing some debugging. However, I think that has more to do with my less-than-perfect understanding of references than with any Perl shortcomings. -Nick -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050203/96d02212/attachment.html From keridee at jayco.net Thu Feb 3 22:04:25 2005 From: keridee at jayco.net (Jacob S.) Date: Thu Feb 3 22:05:34 2005 Subject: [Tutor] i have a question??? References: <20050203135332.67940.qmail@web41007.mail.yahoo.com> Message-ID: <001601c50a34$2b196970$3d5328cf@JSLAPTOP> >From what I understand, range() no longer allows you to use floats as arguments. (Or it gives you a deprication warning) This tutorial must be old. Not the only way, but. import math num = 0 while num <= 2*math.pi: ## Do stuff to figure pi/6 things num = num + math.pi/6.0 ## Don't forget .0 or you'll get an integer result. print ## Result thingy Another way is to use Numarry (Numeric) arange() but that takes extra work. ;-) Jacob > This is from a tutorial > > "EXERCISE 3.9 > Use the math library to write a program to print out > the sin and cos of numbers from 0 to 2pi in intervals > of pi/6. You will need to use the range() function." > > Range won't let me use pi/6 as an incremator > is there some other way i can accomplish this task > im new to programming so all the help i can get is > greatly appreciated. > NI! > alex > > > > > __________________________________ > Do you Yahoo!? > The all-new My Yahoo! - What will yours do? > http://my.yahoo.com > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From keridee at jayco.net Thu Feb 3 22:07:04 2005 From: keridee at jayco.net (Jacob S.) Date: Thu Feb 3 22:06:59 2005 Subject: [Tutor] Better structure? References: <Pine.LNX.4.44.0501311447390.24680-100000@hkn.eecs.berkeley.edu> <41FF6082.70005@tds.net><000001c508cb$5a67e9f0$3b5428cf@JSLAPTOP><42003772.4010808@ccvcorp.com> <002501c508ce$294e4e10$3b5428cf@JSLAPTOP> <016a01c50904$81e75db0$68b78851@xp> <001301c5099a$df6c7dd0$145428cf@JSLAPTOP> <4201A45A.2060205@tds.net><4201A727.1040206@gmail.com><4201A854.8000103@gmail.com> <4201ADE6.1040908@lug-delhi.org> <024e01c50a1f$4a4ab0c0$68b78851@xp> Message-ID: <001901c50a34$5b58f1a0$3d5328cf@JSLAPTOP> You can also iterate over a copy of the list and change the original. i.e. a = range(10) for x in a[:]: if x % 2 == 0: a.remove(x) print a And yes, I did test it this time. Jacob > >> > for x in string: >> > if x in chars: >> > string[i] = '' >> >> I just have a hangover from other languages, but I really wanted to > know >> how Python handles iteration over a variable which is being changed >> within the loop itself. Is the "for" condition evaluated in every > loop? > > Its bad practice to delete a member in the collection being iterated > but Python copes OK if you just change the current item. > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From keridee at jayco.net Thu Feb 3 22:11:39 2005 From: keridee at jayco.net (Jacob S.) Date: Thu Feb 3 22:11:59 2005 Subject: [Tutor] v.00001 References: <Pine.LNX.4.44.0502031056040.18322-100000@hkn.eecs.berkeley.edu> Message-ID: <002901c50a34$f9e5a0c0$3d5328cf@JSLAPTOP> I should have thought of that! Here I looked at the concept of generators, what they can do, and totally overlooked a user defined range type function that allows floats. Any reason why range doesn't? Is it for speed, or to keep the arguments pure (without floating point errors)? Jacob > There are some cute things we can do with some advanced Python. You don't > have to understand this yet, but here's a variation of your program: > > ### >>>> def stepper(start, end, step): > ... i = start > ... while i <= end: > ... yield i > ... i = i + step > ... >>>> from math import pi, cos >>>> for z in stepper(0, 2*pi, pi/6): > ... print z, cos(z) > ... > 0 1.0 > 0.523598775598 0.866025403784 > 1.0471975512 0.5 > 1.57079632679 6.12303176911e-17 > 2.09439510239 -0.5 > 2.61799387799 -0.866025403784 > 3.14159265359 -1.0 > 3.66519142919 -0.866025403784 > 4.18879020479 -0.5 > 4.71238898038 -1.83690953073e-16 > 5.23598775598 0.5 > 5.75958653158 0.866025403784 > ### > > > stepper() acts like the range() function, but it can work on floating > point numbers. range (and xrange) only work on integers: > > http://www.python.org/doc/lib/built-in-funcs.html#l2h-56 > > If we want to do some stepping across a range with floats, we can use the > stepper() definition above. > > > Best of wishes to you! > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From miles at mstevenson.org Thu Feb 3 22:13:45 2005 From: miles at mstevenson.org (Miles Stevenson) Date: Thu Feb 3 22:12:14 2005 Subject: [Tutor] Ogg Tag Module recommendations Message-ID: <200502031613.48146.miles@mstevenson.org> Can anyone recommend to me a Python module to work with ID3v2 tags in Ogg Vorbis files? I tried using the EyeD3 module, but it only supports mp3 right now, and I couldn't get the pyid3tag module to work reliably, or I'm just not understanding the documentation. I just need to retrieve all of the ID3v2 tag info from a collection of ogg files, store them in a file, and then insert them back into different ogg files. Anyone have a module/library they recommend? Thanks. -- Miles Stevenson miles@mstevenson.org PGP FP: 035F 7D40 44A9 28FA 7453 BDF4 329F 889D 767D 2F63 -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050203/aca7aa4b/attachment.pgp From ternary at gmail.com Thu Feb 3 22:30:42 2005 From: ternary at gmail.com (Mike Bell) Date: Thu Feb 3 22:30:46 2005 Subject: [Tutor] i have a question??? In-Reply-To: <001601c50a34$2b196970$3d5328cf@JSLAPTOP> References: <20050203135332.67940.qmail@web41007.mail.yahoo.com> <001601c50a34$2b196970$3d5328cf@JSLAPTOP> Message-ID: <82975b0c050203133067f1d002@mail.gmail.com> > num = num + math.pi/6.0 ## Don't forget .0 or you'll get an integer the division operator returns a float when either of the operands are floats -- in this case math.pi is, so you don't have to worry about passing it 6.0 instead of 6 >>> import math >>> math.pi 3.1415926535897931 >>> math.pi / 6 0.52359877559829882 >>> type(math.pi) <type 'float'> >>> type(6) <type 'int'> >>> type(6.0) <type 'float'> mike On Thu, 3 Feb 2005 16:04:25 -0500, Jacob S. <keridee@jayco.net> wrote: > >From what I understand, range() no longer allows you to use floats as > arguments. (Or it gives you a deprication warning) > This tutorial must be old. > > Not the only way, but. > > import math > num = 0 > while num <= 2*math.pi: > ## Do stuff to figure pi/6 things > > num = num + math.pi/6.0 ## Don't forget .0 or you'll get an integer > result. > print ## Result thingy > > Another way is to use Numarry (Numeric) arange() but that takes extra work. > ;-) > Jacob > > > > This is from a tutorial > > > > "EXERCISE 3.9 > > Use the math library to write a program to print out > > the sin and cos of numbers from 0 to 2pi in intervals > > of pi/6. You will need to use the range() function." > > > > Range won't let me use pi/6 as an incremator > > is there some other way i can accomplish this task > > im new to programming so all the help i can get is > > greatly appreciated. > > NI! > > alex > > > > > > > > > > __________________________________ > > Do you Yahoo!? > > The all-new My Yahoo! - What will yours do? > > http://my.yahoo.com > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From shaleh at speakeasy.net Thu Feb 3 22:34:10 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Thu Feb 3 22:34:31 2005 Subject: [Tutor] Ogg Tag Module recommendations In-Reply-To: <200502031613.48146.miles@mstevenson.org> References: <200502031613.48146.miles@mstevenson.org> Message-ID: <420298D2.9060607@speakeasy.net> Miles Stevenson wrote: > Can anyone recommend to me a Python module to work with ID3v2 tags in Ogg > Vorbis files? I tried using the EyeD3 module, but it only supports mp3 right > now, and I couldn't get the pyid3tag module to work reliably, or I'm just not > understanding the documentation. > > I just need to retrieve all of the ID3v2 tag info from a collection of ogg > files, store them in a file, and then insert them back into different ogg > files. Anyone have a module/library they recommend? > The Ogg guys actually made a wrapper for Python, pyvorbis I think it is called. From keridee at jayco.net Thu Feb 3 22:40:24 2005 From: keridee at jayco.net (Jacob S.) Date: Thu Feb 3 22:40:14 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <C4C644CF4ADA9448904C3E8BACC4B97C02E672F6@medexch1.medplus.com> Message-ID: <007c01c50a38$fecfba40$3d5328cf@JSLAPTOP> MessageI hate to be a spoiled sport and do exactly what you said to not do. But I present two counter examples 1. The indentation IS the closure on flow statements. Indenting starts a flow, then removing indentation on next line closes the flow. Again its all about the language. If your English then don't look at Greek words and not want to learn them because you don't understand them. 2. The lack of "use strict semantics" is just one python's ways of using the term "There is more than one way to do it" Sorry, Jacob 1. Lack of closure on flow statements. I've already been bitten by: if test: do this do that where "do that" should have been out-dented. For a non-Python programmer, this "feature" can lead to some very non-intuitive coding should someone be so perverse as to write it :-) 2. Lack of "use strict" semantics. I know that pychecker can supposedly do this but I still believe it belongs in the language. Don't try to defend them. I've read all the arguments but I just don't agree with the design choice. Jeff -----Original Message----- From: Nicholas.Montpetit@deluxe.com [mailto:Nicholas.Montpetit@deluxe.com] Sent: Thursday, February 03, 2005 8:43 AM To: tutor@python.org Subject: Re: [Tutor] Are you allowed to shoot camels? [kinda OT] Well, here's my $0.02. I would recommend caution regarding the trashing of Perl. One thing I've been very impressed with on this list (and other segments of the Python community) is the _fairly_ cordial relationship between the supporters of the two languages. Contrast that to a lot of PHP literature I've seen, which doesn't even acknowledge that Perl exists. My theory is that many who use PHP got kicked around by trying to learn Perl, and bitterness set in. But that's a digression... Anyway, I'm on the fence as to whether I want to learn Python (not exactly a "core competency" for statisticians, but I do line the numerical computation capabilities which look _much_ better than those of Perl), and I wouldn't want this negativity to push me (or others) away. >... Nicholas Montpetit Deluxe Business Services 651-787-1008 _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From jeff at ccvcorp.com Thu Feb 3 22:59:38 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu Feb 3 22:58:55 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <93fef199885ae5cf5b466c6e0e724ae5@yahoo.fr> References: <f2ff2d0502021518547f14c0@mail.gmail.com><86626245450c1bfcf3190400baffe178@yahoo.fr><9bb26ab5f9c3d8166f27d39464b9c750@yahoo.fr><f2ff2d0502021642627b77ee@mail.gmail.com> <56abcbca5acfdc78d0b13c480c1af850@yahoo.fr> <021301c509d5$89daa960$68b78851@xp> <93fef199885ae5cf5b466c6e0e724ae5@yahoo.fr> Message-ID: <42029ECA.2070305@ccvcorp.com> Max Noel wrote: > On Feb 3, 2005, at 09:48, Alan Gauld wrote: > >> Pythons lambda feature is a bare minimum (and Guido wants to remove >> it!). > > Does he? Damn, just when I was learning functional programming! (in > Haskell, if you're curious ^^) However, Python doesn't need lambdas to be able to write in a functional style. Functions are first-class objects and can be passed around quite easily, and IIRC Python's list comprehensions were borrowed (though probably with notable modification) from Haskell. Keep in mind that both lambdas and named functions are created at runtime, so the creation of both is fully dynamic. Indeed, there are only a few differences between lambdas and named functions in Python: - Anonymous vs named - Single expression vs suite of statements - Inline vs. pre-created Note that the second of these is a consequence of the third -- given Python's block-indentation-based structure, there's no good way to inline a multi-statement suite (how many of those statements belong to that 'if' suite?). Statements need to have a clear indentation level, and while one can sometimes fudge that for a single statement, it gets exponentially messier as the number of statements goes up. I'd also argue that the inline nature is the *true* differentiating feature of lambdas -- the fact that they're anonymous is relatively minor. Consider, also, that if they weren't inline then you'd need a name to refer to them by... and at that point, you *have* a 'normal' function. So, while there are some advantages to having single-use callables be defined inline (i.e. lambdas), their removal from Python (which wouldn't happen before the mythical Python 3k anyhow) isn't likely to be as devastating as some might lead you to believe. ;) It certainly won't prevent you from using Python for functional programming... (And personally, I suspect that if lambdas *are* removed, they will be replaced with a different construct that will fill the same needs in a more Pythonic way...) Jeff Shannon Technician/Programmer Credit International From shaleh at speakeasy.net Thu Feb 3 23:10:07 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Thu Feb 3 23:10:28 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <42029ECA.2070305@ccvcorp.com> References: <f2ff2d0502021518547f14c0@mail.gmail.com><86626245450c1bfcf3190400baffe178@yahoo.fr><9bb26ab5f9c3d8166f27d39464b9c750@yahoo.fr><f2ff2d0502021642627b77ee@mail.gmail.com> <56abcbca5acfdc78d0b13c480c1af850@yahoo.fr> <021301c509d5$89daa960$68b78851@xp> <93fef199885ae5cf5b466c6e0e724ae5@yahoo.fr> <42029ECA.2070305@ccvcorp.com> Message-ID: <4202A13F.70109@speakeasy.net> Jeff Shannon wrote: > > However, Python doesn't need lambdas to be able to write in a functional > style. Functions are first-class objects and can be passed around quite > easily, and IIRC Python's list comprehensions were borrowed (though > probably with notable modification) from Haskell. > Note, it is haskell convention to name a list of objects with a plural. So xs -> list of x. haskell: [ x | x <- xs ] [ foo x | x <- xs, x > 2 ] python [ x for x in xs ] [ foo(x) for x in xs if x > 2 ] shaleh still mastering haskell, but loving it. Like python for functional languages. From alan.gauld at freenet.co.uk Thu Feb 3 23:13:52 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Feb 3 23:12:57 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <OFF55EC37B.D4DBA228-ON86256F9D.005243A8-86256F9D.00535A47@deluxe.com> Message-ID: <02b101c50a3d$a5574550$68b78851@xp> > > For the non-Perl people here, let me defend Perl by saying it is > > VERY good at what it was built for and not so good (but passable) at > > what it was not built for. > > > > What it is good at: > > Very rapid development of small scripts > > Replacing sed/awk/ksh/etc for scripting > > Manipulating strings > > System administration tasks Absolutely true and the reason I used Perl for several years before I used Python - even though I was aware of Python and had even fired up the interpreter a couple of times. But then I had the advantage of using C and C++ and Pascal(Delphi) and Lisp and Smalltalk for more complex programs. And I still used awk because Perl makes a lousy awk replacement! But as a shell replacement its great, and for string manipulation only Snoball beats it. The only reason I initially took Python seriously was as a teaching language for my tutorial, but once I got into it I realised it was a lot more powerful than I had originally thought. > > What it is only passable at > > Large scale team development > > OOP Passable is optimistic, I used Perl with a team of only 6 programmers and it was a disaster! > > Most of what Python developmers complain about in Perl are aimed at > > the rapid development thing. Perl is very terse which allows you do > > quickly script up small filters and data miners. I still use Perl > > for this and don't think that will ever change. Absolutely and I agree. The things I don't like are not the rapid development things, the $,@ symbology is completely unnecessary and is extremely counter intuitive even for experienced Perl coders. We still have arguments about references versus scalars etc yet after 10 years of using Perl in prodsuction code... It was a side effct of shell programming that should never have happened (although I will grant it yields a marginal speed increase by improving optimisation in the compiler!) > > Someone also complained about the "many way to exit" issue. > > Personally, I love that and use it to clarify my code. On a normal > > if statement I will put the test first: And for one person projects, where a consistent style is used its fine, but the minute you get beyond small projects its another complication waiting to bite. But again thats Perls background showing through. Python was never intended just for quick n dirty scripting it was from the outset designed as a general purpose language so embodied "best practice" - or Guidos take on that - as discovered by computer science research. Larry Wall simply created a language to do a job, it turned out to be powerful and got used a lot more than he expected! There is no perfect language, and very few truly bad languages - they never get out of the lab - they all have something that they are good at and from which we can learn! Alan G. From jsmith at medplus.com Thu Feb 3 23:21:51 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Thu Feb 3 23:21:55 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: <C4C644CF4ADA9448904C3E8BACC4B97C02E67387@medexch1.medplus.com> Jacob, As I said I'm well aware of the defense of these peculiarities of Python but I still disagree with them from a language design choice. That doesn't stop me from learning and using and enjoying Python but I feel that both of them introduce some instability to the langauge. In only 6 months of programming, I've already seen one case where if test: this that Was accidentally coded if test: this that (In fact, I suspect variations on this this may be the reason for the line spacing suggestions in PEP-8.) I've also seen several cases where an unbound variable caused an exception at runtime. True, these could be caught by extensive unit testing but know the reality of that happening :-) Perl and Python both resist the introduction of a switch statement which I (and many others) feel is the most elegant way to express what it does. I also wish Python would take up the C ternary operator which is also quite clear and elegant. Of course, there are things I disklike about every other language I've used. To paraphrase the famous quote: There are no good programming languages, just some that aren't as bad in some situations. Jeff -----Original Message----- From: Jacob S. [mailto:keridee@jayco.net] Sent: Thursday, February 03, 2005 4:40 PM To: Smith, Jeff; Nicholas.Montpetit@deluxe.com; tutor@python.org Subject: Re: [Tutor] Are you allowed to shoot camels? [kinda OT] MessageI hate to be a spoiled sport and do exactly what you said to not do. But I present two counter examples 1. The indentation IS the closure on flow statements. Indenting starts a flow, then removing indentation on next line closes the flow. Again its all about the language. If your English then don't look at Greek words and not want to learn them because you don't understand them. 2. The lack of "use strict semantics" is just one python's ways of using the term "There is more than one way to do it" Sorry, Jacob 1. Lack of closure on flow statements. I've already been bitten by: if test: do this do that where "do that" should have been out-dented. For a non-Python programmer, this "feature" can lead to some very non-intuitive coding should someone be so perverse as to write it :-) 2. Lack of "use strict" semantics. I know that pychecker can supposedly do this but I still believe it belongs in the language. Don't try to defend them. I've read all the arguments but I just don't agree with the design choice. Jeff -----Original Message----- From: Nicholas.Montpetit@deluxe.com [mailto:Nicholas.Montpetit@deluxe.com] Sent: Thursday, February 03, 2005 8:43 AM To: tutor@python.org Subject: Re: [Tutor] Are you allowed to shoot camels? [kinda OT] Well, here's my $0.02. I would recommend caution regarding the trashing of Perl. One thing I've been very impressed with on this list (and other segments of the Python community) is the _fairly_ cordial relationship between the supporters of the two languages. Contrast that to a lot of PHP literature I've seen, which doesn't even acknowledge that Perl exists. My theory is that many who use PHP got kicked around by trying to learn Perl, and bitterness set in. But that's a digression... Anyway, I'm on the fence as to whether I want to learn Python (not exactly a "core competency" for statisticians, but I do line the numerical computation capabilities which look _much_ better than those of Perl), and I wouldn't want this negativity to push me (or others) away. >... Nicholas Montpetit Deluxe Business Services 651-787-1008 _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From jsmith at medplus.com Thu Feb 3 23:27:26 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Thu Feb 3 23:27:31 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: <C4C644CF4ADA9448904C3E8BACC4B97C02E67388@medexch1.medplus.com> Alan, We'll just have to have to disagree about awk. I starting learning Perl to avoid learning awk :-) I also disagree about the symbology. I am never confused by it. In fact, I find it clarifies the language although I agree its ugly. When I see a random variable in Perl I can tell at a glance whether it's a scalar, list, or hash. That isn't true in Python (or most other languages). I realize that doesn't mean much in large OOP programs but in medium to large single-purpose scripts it does simplify debugging and maintenance. Jeff -----Original Message----- From: Alan Gauld [mailto:alan.gauld@freenet.co.uk] Sent: Thursday, February 03, 2005 5:14 PM To: Nicholas.Montpetit@deluxe.com; Smith, Jeff Cc: tutor@python.org; tutor-bounces@python.org Subject: Re: [Tutor] Are you allowed to shoot camels? [kinda OT] > > For the non-Perl people here, let me defend Perl by saying it is > > VERY good at what it was built for and not so good (but passable) at > > what it was not built for. > > > > What it is good at: > > Very rapid development of small scripts > > Replacing sed/awk/ksh/etc for scripting > > Manipulating strings > > System administration tasks Absolutely true and the reason I used Perl for several years before I used Python - even though I was aware of Python and had even fired up the interpreter a couple of times. But then I had the advantage of using C and C++ and Pascal(Delphi) and Lisp and Smalltalk for more complex programs. And I still used awk because Perl makes a lousy awk replacement! But as a shell replacement its great, and for string manipulation only Snoball beats it. The only reason I initially took Python seriously was as a teaching language for my tutorial, but once I got into it I realised it was a lot more powerful than I had originally thought. > > What it is only passable at > > Large scale team development > > OOP Passable is optimistic, I used Perl with a team of only 6 programmers and it was a disaster! > > Most of what Python developmers complain about in Perl are aimed at > > the rapid development thing. Perl is very terse which allows you do > > quickly script up small filters and data miners. I still use Perl > > for this and don't think that will ever change. Absolutely and I agree. The things I don't like are not the rapid development things, the $,@ symbology is completely unnecessary and is extremely counter intuitive even for experienced Perl coders. We still have arguments about references versus scalars etc yet after 10 years of using Perl in prodsuction code... It was a side effct of shell programming that should never have happened (although I will grant it yields a marginal speed increase by improving optimisation in the compiler!) > > Someone also complained about the "many way to exit" issue. > > Personally, I love that and use it to clarify my code. On a normal > > if statement I will put the test first: And for one person projects, where a consistent style is used its fine, but the minute you get beyond small projects its another complication waiting to bite. But again thats Perls background showing through. Python was never intended just for quick n dirty scripting it was from the outset designed as a general purpose language so embodied "best practice" - or Guidos take on that - as discovered by computer science research. Larry Wall simply created a language to do a job, it turned out to be powerful and got used a lot more than he expected! There is no perfect language, and very few truly bad languages - they never get out of the lab - they all have something that they are good at and from which we can learn! Alan G. From maxnoel_fr at yahoo.fr Thu Feb 3 23:39:54 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu Feb 3 23:40:03 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <C4C644CF4ADA9448904C3E8BACC4B97C02E67387@medexch1.medplus.com> References: <C4C644CF4ADA9448904C3E8BACC4B97C02E67387@medexch1.medplus.com> Message-ID: <03069c6c3fc10b69ddf897e517d944e6@yahoo.fr> On Feb 3, 2005, at 22:21, Smith, Jeff wrote: > Perl and Python both resist the introduction of a switch statement > which > I (and many others) feel is the most elegant way to express what it > does. I echo that. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From alan.gauld at freenet.co.uk Thu Feb 3 23:47:21 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Feb 3 23:46:25 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <C4C644CF4ADA9448904C3E8BACC4B97C02E67388@medexch1.medplus.com> Message-ID: <02ee01c50a42$52f6ea40$68b78851@xp> > I also disagree about the symbology. I am never confused by it. I'll believe you, but its interesting that computer scientists have done lots of studies to test people's comprehension of programs and in every single case there has been clear evidence that additional prefixes/characters etc obscure undestanding. Even by those who thought they were fluent in the language concerned. Check the book Code Complete for some references, or try searching the Software Engineering Institute stuff at CMU. Its like the old argument in C over whether int f(){ blah() } or int f() { blah() } was clearer. Many people claim to prefer the second but objective testing repeatedly shows that the first form produces measurably better results. In both of these cases its not about style its about what works. I suspect Guido was aware of that research and applied it to Python's design. Larry wasn't and didn't... (although he sure is now! :-) Alan G. From jsmith at medplus.com Thu Feb 3 23:49:20 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Thu Feb 3 23:49:31 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: <C4C644CF4ADA9448904C3E8BACC4B97C02E6738B@medexch1.medplus.com> I think the point is that different people are...different. It probably won't surprise you to find out that I am in the C camp that prefers your second example. I'm sure what those studies show is what the "majority" find easier not what "everyone" finds easier. Who knows, maybe it's a left-brain, right-brain thing. And it wouldn't be the first time I was told my brain was "wired differently" from the general public. Just ask my wife :-) Jeff -----Original Message----- From: Alan Gauld [mailto:alan.gauld@freenet.co.uk] Sent: Thursday, February 03, 2005 5:47 PM To: Smith, Jeff; Nicholas.Montpetit@deluxe.com Cc: tutor@python.org; tutor-bounces@python.org Subject: Re: [Tutor] Are you allowed to shoot camels? [kinda OT] > I also disagree about the symbology. I am never confused by it. I'll believe you, but its interesting that computer scientists have done lots of studies to test people's comprehension of programs and in every single case there has been clear evidence that additional prefixes/characters etc obscure undestanding. Even by those who thought they were fluent in the language concerned. Check the book Code Complete for some references, or try searching the Software Engineering Institute stuff at CMU. Its like the old argument in C over whether int f(){ blah() } or int f() { blah() } was clearer. Many people claim to prefer the second but objective testing repeatedly shows that the first form produces measurably better results. In both of these cases its not about style its about what works. I suspect Guido was aware of that research and applied it to Python's design. Larry wasn't and didn't... (although he sure is now! :-) Alan G. From lumbricus at gmx.net Fri Feb 4 00:10:32 2005 From: lumbricus at gmx.net (lumbricus@gmx.net) Date: Fri Feb 4 00:10:34 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <C4C644CF4ADA9448904C3E8BACC4B97C02E67388@medexch1.medplus.com> Message-ID: <24692.1107472232@www13.gmx.net> > Alan, > > We'll just have to have to disagree about awk. I starting learning Perl > to avoid learning awk :-) But awk is smaller and simpler than perl. So it should be faster (esp. at startup) for small and simple tasks. As usual: Right tool for right task. > Jeff _______________ Greetings, J"o! (being glad to have a choice) -- Wir sind jetzt ein Imperium und wir schaffen uns unsere eigene Realitaet. Wir sind die Akteure der Geschichte, und Ihnen, Ihnen allen bleibt nichts, als die Realitaet zu studieren, die wir geschaffen haben. -- Karl Rove zu Ron Suskind (NYT) DSL Komplett von GMX +++ Supergünstig und stressfrei einsteigen! AKTION "Kein Einrichtungspreis" nutzen: http://www.gmx.net/de/go/dsl From alan.gauld at freenet.co.uk Fri Feb 4 00:17:11 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 00:16:19 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <f2ff2d0502021518547f14c0@mail.gmail.com><86626245450c1bfcf3190400baffe178@yahoo.fr><9bb26ab5f9c3d8166f27d39464b9c750@yahoo.fr><f2ff2d0502021642627b77ee@mail.gmail.com> <56abcbca5acfdc78d0b13c480c1af850@yahoo.fr> <021301c509d5$89daa960$68b78851@xp><93fef199885ae5cf5b466c6e0e724ae5@yahoo.fr> <42029ECA.2070305@ccvcorp.com> Message-ID: <02ff01c50a46$7d75d570$68b78851@xp> > >> Pythons lambda feature is a bare minimum (and Guido wants to remove > >> it!). > However, Python doesn't need lambdas to be able to write in a > functional style. I disagree Jeff. It does need lambdas to do FP properly, and better lambdas than we have currently. What it doesn't need is the lambda keyword and syntax - although pesonally I like lambda since it is descriptive! > Functions are first-class objects and can be passed > around quite easily, Yes, but lambdas are more than first class functions, they are anonymous functions! In fact really just callable code blocks, not necessarily functions in the strictest sense (except that every callable in FP is a function...! ;-) Having to define every function before using it would be a big hassle and make code less readable IMHO. > borrowed (though probably with notable modification) from Haskell. Conceptually not much modification, but the two syntaxes are poles apart! > only a few differences between lambdas and named functions in Python: > > - Anonymous vs named the key feature > - Single expression vs suite of statements A python restriction. > - Inline vs. pre-created A key usage point > Note that the second of these is a consequence of the third Again a Python restriction. And hard to see how you avoid given Pythons structure. > I'd also argue that the inline nature is the *true* differentiating > feature of lambdas -- the fact that they're anonymous is relatively > minor. I agree, if I had an inline mechanism that forced me to provide a name I could just use 'f' over and over and not feel too cheated, but its nicer not to have an artificial name when theres no need. > So, while there are some advantages to having single-use callables be > defined inline The other advantage is the huge conceptial advantage that real lambdas confer. The breakthrough idea of def f(x): return x+x being the same as f = lambda x: x+x is only possible to demonstrate if you have lambda to start with. And yet that concept of a function name being just another variable and the callable code being an object in its own right becomes much more obvious in my opinion. lambda is a learning tool which shows what is really happening whereas def is just syntactic sugar. > (And personally, I suspect that if lambdas *are* removed, they will be > replaced with a different construct that will fill the same needs in a > more Pythonic way...) I believe (and hope) this too. Certainly the stink it has created on c.l.p should hopefully convince Guido that there is a groundswell of demand for the facility if not the name... Alan G. From alan.gauld at freenet.co.uk Fri Feb 4 00:19:15 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 00:21:14 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <f2ff2d0502021518547f14c0@mail.gmail.com><86626245450c1bfcf3190400baffe178@yahoo.fr><9bb26ab5f9c3d8166f27d39464b9c750@yahoo.fr><f2ff2d0502021642627b77ee@mail.gmail.com> <56abcbca5acfdc78d0b13c480c1af850@yahoo.fr> <021301c509d5$89daa960$68b78851@xp> <93fef199885ae5cf5b466c6e0e724ae5@yahoo.fr><42029ECA.2070305@ccvcorp.com> <4202A13F.70109@speakeasy.net> Message-ID: <030401c50a46$c7d41280$68b78851@xp> > haskell: > > [ x | x <- xs ] > [ foo x | x <- xs, x > 2 ] > > python > > [ x for x in xs ] > [ foo(x) for x in xs if x > 2 ] > Sean, what book/tutor are you using for Haskell? I learned it from "The Haskell School of Expression" which was OK but very graphics focused, I'd be interested in recommended second source on Haskell. Alan G. From alan.gauld at freenet.co.uk Fri Feb 4 00:28:36 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 00:27:35 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <C4C644CF4ADA9448904C3E8BACC4B97C02E67387@medexch1.medplus.com> Message-ID: <030b01c50a48$15e2df00$68b78851@xp> > Perl and Python both resist the introduction of a switch statement > which I (and many others) feel is the most elegant way to express > what it does. Interesting. What do you feel is the problem with elif? Its not even much more typing and allows for much more expressive test conditions. Switch is really only useful for a single subset of tests. And of course switch statements are notorious bug factories and maintenance nightmares - the reason why OOP tries to eliminate them wherever possible. > I also wish Python would take up the C ternary operator > which is also quite clear and elegant. :-) You joke I assume? ':?' is clear? Its succinct but also prone to abuse. I don't think the Python equivalent foo = x and y or z is much less elegant than foo = x ? y : z > ... To paraphrase the famous quote: There are no good programming languages, just some that aren't as bad in some situations. Absolutely true. I still use assembler occasionally, and I even like bits of COBOL (although not much, its my least favourite language!). And probably my favourite language of all is Logo even though I've never used it for any serious projects. Alan G. From alan.gauld at freenet.co.uk Fri Feb 4 00:30:37 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 00:31:14 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <C4C644CF4ADA9448904C3E8BACC4B97C02E67388@medexch1.medplus.com> Message-ID: <031001c50a48$5e1cb570$68b78851@xp> > We'll just have to have to disagree about awk. > I starting learning Perl to avoid learning awk :-) Really? Why for? awk is far easier to learn than Perl - and far less generally capable! - but it makes Perl seem positively verbose! Alan G. From jeff at ccvcorp.com Fri Feb 4 00:41:25 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri Feb 4 00:40:42 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <02b101c50a3d$a5574550$68b78851@xp> References: <OFF55EC37B.D4DBA228-ON86256F9D.005243A8-86256F9D.00535A47@deluxe.com> <02b101c50a3d$a5574550$68b78851@xp> Message-ID: <4202B6A5.3030805@ccvcorp.com> Alan Gauld wrote: > There is no perfect language, and very few truly bad > languages - they never get out of the lab - they all > have something that they are good at and from which > we can learn! Heh, I'd look at that a bit differently -- I think that there's a *lot* of bad languages, it's just that we're spared ever hearing about the majority of them because they don't ever get very far. ;) (But then, at my job I'm stuck using a horrible Frankenstein's monster of a proprietary language on a daily basis, so I can't help but believe that there's plenty more awful languages around that didn't happen to be "rescued" from oblivion by an accident of history...) Jeff Shannon Technician/Programmer Credit International From alan.gauld at freenet.co.uk Fri Feb 4 00:41:33 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 00:41:08 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <C4C644CF4ADA9448904C3E8BACC4B97C02E6738B@medexch1.medplus.com> Message-ID: <031901c50a49$e5142440$68b78851@xp> > second example. I'm sure what those studies show is what the "majority" > find easier not what "everyone" finds easier. They are statistical its true, but they were based on the folks who actually used the second style indent and they actually got worse scores in the tests using their own style than when they used the style they were less used too. The tests have been repeated many times using multiple languages and thousands of subjects ranging from students through to professionals with years of experience. The reasons for the K&R style of brace winning is to do with the way the brain process structure and despite the subjects stated preference for the 'Pascal' style they still had lower perception scores. As I said its not a style issue its to do with how the brain works and the outcome of a lot of studies over at least 30 years produces a pretty solid case. > left-brain, right-brain thing. Nope they tried that too, comparing creative types with science types etc. Same result. > told my brain was "wired differently" from the general > public. Just ask my wife :-) And they tried mixing up the sexes too, no difference. There may be a few individuals for whom it doesn't apply but in the vast majority of cases its a fact. In fact the best style of all is neither of the two I showed, its actually this - which early everyone hates when they see it! inf f(x) { bah() } After reading the studies I changed my C style to the above, it certainly hasn't made my code harder to debug and I don't see any increase in bug count, but I can't honestly say I notice a reduction either, but it helps to know that I'm increasing the chances of my code being understood by someone else... Alan G. From maxnoel_fr at yahoo.fr Fri Feb 4 00:47:47 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri Feb 4 00:47:56 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <030401c50a46$c7d41280$68b78851@xp> References: <f2ff2d0502021518547f14c0@mail.gmail.com><86626245450c1bfcf3190400baffe178@yahoo.fr><9bb26ab5f9c3d8166f27d39464b9c750@yahoo.fr><f2ff2d0502021642627b77ee@mail.gmail.com> <56abcbca5acfdc78d0b13c480c1af850@yahoo.fr> <021301c509d5$89daa960$68b78851@xp> <93fef199885ae5cf5b466c6e0e724ae5@yahoo.fr><42029ECA.2070305@ccvcorp.com> <4202A13F.70109@speakeasy.net> <030401c50a46$c7d41280$68b78851@xp> Message-ID: <e2c7f84ed8549b21c97c428ece9a30f9@yahoo.fr> On Feb 3, 2005, at 23:19, Alan Gauld wrote: > Sean, what book/tutor are you using for Haskell? > I learned it from "The Haskell School of Expression" which > was OK but very graphics focused, I'd be interested in > recommended second source on Haskell. I'm not Sean, but I'm using Simon Thompson's "Haskell: The Craft of Functional Programming", which I find quite good. However, it's a bit odd, in that it almost reads like a mathematics book, which is something you may or may not like. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From maxnoel_fr at yahoo.fr Fri Feb 4 00:51:41 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri Feb 4 00:51:53 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <4202B6A5.3030805@ccvcorp.com> References: <OFF55EC37B.D4DBA228-ON86256F9D.005243A8-86256F9D.00535A47@deluxe.com> <02b101c50a3d$a5574550$68b78851@xp> <4202B6A5.3030805@ccvcorp.com> Message-ID: <56c97b3bed48eeaf1d13a6e97311cd9a@yahoo.fr> On Feb 3, 2005, at 23:41, Jeff Shannon wrote: > (But then, at my job I'm stuck using a horrible Frankenstein's monster > of a proprietary language on a daily basis, so I can't help but > believe that there's plenty more awful languages around that didn't > happen to be "rescued" from oblivion by an accident of history...) Yeah. Sometimes I read a little bit of Wikipedia's "Esoteric Programming Languages" page, and some of them just leave me in awe. Brainfuck (and its variant Ook!) and INTERCAL ("GOTO is considered harmful, so we removed it -- INTERCAL uses COME FROM instead") are already quite impressive, but the very idea of Befunge makes my brain want to explode. Especially that extension to the language that allows one to write N-dimensional programs. :D -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From maxnoel_fr at yahoo.fr Fri Feb 4 00:57:16 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri Feb 4 00:57:22 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <031901c50a49$e5142440$68b78851@xp> References: <C4C644CF4ADA9448904C3E8BACC4B97C02E6738B@medexch1.medplus.com> <031901c50a49$e5142440$68b78851@xp> Message-ID: <6b97374ce906150985bb042f036797ba@yahoo.fr> On Feb 3, 2005, at 23:41, Alan Gauld wrote: > The reasons for the K&R style of brace winning is to do > with the way the brain process structure and despite > the subjects stated preference for the 'Pascal' style > they still had lower perception scores. Little nit-picking here: if(foo) { bar(); } Is not K&R style, but Allman style. K&R style (also known as One True Brace Style or 1TBS) is this: if(foo) { bar; } -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From jeff at ccvcorp.com Fri Feb 4 01:06:55 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri Feb 4 01:06:12 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <02ff01c50a46$7d75d570$68b78851@xp> References: <f2ff2d0502021518547f14c0@mail.gmail.com><86626245450c1bfcf3190400baffe178@yahoo.fr><9bb26ab5f9c3d8166f27d39464b9c750@yahoo.fr><f2ff2d0502021642627b77ee@mail.gmail.com> <56abcbca5acfdc78d0b13c480c1af850@yahoo.fr> <021301c509d5$89daa960$68b78851@xp><93fef199885ae5cf5b466c6e0e724ae5@yahoo.fr> <42029ECA.2070305@ccvcorp.com> <02ff01c50a46$7d75d570$68b78851@xp> Message-ID: <4202BC9F.8080800@ccvcorp.com> Alan Gauld wrote: > >>However, Python doesn't need lambdas to be able to write in a >>functional style. > > I disagree Jeff. It does need lambdas to do FP properly, and > better lambdas than we have currently. What it doesn't need > is the lambda keyword and syntax - although pesonally I like > lambda since it is descriptive! Well, we'll have to continue to disagree on that. ;) Personally, I can't help but think that 'lambda' is descriptive only to people who've experienced it elsewhere, and that that does *not* include the majority of the programming community, but I could be mistaken. :) >>Functions are first-class objects and can be passed >>around quite easily, > > Yes, but lambdas are more than first class functions, they > are anonymous functions! In fact really just callable code > blocks, not necessarily functions in the strictest sense > (except that every callable in FP is a function...! ;-) Well, given that in Python a function is just a callable code block that's bound to a name... ;) Personally, I fail to see why having an anonymous function is such a huge conceptual advantage, no matter how many times this is proclaimed as truth by lambda-users, but again this is just my own impression. > Having to define every function before using it would > be a big hassle and make code less readable IMHO. Here, ISTM that you're emphasizing the in-line nature of lambdas as being their key usage point... And personally, I prefer to have a glossary of terms rather than having to decipher jargon by context. ;) >>only a few differences between lambdas and named functions in >> Python: >> >> - Anonymous vs named > > the key feature Again, I fail to see why this is such an advantage -- I've seen assertions that it is, over and over again, but never any convincing evidence.... >> - Single expression vs suite of statements > > A python restriction. Well, I *did* specify that I was talking about 'in Python'... ;) >>I'd also argue that the inline nature is the *true* differentiating >>feature of lambdas -- the fact that they're anonymous is relatively >>minor. > > I agree, if I had an inline mechanism that forced me to > provide a name I could just use 'f' over and over and > not feel too cheated, but its nicer not to have an artificial > name when theres no need. Personally, I prefer to have the opportunity to provide a meaningful name, and don't see where a generic name is any more restrictive than having no name, but again, maybe that's just me. >>So, while there are some advantages to having single-use callables >>be defined inline > > The other advantage is the huge conceptial advantage that > real lambdas confer. The breakthrough idea of > > def f(x): return x+x > > being the same as > > f = lambda x: x+x > > is only possible to demonstrate if you have lambda to start with. > And yet that concept of a function name being just another variable > and the callable code being an object in its own right becomes > much more obvious in my opinion. lambda is a learning tool which > shows what is really happening whereas def is just syntactic sugar. Hm, I understood the idea of functions being just code objects that were bound to a name, and could be passed around, stored in collections, and effectively renamed, well before I really got a hold on lambdas as anything more than some confusing bit of magic. Of course, I started in C, where I was fairly comfortable with the idea of function pointers; function objects are a pretty simple step up, abstraction-wise, from that. I suppose that one might argue that I *still* just don't really get lambdas (and I wouldn't argue with that). I can see some advantages to small inline functions, though I suspect that a more-explicit currying mechanism (such as the proposed partial() higher-order function) could easily replace such uses. I'm sorry to say, though, that the supposed advantages of anonymity come across as little more than handwaving assertions to me, no matter how sincerely they're intended. (I've just started to read through SICP, to pick up some lisp/scheme, in hopes of understanding the appeal a bit better, so maybe there's hope for me yet. ;) ) Jeff Shannon Technician/Programmer Credit International From keridee at jayco.net Fri Feb 4 01:23:25 2005 From: keridee at jayco.net (Jacob S.) Date: Fri Feb 4 01:23:45 2005 Subject: [Tutor] i have a question??? References: <20050203135332.67940.qmail@web41007.mail.yahoo.com><001601c50a34$2b196970$3d5328cf@JSLAPTOP> <82975b0c050203133067f1d002@mail.gmail.com> Message-ID: <008001c50a4f$d76aec10$3d5328cf@JSLAPTOP> Sorry, over paranoid. ;-) Jacob >> num = num + math.pi/6.0 ## Don't forget .0 or you'll get an integer > > the division operator returns a float when either of the operands are > floats -- in this case math.pi is, so you don't have to worry about > passing it 6.0 instead of 6 > >>>> import math >>>> math.pi > 3.1415926535897931 >>>> math.pi / 6 > 0.52359877559829882 > >>>> type(math.pi) > <type 'float'> >>>> type(6) > <type 'int'> >>>> type(6.0) > <type 'float'> > > > mike > > > > On Thu, 3 Feb 2005 16:04:25 -0500, Jacob S. <keridee@jayco.net> wrote: >> >From what I understand, range() no longer allows you to use floats as >> arguments. (Or it gives you a deprication warning) >> This tutorial must be old. >> >> Not the only way, but. >> >> import math >> num = 0 >> while num <= 2*math.pi: >> ## Do stuff to figure pi/6 things >> >> num = num + math.pi/6.0 ## Don't forget .0 or you'll get an integer >> result. >> print ## Result thingy >> >> Another way is to use Numarry (Numeric) arange() but that takes extra >> work. >> ;-) >> Jacob >> >> >> > This is from a tutorial >> > >> > "EXERCISE 3.9 >> > Use the math library to write a program to print out >> > the sin and cos of numbers from 0 to 2pi in intervals >> > of pi/6. You will need to use the range() function." >> > >> > Range won't let me use pi/6 as an incremator >> > is there some other way i can accomplish this task >> > im new to programming so all the help i can get is >> > greatly appreciated. >> > NI! >> > alex >> > >> > >> > >> > >> > __________________________________ >> > Do you Yahoo!? >> > The all-new My Yahoo! - What will yours do? >> > http://my.yahoo.com >> > _______________________________________________ >> > Tutor maillist - Tutor@python.org >> > http://mail.python.org/mailman/listinfo/tutor >> > >> > >> >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From cyresse at gmail.com Fri Feb 4 01:25:31 2005 From: cyresse at gmail.com (Liam Clarke) Date: Fri Feb 4 01:25:36 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <4202BC9F.8080800@ccvcorp.com> References: <f2ff2d0502021518547f14c0@mail.gmail.com> <86626245450c1bfcf3190400baffe178@yahoo.fr> <9bb26ab5f9c3d8166f27d39464b9c750@yahoo.fr> <f2ff2d0502021642627b77ee@mail.gmail.com> <56abcbca5acfdc78d0b13c480c1af850@yahoo.fr> <021301c509d5$89daa960$68b78851@xp> <93fef199885ae5cf5b466c6e0e724ae5@yahoo.fr> <42029ECA.2070305@ccvcorp.com> <02ff01c50a46$7d75d570$68b78851@xp> <4202BC9F.8080800@ccvcorp.com> Message-ID: <f2ff2d05020316257f11e493@mail.gmail.com> >I suppose that one might argue that I *still* just don't really get >lambdas (and I wouldn't argue with that). I can see some advantages >to small inline functions, though I suspect that a more-explicit >currying mechanism (such as the proposed partial() higher-order >function) could easily replace such uses. I'm sorry to say, though, >that the supposed advantages of anonymity come across as little more >than handwaving assertions to me, no matter how sincerely they're >intended. I'm with Jeff on this one - I've yet to see the light regarding lambda's. I understand they're used through-out Tkinter GUI stuff, can anyone put up an example of why a lambda is better? I would like to 'get' the concepts. Is this one of those conceptual things like OOP? Or is it a subtlety that a Masters in COSC is necessary to appreciate? On Thu, 03 Feb 2005 16:06:55 -0800, Jeff Shannon <jeff@ccvcorp.com> wrote: > Alan Gauld wrote: > > > > >>However, Python doesn't need lambdas to be able to write in a > >>functional style. > > > > I disagree Jeff. It does need lambdas to do FP properly, and > > better lambdas than we have currently. What it doesn't need > > is the lambda keyword and syntax - although pesonally I like > > lambda since it is descriptive! > > Well, we'll have to continue to disagree on that. ;) Personally, I > can't help but think that 'lambda' is descriptive only to people > who've experienced it elsewhere, and that that does *not* include the > majority of the programming community, but I could be mistaken. :) > > >>Functions are first-class objects and can be passed > >>around quite easily, > > > > Yes, but lambdas are more than first class functions, they > > are anonymous functions! In fact really just callable code > > blocks, not necessarily functions in the strictest sense > > (except that every callable in FP is a function...! ;-) > > Well, given that in Python a function is just a callable code block > that's bound to a name... ;) Personally, I fail to see why having an > anonymous function is such a huge conceptual advantage, no matter how > many times this is proclaimed as truth by lambda-users, but again this > is just my own impression. > > > Having to define every function before using it would > > be a big hassle and make code less readable IMHO. > > Here, ISTM that you're emphasizing the in-line nature of lambdas as > being their key usage point... And personally, I prefer to have a > glossary of terms rather than having to decipher jargon by context. ;) > > >>only a few differences between lambdas and named functions in > >> Python: > >> > >> - Anonymous vs named > > > > the key feature > > Again, I fail to see why this is such an advantage -- I've seen > assertions that it is, over and over again, but never any convincing > evidence.... > > >> - Single expression vs suite of statements > > > > A python restriction. > > Well, I *did* specify that I was talking about 'in Python'... ;) > > > >>I'd also argue that the inline nature is the *true* differentiating > >>feature of lambdas -- the fact that they're anonymous is relatively > >>minor. > > > > I agree, if I had an inline mechanism that forced me to > > provide a name I could just use 'f' over and over and > > not feel too cheated, but its nicer not to have an artificial > > name when theres no need. > > Personally, I prefer to have the opportunity to provide a meaningful > name, and don't see where a generic name is any more restrictive than > having no name, but again, maybe that's just me. > > >>So, while there are some advantages to having single-use callables > >>be defined inline > > > > The other advantage is the huge conceptial advantage that > > real lambdas confer. The breakthrough idea of > > > > def f(x): return x+x > > > > being the same as > > > > f = lambda x: x+x > > > > is only possible to demonstrate if you have lambda to start with. > > And yet that concept of a function name being just another variable > > and the callable code being an object in its own right becomes > > much more obvious in my opinion. lambda is a learning tool which > > shows what is really happening whereas def is just syntactic sugar. > > Hm, I understood the idea of functions being just code objects that > were bound to a name, and could be passed around, stored in > collections, and effectively renamed, well before I really got a hold > on lambdas as anything more than some confusing bit of magic. Of > course, I started in C, where I was fairly comfortable with the idea > of function pointers; function objects are a pretty simple step up, > abstraction-wise, from that. > > I suppose that one might argue that I *still* just don't really get > lambdas (and I wouldn't argue with that). I can see some advantages > to small inline functions, though I suspect that a more-explicit > currying mechanism (such as the proposed partial() higher-order > function) could easily replace such uses. I'm sorry to say, though, > that the supposed advantages of anonymity come across as little more > than handwaving assertions to me, no matter how sincerely they're > intended. (I've just started to read through SICP, to pick up some > lisp/scheme, in hopes of understanding the appeal a bit better, so > maybe there's hope for me yet. ;) ) > > Jeff Shannon > Technician/Programmer > Credit International > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cyresse at gmail.com Fri Feb 4 01:33:30 2005 From: cyresse at gmail.com (Liam Clarke) Date: Fri Feb 4 01:33:33 2005 Subject: [Tutor] Better structure? In-Reply-To: <024e01c50a1f$4a4ab0c0$68b78851@xp> References: <Pine.LNX.4.44.0501311447390.24680-100000@hkn.eecs.berkeley.edu> <42003772.4010808@ccvcorp.com> <002501c508ce$294e4e10$3b5428cf@JSLAPTOP> <016a01c50904$81e75db0$68b78851@xp> <001301c5099a$df6c7dd0$145428cf@JSLAPTOP> <4201A45A.2060205@tds.net> <4201A727.1040206@gmail.com> <4201A854.8000103@gmail.com> <4201ADE6.1040908@lug-delhi.org> <024e01c50a1f$4a4ab0c0$68b78851@xp> Message-ID: <f2ff2d05020316332c7ece70@mail.gmail.com> Alan said - > Its bad practice to delete a member in the collection being iterated > but Python copes OK if you just change the current item. Yeah, that's very bad. Makes for all sorts of subtle errors. I usually do the iteration as a for i in range(len(someList) type thing, and collect the indexes - like so j=[1, 2,3,4, 5,6,7,8] delIndexes=[] for index in range(len(j)): if not j[index] % 2: delIndexes.append(index) delIndexes.reverse() for item in delIndexes: del(j[item]) print j [1, 3, 5, 7] Although, (and this will be rough) a list comprehension would be probably do the same thing j=[1, 2,3,4, 5,6,7,8] q = [if not item % 2 for item in j] I really think I've got that 'if not item % 2' wrong, as I can't test it, but I'd be hoping for print q [1, 3, 5, 7] -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From budr at netride.net Fri Feb 4 01:43:36 2005 From: budr at netride.net (Bud Rogers) Date: Fri Feb 4 01:44:02 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <031901c50a49$e5142440$68b78851@xp> References: <C4C644CF4ADA9448904C3E8BACC4B97C02E6738B@medexch1.medplus.com> <031901c50a49$e5142440$68b78851@xp> Message-ID: <200502031843.37545.budr@netride.net> On Thursday 03 February 2005 17:41, Alan Gauld wrote: > In fact the best style of all is neither of the two I showed, > its actually this - which early everyone hates when they see it! > > inf f(x) > ? ? { > ? ? bah() > ? ? } Ugh. Alan, I won't even try to dispute the study. But if I have to write code like that, I'll just take up gardening instead. :} -- Bud Rogers <budr@netride.net> KD5SZ From keridee at jayco.net Fri Feb 4 02:26:05 2005 From: keridee at jayco.net (Jacob S.) Date: Fri Feb 4 02:25:51 2005 Subject: [Tutor] Better structure? References: <Pine.LNX.4.44.0501311447390.24680-100000@hkn.eecs.berkeley.edu><42003772.4010808@ccvcorp.com><002501c508ce$294e4e10$3b5428cf@JSLAPTOP><016a01c50904$81e75db0$68b78851@xp><001301c5099a$df6c7dd0$145428cf@JSLAPTOP> <4201A45A.2060205@tds.net><4201A727.1040206@gmail.com> <4201A854.8000103@gmail.com><4201ADE6.1040908@lug-delhi.org> <024e01c50a1f$4a4ab0c0$68b78851@xp> <f2ff2d05020316332c7ece70@mail.gmail.com> Message-ID: <00d801c50a58$83f68c20$3d5328cf@JSLAPTOP> > Although, (and this will be rough) a list comprehension would be > probably do the same thing > j=[1, 2,3,4, 5,6,7,8] > > q = [if not item % 2 for item in j] > > I really think I've got that 'if not item % 2' wrong, as I can't test > it, but I'd be hoping for > print q > [1, 3, 5, 7] Backwards. ;-) q = [item for item in j if not item % 2 == 0] A word of warning. You want odd numbers, so even if the syntax was correct for your list comprehension, you would have gotten even numbers -- item % 2 would register False if item %2 == 0, then not False would be True so you would get all of the items that were even. Does that make sense? You could also do q = [item for item in j if item % 2] Which says if item % 2 is True (not equal to False, 0) then append item to q. Okay, so that's not exactly what it says HTH, Jacob From jeff at ccvcorp.com Fri Feb 4 03:22:01 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri Feb 4 03:21:18 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <56c97b3bed48eeaf1d13a6e97311cd9a@yahoo.fr> References: <OFF55EC37B.D4DBA228-ON86256F9D.005243A8-86256F9D.00535A47@deluxe.com> <02b101c50a3d$a5574550$68b78851@xp> <4202B6A5.3030805@ccvcorp.com> <56c97b3bed48eeaf1d13a6e97311cd9a@yahoo.fr> Message-ID: <4202DC49.3050105@ccvcorp.com> Max Noel wrote: > On Feb 3, 2005, at 23:41, Jeff Shannon wrote: > >> (But then, at my job I'm stuck using a horrible Frankenstein's monster >> of a proprietary language on a daily basis, so I can't help but >> believe that there's plenty more awful languages around that didn't >> happen to be "rescued" from oblivion by an accident of history...) > > Yeah. Sometimes I read a little bit of Wikipedia's "Esoteric > Programming Languages" page, and some of them just leave me in awe. > Brainfuck (and its variant Ook!) and INTERCAL ("GOTO is considered > harmful, so we removed it -- INTERCAL uses COME FROM instead") are > already quite impressive, but the very idea of Befunge makes my brain > want to explode. Especially that extension to the language that allows > one to write N-dimensional programs. :D The difference here is that those are languages that were *intended* to be brain-melting. The language I'm talking about (Pick Proc, aka UHL) was intended to do real work with -- though at times I think it was designed by a brain-damaged lemur that was huffing paint fumes. For example, every line (except flow-control statements i.e. 'if' and 'go' (there's a few other exceptions as well, but anyhow...)) must begin with a single character that denotes what the line does - 'c' for comment, 'o' for output (print to terminal), 'h' to build a command, 'p' to execute that command... empty lines are forbidden. Note also that the position *after* the final newline character is considered a line, and therefore a file cannot end with a newline. Especially when combined with several of the utilities that it's commonly used to script for, it begins to approach Perl in indecipherability, without even having the excuse of being largely non-alpha characters. I'd consider writing a Python extension that would interact with the system such that I wouldn't need to use this awful little scripting language, but that would require more effort and thought than I'm willing to invest in learning the details of this system. Jeff Shannon Technician/Programmer Credit International From flaxeater at yahoo.com Fri Feb 4 03:54:18 2005 From: flaxeater at yahoo.com (Chad Crabtree) Date: Fri Feb 4 03:54:21 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: <20050204025418.49854.qmail@web54307.mail.yahoo.com> How about a concrete example where lambda is more elegant than a named block of code aList=['a','bb','ccc','dddd','ee'] bList=aList[:] #deep copy assert not bList is aList def sortByLength(item1,item2): return cmp(len(item1),len(item2)) bList.sort(sortByLength) assert bList==['a', 'bb', 'ee', 'ccc', 'dddd'] aList.sort(lambda x,y:cmp(len(x),len(y))) assert aList==['a', 'bb', 'ee', 'ccc', 'dddd'] Now this is a concrete example of how lambda simplifies code, at least for me because it does not clutter my mental name space. Also it is much shorter. However it should be said that this is very much a question of taste. However I must say that lambda's are very useful even necessary for using Tkinter. Here's something else, while not exactly the same but an illustration. aFuncList=[] def x(): print "one" aFuncList.append(x) def x(): print "two" aFuncList.append(x) def x(): print "three" aFuncList.append(x) for item in aFuncList: item() In summary there has been a great deal of argument about lambda's, even on this mostly sanguine mailing list. I feel that it's one of those strange things about python true. Guido purposely made it very limited because it could get hairy very fast with more powerful lambda's, the functional people would make code that would break newcomers heads. God knows I had a hard enough time with them at first. __________________________________ Do you Yahoo!? Yahoo! Mail - Easier than ever with enhanced search. Learn more. http://info.mail.yahoo.com/mail_250 From flaxeater at yahoo.com Fri Feb 4 07:39:43 2005 From: flaxeater at yahoo.com (Chad Crabtree) Date: Fri Feb 4 07:39:49 2005 Subject: [Tutor] This Deletes All my Files Message-ID: <20050204063943.83241.qmail@web54308.mail.yahoo.com> I've tried this and I cannot figure out why this does not work. I figure this has something to do with order of operations. I figured someone would know exactly why it doesn't work. Wouldn't this start inside parens then from left to right? open(item,'w').write(open(item,'r').read().replace(' ','')) I tried this on the shell just trying to do some quick text replacement because I could figure out how to get awk to do it, and I didn't want to spend 5 hours RTFM. I got it to work by breaking it up to several statements, but I would like to know. __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From pierre.barbier at cirad.fr Fri Feb 4 09:07:26 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Fri Feb 4 09:05:22 2005 Subject: [Tutor] This Deletes All my Files In-Reply-To: <20050204063943.83241.qmail@web54308.mail.yahoo.com> References: <20050204063943.83241.qmail@web54308.mail.yahoo.com> Message-ID: <42032D3E.5040904@cirad.fr> Ok, so in Python, arguments are evaluated first, left to right ! The outer-most function used in your sample is : file.write(self, filename, mode) So the first argument evaluated is "self" ... and in your case "self" is "open(item, 'w')" so the first thing your line does is opening for writing the file named by "item" and as "w" empty the file ... you can read it afterward, it will be empty ! Pierre PS: general in programs: do NEVER rely on arguments evaluation order, unless you have no other choices and you are damn sure of what you're doing. In any case, do NEVER do that if you're no expert in the programming language used. Chad Crabtree a ?crit : > I've tried this and I cannot figure out why this does not work. I > figure this has something to do with order of operations. I figured > someone would know exactly why it doesn't work. Wouldn't this start > inside parens then from left to right? > > open(item,'w').write(open(item,'r').read().replace(' ','')) > > I tried this on the shell just trying to do some quick text > replacement > because I could figure out how to get awk to do it, and I didn't want > to > spend 5 hours RTFM. I got it to work by breaking it up to several > statements, but I would like to know. > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 From shaleh at speakeasy.net Fri Feb 4 09:13:29 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Fri Feb 4 09:14:06 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <030401c50a46$c7d41280$68b78851@xp> References: <f2ff2d0502021518547f14c0@mail.gmail.com><86626245450c1bfcf3190400baffe178@yahoo.fr><9bb26ab5f9c3d8166f27d39464b9c750@yahoo.fr><f2ff2d0502021642627b77ee@mail.gmail.com> <56abcbca5acfdc78d0b13c480c1af850@yahoo.fr> <021301c509d5$89daa960$68b78851@xp> <93fef199885ae5cf5b466c6e0e724ae5@yahoo.fr><42029ECA.2070305@ccvcorp.com> <4202A13F.70109@speakeasy.net> <030401c50a46$c7d41280$68b78851@xp> Message-ID: <42032EA9.1000600@speakeasy.net> Alan Gauld wrote: > > Sean, what book/tutor are you using for Haskell? > I learned it from "The Haskell School of Expression" which > was OK but very graphics focused, I'd be interested in > recommended second source on Haskell. > as with Max I am reading Haskell: Craft of Functional Programming. I am about half way through it (have not got to Monads yet which are the mind benders). So far I really like it. Thought provoking examples and exercises. However there are no answers to the exercises. Which for a relative newbie to functional programming would have been nice. From maxnoel_fr at yahoo.fr Fri Feb 4 09:15:04 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri Feb 4 09:15:10 2005 Subject: [Tutor] This Deletes All my Files In-Reply-To: <20050204063943.83241.qmail@web54308.mail.yahoo.com> References: <20050204063943.83241.qmail@web54308.mail.yahoo.com> Message-ID: <66f660b9e70d3a96f9e0fc4dc7fae398@yahoo.fr> On Feb 4, 2005, at 06:39, Chad Crabtree wrote: > I've tried this and I cannot figure out why this does not work. I > figure this has something to do with order of operations. I figured > someone would know exactly why it doesn't work. Wouldn't this start > inside parens then from left to right? > > open(item,'w').write(open(item,'r').read().replace(' ','')) > > I tried this on the shell just trying to do some quick text > replacement > because I could figure out how to get awk to do it, and I didn't want > to > spend 5 hours RTFM. I got it to work by breaking it up to several > statements, but I would like to know. It's quite easy: evaluation starts from left to right. The program opens item for writing (thus deleting it), creating a file object, then executes its write method on the argument in the parens. However, since at that point item is now empty, there is nothing to read from. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From project5 at redrival.net Fri Feb 4 09:51:57 2005 From: project5 at redrival.net (Andrei) Date: Fri Feb 4 09:52:59 2005 Subject: [Tutor] Re: This Deletes All my Files References: <20050204063943.83241.qmail@web54308.mail.yahoo.com> Message-ID: <loom.20050204T090540-499@post.gmane.org> Chad Crabtree <flaxeater <at> yahoo.com> writes: > I've tried this and I cannot figure out why this does not work. I > figure this has something to do with order of operations. I figured > someone would know exactly why it doesn't work. Wouldn't this start > inside parens then from left to right? > > open(item,'w').write(open(item,'r').read().replace(' ','')) Well, what your code says is this: 1. open item for writing and return a file object 2. call on that file object the write method (at this point its contents are wiped out) 3. open that same file for reading (but it's empty now) 4. read everything from it (nothing) 5. write nothing back to the file. You can test it by implementing a dummy open method and a dummy file class which log what happens to them: >>> s = "d:/tests/test.txt" >>> class dummyfile(object): ... def open(self, *args): ... print "dummyfile.open:", args ... def write(self, *args): ... print "dummyfile.write:", args ... def read(self, *args): ... print "dummyfile.read:", args ... return "" >>> def dummyopen(filename, type): ... print "dummyopen:", filename, type ... d = dummyfile() ... d.open(filename, type) ... return d >>> dummyopen(s, 'w').write(dummyopen(s, 'r').read()) dummyopen: d:/tests/test.txt w dummyfile.open: ('d:/tests/test.txt', 'w') <--- first open for writing dummyopen: d:/tests/test.txt r dummyfile.open: ('d:/tests/test.txt', 'r') <--- then for reading dummyfile.read: () dummyfile.write: ('',) > spend 5 hours RTFM. I got it to work by breaking it up to several > statements, but I would like to know. And that's the way you *should* write it - code like this doesn't deserve to work anyway :). Yours, Andrei From alan.gauld at freenet.co.uk Fri Feb 4 09:58:41 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 09:57:41 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <C4C644CF4ADA9448904C3E8BACC4B97C02E67388@medexch1.medplus.com> <24692.1107472232@www13.gmx.net> Message-ID: <034301c50a97$b9b7b110$68b78851@xp> > > We'll just have to have to disagree about awk. I starting learning Perl > > to avoid learning awk :-) > > But awk is smaller and simpler than perl. So it should be faster > (esp. at startup) for small and simple tasks. > As usual: Right tool for right task. awk starts faster but perl is more efficient because it compiles the code prior to execution. So for any long files or big programs Perl is significantly faster than awk. But awk is just so elegant and quick to write that I use it for everything except huge files. Alan G. From alan.gauld at freenet.co.uk Fri Feb 4 10:05:04 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 10:04:19 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <f2ff2d0502021518547f14c0@mail.gmail.com><86626245450c1bfcf3190400baffe178@yahoo.fr><9bb26ab5f9c3d8166f27d39464b9c750@yahoo.fr><f2ff2d0502021642627b77ee@mail.gmail.com> <56abcbca5acfdc78d0b13c480c1af850@yahoo.fr> <021301c509d5$89daa960$68b78851@xp> <93fef199885ae5cf5b466c6e0e724ae5@yahoo.fr><42029ECA.2070305@ccvcorp.com><4202A13F.70109@speakeasy.net> <030401c50a46$c7d41280$68b78851@xp> <e2c7f84ed8549b21c97c428ece9a30f9@yahoo.fr> Message-ID: <035401c50a98$9e54ee00$68b78851@xp> > > Sean, what book/tutor are you using for Haskell? > > I'm not Sean, Oops, sorry, I picked the name from the post I was replying to, apologies! > but I'm using Simon Thompson's "Haskell: The Craft of > Functional Programming", which I find quite good. However, it's a bit > odd, in that it almost reads like a mathematics book, which is > something you may or may not like. FP generally is math oriented, all the Haskell books I've seen are the same. In fact the reason I chose mine was because it seemed the least math oriented, but in practice, because I'm not much into graphics, I spent a lot of time trying to think how to apply the principles elsewhere... I'll have a look for your one. Alan G. From alan.gauld at freenet.co.uk Fri Feb 4 10:09:11 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 10:08:15 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <C4C644CF4ADA9448904C3E8BACC4B97C02E6738B@medexch1.medplus.com><031901c50a49$e5142440$68b78851@xp> <6b97374ce906150985bb042f036797ba@yahoo.fr> Message-ID: <035b01c50a99$31229070$68b78851@xp> > > The reasons for the K&R style of brace winning is to do > > with the way the brain process structure and despite > > the subjects stated preference for the 'Pascal' style > > they still had lower perception scores. > > Little nit-picking here: > > if(foo) > { > bar(); > } > > Is not K&R style, but Allman style. K&R style (also known as One True > Brace Style or 1TBS) is this: Correct. The style you show (which I called Pascal style) is the one that doesn't work. K&R style > if(foo) { > bar; > } Is the one that won the shootout. With the outsider(which I dont know a name for!) beating both... if (foo) { bar; } Which is the one that Python uses... Alan G. From alan.gauld at freenet.co.uk Fri Feb 4 10:28:24 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 10:27:22 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <f2ff2d0502021518547f14c0@mail.gmail.com><86626245450c1bfcf3190400baffe178@yahoo.fr><9bb26ab5f9c3d8166f27d39464b9c750@yahoo.fr><f2ff2d0502021642627b77ee@mail.gmail.com> <56abcbca5acfdc78d0b13c480c1af850@yahoo.fr> <021301c509d5$89daa960$68b78851@xp><93fef199885ae5cf5b466c6e0e724ae5@yahoo.fr> <42029ECA.2070305@ccvcorp.com><02ff01c50a46$7d75d570$68b78851@xp> <4202BC9F.8080800@ccvcorp.com> Message-ID: <036001c50a9b$e0a33c50$68b78851@xp> > > I disagree Jeff. It does need lambdas to do FP properly, and > > Well, we'll have to continue to disagree on that. ;) Personally, I > can't help but think that 'lambda' is descriptive only to people > who've experienced it elsewhere, and that that does *not* include the > majority of the programming community, but I could be mistaken. :) I would agree, in the same way that complex numbers only make sense to those who've used them. But lambda calculus is the foundation of all programming and all formally trained programmers *should* have had a grounding in Lambda calculus. Unfortunately the nature of the industry is such that many programmers have no theoretical understanding of programming, they just know some languages and get on with it. That's OK, and most programmers can quite happily ignore lambdas - and do! [The analogy is that you don't need to understand electron mechanics to be an electrician, but a electronic component designer probably should!] But lambda is just as much a valid mathematical term as "function" or "set" or "complex number", its not a *construct* from another language, its a mathematical concept with whole books written about it. > Well, given that in Python a function is just a callable code block > that's bound to a name... ;) Personally, I fail to see why having an > anonymous function is such a huge conceptual advantage, Because often you just want to pass in a bit of code that doesn't have a very meaningful function, typically as a parameter to a control structure. In fact, thinking about it, I'd guess the most common case for anonymous functions is when defining new control structures. Now you can give arbitrary names "codeBlock" or similar def codeBlock(): blah blah blah repeat(codeBlock,test) But its more appropriate to the task to do: repeat( blah blah blah, test) It keeps the code block at the execution point. > Here, ISTM that you're emphasizing the in-line nature of lambdas as > being their key usage point... And personally, I prefer to have a > glossary of terms rather than having to decipher jargon by context. ;) But a glossary of terms is only useful if it means something. Its especially useful for things that hang around and get reused, but for something you use once and throw away labelling it is a lot of work! > collections, and effectively renamed, well before I really got a hold > on lambdas as anything more than some confusing bit of magic. Of > course, I started in C, where I was fairly comfortable with the idea > of function pointers; function objects are a pretty simple step up, > abstraction-wise, from that. I started wth C then moved to Lisp. When I saw Lambdas in Lisp C function pointers suddenly took on a new lease of life and that was what started me reading up on lambda calculus. Like most programmers I don't use lambda a lot, but its really nice to have it there for the few occasions I want it... > intended. (I've just started to read through SICP, to pick up some > lisp/scheme, in hopes of understanding the appeal a bit better, so > maybe there's hope for me yet. ;) ) Maybe. It'll be interesting to hear what you make of it. Keep us posted. Alan G. From alan.gauld at freenet.co.uk Fri Feb 4 10:37:03 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 10:36:45 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <f2ff2d0502021518547f14c0@mail.gmail.com><86626245450c1bfcf3190400baffe178@yahoo.fr><9bb26ab5f9c3d8166f27d39464b9c750@yahoo.fr><f2ff2d0502021642627b77ee@mail.gmail.com><56abcbca5acfdc78d0b13c480c1af850@yahoo.fr><021301c509d5$89daa960$68b78851@xp><93fef199885ae5cf5b466c6e0e724ae5@yahoo.fr><42029ECA.2070305@ccvcorp.com> <02ff01c50a46$7d75d570$68b78851@xp><4202BC9F.8080800@ccvcorp.com> <f2ff2d05020316257f11e493@mail.gmail.com> Message-ID: <037301c50a9d$15b40630$68b78851@xp> > I'm with Jeff on this one - I've yet to see the light regarding > lambda's. I understand they're used through-out Tkinter GUI stuff They often are in practice although they are rarely (never) necessary(*). But they are a convenient way of defining a one liner function without the overhead of certing lots of defined functions. (*)Except that all function definitions are really lambdas, they just don't use the keyword lambda anywhere.... > anyone put up an example of why a lambda is better? I would like to > 'get' the concepts. I gave a pseudo coe example in my reply to Jeff. Also in my Functional Programming page there are some examples. > Is this one of those conceptual things like OOP? Yes, but its a bit more fundamental than OOP Its about how programming languages are constructed and function. Its like the theory behind how elictricity flows in a circuit - you can change a fuse without knowing that stuff but its more important if you have to design the fuse! Lambdas really start to work when you start building new language constructs and the like. > Or is it a subtlety that a Masters in COSC is necessary to appreciate? Certainly a Masters in CS should teach you about Lambdas but you don't need that to appreciate them. They really aren't that hard, its just the fancy Greek name puts folks off I suspect :-) From alan.gauld at freenet.co.uk Fri Feb 4 10:39:40 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 10:38:40 2005 Subject: [Tutor] Better structure? References: <Pine.LNX.4.44.0501311447390.24680-100000@hkn.eecs.berkeley.edu><42003772.4010808@ccvcorp.com><002501c508ce$294e4e10$3b5428cf@JSLAPTOP><016a01c50904$81e75db0$68b78851@xp><001301c5099a$df6c7dd0$145428cf@JSLAPTOP> <4201A45A.2060205@tds.net><4201A727.1040206@gmail.com> <4201A854.8000103@gmail.com><4201ADE6.1040908@lug-delhi.org> <024e01c50a1f$4a4ab0c0$68b78851@xp> <f2ff2d05020316332c7ece70@mail.gmail.com> Message-ID: <037801c50a9d$7333b940$68b78851@xp> > Although, (and this will be rough) a list comprehension would be > probably do the same thing > j=[1, 2,3,4, 5,6,7,8] > > q = [if not item % 2 for item in j] I think you mean: q = [ item for item in j if item % 2] item % 2 will return zero = false on even numbers, so your test is true for odd numbers. No need for 'not'. Alan G. From alan.gauld at freenet.co.uk Fri Feb 4 10:42:42 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 10:41:35 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <C4C644CF4ADA9448904C3E8BACC4B97C02E6738B@medexch1.medplus.com><031901c50a49$e5142440$68b78851@xp> <200502031843.37545.budr@netride.net> Message-ID: <037d01c50a9d$e01d0a70$68b78851@xp> On Thursday 03 February 2005 17:41, Alan Gauld wrote: >> In fact the best style of all is neither of the two I showed, >> its actually this - which early everyone hates when they see it! >> >> inf f(x) >> { >> bah() >> } > >Ugh. Alan, I won't even try to dispute the study. But if I have to >write code like that, I'll just take up gardening instead. :} Look at it conceptually: XXXXXXXXXXXX XXXXX XXXXX XXXXX Thats Python! Since you are on this list I suspect you do write "code like that" Its just Guido removed the now extraneous {}... :-) Alan G. From alan.gauld at freenet.co.uk Fri Feb 4 11:11:50 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 11:12:46 2005 Subject: [Tutor] This Deletes All my Files References: <20050204063943.83241.qmail@web54308.mail.yahoo.com> Message-ID: <038801c50aa1$f233a350$68b78851@xp> > I've tried this and I cannot figure out why this does not work. So what happens? And how are you closing the file? > open(item,'w').write(open(item,'r').read().replace(' ','')) I can't see the obvious flaw, but using anonymous files(*) is not a good idea IMHO. (*)Unlike anonymous functions ;-) Alan G. From alan.gauld at freenet.co.uk Fri Feb 4 11:14:37 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 11:13:29 2005 Subject: [Tutor] This Deletes All my Files References: <20050204063943.83241.qmail@web54308.mail.yahoo.com> <42032D3E.5040904@cirad.fr> Message-ID: <039a01c50aa2$55715e80$68b78851@xp> > So the first argument evaluated is "self" ... and in your case "self" is > "open(item, 'w')" so the first thing your line does is opening for > writing the file named by "item" and as "w" empty the file ... you can > read it afterward, it will be empty ! Ah! well spotted Pierre, I hadn't noticed that both input and output files were the same file! Alan G. From alan.gauld at freenet.co.uk Fri Feb 4 11:20:38 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 11:19:53 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <f2ff2d0502021518547f14c0@mail.gmail.com><86626245450c1bfcf3190400baffe178@yahoo.fr><9bb26ab5f9c3d8166f27d39464b9c750@yahoo.fr><f2ff2d0502021642627b77ee@mail.gmail.com><56abcbca5acfdc78d0b13c480c1af850@yahoo.fr><021301c509d5$89daa960$68b78851@xp><93fef199885ae5cf5b466c6e0e724ae5@yahoo.fr><42029ECA.2070305@ccvcorp.com><02ff01c50a46$7d75d570$68b78851@xp><4202BC9F.8080800@ccvcorp.com><f2ff2d05020316257f11e493@mail.gmail.com> <037301c50a9d$15b40630$68b78851@xp> Message-ID: <03ad01c50aa3$36f41500$68b78851@xp> > and function. Its like the theory behind how elictricity Yikes! Did I really manage to type elictricity And I can't blame finger trouble, e and i are miles apart on the keyboard! Blush.... Alan G. From maxnoel_fr at yahoo.fr Fri Feb 4 11:47:08 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri Feb 4 11:47:14 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <035b01c50a99$31229070$68b78851@xp> References: <C4C644CF4ADA9448904C3E8BACC4B97C02E6738B@medexch1.medplus.com><031901c50a49$e5142440$68b78851@xp> <6b97374ce906150985bb042f036797ba@yahoo.fr> <035b01c50a99$31229070$68b78851@xp> Message-ID: <3f7e4a2ab102617eb48349ae27a6171b@yahoo.fr> On Feb 4, 2005, at 09:09, Alan Gauld wrote: > Correct. The style you show (which I called Pascal style) is > the one that doesn't work. K&R style > >> if(foo) { >> bar; >> } > > > Is the one that won the shootout. > > With the outsider(which I dont know a name for!) beating both... > > if (foo) > { > bar; > } According to the Jargon file, this one is called Whitesmiths style. I tend to use Allman style myself, but given the code completion, spellchecking, etc. in modern IDEs, I suspect it's become more a question of personal preference than anything else. A bit like if(foo) versus if (foo), and whether or not to use braces for single-line blocks. (the latter issue being why I think The Whitespace Thing is an instance of Best Thing Ever(TM)) -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From rschroev_nospam_ml at fastmail.fm Fri Feb 4 12:14:43 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri Feb 4 12:15:16 2005 Subject: [Tutor] Re: Are you allowed to shoot camels? [kinda OT] In-Reply-To: <030b01c50a48$15e2df00$68b78851@xp> References: <C4C644CF4ADA9448904C3E8BACC4B97C02E67387@medexch1.medplus.com> <030b01c50a48$15e2df00$68b78851@xp> Message-ID: <ctvldn$cud$1@sea.gmane.org> Alan Gauld wrote: >>I also wish Python would take up the C ternary operator >>which is also quite clear and elegant. > > > :-) > You joke I assume? ':?' is clear? Its succinct but also > prone to abuse. I don't think the Python equivalent > > foo = x and y or z > > > is much less elegant than > > foo = x ? y : z You must be joking too... You think that x and y or z is as clear as x ? y : z even though the former is just a hack that was not meant to be used as such, while the latter is a well-documented feature that is designed to do what it does? Ugly as I think it is, I could live with that. But it's worse: x and y or z doesn't even work if y evaluates to False. That alone makes me never want to use the construct: whether the expression evaluates to y or z should depend on the value of x, not the value of y or z. As far as I'm concerned, the lack of a proper ternary if/then/else operator is a wart in the otherwise very clean design of Python. The lack of a switch statement too, but to a much lesser degree. -- "Codito ergo sum" Roel Schroeven From rschroev_nospam_ml at fastmail.fm Fri Feb 4 12:26:17 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri Feb 4 12:26:40 2005 Subject: [Tutor] Re: Are you allowed to shoot camels? [kinda OT] In-Reply-To: <031901c50a49$e5142440$68b78851@xp> References: <C4C644CF4ADA9448904C3E8BACC4B97C02E6738B@medexch1.medplus.com> <031901c50a49$e5142440$68b78851@xp> Message-ID: <ctvm3d$eln$1@sea.gmane.org> Alan Gauld wrote: > In fact the best style of all is neither of the two I showed, > its actually this - which early everyone hates when they see it! > > inf f(x) > { > bah() > } Yikes. We use that style at work. At first I found it ugly, but I thought I'd get used to it after a while. Well, 3 years later I still find it ugly and, more importantly, much harder to understand the structure. Do you have a link to these studies? I'm always skeptical about the methodology in those studies, but I'm willing to be proven wrong. -- "Codito ergo sum" Roel Schroeven From rschroev_nospam_ml at fastmail.fm Fri Feb 4 12:31:48 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri Feb 4 12:32:02 2005 Subject: [Tutor] Re: Are you allowed to shoot camels? [kinda OT] In-Reply-To: <037d01c50a9d$e01d0a70$68b78851@xp> References: <C4C644CF4ADA9448904C3E8BACC4B97C02E6738B@medexch1.medplus.com><031901c50a49$e5142440$68b78851@xp> <200502031843.37545.budr@netride.net> <037d01c50a9d$e01d0a70$68b78851@xp> Message-ID: <ctvmdo$fjv$1@sea.gmane.org> Alan Gauld wrote: > Look at it conceptually: > > XXXXXXXXXXXX > XXXXX > XXXXX > XXXXX > > Thats Python! Since you are on this list I suspect you do write > "code like that" Its just Guido removed the now extraneous {}... My favorite, Allman style, is also Python if you remove the {} ! BTW, Steve McConnell recommends your favorite too in Code Complete. But he also didn't manage to convince me. -- "Codito ergo sum" Roel Schroeven From melnyk at gmail.com Fri Feb 4 12:38:51 2005 From: melnyk at gmail.com (Scott Melnyk) Date: Fri Feb 4 12:38:54 2005 Subject: [Tutor] variation of Unique items question Message-ID: <dc4ecc9d0502040338179254e8@mail.gmail.com> Hello once more. I am stuck on how best to tie the finding Unique Items in Lists ideas to my file I am stuck at level below: What I have here taken from the unique items thread does not work as I need to separate each grouping to the hg chain it is in (see below for examples) import sys WFILE=open(sys.argv[1], 'w') def get_list_dup_dict(fname='Z:/datasets/fooyoo.txt', threshold=2): a_list=open(fname, 'r') #print "beginning get_list_dup" items_dict, dup_dict = {}, {} for i in a_list: items_dict[i] = items_dict.get(i, 0) + 1 for k, v in items_dict.iteritems(): if v==threshold: dup_dict[k] = v return dup_dict def print_list_dup_report(fname='Z:/datasets/fooyoo.txt', threshold=2): #print "Beginning report generation" dup_dict = get_list_dup_dict(fname='Z:/datasets/fooyoo.txt', threshold=2) for k, v in sorted(dup_dict.iteritems()): print WFILE,'%s occurred %s times' %(k, v) if __name__ == '__main__': print_list_dup_report() My issue is that my file is as follows: hg17_chainMm5_chr15 range=chr7:148238502-148239073 ENST00000339563.1 ENST00000342196.1 ENST00000339563.1 ENST00000344055.1 hg17_chainMm5_chr13 range=chr5:42927967-42928726 ENST00000279800.3 ENST00000309556.3 hg17_chainMm5_chr6 range=chr1:155548627-155549517 ENST00000321157.3 ENST00000256324.4 I need a print out that would give the line hg17.... and then any instances of the ENST that occur more than once only for that chain section. Even better it only prints the hg17 line if it is followed by an instance of ENST that occurs more than once I am hoping for something that gives me an out file roughly like: hg17_chainMm5_chr15 range=chr7:148238502-148239073 ENST00000339563.1 occurs 2 times hg17_chainMm5_chr13 range=chr5:42927967-42928726 ENST00000279800.3 occurs 2 times All help and ideas appreciated, I am trying to get this finished as soon as possible, the output file will be used to go back to my 2 gb file and pull out the rest of the data I need. Thanks, Scott From rschroev_nospam_ml at fastmail.fm Fri Feb 4 12:38:14 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri Feb 4 12:40:16 2005 Subject: [Tutor] Re: Are you allowed to shoot camels? [kinda OT] In-Reply-To: <20050204025418.49854.qmail@web54307.mail.yahoo.com> References: <20050204025418.49854.qmail@web54307.mail.yahoo.com> Message-ID: <ctvmpq$gha$1@sea.gmane.org> Chad Crabtree wrote: > How about a concrete example where lambda is more elegant than a > named > block of code > > aList=['a','bb','ccc','dddd','ee'] > bList=aList[:] #deep copy > assert not bList is aList > > def sortByLength(item1,item2): > return cmp(len(item1),len(item2)) > > bList.sort(sortByLength) > assert bList==['a', 'bb', 'ee', 'ccc', 'dddd'] > > aList.sort(lambda x,y:cmp(len(x),len(y))) > assert aList==['a', 'bb', 'ee', 'ccc', 'dddd'] > > Now this is a concrete example of how lambda simplifies code, at > least for me because it does not clutter my mental name space. Also > it is much shorter. However it should be said that this is very much > a question of taste. Indeed. In this case, I like the version without lambda. Naming the function serves as documentation, so I don't even need to read an interpret the body of the function to know what it does. Assuming that the name correctly describes the behavior of course, but I need to check that only once. From then on, sort(sortByLength) instantly explains what it does, while sort(lambda x,y: cmp(len(x),len(y)) needs much more parsing. But I agree that there are cases where lambda is more useful and/or clearer. -- "Codito ergo sum" Roel Schroeven From kent37 at tds.net Fri Feb 4 13:22:17 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Feb 4 13:22:23 2005 Subject: [Tutor] variation of Unique items question In-Reply-To: <dc4ecc9d0502040338179254e8@mail.gmail.com> References: <dc4ecc9d0502040338179254e8@mail.gmail.com> Message-ID: <420368F9.3060705@tds.net> You need to reset your items_dict when you see an hg17 line. Here is one way to do it. I used a class to make it easier to break the problem into functions. Putting the functions in a class makes it easy to share the header and counts. class Grouper: ''' Process a sequence of strings of the form Header Data Data Header ... Look for repeated Data items under a single Header. When found, print the Header and the repeated item. Possible usage: out = open('outfile.txt', 'w') Grouper().process(open('infile.txt'), 'hg17', out) out.close() ''' def reset(self, header='No header'): ''' Reset the current header and counts ''' self.currHeader = header self.counts = {} def process(self, data, headerStart, out): ''' Find duplicates within groups of lines of data ''' self.reset() for line in data: line = line.strip() # get rid of newlines from file input if line.startswith(headerStart): # Found a new header line, show the current group and restart self.showDups(out) self.reset(line) elif line: # Found a data line, count it self.counts[line] = self.counts.get(line, 0) + 1 # Show the last group self.showDups(out) def showDups(self, out): # Get list of items with count > 1 items = [ (k, cnt) for k, cnt in self.counts.items() if cnt > 1 ] # Show the items if items: items.sort() print >> out, self.currHeader for k, cnt in sorted(items): print >> out, '%s occurs %d times' % (k, cnt) print >> out if __name__ == '__main__': import sys data = '''hg17_chainMm5_chr15 range=chr7:148238502-148239073 ENST00000339563.1 ENST00000342196.1 ENST00000339563.1 ENST00000344055.1 hg17_chainMm5_chr13 range=chr5:42927967-42928726 ENST00000279800.3 ENST00000309556.3 ENST00000279800.3 hg17_chainMm5_chr6 range=chr1:155548627-155549517 ENST00000321157.3 ENST00000256324.4'''.split('\n') Grouper().process(data, 'hg17', sys.stdout) Kent Scott Melnyk wrote: > Hello once more. > > I am stuck on how best to tie the finding Unique Items in Lists ideas to my file > > I am stuck at level below: What I have here taken from the unique > items thread does not work as I need to separate each grouping to the > hg chain it is in (see below for examples) > > import sys > WFILE=open(sys.argv[1], 'w') > def get_list_dup_dict(fname='Z:/datasets/fooyoo.txt', threshold=2): > a_list=open(fname, 'r') > #print "beginning get_list_dup" > items_dict, dup_dict = {}, {} > > for i in a_list: > items_dict[i] = items_dict.get(i, 0) + 1 > > for k, v in items_dict.iteritems(): > if v==threshold: > dup_dict[k] = v > > return dup_dict > > def print_list_dup_report(fname='Z:/datasets/fooyoo.txt', threshold=2): > #print "Beginning report generation" > dup_dict = get_list_dup_dict(fname='Z:/datasets/fooyoo.txt', threshold=2) > for k, v in sorted(dup_dict.iteritems()): > print WFILE,'%s occurred %s times' %(k, v) > > if __name__ == '__main__': > print_list_dup_report() > > > My issue is that my file is as follows: > hg17_chainMm5_chr15 range=chr7:148238502-148239073 > ENST00000339563.1 > ENST00000342196.1 > ENST00000339563.1 > ENST00000344055.1 > > hg17_chainMm5_chr13 range=chr5:42927967-42928726 > ENST00000279800.3 > ENST00000309556.3 > > hg17_chainMm5_chr6 range=chr1:155548627-155549517 > ENST00000321157.3 > ENST00000256324.4 > > I need a print out that would give the line hg17.... and then any > instances of the ENST that occur more than once only for that chain > section. Even better it only prints the hg17 line if it is followed > by an instance of ENST that occurs more than once > > I am hoping for something that gives me an out file roughly like: > > hg17_chainMm5_chr15 range=chr7:148238502-148239073 > ENST00000339563.1 occurs 2 times > > hg17_chainMm5_chr13 range=chr5:42927967-42928726 > ENST00000279800.3 occurs 2 times > > > All help and ideas appreciated, I am trying to get this finished as > soon as possible, the output file will be used to go back to my 2 gb > file and pull out the rest of the data I need. > > Thanks, > Scott > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From h-tamm at ti.com Fri Feb 4 14:18:28 2005 From: h-tamm at ti.com (Tamm, Heiko) Date: Fri Feb 4 14:18:32 2005 Subject: [Tutor] Hex to Str Message-ID: <812D33B03107804389D6F4247B69EFAC3A2927@dfre2k03.itg.ti.com> Hello, I like to know, if it's possible to convert a Hex number into String or other formats? How can it be done? Kind regards Heiko -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050204/1b144def/attachment.htm From pierre.barbier at cirad.fr Fri Feb 4 14:34:32 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Fri Feb 4 14:32:29 2005 Subject: [Tutor] Hex to Str In-Reply-To: <812D33B03107804389D6F4247B69EFAC3A2927@dfre2k03.itg.ti.com> References: <812D33B03107804389D6F4247B69EFAC3A2927@dfre2k03.itg.ti.com> Message-ID: <420379E8.8010804@cirad.fr> Given you have a number in 'a' : hex(a) returns the hexadecimal representation of 'a' as a string ! You can also try : "%x" % a After that, I don't know if there is some builtin to print a number in any base you want ! Pierre Tamm, Heiko a ?crit : > Hello, > > I like to know, if it's possible to convert a Hex number into String or > other formats? > > How can it be done? > > > Kind regards > > Heiko > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 From kent37 at tds.net Fri Feb 4 14:36:50 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Feb 4 14:36:56 2005 Subject: [Tutor] Hex to Str In-Reply-To: <812D33B03107804389D6F4247B69EFAC3A2927@dfre2k03.itg.ti.com> References: <812D33B03107804389D6F4247B69EFAC3A2927@dfre2k03.itg.ti.com> Message-ID: <42037A72.2040207@tds.net> Use the hex() function to convert an integer to a hex string representation: >>> hex(54) '0x36' >>> hex(0x54) '0x54' or for more control use %x string formatting: >>> '%x' % 54 '36' >>> '%04X' % 0xab '00AB' etc. Kent Tamm, Heiko wrote: > Hello, > > I like to know, if it's possible to convert a Hex number into String or > other formats? > > How can it be done? > > > Kind regards > > Heiko > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From h-tamm at ti.com Fri Feb 4 14:36:54 2005 From: h-tamm at ti.com (Tamm, Heiko) Date: Fri Feb 4 14:37:17 2005 Subject: [Tutor] Hex to Str - still an open issue Message-ID: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> Thank you, Pierre, But I'm looking for a solution to convert a Hex number into binary, decimal, interger numbers. E.g.: What is the the binary value of the hex number 1F4. Is there a function available, or how can it be done? Kind regards and a nice weekend Heiko -----Original Message----- From: Pierre Barbier de Reuille [mailto:pierre.barbier@cirad.fr] Sent: Friday, February 04, 2005 2:35 PM To: Tamm, Heiko Cc: tutor@python.org Subject: Re: [Tutor] Hex to Str Given you have a number in 'a' : hex(a) returns the hexadecimal representation of 'a' as a string ! You can also try : "%x" % a After that, I don't know if there is some builtin to print a number in any base you want ! Pierre Tamm, Heiko a ?crit : > Hello, > > I like to know, if it's possible to convert a Hex number into String > or other formats? > > How can it be done? > > > Kind regards > > Heiko > > > > ---------------------------------------------------------------------- > -- > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 From ewald.ertl at hartter.com Fri Feb 4 14:37:37 2005 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Fri Feb 4 14:37:41 2005 Subject: [Tutor] Hex to Str In-Reply-To: <812D33B03107804389D6F4247B69EFAC3A2927@dfre2k03.itg.ti.com> References: <812D33B03107804389D6F4247B69EFAC3A2927@dfre2k03.itg.ti.com> Message-ID: <20050204143737.00006e81@sunray1> Hello Heiko, I do not really know what you like to get, but the hex-number's in Python are usedd in a numeric representation. As far as I have seen in the interpreter, this depends on the value: >>> a=0xaaaaabbbbbccccccddddddd >>> type(a) <type 'long'> >>> a=0xaabb >>> type(a) <type 'int'> If you like to see the number as a hex-String you can use >>> hex(a) '0xaabb' the representation as an octal number >>> oct(a) '0125273' HTH Ewald on Fri, 4 Feb 2005 14:18:28 +0100 "Tamm, Heiko" <h-tamm@ti.com> wrote : --------------------------------------------------------------------------------------------- Tamm, Heiko > Hello, Tamm, Heiko > Tamm, Heiko > I like to know, if it's possible to convert a Hex number into String or Tamm, Heiko > other formats? Tamm, Heiko > Tamm, Heiko > How can it be done? Tamm, Heiko > Tamm, Heiko > Tamm, Heiko > Kind regards Tamm, Heiko > Tamm, Heiko > Heiko ------------------- end ---------------------- From kent37 at tds.net Fri Feb 4 14:50:42 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Feb 4 14:50:46 2005 Subject: [Tutor] Hex to Str - still an open issue In-Reply-To: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> Message-ID: <42037DB2.8060207@tds.net> You might be interested in these: http://groups-beta.google.com/group/comp.lang.python/msg/c2cb941ea70dcdad http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/111286 Kent Tamm, Heiko wrote: > Thank you, Pierre, > > But I'm looking for a solution to convert a Hex number into binary, decimal, interger numbers. > > E.g.: > > What is the the binary value of the hex number 1F4. > > Is there a function available, or how can it be done? > > > > Kind regards and a nice weekend > > Heiko > > > > -----Original Message----- > From: Pierre Barbier de Reuille [mailto:pierre.barbier@cirad.fr] > Sent: Friday, February 04, 2005 2:35 PM > To: Tamm, Heiko > Cc: tutor@python.org > Subject: Re: [Tutor] Hex to Str > > Given you have a number in 'a' : > > hex(a) > > returns the hexadecimal representation of 'a' as a string ! > You can also try : > > "%x" % a > > After that, I don't know if there is some builtin to print a number in any base you want ! > > Pierre > > Tamm, Heiko a ?crit : > >>Hello, >> >>I like to know, if it's possible to convert a Hex number into String >>or other formats? >> >>How can it be done? >> >> >>Kind regards >> >> Heiko >> >> >> >>---------------------------------------------------------------------- >>-- >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor > > > -- > Pierre Barbier de Reuille > > INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde > 34398 MONTPELLIER CEDEX 5, France > > tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From melnyk at gmail.com Fri Feb 4 14:57:00 2005 From: melnyk at gmail.com (Scott Melnyk) Date: Fri Feb 4 14:57:03 2005 Subject: [Tutor] Re: variation of Unique items question Message-ID: <dc4ecc9d050204055767d75e3a@mail.gmail.com> Hello. Kent once again you have responded incredibly quickly in a most helpful manor. I sometimes wonder if the old reference to a "Kent-bot" has some truth to it. Thanks again, I will play with it and keep on going. Scott From h-tamm at ti.com Fri Feb 4 15:11:00 2005 From: h-tamm at ti.com (Tamm, Heiko) Date: Fri Feb 4 15:11:08 2005 Subject: [Tutor] Hex to Str - still an open issue Message-ID: <812D33B03107804389D6F4247B69EFAC3A294F@dfre2k03.itg.ti.com> Ok, thank you. Does anybody know how to convert a HEX into a BINARY? Best regards Heiko -----Original Message----- From: Pierre Barbier de Reuille [mailto:pierre.barbier@cirad.fr] Sent: Friday, February 04, 2005 2:55 PM To: Tamm, Heiko Subject: Re: [Tutor] Hex to Str - still an open issue Oh ! You meant the other way around ? If you have a string with an Hex number in it it's very easy : a = int("F04", 16) you can replace "16" with every base you want :) After that, to get an octal representation : "%o" % a But I don't know for binary representation ... nor for any other base :( That's somthing missing I think ! Pierre Tamm, Heiko a ?crit : > Thank you, Pierre, > > But I'm looking for a solution to convert a Hex number into binary, decimal, interger numbers. > > E.g.: > > What is the the binary value of the hex number 1F4. > > Is there a function available, or how can it be done? > > > > Kind regards and a nice weekend > > Heiko > > > > -----Original Message----- > From: Pierre Barbier de Reuille [mailto:pierre.barbier@cirad.fr] > Sent: Friday, February 04, 2005 2:35 PM > To: Tamm, Heiko > Cc: tutor@python.org > Subject: Re: [Tutor] Hex to Str > > Given you have a number in 'a' : > > hex(a) > > returns the hexadecimal representation of 'a' as a string ! > You can also try : > > "%x" % a > > After that, I don't know if there is some builtin to print a number in any base you want ! > > Pierre > > Tamm, Heiko a ?crit : > >>Hello, >> >>I like to know, if it's possible to convert a Hex number into String >>or other formats? >> >>How can it be done? >> >> >>Kind regards >> >> Heiko >> >> >> >>---------------------------------------------------------------------- >>-- >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor > > > -- > Pierre Barbier de Reuille > > INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et > Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de > la Lironde > 34398 MONTPELLIER CEDEX 5, France > > tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 > -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 From jsmith at medplus.com Fri Feb 4 15:11:35 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Fri Feb 4 15:11:44 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: <C4C644CF4ADA9448904C3E8BACC4B97C02E673B1@medexch1.medplus.com> The problem with if/elif is that it doesn't express what is actually gong on. What you are try to do is "execute a block of code based on the value of a single statement." if/elif doesn't do that and thereby introduces the possibility of errors. switch on-this: case 'a': do something case 'b': do something else case 'c': do yet something else Is much clearer and more maintatinable than if on-this == 'a': do something elif on-this == 'b': do something else elif on-this == 'c': do yet something else Note that the logic intended is that "on-this." So why force the programmer to rewrite it N times and thereby introduce the possibility of N-1 typographical errors...particularly if the "on-this" is sufficiently complex. Note that I've left out break. I'm not convinced that fall-through is an important feature in switch and is usually the culpit in the cases of abuse. Of course, abuse has nothing to do with it. Someone somewhere will abuse any syntax you give them. Just because it *can* be abused doesn't mean it doesn't have value when used properly. This is also true for the ternary operator. The desired logic is to assign the value of a variable based on the value of some other variable. The assignment is the primary action and therefore should be the primary feature in the statement. Using if/else makes the decision point the primary action and leads to people stuffing other things in the clauses which don't belong there. IMHO, if/elif/else statements are far more abused than either switch or ternary but I certainly wouldn't argue they should be removed from the language. I also like Perl's unless statement but really prefer VBs DO/WHILE/UNTIL/LOOP constuct. Nothing beats it for clarity of expression. Jeff -----Original Message----- From: Alan Gauld [mailto:alan.gauld@freenet.co.uk] Sent: Thursday, February 03, 2005 6:29 PM To: Smith, Jeff; Jacob S.; Nicholas.Montpetit@deluxe.com; tutor@python.org Subject: Re: [Tutor] Are you allowed to shoot camels? [kinda OT] > Perl and Python both resist the introduction of a switch statement > which I (and many others) feel is the most elegant way to express > what it does. Interesting. What do you feel is the problem with elif? Its not even much more typing and allows for much more expressive test conditions. Switch is really only useful for a single subset of tests. And of course switch statements are notorious bug factories and maintenance nightmares - the reason why OOP tries to eliminate them wherever possible. > I also wish Python would take up the C ternary operator > which is also quite clear and elegant. :-) You joke I assume? ':?' is clear? Its succinct but also prone to abuse. I don't think the Python equivalent foo = x and y or z is much less elegant than foo = x ? y : z > ... To paraphrase the famous quote: There are no good programming languages, just some that aren't as bad in some situations. Absolutely true. I still use assembler occasionally, and I even like bits of COBOL (although not much, its my least favourite language!). And probably my favourite language of all is Logo even though I've never used it for any serious projects. Alan G. From jsmith at medplus.com Fri Feb 4 15:17:46 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Fri Feb 4 15:17:54 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: <C4C644CF4ADA9448904C3E8BACC4B97C02E673B2@medexch1.medplus.com> Disagree to disagree again. I certainly don't think Perl is less capable than awk. And awk is only easier to learn because there's less to it. If someone only wanted to use Perl for exactly what awk does I suspect they would find Perl easier. And awk's terseness is part of what I don't like about it. Unwrapping those statement's and puzzling out what they do can be hellish. Of course, I do understand that if you use it every day, you get use to it like any other language...then again, that was the whole theory behinf APL :-) For what it's worth, I'm a big fan of LISP and Prolog but can't find any reason to really use them any more. And for whoever complained about the proprietary language they have to use daily, I suggest you take a look at ADA. It was intended to be self documenting and was designed by committee. They started with Pascal and decided it was too terse :-) PROCEDURE myfun Became PROCEDURE myfun BODY IS (or something similar, it's been years...err, decades) Jeff -----Original Message----- From: Alan Gauld [mailto:alan.gauld@freenet.co.uk] Sent: Thursday, February 03, 2005 6:31 PM To: Smith, Jeff; Nicholas.Montpetit@deluxe.com Cc: tutor@python.org; tutor-bounces@python.org Subject: Re: [Tutor] Are you allowed to shoot camels? [kinda OT] > We'll just have to have to disagree about awk. > I starting learning Perl to avoid learning awk :-) Really? Why for? awk is far easier to learn than Perl - and far less generally capable! - but it makes Perl seem positively verbose! Alan G. From kent37 at tds.net Fri Feb 4 15:58:20 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Feb 4 15:58:22 2005 Subject: [Tutor] Hex to Str - still an open issue In-Reply-To: <812D33B03107804389D6F4247B69EFAC3A294F@dfre2k03.itg.ti.com> References: <812D33B03107804389D6F4247B69EFAC3A294F@dfre2k03.itg.ti.com> Message-ID: <42038D8C.9020503@tds.net> Please give us an example of what you would like to do since we don't seem to understand. Imagine there is a function that does exactly what you want and show how you would use it and what results you would get. Repeating the same question is not likely to get a better answer, just more guesses. Kent Tamm, Heiko wrote: > > > Ok, thank you. > > > Does anybody know how to convert a HEX into a BINARY? > > > Best regards > > > Heiko > > > > > > -----Original Message----- > From: Pierre Barbier de Reuille [mailto:pierre.barbier@cirad.fr] > Sent: Friday, February 04, 2005 2:55 PM > To: Tamm, Heiko > Subject: Re: [Tutor] Hex to Str - still an open issue > > Oh ! You meant the other way around ? > > If you have a string with an Hex number in it it's very easy : > > a = int("F04", 16) > > you can replace "16" with every base you want :) > > After that, to get an octal representation : > > "%o" % a > > But I don't know for binary representation ... nor for any other base :( That's somthing missing I think ! > > Pierre > > Tamm, Heiko a ?crit : > >>Thank you, Pierre, >> >>But I'm looking for a solution to convert a Hex number into binary, decimal, interger numbers. >> >>E.g.: >> >>What is the the binary value of the hex number 1F4. >> >>Is there a function available, or how can it be done? >> >> >> >>Kind regards and a nice weekend >> >> Heiko >> >> >> >>-----Original Message----- >>From: Pierre Barbier de Reuille [mailto:pierre.barbier@cirad.fr] >>Sent: Friday, February 04, 2005 2:35 PM >>To: Tamm, Heiko >>Cc: tutor@python.org >>Subject: Re: [Tutor] Hex to Str >> >>Given you have a number in 'a' : >> >>hex(a) >> >>returns the hexadecimal representation of 'a' as a string ! >>You can also try : >> >>"%x" % a >> >>After that, I don't know if there is some builtin to print a number in any base you want ! >> >>Pierre >> >>Tamm, Heiko a ?crit : >> >> >>>Hello, >>> >>>I like to know, if it's possible to convert a Hex number into String >>>or other formats? >>> >>>How can it be done? >>> >>> >>>Kind regards >>> >>> Heiko >>> >>> >>> >>>---------------------------------------------------------------------- >>>-- >>> >>>_______________________________________________ >>>Tutor maillist - Tutor@python.org >>>http://mail.python.org/mailman/listinfo/tutor >> >> >>-- >>Pierre Barbier de Reuille >> >>INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et >>Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de >>la Lironde >>34398 MONTPELLIER CEDEX 5, France >> >>tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 >> > > > -- > Pierre Barbier de Reuille > > INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde > 34398 MONTPELLIER CEDEX 5, France > > tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Fri Feb 4 16:02:25 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Feb 4 16:02:27 2005 Subject: [Tutor] Re: variation of Unique items question In-Reply-To: <dc4ecc9d050204055767d75e3a@mail.gmail.com> References: <dc4ecc9d050204055767d75e3a@mail.gmail.com> Message-ID: <42038E81.4020906@tds.net> I will give some credit to you for asking a clear question. You included - a clear description of what you want to do - sample data - desired results - code that attempts to solve the problem When all of these are present I am much more likely to respond. The first three elements especially make a big difference. Kent Scott Melnyk wrote: > Hello. > > Kent once again you have responded incredibly quickly in a most > helpful manor. I sometimes wonder if the old reference to a > "Kent-bot" has some truth to it. > > Thanks again, I will play with it and keep on going. > > Scott > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From bill.mill at gmail.com Fri Feb 4 17:46:23 2005 From: bill.mill at gmail.com (Bill Mill) Date: Fri Feb 4 17:46:27 2005 Subject: [Tutor] Hex to Str - still an open issue In-Reply-To: <812D33B03107804389D6F4247B69EFAC3A294F@dfre2k03.itg.ti.com> References: <812D33B03107804389D6F4247B69EFAC3A294F@dfre2k03.itg.ti.com> Message-ID: <797fe3d4050204084621c71f06@mail.gmail.com> Tamm, Try searching before you get snippy on a group where people are helping you for free. This question gets asked a lot, and the answer can be found all over the place. A particularly comprehensive thread discussing the issue can be found at http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/bdd85f1d1298a191 . Peace Bill Mill bill.mill at gmail.com On Fri, 4 Feb 2005 15:11:00 +0100, Tamm, Heiko <h-tamm@ti.com> wrote: > > > Ok, thank you. > > Does anybody know how to convert a HEX into a BINARY? > > Best regards > > > Heiko > > -----Original Message----- > From: Pierre Barbier de Reuille [mailto:pierre.barbier@cirad.fr] > Sent: Friday, February 04, 2005 2:55 PM > To: Tamm, Heiko > Subject: Re: [Tutor] Hex to Str - still an open issue > > Oh ! You meant the other way around ? > > If you have a string with an Hex number in it it's very easy : > > a = int("F04", 16) > > you can replace "16" with every base you want :) > > After that, to get an octal representation : > > "%o" % a > > But I don't know for binary representation ... nor for any other base :( That's somthing missing I think ! > > Pierre > > Tamm, Heiko a ?crit : > > Thank you, Pierre, > > > > But I'm looking for a solution to convert a Hex number into binary, decimal, interger numbers. > > > > E.g.: > > > > What is the the binary value of the hex number 1F4. > > > > Is there a function available, or how can it be done? > > > > > > > > Kind regards and a nice weekend > > > > Heiko > > > > > > > > -----Original Message----- > > From: Pierre Barbier de Reuille [mailto:pierre.barbier@cirad.fr] > > Sent: Friday, February 04, 2005 2:35 PM > > To: Tamm, Heiko > > Cc: tutor@python.org > > Subject: Re: [Tutor] Hex to Str > > > > Given you have a number in 'a' : > > > > hex(a) > > > > returns the hexadecimal representation of 'a' as a string ! > > You can also try : > > > > "%x" % a > > > > After that, I don't know if there is some builtin to print a number in any base you want ! > > > > Pierre > > > > Tamm, Heiko a ?crit : > > > >>Hello, > >> > >>I like to know, if it's possible to convert a Hex number into String > >>or other formats? > >> > >>How can it be done? > >> > >> > >>Kind regards > >> > >> Heiko > >> > >> > >> > >>---------------------------------------------------------------------- > >>-- > >> > >>_______________________________________________ > >>Tutor maillist - Tutor@python.org > >>http://mail.python.org/mailman/listinfo/tutor > > > > > > -- > > Pierre Barbier de Reuille > > > > INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et > > Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de > > la Lironde > > 34398 MONTPELLIER CEDEX 5, France > > > > tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 > > > > -- > Pierre Barbier de Reuille > > INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde > 34398 MONTPELLIER CEDEX 5, France > > tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at freenet.co.uk Fri Feb 4 19:13:31 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 19:13:24 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <C4C644CF4ADA9448904C3E8BACC4B97C02E673B1@medexch1.medplus.com> Message-ID: <03b901c50ae5$3c94cb20$68b78851@xp> > What you are try to do is "execute a block of code based on the value of > a single statement." if/elif doesn't do that and thereby introduces the > possibility of errors. In that case the best solution is a dictionary jump table. That is more maintainable than either and much faster too. And its also shorter to write. [Especially with lambdas :-)] > Note that the logic intended is that "on-this." So why force the > programmer to rewrite it N times and thereby introduce the possibility > of N-1 typographical errors... Thats a fair point although the dictionary solution avoids that. OTOH such switches tend to proliferate thropugh code and become a big source of maintenance headaches in their own right - multiple update syndrome across multiple files potentially. > Note that I've left out break. I'm not convinced that > fall-through is an important feature in switch and is > usually the culpit in the cases of abuse. The problem is its so hard to tell when fall though is happening intentionally or by accident because someone forgot a break sytatement. But when it comes to abuuse the fall through mechanism is one of the worst offenders in C, its just too tempting to be "clever" with it. > This is also true for the ternary operator. The desired logic is to > assign the value of a variable based on the value of some other > variable. But its not its based on the value of an *expression*. If the test could be limited to a single valiable value it might be justified but its an arbitrary expression. That makes it a conditional statement, which is most clearly represented by an if/else... Well I think so :-) > I also like Perl's unless statement but really prefer > VBs DO/WHILE/UNTIL/LOOP constuct. Nothing beats it for > clarity of expression. I won't argue on either point, Python's minimalist approach - there's only one way to do it - means a paucity of looping constructs - something I point out in my tutorial. But I can live with it for the other niceties it brings. Alan G. From flaxeater at yahoo.com Fri Feb 4 19:22:14 2005 From: flaxeater at yahoo.com (Chad Crabtree) Date: Fri Feb 4 19:22:19 2005 Subject: [Tutor] Re: This Deletes All my Files Message-ID: <20050204182214.28143.qmail@web54310.mail.yahoo.com> Thank you all for answering my question. I thought it would be some misunderstanding on my part. The example Andrei made was very telling. Andrei wrote: >>>>s = "d:/tests/test.txt" >>>>class dummyfile(object): >>>> >>>> >... def open(self, *args): >... print "dummyfile.open:", args >... def write(self, *args): >... print "dummyfile.write:", args >... def read(self, *args): >... print "dummyfile.read:", args >... return "" > > >>>>def dummyopen(filename, type): >>>> >>>> >... print "dummyopen:", filename, type >... d = dummyfile() >... d.open(filename, type) >... return d > > > >>>>dummyopen(s, 'w').write(dummyopen(s, 'r').read()) >>>> >>>> >dummyopen: d:/tests/test.txt w >dummyfile.open: ('d:/tests/test.txt', 'w') <--- first open for writing >dummyopen: d:/tests/test.txt r >dummyfile.open: ('d:/tests/test.txt', 'r') <--- then for reading >dummyfile.read: () >dummyfile.write: ('',) > > > >>spend 5 hours RTFM. I got it to work by breaking it up to several >>statements, but I would like to know. >> >> > >And that's the way you *should* write it - code like this doesn't deserve to >work anyway :). > >Yours, > >Andrei > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > __________________________________ Do you Yahoo!? The all-new My Yahoo! - Get yours free! http://my.yahoo.com From alan.gauld at freenet.co.uk Fri Feb 4 19:23:09 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 19:25:13 2005 Subject: [Tutor] Re: Are you allowed to shoot camels? [kinda OT] References: <C4C644CF4ADA9448904C3E8BACC4B97C02E67387@medexch1.medplus.com><030b01c50a48$15e2df00$68b78851@xp> <ctvldn$cud$1@sea.gmane.org> Message-ID: <03e001c50ae6$94dd15c0$68b78851@xp> > > foo = x and y or z > > > > is much less elegant than > > > > foo = x ? y : z > > You must be joking too... You think that > > x and y or z > > is as clear as > > x ? y : z I think its clearer! It says that the first two things happen or else the last thing. Plain English. '?:' means absolutely nothing without somebody to explain it. > Ugly as I think it is, I could live with that. But it's worse: > > x and y or z > > doesn't even work if y evaluates to False. Sure I wasn't recommending that and/or is a good idea I just meant that ugly as it was it was clearer than the meaningless ?: > As far as I'm concerned, the lack of a proper ternary if/then/else > operator is a wart in the otherwise very clean design of Python. The > lack of a switch statement too, but to a much lesser degree. Interesting, obviously a lot of support for both, yet they are features I try to avoid in C(*) and never miss in Python. If given the choice I'd much rather have decent lambdas or even a repeat/until loop! (*)And most software houses I've worked with have ternary operators on their "do not use" list along with switch fall-throughs. BTW I do confess that if switch exists I will use it where I can't use OOP or a dictionary to avoid it - like in vanilla C...! Alan G. From alan.gauld at freenet.co.uk Fri Feb 4 19:29:57 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 19:29:44 2005 Subject: [Tutor] Re: Are you allowed to shoot camels? [kinda OT] References: <C4C644CF4ADA9448904C3E8BACC4B97C02E6738B@medexch1.medplus.com><031901c50a49$e5142440$68b78851@xp> <ctvm3d$eln$1@sea.gmane.org> Message-ID: <03e501c50ae7$882e0e50$68b78851@xp> > Do you have a link to these studies? I'm always skeptical about the > methodology in those studies, but I'm willing to be proven wrong. Check "Code Complete" by Steve McConnel, he gives the explanation and also several references. One that I found from a quick glance is "Hansen & Yim, 1987". Also a bibliography(!) on the subject of code style is cited: "Edward & Oman in Sigplan Notices Feb 1990". McConnell has a new version of his book out it may have more recent references too, I only have the 1993 edition at hand. Alan G. From alan.gauld at freenet.co.uk Fri Feb 4 19:32:30 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 19:32:23 2005 Subject: [Tutor] Re: Are you allowed to shoot camels? [kinda OT] References: <C4C644CF4ADA9448904C3E8BACC4B97C02E6738B@medexch1.medplus.com><031901c50a49$e5142440$68b78851@xp> <200502031843.37545.budr@netride.net><037d01c50a9d$e01d0a70$68b78851@xp> <ctvmdo$fjv$1@sea.gmane.org> Message-ID: <03ea01c50ae7$e2ffb860$68b78851@xp> > > XXXXXXXXXXXX > > XXXXX > > XXXXX > > XXXXX > > > > Thats Python! Since you are on this list I suspect you do write > > "code like that" Its just Guido removed the now extraneous {}... > > My favorite, Allman style, is also Python if you remove the {} ! Yep but the braces in Allman completely wreck the block structure XXXXXXXXXXXXXXXXX XXX XXXXXX XXX > BTW, Steve McConnell recommends your favorite too in Code Complete. But > he also didn't manage to convince me. Thats where I first found it, I looked up a couple of references and the message was consistent, so I changed my style. (And my emacs settings :-) Alan G. From alan.gauld at freenet.co.uk Fri Feb 4 19:37:46 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 19:37:33 2005 Subject: [Tutor] Hex to Str References: <812D33B03107804389D6F4247B69EFAC3A2927@dfre2k03.itg.ti.com> Message-ID: <03fe01c50ae8$9f5d4ef0$68b78851@xp> > I like to know, if it's possible to convert a Hex number into > String or other formats? Use the string format operator: >>> print "%X" % 0xB5 B5 >>> print "%X" % 181 B5 Lowercase '%x' uses lowercase letters on output... Or use the int() function with a base argument to go the other way: >>> print int('0xB5',16) 181 string to integer - which is of course stored in binary format in the computer! Alan G. From alan.gauld at freenet.co.uk Fri Feb 4 19:43:15 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 19:43:15 2005 Subject: [Tutor] Hex to Str - still an open issue References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> Message-ID: <041401c50ae9$63c21a50$68b78851@xp> > But I'm looking for a solution to convert a Hex number > into binary, decimal, interger numbers. WE need to be very specific about our terminology here. All numbers in the computer are stored in binary. Only the string representation on the screen is in decimal, octal, hex etc. > What is the the binary value of the hex number 1F4. The binary value is the same as the hex value. The binary representation is 000111110100, but unfortunately Python doesn't support binary in its string formatting(although it does in int()! It does support decimal(%d) and octal(%o) though. And if you search the list archives you will find several functions that you can use to generate binary strings. Alan G. From flaxeater at yahoo.com Fri Feb 4 19:44:20 2005 From: flaxeater at yahoo.com (Chad Crabtree) Date: Fri Feb 4 19:44:25 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: <20050204184421.16624.qmail@web54301.mail.yahoo.com> Max Noel wrote: > > According to the Jargon file, this one is called Whitesmiths > style. I tend to use Allman style myself, but given the code > completion, spellchecking, etc. in modern IDEs, I suspect it's become > more a question of personal preference than anything else. > > A bit like if(foo) versus if (foo), and whether or not to use > braces for single-line blocks. (the latter issue being why I think The > Whitespace Thing is an instance of Best Thing Ever(TM)) Bracing single line expressions is something I constantly agonize over. I'm always thinking may as well brace it because I may want to add more to this if clause. That's one of the reasons I like python is because it's relatively painless to make sure that your blocks are closed properly, especially when you aren't using a decent IDE. __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From alan.gauld at freenet.co.uk Fri Feb 4 19:51:58 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 19:51:56 2005 Subject: [Tutor] Hex to Str - still an open issue References: <812D33B03107804389D6F4247B69EFAC3A294F@dfre2k03.itg.ti.com> Message-ID: <042001c50aea$9d0e1ce0$68b78851@xp> > Does anybody know how to convert a HEX into a BINARY? The easiest way I know is to use a lookup table on the octal representation. def bin(n): bins = ['000','001','010,'011',....'111'] result = '' for c in oct(n): result += bins[int(c,8)] return result HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Fri Feb 4 19:54:05 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 19:54:03 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <C4C644CF4ADA9448904C3E8BACC4B97C02E673B2@medexch1.medplus.com> Message-ID: <042601c50aea$e6edb410$68b78851@xp> > Disagree to disagree again. I certainly don't think Perl is less > capable than awk. Neither do I... >> Really? Why for? awk is far easier to learn than Perl >> - and far less generally capable! - but it makes Perl seem >> positively verbose! I said awk was easier to learn but less capable than Perl. Perl is capable of things that awk can only dream of! Alan G. From rschroev_nospam_ml at fastmail.fm Fri Feb 4 20:00:15 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri Feb 4 20:01:36 2005 Subject: [Tutor] Re: Are you allowed to shoot camels? [kinda OT] In-Reply-To: <03e001c50ae6$94dd15c0$68b78851@xp> References: <C4C644CF4ADA9448904C3E8BACC4B97C02E67387@medexch1.medplus.com><030b01c50a48$15e2df00$68b78851@xp> <ctvldn$cud$1@sea.gmane.org> <03e001c50ae6$94dd15c0$68b78851@xp> Message-ID: <cu0gmg$5o3$1@sea.gmane.org> Alan Gauld wrote: >>>foo = x and y or z >>> >>>is much less elegant than >>> >>>foo = x ? y : z >> >>You must be joking too... You think that >> >>x and y or z >> >>is as clear as >> >>x ? y : z > > > I think its clearer! It says that the first two things happen > or else the last thing. Plain English. That's apparently subjective then. I know what it means because I've read about it, but I still have trouble really grokking it. I don't have any problem with 'x and y' or with 'x or y', but somehow the combination of the two is one step too many for me. > '?:' means absolutely nothing without somebody to explain it. But ever since it was explained to me, I can parse it in the blink of an eye. (x**2 for x in range(10)) didn't mean anything to me either, the first time I saw it. > Interesting, obviously a lot of support for both, yet they are > features I try to avoid in C(*) and never miss in Python. If > given the choice I'd much rather have decent lambdas or > even a repeat/until loop! I don't really try to avoid them; I just use them when appropriate, which is not very often. But in those rare cases, I'm glad I don't have to resort to other, less appropriate constructs. And yes, a decent lambda would be nice indeed. Repeat/until too: I used it quite a lot in my Pascal days. But I don't know if it's worth cluttering the language up for. > (*)And most software houses I've worked with have ternary > operators on their "do not use" list along with switch fall-throughs. In my experience, such lists often go too far in that respect. I agree that fall-trough should mostly be avoided (except when multiple values should leed to the same branch). Ternary operators can certainly be abused (as demonstrated by much of the IOCCC entries), but can absolutely be useful when judisciously used. Many such lists seem to assume that developers can't judge such things for themselves. I think that if you have developers that can't do that, you have worse problems than a ternary operator here and there. -- "Codito ergo sum" Roel Schroeven From rschroev_nospam_ml at fastmail.fm Fri Feb 4 20:02:46 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri Feb 4 20:11:41 2005 Subject: [Tutor] Re: Are you allowed to shoot camels? [kinda OT] In-Reply-To: <03ea01c50ae7$e2ffb860$68b78851@xp> References: <C4C644CF4ADA9448904C3E8BACC4B97C02E6738B@medexch1.medplus.com><031901c50a49$e5142440$68b78851@xp> <200502031843.37545.budr@netride.net><037d01c50a9d$e01d0a70$68b78851@xp> <ctvmdo$fjv$1@sea.gmane.org> <03ea01c50ae7$e2ffb860$68b78851@xp> Message-ID: <cu0gr6$5o3$2@sea.gmane.org> Alan Gauld wrote: >>BTW, Steve McConnell recommends your favorite too in Code Complete. > > But > >>he also didn't manage to convince me. > > > Thats where I first found it, I looked up a couple of references and > the > message was consistent, so I changed my style. (And my emacs settings > :-) I'll have to read that part of the book again. But I don't have my hopes up since three years of using it at work didn't change my feelings about it (and not for a lack of trying). -- "Codito ergo sum" Roel Schroeven From dyoo at hkn.eecs.berkeley.edu Fri Feb 4 20:15:51 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Feb 4 20:15:56 2005 Subject: [Tutor] switch vs table dispatch In-Reply-To: <C4C644CF4ADA9448904C3E8BACC4B97C02E673B1@medexch1.medplus.com> Message-ID: <Pine.LNX.4.44.0502041053180.2828-100000@hkn.eecs.berkeley.edu> On Fri, 4 Feb 2005, Smith, Jeff wrote: > What you are try to do is "execute a block of code based on the value of > a single statement." if/elif doesn't do that and thereby introduces the > possibility of errors. > > switch on-this: > case 'a': > do something > case 'b': > do something else > case 'c': > do yet something else > > Is much clearer and more maintatinable than > > if on-this == 'a': > do something > elif on-this == 'b': > do something else > elif on-this == 'c': > do yet something else Hi Jeff, if/elif chains like this can be improved by using a table-dispatch technique: ### Python Pseudocode ### def doActionA(): ... def doActionB(): ... def doActionC(): ... dispatchTable = { 'a' : doActionA, 'b' : doActionB, 'c' : doActionC } dispatchTable[on_this]() ###### We perfectly agree with you about the hideousness of using if/elif/elif to do a 'switch'-style control flow. But that's not the only tool in our arsenal. *grin* switch() in other languages like C or Java have other limitations that are hard to explain to beginners. As one concrete example: we can't use a string as the dispatch value in Java's switch. We're restricted to use chars, bytes, shorts, or ints, due to the low-level implementation nature of 'switch': http://java.sun.com/docs/books/jls/second_edition/html/statements.doc.html#35518 (I believe the expression is used as an index into a jump table, which limits it to something small and numeric.) Ultimately, this restricts the use of 'switch' to simple dispatch tasks, and we can already handle those nicely with a dictionary lookup. Hope this helps! From jeff at ccvcorp.com Fri Feb 4 22:23:06 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri Feb 4 22:22:25 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <C4C644CF4ADA9448904C3E8BACC4B97C02E673B1@medexch1.medplus.com> References: <C4C644CF4ADA9448904C3E8BACC4B97C02E673B1@medexch1.medplus.com> Message-ID: <4203E7BA.30109@ccvcorp.com> Smith, Jeff wrote: > IMHO, if/elif/else statements are far more abused than either switch or > ternary but I certainly wouldn't argue they should be removed from the > language. IMHO, if it's true that if/elif/else statements are more abused than ternaries, then it's only because they're *used* far more often than ternaries. I'd say that the percentage of uses which could count as abuse is *far* higher for ternary than for if/elif/else. And I avoid (and recommend against) Python's "a and b or c" trick for similar reasons -- it *is* a trick. A 'real' ternary operator is confusing enough; this trick is more readable (words instead of opaque symbols) but more difficult to write correctly given the constraints on 'a'... Maybe I'm just weird, but I just don't find so much benefit to putting *everything* in-line. Occassionally it improves readability, but more often it obscures and obfuscates. Jeff Shannon Technician/Programmer Credit International From jsmith at medplus.com Fri Feb 4 22:36:44 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Fri Feb 4 22:36:50 2005 Subject: [Tutor] Re: Are you allowed to shoot camels? [kinda OT] Message-ID: <C4C644CF4ADA9448904C3E8BACC4B97C02E6741F@medexch1.medplus.com> Roel, That was well put. Too many people complain about certain language features because of the way they are abused independent of whether or not they have any value when used properly. In that case it's throwing the baby out with the bath-water...and won't achieve anything since bad programmers will be bad programmers no matter how much you try and constrain them. And in doing so you manage to prevent good programmers from creating clear conscise statements that exactly express the logic that they are trying to impliment. Jeff -----Original Message----- From: Roel Schroeven [mailto:rschroev_nospam_ml@fastmail.fm] Sent: Friday, February 04, 2005 2:00 PM To: tutor@python.org Subject: [Tutor] Re: Are you allowed to shoot camels? [kinda OT] In my experience, such lists often go too far in that respect. I agree that fall-trough should mostly be avoided (except when multiple values should leed to the same branch). Ternary operators can certainly be abused (as demonstrated by much of the IOCCC entries), but can absolutely be useful when judisciously used. Many such lists seem to assume that developers can't judge such things for themselves. I think that if you have developers that can't do that, you have worse problems than a ternary operator here and there. From patrick at kirks.net Fri Feb 4 22:47:58 2005 From: patrick at kirks.net (Patrick Kirk) Date: Fri Feb 4 22:48:00 2005 Subject: [Tutor] Small GUI toolkit and executable creators Message-ID: <4203ED8E.9090407@kirks.net> Hi all, I'm writing an application that will distributed by download and want it to be as small as possible. The target platform is Windows. For the GUI toolkit, I am looking at wxPython and tkinter. For a small application with only 4 working forms, which can be expected to produce the smaller programs? To create executables, I'm looking at using py2exe - http://starship.python.net/crew/theller/py2exe/ or Installer - http://davidf.sjsoft.com/mirrors/mcmillan-inc/install1.html Has anyone any comments on which produces smaller executables and and if either is qualitively better than the other. Thanks in advance. Patrick From jsmith at medplus.com Fri Feb 4 22:55:53 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Fri Feb 4 22:56:00 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: <C4C644CF4ADA9448904C3E8BACC4B97C02E67421@medexch1.medplus.com> Now who's joking? Are you saying that switch var: case 'a': print 'a' case 'b' or 'c': print 'b or c' case 'd': pass default: print 'default case' Is less clear and maintainable than def do_this_function(): print 'a' def do_that_function(): print 'b or c' def do_pass_function(): pass def do_default_function(): print 'default case' ftable = { 'a' : do_this_function, 'b' : do_that_function, 'c' : do_that_function, 'd' : do_pass_function } ftable.get(var, do_default_function)() Ugh! -----Original Message----- From: Alan Gauld [mailto:alan.gauld@freenet.co.uk] Sent: Friday, February 04, 2005 1:14 PM To: Smith, Jeff; Jacob S.; Nicholas.Montpetit@deluxe.com; tutor@python.org Subject: Re: [Tutor] Are you allowed to shoot camels? [kinda OT] > What you are try to do is "execute a block of code based on the value of > a single statement." if/elif doesn't do that and thereby introduces the > possibility of errors. In that case the best solution is a dictionary jump table. That is more maintainable than either and much faster too. And its also shorter to write. [Especially with lambdas :-)] > Note that the logic intended is that "on-this." So why force the > programmer to rewrite it N times and thereby introduce the possibility > of N-1 typographical errors... Thats a fair point although the dictionary solution avoids that. OTOH such switches tend to proliferate thropugh code and become a big source of maintenance headaches in their own right - multiple update syndrome across multiple files potentially. > Note that I've left out break. I'm not convinced that fall-through is > an important feature in switch and is usually the culpit in the cases > of abuse. The problem is its so hard to tell when fall though is happening intentionally or by accident because someone forgot a break sytatement. But when it comes to abuuse the fall through mechanism is one of the worst offenders in C, its just too tempting to be "clever" with it. > This is also true for the ternary operator. The desired logic is to > assign the value of a variable based on the value of some other > variable. But its not its based on the value of an *expression*. If the test could be limited to a single valiable value it might be justified but its an arbitrary expression. That makes it a conditional statement, which is most clearly represented by an if/else... Well I think so :-) > I also like Perl's unless statement but really prefer > VBs DO/WHILE/UNTIL/LOOP constuct. Nothing beats it for clarity of > expression. I won't argue on either point, Python's minimalist approach - there's only one way to do it - means a paucity of looping constructs - something I point out in my tutorial. But I can live with it for the other niceties it brings. Alan G. From marilyn at deliberate.com Fri Feb 4 23:07:14 2005 From: marilyn at deliberate.com (Marilyn Davis) Date: Fri Feb 4 23:12:03 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <C4C644CF4ADA9448904C3E8BACC4B97C02E67421@medexch1.medplus.com> Message-ID: <Pine.LNX.4.44.0502041401230.27971-100000@Kuna> I think Danny was saying that if you don't like: if var == 'a': print 'a' elif var == 'b' or var == 'c': print 'b or c' elif var == 'd': pass else: print 'default case' you might like his dispatch scheme. And it has been mighty nice and handy for me since he taught me, in some special cases. I'll whisper that I'm a tiny bit disappointed to see the vaguely demeaning 'are you joking' theme that has emerged in here. It's unusual for us to be anything but generous and kind with each other. I guess this is a hot topic. :^) Marilyn On Fri, 4 Feb 2005, Smith, Jeff wrote: > Now who's joking? Are you saying that > > switch var: > case 'a': > print 'a' > case 'b' or 'c': > print 'b or c' > case 'd': > pass > default: > print 'default case' > > Is less clear and maintainable than > > def do_this_function(): > print 'a' > > def do_that_function(): > print 'b or c' > > def do_pass_function(): > pass > > def do_default_function(): > print 'default case' > > ftable = { 'a' : do_this_function, > 'b' : do_that_function, > 'c' : do_that_function, > 'd' : do_pass_function } > ftable.get(var, do_default_function)() > > Ugh! > > > -----Original Message----- > From: Alan Gauld [mailto:alan.gauld@freenet.co.uk] > Sent: Friday, February 04, 2005 1:14 PM > To: Smith, Jeff; Jacob S.; Nicholas.Montpetit@deluxe.com; > tutor@python.org > Subject: Re: [Tutor] Are you allowed to shoot camels? [kinda OT] > > > > What you are try to do is "execute a block of code based on the > value of > > a single statement." if/elif doesn't do that and thereby introduces > the > > possibility of errors. > > In that case the best solution is a dictionary jump table. > That is more maintainable than either and much faster too. > And its also shorter to write. > [Especially with lambdas :-)] > > > Note that the logic intended is that "on-this." So why force the > > programmer to rewrite it N times and thereby introduce the > possibility > > of N-1 typographical errors... > > Thats a fair point although the dictionary solution avoids that. OTOH > such switches tend to proliferate thropugh code and become a big source > of maintenance headaches in their own right - multiple update syndrome > across multiple files potentially. > > > Note that I've left out break. I'm not convinced that fall-through is > > > an important feature in switch and is usually the culpit in the cases > > of abuse. > > The problem is its so hard to tell when fall though is happening > intentionally or by accident because someone forgot a break sytatement. > > But when it comes to abuuse the fall through mechanism is one of the > worst offenders in C, its just too tempting to be "clever" with it. > > > This is also true for the ternary operator. The desired logic is to > > assign the value of a variable based on the value of some other > > variable. > > But its not its based on the value of an *expression*. If the test could > be limited to a single valiable value it might be justified but its an > arbitrary expression. That makes it a conditional statement, which is > most clearly represented by an if/else... Well I think so :-) > > > I also like Perl's unless statement but really prefer > > VBs DO/WHILE/UNTIL/LOOP constuct. Nothing beats it for clarity of > > expression. > > I won't argue on either point, Python's minimalist > approach - there's only one way to do it - means a > paucity of looping constructs - something I point > out in my tutorial. But I can live with it for the > other niceties it brings. > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- From project5 at redrival.net Fri Feb 4 23:16:12 2005 From: project5 at redrival.net (Andrei) Date: Fri Feb 4 23:16:42 2005 Subject: [Tutor] Re: Small GUI toolkit and executable creators References: <4203ED8E.9090407@kirks.net> Message-ID: <1fjuzrb22jpfw.18mlutwc2tokg$.dlg@40tude.net> Patrick Kirk wrote on Fri, 04 Feb 2005 21:47:58 +0000: > I'm writing an application that will distributed by download and want it > to be as small as possible. The target platform is Windows. Python isn't the right choice if your aim is minimum "executable" size. I wouldn't worry too much about it though, people are perfectly used to downloading multi-megabyte applications and service packs which run into the hundreds of megabytes. > For the GUI toolkit, I am looking at wxPython and tkinter. For a small > application with only 4 working forms, which can be expected to produce > the smaller programs? I have no idea. The number of forms is not relevant, since it's the toolkit that takes up all the space, not the forms. I can tell you that a packaged wxPython app is roughly 4 MB, don't know about Tkinter. wxPython looks better (more native) though. > Has anyone any comments on which produces smaller executables and and if > either is qualitively better than the other. You shouldn't expect much difference in that respect, since they all do pretty much the same thing: pack up the junk and put an exe stub on it, and there's only so much compressing you can do. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From jsmith at medplus.com Fri Feb 4 23:18:49 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Fri Feb 4 23:19:24 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: <C4C644CF4ADA9448904C3E8BACC4B97C02E67428@medexch1.medplus.com> Please don't take offense. I should have included the smiley. To reiterate an earlier statement: I like Python...a lot. But as with all langauges there are some things I don't like and I believe they were left out for the wrong reasons. On the indentation topic. I would be curious to know if anyone has had an experience where a rogue process or editor has trashed the indentation in your Python and how you recovered from it. Jeff -----Original Message----- From: Marilyn Davis [mailto:marilyn@deliberate.com] Sent: Friday, February 04, 2005 5:07 PM To: tutor@python.org Subject: RE: [Tutor] Are you allowed to shoot camels? [kinda OT] I think Danny was saying that if you don't like: if var == 'a': print 'a' elif var == 'b' or var == 'c': print 'b or c' elif var == 'd': pass else: print 'default case' you might like his dispatch scheme. And it has been mighty nice and handy for me since he taught me, in some special cases. I'll whisper that I'm a tiny bit disappointed to see the vaguely demeaning 'are you joking' theme that has emerged in here. It's unusual for us to be anything but generous and kind with each other. I guess this is a hot topic. :^) Marilyn On Fri, 4 Feb 2005, Smith, Jeff wrote: > Now who's joking? Are you saying that > > switch var: > case 'a': > print 'a' > case 'b' or 'c': > print 'b or c' > case 'd': > pass > default: > print 'default case' > > Is less clear and maintainable than > > def do_this_function(): > print 'a' > > def do_that_function(): > print 'b or c' > > def do_pass_function(): > pass > > def do_default_function(): > print 'default case' > > ftable = { 'a' : do_this_function, > 'b' : do_that_function, > 'c' : do_that_function, > 'd' : do_pass_function } > ftable.get(var, do_default_function)() > > Ugh! > > > -----Original Message----- > From: Alan Gauld [mailto:alan.gauld@freenet.co.uk] > Sent: Friday, February 04, 2005 1:14 PM > To: Smith, Jeff; Jacob S.; Nicholas.Montpetit@deluxe.com; > tutor@python.org > Subject: Re: [Tutor] Are you allowed to shoot camels? [kinda OT] > > > > What you are try to do is "execute a block of code based on the > value of > > a single statement." if/elif doesn't do that and thereby introduces > the > > possibility of errors. > > In that case the best solution is a dictionary jump table. That is > more maintainable than either and much faster too. And its also > shorter to write. [Especially with lambdas :-)] > > > Note that the logic intended is that "on-this." So why force the > > programmer to rewrite it N times and thereby introduce the > possibility > > of N-1 typographical errors... > > Thats a fair point although the dictionary solution avoids that. OTOH > such switches tend to proliferate thropugh code and become a big > source of maintenance headaches in their own right - multiple update > syndrome across multiple files potentially. > > > Note that I've left out break. I'm not convinced that fall-through > > is > > > an important feature in switch and is usually the culpit in the > > cases > > of abuse. > > The problem is its so hard to tell when fall though is happening > intentionally or by accident because someone forgot a break > sytatement. > > But when it comes to abuuse the fall through mechanism is one of the > worst offenders in C, its just too tempting to be "clever" with it. > > > This is also true for the ternary operator. The desired logic is to > > assign the value of a variable based on the value of some other > > variable. > > But its not its based on the value of an *expression*. If the test > could be limited to a single valiable value it might be justified but > its an arbitrary expression. That makes it a conditional statement, > which is most clearly represented by an if/else... Well I think so :-) > > > I also like Perl's unless statement but really prefer > > VBs DO/WHILE/UNTIL/LOOP constuct. Nothing beats it for clarity of > > expression. > > I won't argue on either point, Python's minimalist > approach - there's only one way to do it - means a > paucity of looping constructs - something I point > out in my tutorial. But I can live with it for the > other niceties it brings. > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From budr at netride.net Fri Feb 4 23:28:58 2005 From: budr at netride.net (Bud Rogers) Date: Fri Feb 4 23:30:20 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <037d01c50a9d$e01d0a70$68b78851@xp> References: <C4C644CF4ADA9448904C3E8BACC4B97C02E6738B@medexch1.medplus.com> <200502031843.37545.budr@netride.net> <037d01c50a9d$e01d0a70$68b78851@xp> Message-ID: <200502041628.59359.budr@netride.net> On Friday 04 February 2005 03:42, Alan Gauld wrote: > On Thursday 03 February 2005 17:41, Alan Gauld wrote: > >> In fact the best style of all is neither of the two I showed, > >> its actually this - which early everyone hates when they see it! > >> > >> inf f(x) > >> { > >> bah() > >> } > > > >Ugh. Alan, I won't even try to dispute the study. But if I have to > >write code like that, I'll just take up gardening instead. :} > > Look at it conceptually: > > XXXXXXXXXXXX > XXXXX > XXXXX > XXXXX > > Thats Python! Since you are on this list I suspect you do write > "code like that" Its just Guido removed the now extraneous {}... Oh yes, you are absolutely right. If you remove the braces, all three (four?) styles of indentation are conceptually identical AFAICS. My objection is purely personal and aesthetic. The style above is just plain ugly to me. I'm not clear on which style is which, but I think the Allman style(?): if (foo) { bar; } is also ugly but slightly less so. The K&R style(?): if (foo) { bar; } is what I use in perl. I wouldn't go so far as to say it's pretty, it's just the least ugly of the styles I know about. And of course from a personal aesthetic perspective, I think python style is much prettier. Well written python reads like pseudocode. It's actually pleasant to read. If a routine is well written, with good variable names, etc, you don't even have to know much about python to understand what it does. That's one of the things that attracted me to python in the first place. -- Bud Rogers <budr@netride.net> KD5SZ From cyresse at gmail.com Fri Feb 4 23:36:58 2005 From: cyresse at gmail.com (Liam Clarke) Date: Fri Feb 4 23:37:01 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <C4C644CF4ADA9448904C3E8BACC4B97C02E67428@medexch1.medplus.com> References: <C4C644CF4ADA9448904C3E8BACC4B97C02E67428@medexch1.medplus.com> Message-ID: <f2ff2d050204143618f7da0a@mail.gmail.com> I had a problem with nested while 1: ... . ... ... break blocks. So, I got some sleep, fixed it, and now do everything in my power to not nest while 1 - break blocks. Not that it's really relevant. On Fri, 4 Feb 2005 17:18:49 -0500, Smith, Jeff <jsmith@medplus.com> wrote: > Please don't take offense. I should have included the smiley. To > reiterate an earlier statement: I like Python...a lot. But as with all > langauges there are some things I don't like and I believe they were > left out for the wrong reasons. > > On the indentation topic. I would be curious to know if anyone has had > an experience where a rogue process or editor has trashed the > indentation in your Python and how you recovered from it. > > Jeff > > -----Original Message----- > From: Marilyn Davis [mailto:marilyn@deliberate.com] > Sent: Friday, February 04, 2005 5:07 PM > To: tutor@python.org > Subject: RE: [Tutor] Are you allowed to shoot camels? [kinda OT] > > I think Danny was saying that if you don't like: > > if var == 'a': > print 'a' > elif var == 'b' or var == 'c': > print 'b or c' > elif var == 'd': > pass > else: > print 'default case' > > you might like his dispatch scheme. And it has been mighty nice and > handy for me since he taught me, in some special cases. > > I'll whisper that I'm a tiny bit disappointed to see the vaguely > demeaning 'are you joking' theme that has emerged in here. It's unusual > for us to be anything but generous and kind with each other. I guess > this is a hot topic. :^) > > Marilyn > > On Fri, 4 Feb 2005, Smith, Jeff wrote: > > > Now who's joking? Are you saying that > > > > switch var: > > case 'a': > > print 'a' > > case 'b' or 'c': > > print 'b or c' > > case 'd': > > pass > > default: > > print 'default case' > > > > Is less clear and maintainable than > > > > def do_this_function(): > > print 'a' > > > > def do_that_function(): > > print 'b or c' > > > > def do_pass_function(): > > pass > > > > def do_default_function(): > > print 'default case' > > > > ftable = { 'a' : do_this_function, > > 'b' : do_that_function, > > 'c' : do_that_function, > > 'd' : do_pass_function } > > ftable.get(var, do_default_function)() > > > > Ugh! > > > > > > -----Original Message----- > > From: Alan Gauld [mailto:alan.gauld@freenet.co.uk] > > Sent: Friday, February 04, 2005 1:14 PM > > To: Smith, Jeff; Jacob S.; Nicholas.Montpetit@deluxe.com; > > tutor@python.org > > Subject: Re: [Tutor] Are you allowed to shoot camels? [kinda OT] > > > > > > > What you are try to do is "execute a block of code based on the > > value of > > > a single statement." if/elif doesn't do that and thereby introduces > > the > > > possibility of errors. > > > > In that case the best solution is a dictionary jump table. That is > > more maintainable than either and much faster too. And its also > > shorter to write. [Especially with lambdas :-)] > > > > > Note that the logic intended is that "on-this." So why force the > > > programmer to rewrite it N times and thereby introduce the > > possibility > > > of N-1 typographical errors... > > > > Thats a fair point although the dictionary solution avoids that. OTOH > > such switches tend to proliferate thropugh code and become a big > > source of maintenance headaches in their own right - multiple update > > syndrome across multiple files potentially. > > > > > Note that I've left out break. I'm not convinced that fall-through > > > is > > > > > an important feature in switch and is usually the culpit in the > > > cases > > > of abuse. > > > > The problem is its so hard to tell when fall though is happening > > intentionally or by accident because someone forgot a break > > sytatement. > > > > But when it comes to abuuse the fall through mechanism is one of the > > worst offenders in C, its just too tempting to be "clever" with it. > > > > > This is also true for the ternary operator. The desired logic is to > > > assign the value of a variable based on the value of some other > > > variable. > > > > But its not its based on the value of an *expression*. If the test > > could be limited to a single valiable value it might be justified but > > its an arbitrary expression. That makes it a conditional statement, > > which is most clearly represented by an if/else... Well I think so :-) > > > > > I also like Perl's unless statement but really prefer > > > VBs DO/WHILE/UNTIL/LOOP constuct. Nothing beats it for clarity of > > > expression. > > > > I won't argue on either point, Python's minimalist > > approach - there's only one way to do it - means a > > paucity of looping constructs - something I point > > out in my tutorial. But I can live with it for the > > other niceties it brings. > > > > Alan G. > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > -- > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only ba sic human duty, to take the consequences. From pythontutor at yahoo.com Fri Feb 4 23:48:55 2005 From: pythontutor at yahoo.com (alieks lao) Date: Fri Feb 4 23:48:59 2005 Subject: [Tutor] arrays Message-ID: <20050204224855.33514.qmail@web61306.mail.yahoo.com> in this tutorial it's telling me to "from Numeric import *" to load array functions but it doesn't work is there a replacement for "Numeric" or are arrays built in functions? thanks alex __________________________________ Do you Yahoo!? Yahoo! Mail - Helps protect you from nasty viruses. http://promotions.yahoo.com/new_mail From dyoo at hkn.eecs.berkeley.edu Sat Feb 5 00:03:05 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Feb 5 00:03:08 2005 Subject: [Tutor] arrays In-Reply-To: <20050204224855.33514.qmail@web61306.mail.yahoo.com> Message-ID: <Pine.LNX.4.44.0502041501180.18141-100000@hkn.eecs.berkeley.edu> On Fri, 4 Feb 2005, alieks lao wrote: > in this tutorial it's telling me to > > "from Numeric import *" > > to load array functions > but it doesn't work is there a replacement for > "Numeric" or are arrays built in functions? Hi Alieks, Just out of curiosity, which tutorial are you reading? The 'Numeric' library isn't built-in: it is a third party library that's available here: http://www.pfdubois.com/numpy/ You'll need to install Numpy first; this should make the Numeric library available, and hopefully the error message should go away. *grin* Best of wishes to you! From kent37 at tds.net Sat Feb 5 00:13:49 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat Feb 5 00:13:53 2005 Subject: [Tutor] arrays In-Reply-To: <20050204224855.33514.qmail@web61306.mail.yahoo.com> References: <20050204224855.33514.qmail@web61306.mail.yahoo.com> Message-ID: <420401AD.3060506@tds.net> Numeric is an add-on module, not part of the standard distribution. You have to download it and install it. (I'm surprised your tutorial doesn't point that out!) Numeric is still in use but there is a newer version called numarray. You can read about them both here: http://www.pfdubois.com/numpy/ Kent alieks lao wrote: > in this tutorial it's telling me to > > "from Numeric import *" > > to load array functions > but it doesn't work is there a replacement for > "Numeric" or are arrays built in functions? > thanks > alex > > > > __________________________________ > Do you Yahoo!? > Yahoo! Mail - Helps protect you from nasty viruses. > http://promotions.yahoo.com/new_mail > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo at hkn.eecs.berkeley.edu Sat Feb 5 00:19:17 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Feb 5 00:19:21 2005 Subject: [Tutor] Whitespace indentation In-Reply-To: <C4C644CF4ADA9448904C3E8BACC4B97C02E67428@medexch1.medplus.com> Message-ID: <Pine.LNX.4.44.0502041508090.18141-100000@hkn.eecs.berkeley.edu> On Fri, 4 Feb 2005, Smith, Jeff wrote: > On the indentation topic. I would be curious to know if anyone has had > an experience where a rogue process or editor has trashed the > indentation in your Python and how you recovered from it. [Meta: switching subject line again --- this conversation seems to be veering off to other subtopics.] Hi Jeff, I have run into some whitespace issues, but it had more to do with line-ending terminators for code sent between Windows and Unix machines. But that's more of a Unix vs. Windows thing than anything else. *grin* On the whole, though, using indentation as blocks has worked really well for me, and hasn't been a liability. I do try to keep my code backed by a version control system like Subversion or CVS: http://subversion.tigris.org/ https://www.cvshome.org/ which seems to keep me safe from my own incompetence most of the time. Best of wishes to you! From dyoo at hkn.eecs.berkeley.edu Sat Feb 5 00:25:53 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Feb 5 00:25:56 2005 Subject: [Tutor] arrays In-Reply-To: <20050204231727.43074.qmail@web61306.mail.yahoo.com> Message-ID: <Pine.LNX.4.44.0502041521320.18141-100000@hkn.eecs.berkeley.edu> On Fri, 4 Feb 2005, alieks lao wrote: > > Just out of curiosity, which tutorial are you reading? > > heres the url... > http://www.pentangle.net/python/ Hi Alieks, Ah, ok, that makes sense now. Michael William's tutorial assumes an environment where some third-party modules, like Numeric, have already been installed by the Sun system administrators that the author refers to at the beginning of Chapter Two. So there will probably be small things in that coursebook that are really external resources. It would have been good for the author to explicitely mention things like Numeric though... oh well. We'll do what we can on Tutor to help if you run into issues like that again. Best of wishes! From alan.gauld at freenet.co.uk Sat Feb 5 00:39:10 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Feb 5 00:39:00 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <C4C644CF4ADA9448904C3E8BACC4B97C02E67421@medexch1.medplus.com> Message-ID: <045901c50b12$ba9ac830$68b78851@xp> > Now who's joking? :-) > Are you saying that > > switch var: > case 'a': > print 'a' > ... > default: > print 'default case' > > Is less clear and maintainable than I don;tthink I said (certainly didn't mean) less clear, but yes it is less maintainable. But then... > def do_this_function(): > print 'a' > .... > ftable = { 'a' : do_this_function, > 'b' : do_that_function, > 'c' : do_that_function, > 'd' : do_pass_function } > ftable.get(var, do_default_function)() I did also say that it was best with proper lambdas ftable = {'a' : lambda: print 'a', 'b' : lambda: print 'b' etc/// and I'd code the calling section: try: ftable[value]() except KeyError: doDefaultFunction() Its more maintainable because even if the switches proliferates as they tend to do, the dictionary stays in one place and the calling code never needs changing. So the changes are much more localised. And of course the more complex the case actions are, the more effective the dictionary/function approach becomes. Alan G. From alan.gauld at freenet.co.uk Sat Feb 5 01:18:25 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Feb 5 01:18:08 2005 Subject: [Tutor] Re: Are you allowed to shoot camels? [kinda OT] References: <C4C644CF4ADA9448904C3E8BACC4B97C02E67387@medexch1.medplus.com><030b01c50a48$15e2df00$68b78851@xp> <ctvldn$cud$1@sea.gmane.org><03e001c50ae6$94dd15c0$68b78851@xp> <cu0gmg$5o3$1@sea.gmane.org> Message-ID: <049901c50b18$3605fd50$68b78851@xp> > > I think its clearer! It says that the first two things happen > > or else the last thing. Plain English. > > That's apparently subjective then. So it seems. You always assume that whats clear to you will be clear to all! This discussion proves it ain't necessarily so... > eye. (x**2 for x in range(10)) didn't mean anything to me either, the > first time I saw it. Nor me and I knew comprehensions from Haskell. Its taken me about 203 years to get comfortable with LCS inPython. I really wish they'd stick a marker (| or : or even a $!) between the first item and the loop: [x**2 | for x in range(10)] I'd have found it much easier to grok. And I can't think iof any syntax rules of expressions it wouuld break. Do we use | as a bitwise operatorin Python? I don't think so... > absolutely be useful when judisciously used. Many such lists seem to > assume that developers can't judge such things for themselves. I think Having been involved in creating a couple such coding guidelines lists I can say from experience that they mostly reflect the problems the maintenance teams struggle with most. And having led a team of maintenance C programmers for 2 years I fully sympathise with the view that programmers can't judge very well. (And that includes myself, I am well aware that what seems perfectly clear to me when I write it may not be to some poor sap who has to fix/enhance it) And remember too that maintenance accounts for 80% of the cost on most software projects... Alan G. From alan.gauld at freenet.co.uk Sat Feb 5 01:24:21 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Feb 5 01:25:12 2005 Subject: [Tutor] Small GUI toolkit and executable creators References: <4203ED8E.9090407@kirks.net> Message-ID: <04a601c50b19$0a2ff450$68b78851@xp> > I'm writing an application that will distributed by download and want it > to be as small as possible. The target platform is Windows. In that case distribute Python source not executables! Or write in assembler... > For the GUI toolkit, I am looking at wxPython and tkinter. For a small > application with only 4 working forms, which can be expected to produce > the smaller programs? Sorry no idea on that one, any responses will be interesting. > To create executables, I'm looking at using > py2exe - http://starship.python.net/crew/theller/py2exe/ > or > Installer - http://davidf.sjsoft.com/mirrors/mcmillan-inc/install1.html Both will make your programs much bigger and, worse still, if you distribute updates each version with replicate the Python engine, better to do a two part downloiad IMHO - the python core then your programs as source(or compiled modules). Basically using Python for small downloads is probably not the best approach! But the really small sizes are much more effort to create! Alan G. From alan.gauld at freenet.co.uk Sat Feb 5 01:27:51 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Feb 5 01:27:38 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <Pine.LNX.4.44.0502041401230.27971-100000@Kuna> Message-ID: <04ad01c50b19$87635890$68b78851@xp> Marilyn, > I'll whisper that I'm a tiny bit disappointed to see the vaguely > demeaning 'are you joking' theme that has emerged in here. It's > unusual for us to be anything but generous and kind with each other. > I guess this is a hot topic. :^) Languages (and editors) are always emotional topics on the 'net... But I was actually thinking that here we are on a mailing list having a mini-language war and by internet standards its extremely civilised! Nobody has called anyone a moron or an idiot yet and an 'are you joking' is, to me at least, just a term of speech, not an insult. Certainly if anyone has been offended I apologise profusely it was never meant thus. Alan G. From alan.gauld at freenet.co.uk Sat Feb 5 01:29:40 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Feb 5 01:29:26 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <C4C644CF4ADA9448904C3E8BACC4B97C02E67428@medexch1.medplus.com> Message-ID: <04c001c50b19$c87e1040$68b78851@xp> > an experience where a rogue process or editor has trashed the > indentation in your Python and how you recovered from it. Only in mailing list emails!! Alan G. From marilyn at deliberate.com Sat Feb 5 01:51:28 2005 From: marilyn at deliberate.com (Marilyn Davis) Date: Sat Feb 5 01:56:17 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <04ad01c50b19$87635890$68b78851@xp> Message-ID: <Pine.LNX.4.44.0502041647350.27971-100000@Kuna> On Sat, 5 Feb 2005, Alan Gauld wrote: > Marilyn, > > > I'll whisper that I'm a tiny bit disappointed to see the vaguely > > demeaning 'are you joking' theme that has emerged in here. It's > > unusual for us to be anything but generous and kind with each other. > > I guess this is a hot topic. :^) > > Languages (and editors) are always emotional topics on the 'net... > > But I was actually thinking that here we are on a mailing list having > a mini-language war and by internet standards its extremely civilised! > Nobody has called anyone a moron or an idiot yet and an 'are you > joking' is, to me at least, just a term of speech, not an insult. > Certainly if anyone has been offended I apologise profusely it > was never meant thus. This is a great list. Please don't apologize. Super-super-sensitive people like me are reluctant to post if they sense ridicule, even if it wasn't intended. So I'm sorry for my sensitivity. Thank you again for all the great help I've received, and the safe place to expose my ignorance. Marilyn > > Alan G. > > -- From keridee at jayco.net Sat Feb 5 02:18:32 2005 From: keridee at jayco.net (Jacob S.) Date: Sat Feb 5 02:22:51 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <20050204025418.49854.qmail@web54307.mail.yahoo.com> Message-ID: <000801c50b21$435d6e30$575428cf@JSLAPTOP> > Now this is a concrete example of how lambda simplifies code, at > least > for me because it does not clutter my mental name space. Also it is > much shorter. However it should be said that this is very much a > question of taste. Agreed. Which would make it pointless to remove in a future release. ;-) > However I must say that lambda's are very useful > even necessary for using Tkinter. I'll bet that there is an easy enough way to use Tkinter without them (Before anyone wants to argue my points, I would like to say that I'm neutral in this discussion, I only wish to point out alternative views) > aFuncList=[] > def x(): > print "one" > aFuncList.append(x) > def x(): > print "two" > aFuncList.append(x) > def x(): > print "three" > aFuncList.append(x) > for item in aFuncList: > item() Okay, for this problem (it can be altered otherwise) def makefunct(stri): def x(): print stri return x aFuncList = [makefunct('one'),makefunct('two'),makefunct('three')] for item in aFuncList: item() It's shorter, it works and it looks cool. Thanks to Jeff Shannon for the backbone of this example. Jacob Schmidt From fant at pobox.com Sat Feb 5 00:27:03 2005 From: fant at pobox.com (Andrew D. Fant) Date: Sat Feb 5 02:46:56 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <042601c50aea$e6edb410$68b78851@xp> References: <C4C644CF4ADA9448904C3E8BACC4B97C02E673B2@medexch1.medplus.com> <042601c50aea$e6edb410$68b78851@xp> Message-ID: <420404C7.2030409@pobox.com> Alan Gauld wrote: > > I said awk was easier to learn but less capable than Perl. > > Perl is capable of things that awk can only dream of! Surely you jest, Alan. :-) Both perl and awk are turing complete, hence anything perl can do, awk can do as well. Now, as to which one would be easier to work with for a large scale development project, I will leave that flame-fest up to the regulars. Andy From bvande at po-box.mcgill.ca Sat Feb 5 04:31:41 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat Feb 5 04:32:56 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <420404C7.2030409@pobox.com> References: <C4C644CF4ADA9448904C3E8BACC4B97C02E673B2@medexch1.medplus.com> <042601c50aea$e6edb410$68b78851@xp> <420404C7.2030409@pobox.com> Message-ID: <42043E1D.30702@po-box.mcgill.ca> Andrew D. Fant said unto the world upon 2005-02-04 18:27: > Alan Gauld wrote: > >> >> I said awk was easier to learn but less capable than Perl. >> >> Perl is capable of things that awk can only dream of! > > > Surely you jest, Alan. :-) I'm prettry sure he means it. And stop calling him Surely ;-) Brian vdB From shitizb at yahoo.com Sat Feb 5 04:37:14 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Sat Feb 5 04:37:17 2005 Subject: [Tutor] freeze Message-ID: <20050205033715.43926.qmail@web53807.mail.yahoo.com> Hi, I intend to create compiled python binaries on linux. I understand that freeze can be used to do this. But I have few doubts i would like to clarify. 1. In the freeze documentation i found the lines: "One tricky issue: Freeze assumes that the Python interpreter and environment you're using to run Freeze is the same one that would be used to run your program, which should also be the same whose sources and installed files you will learn about in the next section. In particular, your PYTHONPATH setting should be the same as for running your program locally. (Tip: if the program doesn't run when you type "python hello.py" there's little chance of getting the frozen version to run.)" My intention is to create files which can be run on Linux systems with python not installed.Do the above lines mean that freeze can't do it(which defeats the very pupose of the program i guess.). 2. While compiling with freeze....it seems that it is including all the available modules, even if they are not required.Of course using freeze -X is one option,but it being really cumbersome, is there a better option available. In case the above issues do present a problem, is there any alternative to freeze? Shitiz __________________________________ Do you Yahoo!? The all-new My Yahoo! - Get yours free! http://my.yahoo.com From keridee at jayco.net Sat Feb 5 04:58:06 2005 From: keridee at jayco.net (Jacob S.) Date: Sat Feb 5 04:58:24 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <C4C644CF4ADA9448904C3E8BACC4B97C02E67428@medexch1.medplus.com> <04c001c50b19$c87e1040$68b78851@xp> Message-ID: <003501c50b36$eb4da140$215428cf@JSLAPTOP> >> an experience where a rogue process or editor has trashed the >> indentation in your Python and how you recovered from it. > > Only in mailing list emails!! I'll second that!!! Jacob > Alan G. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From keridee at jayco.net Sat Feb 5 05:22:12 2005 From: keridee at jayco.net (Jacob S.) Date: Sat Feb 5 05:22:33 2005 Subject: [Tutor] freeze References: <20050205033715.43926.qmail@web53807.mail.yahoo.com> Message-ID: <008201c50b3a$61e5dc70$215428cf@JSLAPTOP> My two bits. 1) Download py2exe found here http://py2exe.sourceforge.net/ 2) Make a setup file -- intructions can be found through above link, I think. (Hey that rhymes!) 3) Ask if you want my totally cool automation technique 4) Ask more questions, go on we don't mind. HTH, Jacob Schmidt > Hi, > > I intend to create compiled python binaries on linux. > I understand that freeze can be used to do this. > But I have few doubts i would like to clarify. > > 1. In the freeze documentation i found the lines: > > "One tricky issue: Freeze assumes that the Python > interpreter and > environment you're using to run Freeze is the same one > that would be > used to run your program, which should also be the > same whose sources > and installed files you will learn about in the next > section. In > particular, your PYTHONPATH setting should be the same > as for running > your program locally. (Tip: if the program doesn't > run when you type > "python hello.py" there's little chance of getting the > frozen version > to run.)" > > My intention is to create files which can be run on > Linux systems with python not installed.Do the above > lines mean that freeze can't do it(which defeats the > very pupose of the program i guess.). > > 2. While compiling with freeze....it seems that it is > including all the available modules, even if they are > not required.Of course using freeze -X is one > option,but it being really cumbersome, is there a > better option available. > > In case the above issues do present a problem, is > there any alternative to freeze? > > Shitiz > > > > __________________________________ > Do you Yahoo!? > The all-new My Yahoo! - Get yours free! > http://my.yahoo.com > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From keridee at jayco.net Sat Feb 5 05:30:19 2005 From: keridee at jayco.net (Jacob S.) Date: Sat Feb 5 05:30:07 2005 Subject: [Tutor] Hex to Str - still an open issue References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> <041401c50ae9$63c21a50$68b78851@xp> Message-ID: <00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> > The binary value is the same as the hex value. > The binary representation is 000111110100, but > unfortunately Python doesn't support binary in > its string formatting(although it does in int()! Uh, question. Why not? It seems that all simple types should be included. Since the computer stores it as binary, why shouldn't python be able to display a string of it in binary? That seems to be a short coming that should be added to the next release... IMHO of course. Jacob Schmidt From pythontutor at yahoo.com Sat Feb 5 06:23:05 2005 From: pythontutor at yahoo.com (alieks lao) Date: Sat Feb 5 06:23:08 2005 Subject: [Tutor] question about expressing mathematical equations Message-ID: <20050205052306.45646.qmail@web61302.mail.yahoo.com> Once again i have a question concerning something from the tutorial im being tortured by. ___ x.y= \ x (dot)y(dot) /__ i i How would i express this in python. If the above doesn't make any sense to ya'll. It's at the bottom of this page>>> http://www.pentangle.net/python/handbook/node33.html Again thanks in advance... alex __________________________________ Do you Yahoo!? The all-new My Yahoo! - Get yours free! http://my.yahoo.com From patrick at kirks.net Sat Feb 5 07:30:01 2005 From: patrick at kirks.net (Patrick Kirk) Date: Sat Feb 5 07:30:05 2005 Subject: [Tutor] Small GUI toolkit and executable creators In-Reply-To: <42043AFD.4040706@adinet.com.uy> References: <4203ED8E.9090407@kirks.net> <42043AFD.4040706@adinet.com.uy> Message-ID: <420467E9.5070908@kirks.net> That looks fine size wise. Thanks. Ismael Garrido wrote: > Patrick Kirk wrote: > >> Hi all, >> >> I'm writing an application that will distributed by download and want >> it to be as small as possible. The target platform is Windows. > > > Use UPX, 7Z and NSIS. ;-) (and in that order, too :-P) > That's with Py2exe, never tryed the other one. > > I made a program with Tkinter and managed to get it all together in > 1.8Mb, 8kb of source :-S > > Gretz > Ismael From dyoo at hkn.eecs.berkeley.edu Sat Feb 5 07:52:33 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Feb 5 07:52:38 2005 Subject: [Tutor] question about expressing mathematical equations In-Reply-To: <20050205052306.45646.qmail@web61302.mail.yahoo.com> Message-ID: <Pine.LNX.4.44.0502042230380.5463-100000@hkn.eecs.berkeley.edu> On Fri, 4 Feb 2005, alieks lao wrote: > Once again i have a question concerning something from the tutorial im > being tortured by. > > ___ > x.y= \ x (dot)y(dot) > /__ i > i > > How would i express this in python. > If the above doesn't make any sense to ya'll. > It's at the bottom of this page>>> > http://www.pentangle.net/python/handbook/node33.html [Note to author Michael Williams: we found a wacky typography bug on the HTML rendering of the link above. I'm CCing you to make sure you know about it.] Hi Alieks, Ah, ok, I see it: you're talking about exercise 3.10? The guide there is using linear algebra notation: it is defining the dot product between two vectors 'x' and 'y'. I think you're misreading the diagram: it's more like this: ___ x dot y= \ x * y /__ i i i (The period at the end of the equation is really meant to be just a typographic period. *grin*) As a concrete example, if we were taking the dot product between two sequences 'x' and 'y': x = (3, 1, 4, 1, 5) y = (2, 7, 1, 8, 2) then we'd be calculating, in effect: (x[0] * y[0] + x[1] * y[1] + x[2] * y[2] + x[3] * y[3] + x[4] * y[4]) --> ( 3 * 2 + 1 * 7 + 4 * 1 + 1 * 8 + 5 * 2 ) --> ( 6 + 7 + 4 + 8 + 10 ) --> 35 Numeric Python comes with an dot() function built in: http://www.pfdubois.com/numpy/html2/numpy-9.html#pgfId-36540 so if you're dealing strictly with Numeric arrays, you don't need to do any work to 'dot' two arrays together. *grin* ... Oh, that's not good! Warning: It looks like the typography of Exercise 3.10 in the HTML is screwed up. The problem as written in the HTML is nonsensical. Look at the PDF instead. You'll see that the question will make more sense in the PDF here: http://www.pentangle.net/python/handbook.pdf The GIF images in the HTML has some strange offset error that I don't understand, but img22.gif and img23.gif are in the wrong places on the HTML page. I'll CC the author to see if that can get fixed. I notice that you're learning from the "Handbook of the Physics Computing Course". There are other tutorials in: http://www.python.org/moin/BeginnersGuide/NonProgrammers that you may find more approachable if you want less math. Good luck to you! From alan.gauld at freenet.co.uk Sat Feb 5 09:59:30 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Feb 5 09:59:45 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <C4C644CF4ADA9448904C3E8BACC4B97C02E673B2@medexch1.medplus.com><042601c50aea$e6edb410$68b78851@xp> <420404C7.2030409@pobox.com> Message-ID: <04fc01c50b61$01535960$68b78851@xp> > Surely you jest, Alan. :-) Smiley noted but... > Both perl and awk are turing complete, hence anything perl can do, awk > can do as well. This is a popular misconception. Being Turing complete simply means you can implement any algorithm. But if the language doesn't provide I/O access for example it is impossible to write a device driver, or a comms stack, or any of a host of other low level programs. awk is non extendable (unless you have the source code!) so you can't do those things. Perl is not only extendable but actually comes wth a heap of those kinds of features that awk just doesn't have. And no amount of clever algorithms can compensate. Awk was designed for one task which it does spectacularly well but it was never intended for general purpose use. I/O is just one example, there are meny more... Alan G. From pythontutor at yahoo.com Sat Feb 5 11:47:12 2005 From: pythontutor at yahoo.com (alieks lao) Date: Sat Feb 5 11:47:15 2005 Subject: [Tutor] question about expressing mathematical equations In-Reply-To: <Pine.LNX.4.44.0502042230380.5463-100000@hkn.eecs.berkeley.edu> Message-ID: <20050205104712.68003.qmail@web61303.mail.yahoo.com> I've spent hours trying things out and I'm no better off. I don't understand exactly what I'm supposed to do... alieks __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050205/02ff0e20/attachment.html From cyresse at gmail.com Sat Feb 5 12:44:43 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sat Feb 5 12:44:46 2005 Subject: [Tutor] Hex to Str - still an open issue In-Reply-To: <00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> <041401c50ae9$63c21a50$68b78851@xp> <00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> Message-ID: <f2ff2d050205034498e84e@mail.gmail.com> Jacob - just for you, begin your agitation for the next release please ;) binstring.py, as attached. (also pasted up - http://www.rafb.net/paste/results/5feItM57.html) Creating this, was just a brain teaser, but I was thinking 'what if I wanted to make this for the standard library.' And so you can see, I had to include a flag for endianess. But that was really a cheap trick. If this was going into a standard library, I'd want to query the OS for endianess. As for the bits, once again, 32 bit is the norm, but 64 bit is here and spreading. Also, should it display 11111111 as 255 or 256? Both are valid, depending on context. Thirdly, if I can do it in 2 minutes, (well, the main part), then should they bother putting it in the standard library considering also, - How often, really, are you going to need to present a decimal or hex as a binary string. Lastly - this only does base 10 to base 2. Should I include a base 6 to base 2, base 8 to base 2, base 10 to 6, 10 to 8, 8 to 6? I wouldn't like to write for the standard library, because you can never please everyone. But yeah, feel free to use the above, just keep my doc strings and comments. Regards, Liam Clarke On Fri, 4 Feb 2005 23:30:19 -0500, Jacob S. <keridee@jayco.net> wrote: > > The binary value is the same as the hex value. > > The binary representation is 000111110100, but > > unfortunately Python doesn't support binary in > > its string formatting(although it does in int()! > > Uh, question. Why not? It seems that all simple types should be included. > Since the computer stores it as binary, why shouldn't python be able to > display a > string of it in binary? That seems to be a short coming that should be added > to the > next release... IMHO of course. > Jacob Schmidt > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. -------------- next part -------------- A non-text attachment was scrubbed... Name: binstring.py Type: text/x-python Size: 1107 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050206/28f6f80e/binstring.py From dyoo at hkn.eecs.berkeley.edu Sat Feb 5 13:06:06 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Feb 5 13:06:09 2005 Subject: [Tutor] question about expressing mathematical equations In-Reply-To: <20050205104712.68003.qmail@web61303.mail.yahoo.com> Message-ID: <Pine.LNX.4.44.0502050355420.5522-100000@hkn.eecs.berkeley.edu> On Sat, 5 Feb 2005, alieks lao wrote: > I've spent hours trying things out and I'm no better off. I don't > understand exactly what I'm supposed to do. Hi Alieks, What part of the problem are you working on? If you show us what you've tried so far; we can then try to figure out why you're getting stuck on, and help you so you get unstuck. But again, you may have a much easier time if you use a different tutorial. The one you're using right now is actually aimed for physicists! At least, it's aimed for beginning physicists, so they're assuming a familiarity with things like vector math, a particular computing lab environment, and a topical focus that appeals to folks who are doing numerical analysis stuff. This may not be the best tutorial for you. You may like this one better: http://www.freenetpages.co.uk/hp/alan.gauld/ Alan Gauld is the author of this tutorial, and he also answers questions on this mailing list, so if you try this tutorial, you may get answers that are quite, well, authoritative. *grin* If you have any questions, please feel free to ask. From shitizb at yahoo.com Sat Feb 5 13:08:57 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Sat Feb 5 13:09:00 2005 Subject: [Tutor] freeze In-Reply-To: <008201c50b3a$61e5dc70$215428cf@JSLAPTOP> Message-ID: <20050205120857.63243.qmail@web53810.mail.yahoo.com> Hi, Do exe files generated by py2run on linux???i thought it was only for windows. Shitiz --- "Jacob S." <keridee@jayco.net> wrote: > My two bits. > > 1) Download py2exe found here > http://py2exe.sourceforge.net/ > 2) Make a setup file -- intructions can be found > through above link, I > think. > (Hey that rhymes!) > 3) Ask if you want my totally cool automation > technique > 4) Ask more questions, go on we don't mind. > > HTH, > Jacob Schmidt > > > Hi, > > > > I intend to create compiled python binaries on > linux. > > I understand that freeze can be used to do this. > > But I have few doubts i would like to clarify. > > > > 1. In the freeze documentation i found the lines: > > > > "One tricky issue: Freeze assumes that the Python > > interpreter and > > environment you're using to run Freeze is the same > one > > that would be > > used to run your program, which should also be the > > same whose sources > > and installed files you will learn about in the > next > > section. In > > particular, your PYTHONPATH setting should be the > same > > as for running > > your program locally. (Tip: if the program > doesn't > > run when you type > > "python hello.py" there's little chance of getting > the > > frozen version > > to run.)" > > > > My intention is to create files which can be run > on > > Linux systems with python not installed.Do the > above > > lines mean that freeze can't do it(which defeats > the > > very pupose of the program i guess.). > > > > 2. While compiling with freeze....it seems that it > is > > including all the available modules, even if they > are > > not required.Of course using freeze -X is one > > option,but it being really cumbersome, is there a > > better option available. > > > > In case the above issues do present a problem, is > > there any alternative to freeze? > > > > Shitiz > > > > > > > > __________________________________ > > Do you Yahoo!? > > The all-new My Yahoo! - Get yours free! > > http://my.yahoo.com > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > __________________________________ Do you Yahoo!? Yahoo! Mail - You care about security. So do we. http://promotions.yahoo.com/new_mail From alan.gauld at freenet.co.uk Sat Feb 5 14:08:06 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Feb 5 14:10:21 2005 Subject: [Tutor] Hex to Str - still an open issue References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com><041401c50ae9$63c21a50$68b78851@xp> <00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> Message-ID: <051901c50b83$bc638ff0$68b78851@xp> > > unfortunately Python doesn't support binary in > > its string formatting(although it does in int()! > > Uh, question. Why not? It seems that all simple types should be included. I agree it has always seemed bizarre that inary is not included but octal is, IMHO binary is more useful as a representation than octal... My guess is brcause the C sprintf() function doesn't support binary... But that shouldn't really be an excuse. Alan G. From alan.gauld at freenet.co.uk Sat Feb 5 14:26:05 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Feb 5 14:26:04 2005 Subject: [Tutor] question about expressing mathematical equations References: <20050205104712.68003.qmail@web61303.mail.yahoo.com> Message-ID: <052f01c50b86$3efe17d0$68b78851@xp> > I've spent hours trying things out and I'm no better off. > I don't understand exactly what I'm supposed to do... > alieks The tutor you are using is fairly specialised. What are you trying to learn? Python or math in Python? To learn Python use one of the other tutorials that focus on Pyhon itself - if you can already program use the official tutor on the web site(or download it) If you can't already program use one of the tutors on the Beginners page that Danny pointed you towards. If OTOH you can grok Python and want to do math in it then the tutor you have is fine. So what is it you don't understand? The math, otr the Python? Its hard for us to guess... :-) Alan G. From kent37 at tds.net Sat Feb 5 16:48:01 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat Feb 5 16:48:07 2005 Subject: [Tutor] Hex to Str - still an open issue In-Reply-To: <f2ff2d050205034498e84e@mail.gmail.com> References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> <041401c50ae9$63c21a50$68b78851@xp> <00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> <f2ff2d050205034498e84e@mail.gmail.com> Message-ID: <4204EAB1.2050206@tds.net> Liam, I think you misunderstand what endianness is. Big-endian and little-endian refer to the way a number is stored as bytes in the underlying memory of the computer. This is not something you generally need to worry about in a Python program. For example, consider the number 0x12345678. On most modern computers this will be stored in four consecutive bytes of computer memory. The individual bytes will contain the values 0x12, 0x34, 0x56, 0x78. The question is, what is the order of those bytes in memory? On a big-endian computer, the most significant byte - 0x12 - is stored at the lowest memory address, so the sequence of bytes will be 0x12, 0x34, 0x56, 0x78. On a little-endian computer, the least-significant byte is stored at the lowest address, and the order will be reversed: 0x78, 0x56, 0x34, 0x12. Most programming languages will hide this detail from you most of the time. Even in assembly language, you generally load and store integers without worrying about endianness. Math operations just do the right thing so you don't have to worry about it. Endianness becomes an issue when you want to convert between representations, and when binary data is shared between computers which may have different endianness. For example in a C program you might want to get the high byte of an integer when you know the address of the integer. The desired byte will be at (address+0) or (address+3) depending on the endianness of the hardware. Similarly, if an array of integers is written to a file in a binary representation (not as ASCII strings representing the integers, but as 32-bit values), then to correctly read the file you have to know the endianness of the data in the file. OK, so what does this have to do with converting a number to binary in Python? Well, nothing, actually. First, note that 'binary representation' can mean two different things. In the description above, I was talking about the actual bit pattern stored in the computer. Python works with binary numbers all the time, in this sense, but it is under the hood. The other meaning of 'binary representation' is that of a base-2 string representation of a number. So if you ask, "How do I convert a number to binary?" you can mean either of these. The first one is trivial. If you have a decimal string representation of the number, use int() to convert it to binary. If you have an integer already, it's already *in* binary, so you don't have to do anything! So, "How do I convert a number to binary?", to be interesting, must mean "How do I convert an integer to a base-2 string representation?" And how do you do this? Well, you figured out one way using the mathematical properties of integers. These operations are independent of endianness, and so is the desired result. The base-2 string representation of the number (whose base-16 string representation is) 0x1234 is '0001001000110100'. The order of digits here is determined by our convention of writing the most significant digits on the left, not by the endianness of the underlying computer. OK, this is long enough, I hope I have shed some light... Kent Liam Clarke wrote: > Jacob - just for you, begin your agitation for the next release please ;) > > binstring.py, as attached. > (also pasted up - http://www.rafb.net/paste/results/5feItM57.html) > > Creating this, was just a brain teaser, but I was thinking 'what if I > wanted to make this for the standard library.' > > And so you can see, I had to include a flag for endianess. But that > was really a cheap trick. If this was going into a standard library, > I'd want to query the OS for endianess. As for the bits, once again, > 32 bit is the norm, but 64 bit is here and spreading. > > Also, should it display 11111111 as 255 or 256? Both are valid, > depending on context. > > Thirdly, if I can do it in 2 minutes, (well, the main part), then > should they bother putting it in the standard library considering > also, > > - How often, really, are you going to need to present a decimal or hex > as a binary string. > > Lastly - this only does base 10 to base 2. Should I include a base 6 > to base 2, base 8 to base 2, base 10 to 6, 10 to 8, 8 to 6? > > I wouldn't like to write for the standard library, because you can > never please everyone. > > But yeah, feel free to use the above, just keep my doc strings and comments. > > Regards, > > Liam Clarke > > On Fri, 4 Feb 2005 23:30:19 -0500, Jacob S. <keridee@jayco.net> wrote: > >>>The binary value is the same as the hex value. >>>The binary representation is 000111110100, but >>>unfortunately Python doesn't support binary in >>>its string formatting(although it does in int()! >> >>Uh, question. Why not? It seems that all simple types should be included. >>Since the computer stores it as binary, why shouldn't python be able to >>display a >>string of it in binary? That seems to be a short coming that should be added >>to the >>next release... IMHO of course. >>Jacob Schmidt >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> > > > > > ------------------------------------------------------------------------ > > ###### > # binString.py > # by Liam Clarke > #(Let me know when it's included in the standard library ;-)) > ###### > > """Converts a integer base 10 to a string base 2""" > > def binary(decimalInt, bigEndian = True, bits = 32, truncExcess = False): > """ > Integer to be converted is essential, Endianess is an optional flag; > me being a Win32 user, Endianess is big by default, defaults to a 32-bit > representation, most integers in Python being 32 bit. truncExcess will > strip place-holder zeros for succintness. > > Oh, and it will represent 11111111 as 256, as I'm not sure whether you want > to start counting for zero with this. It's a simple matter to change.""" > tempList = ['0' for x in range(bits)] > > for bitPlace in range(bits, -1, -1): > if decimalInt - 2**bitPlace >= 0: > tempList[bitPlace] = '1' > decimalInt = decimalInt - 2**bitPlace > if bigEndian: > tempList.reverse() > > outPut = ''.join(tempList) > > if truncExcess: > if bigEndian: > outPut=outPut.lstrip('0') > else: > outPut=outPut.rstrip('0') > > return outPut > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From mark.kels at gmail.com Sat Feb 5 18:19:04 2005 From: mark.kels at gmail.com (Mark Kels) Date: Sat Feb 5 18:19:08 2005 Subject: [Tutor] A problem with a Tkinter program (using the text widget) Message-ID: <c22592530502050919505e0031@mail.gmail.com> Hi all. Whats wrong here ?? : from Tkinter import * def p_text(): print text.get() root=Tk() text=Text(root).pack() button=Button(root,text="Click here!!",command=p_text).pack() root.mainloop() I get an error that says that nontype object has no attribute 'get'... whats wrong ?? Thanks. -- 1. The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners. 2. Unix is user friendly - it's just picky about it's friends. 3. Documentation is like sex: when it is good, it is very, very good. And when it is bad, it is better than nothing. - Dick Brandon From sandip at lug-delhi.org Sat Feb 5 19:58:08 2005 From: sandip at lug-delhi.org (Sandip Bhattacharya) Date: Sat Feb 5 19:58:38 2005 Subject: [Tutor] Hex to Str - still an open issue In-Reply-To: <812D33B03107804389D6F4247B69EFAC3A294F@dfre2k03.itg.ti.com> References: <812D33B03107804389D6F4247B69EFAC3A294F@dfre2k03.itg.ti.com> Message-ID: <42051740.7040906@lug-delhi.org> Tamm, Heiko wrote: > > > Ok, thank you. > > > Does anybody know how to convert a HEX into a BINARY? > > Just trying my hand out on python : To convert the value of i to binary: ================== i = 456 s = '' while i: s = str(i % 2) + s i/=2 print s ================= in case you have i in the form of a hex string, you can always add "i=int(i,16)" before the loop. - Sandip From kent37 at tds.net Sat Feb 5 20:12:27 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat Feb 5 20:12:31 2005 Subject: [Tutor] A problem with a Tkinter program (using the text widget) In-Reply-To: <c22592530502050919505e0031@mail.gmail.com> References: <c22592530502050919505e0031@mail.gmail.com> Message-ID: <42051A9B.60207@tds.net> Mark Kels wrote: > Hi all. > Whats wrong here ?? : > from Tkinter import * > def p_text(): > print text.get() > root=Tk() > text=Text(root).pack() pack() doesn't return a value. You have to do text = Text(root) text.pack() I've been bitten by this one more than once myself :-( Kent > button=Button(root,text="Click here!!",command=p_text).pack() > root.mainloop() > > I get an error that says that nontype object has no attribute 'get'... > whats wrong ?? > > Thanks. > > From alan.gauld at freenet.co.uk Sat Feb 5 20:29:32 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Feb 5 20:29:29 2005 Subject: [Tutor] A problem with a Tkinter program (using the text widget) References: <c22592530502050919505e0031@mail.gmail.com> Message-ID: <055201c50bb9$05602710$68b78851@xp> > Whats wrong here ?? : > from Tkinter import * > def p_text(): > print text.get() > root=Tk() > text=Text(root).pack() pack() retirns None, YOu *must* use two steps: text = Text(....) text.pack() > button=Button(root,text="Click here!!",command=p_text).pack() > root.mainloop() > > I get an error that says that nontype object has no attribute 'get'... > whats wrong ?? Because your text variable contains None, which doesn't support get... Don't worry, its one of the most common Tkinter mistakes and bites most folks at some stage... Alan G. From keridee at jayco.net Sat Feb 5 22:10:33 2005 From: keridee at jayco.net (Jacob S.) Date: Sat Feb 5 22:10:59 2005 Subject: [Tutor] freeze References: <20050205120857.63243.qmail@web53810.mail.yahoo.com> Message-ID: <000901c50bc7$42718320$c45328cf@JSLAPTOP> Hey! Good question! I have no idea. Jacob Schmidt P.S. Here's a cool setup script for py2exe if you want to try it though. ### setup.py ### # Run the build process by entering 'setup.py py2exe' or # 'python setup.py py2exe' in a console prompt. from distutils.core import setup import py2exe import os def getdir(): current = os.getcwd() m = 'y' while m == 'y': print "Current directory is: %s" % current m = raw_input("Do you wish to change the directory? ") if m == 'y': n = raw_input("What is the new directory? ") if not n.count(":"): current = os.path.join(current,n) else: current = n os.chdir(current) getdir() listed = [] while 1: ask = raw_input('What is the file you want as an executable? ') if ask == 'quit' or ask == 'stop': break else: listed.append(os.path.join(desktop,ask)) os.chdir(uck) setup(console = listed) ## End of setup.py ### From kent37 at tds.net Sat Feb 5 22:22:11 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat Feb 5 22:22:15 2005 Subject: [Tutor] freeze In-Reply-To: <20050205120857.63243.qmail@web53810.mail.yahoo.com> References: <20050205120857.63243.qmail@web53810.mail.yahoo.com> Message-ID: <42053903.8030109@tds.net> Shitiz Bansal wrote: > Hi, > > Do exe files generated by py2run on linux???i thought > it was only for windows. py2exe makes Windows executables only. http://starship.python.net/crew/theller/py2exe/ Kent > > Shitiz > --- "Jacob S." <keridee@jayco.net> wrote: > > >>My two bits. >> >>1) Download py2exe found here >>http://py2exe.sourceforge.net/ >>2) Make a setup file -- intructions can be found >>through above link, I >>think. >>(Hey that rhymes!) >>3) Ask if you want my totally cool automation >>technique >>4) Ask more questions, go on we don't mind. >> >>HTH, >>Jacob Schmidt >> >> >>>Hi, >>> >>>I intend to create compiled python binaries on >> >>linux. >> >>>I understand that freeze can be used to do this. >>>But I have few doubts i would like to clarify. >>> >>>1. In the freeze documentation i found the lines: >>> >>>"One tricky issue: Freeze assumes that the Python >>>interpreter and >>>environment you're using to run Freeze is the same >> >>one >> >>>that would be >>>used to run your program, which should also be the >>>same whose sources >>>and installed files you will learn about in the >> >>next >> >>>section. In >>>particular, your PYTHONPATH setting should be the >> >>same >> >>>as for running >>>your program locally. (Tip: if the program >> >>doesn't >> >>>run when you type >>>"python hello.py" there's little chance of getting >> >>the >> >>>frozen version >>>to run.)" >>> >>>My intention is to create files which can be run >> >>on >> >>>Linux systems with python not installed.Do the >> >>above >> >>>lines mean that freeze can't do it(which defeats >> >>the >> >>>very pupose of the program i guess.). >>> >>>2. While compiling with freeze....it seems that it >> >>is >> >>>including all the available modules, even if they >> >>are >> >>>not required.Of course using freeze -X is one >>>option,but it being really cumbersome, is there a >>>better option available. >>> >>>In case the above issues do present a problem, is >>>there any alternative to freeze? >>> >>>Shitiz >>> >>> >>> >>>__________________________________ >>>Do you Yahoo!? >>>The all-new My Yahoo! - Get yours free! >>>http://my.yahoo.com >>> >>> >>>_______________________________________________ >>>Tutor maillist - Tutor@python.org >>>http://mail.python.org/mailman/listinfo/tutor >>> >>> >> >> > > > > > > __________________________________ > Do you Yahoo!? > Yahoo! Mail - You care about security. So do we. > http://promotions.yahoo.com/new_mail > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From cyresse at gmail.com Sun Feb 6 00:52:50 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sun Feb 6 00:52:53 2005 Subject: [Tutor] Hex to Str - still an open issue In-Reply-To: <4204EAB1.2050206@tds.net> References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> <041401c50ae9$63c21a50$68b78851@xp> <00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> <f2ff2d050205034498e84e@mail.gmail.com> <4204EAB1.2050206@tds.net> Message-ID: <f2ff2d05020515523d4ebfc5@mail.gmail.com> Oh... and while I hate to use acronyms like this, I did indeed LOL. What happened was, I was feeding the strings I got out into the Windows calculator to check it was working. And they worked if they went backwards, and I was wondering why, and I vaguely recalled something I read in a Java book about 'endianess' and Windows being bigendian. So, there you go, thought I, the biggest bit (2**32) goes first, so Windows must be bigEndian! Oops. Next time, I'll google. Thanks Kent for clearing that up. Sandip - Just looking at this - i = 456 s = '' while i: s = str(i % 2) + s i/=2 This works, far simpler than mine, which is always infuriating, but my question is, how exactly? if I have the number 15, when it divides by 2, it will become 7. Yet no error is introduced into the binary. Argggg. Driving me nuts trying to figure out how. I thought maybe a larger odd number would do it, but no. i = 320977545 s = 10011001000011011101010001001 Chuck that into ol' calc, and I get, 320977545. Can anyone shed some more light on this? Regards, Liam Clarke On Sat, 05 Feb 2005 10:48:01 -0500, Kent Johnson <kent37@tds.net> wrote: > Liam, > > I think you misunderstand what endianness is. > > Big-endian and little-endian refer to the way a number is stored as bytes in the underlying memory > of the computer. This is not something you generally need to worry about in a Python program. > > For example, consider the number 0x12345678. On most modern computers this will be stored in four > consecutive bytes of computer memory. The individual bytes will contain the values 0x12, 0x34, 0x56, > 0x78. The question is, what is the order of those bytes in memory? On a big-endian computer, the > most significant byte - 0x12 - is stored at the lowest memory address, so the sequence of bytes will > be 0x12, 0x34, 0x56, 0x78. On a little-endian computer, the least-significant byte is stored at the > lowest address, and the order will be reversed: 0x78, 0x56, 0x34, 0x12. > > Most programming languages will hide this detail from you most of the time. Even in assembly > language, you generally load and store integers without worrying about endianness. Math operations > just do the right thing so you don't have to worry about it. > > Endianness becomes an issue when you want to convert between representations, and when binary data > is shared between computers which may have different endianness. > > For example in a C program you might want to get the high byte of an integer when you know the > address of the integer. The desired byte will be at (address+0) or (address+3) depending on the > endianness of the hardware. > > Similarly, if an array of integers is written to a file in a binary representation (not as ASCII > strings representing the integers, but as 32-bit values), then to correctly read the file you have > to know the endianness of the data in the file. > > OK, so what does this have to do with converting a number to binary in Python? Well, nothing, > actually. First, note that 'binary representation' can mean two different things. In the description > above, I was talking about the actual bit pattern stored in the computer. Python works with binary > numbers all the time, in this sense, but it is under the hood. The other meaning of 'binary > representation' is that of a base-2 string representation of a number. > > So if you ask, "How do I convert a number to binary?" you can mean either of these. > > The first one is trivial. If you have a decimal string representation of the number, use int() to > convert it to binary. If you have an integer already, it's already *in* binary, so you don't have to > do anything! > > So, "How do I convert a number to binary?", to be interesting, must mean "How do I convert an > integer to a base-2 string representation?" And how do you do this? Well, you figured out one way > using the mathematical properties of integers. These operations are independent of endianness, and > so is the desired result. > > The base-2 string representation of the number (whose base-16 string representation is) 0x1234 is > '0001001000110100'. The order of digits here is determined by our convention of writing the most > significant digits on the left, not by the endianness of the underlying computer. > > OK, this is long enough, I hope I have shed some light... > Kent > > > Liam Clarke wrote: > > Jacob - just for you, begin your agitation for the next release please ;) > > > > binstring.py, as attached. > > (also pasted up - http://www.rafb.net/paste/results/5feItM57.html) > > > > Creating this, was just a brain teaser, but I was thinking 'what if I > > wanted to make this for the standard library.' > > > > And so you can see, I had to include a flag for endianess. But that > > was really a cheap trick. If this was going into a standard library, > > I'd want to query the OS for endianess. As for the bits, once again, > > 32 bit is the norm, but 64 bit is here and spreading. > > > > Also, should it display 11111111 as 255 or 256? Both are valid, > > depending on context. > > > > Thirdly, if I can do it in 2 minutes, (well, the main part), then > > should they bother putting it in the standard library considering > > also, > > > > - How often, really, are you going to need to present a decimal or hex > > as a binary string. > > > > Lastly - this only does base 10 to base 2. Should I include a base 6 > > to base 2, base 8 to base 2, base 10 to 6, 10 to 8, 8 to 6? > > > > I wouldn't like to write for the standard library, because you can > > never please everyone. > > > > But yeah, feel free to use the above, just keep my doc strings and comments. > > > > Regards, > > > > Liam Clarke > > > > On Fri, 4 Feb 2005 23:30:19 -0500, Jacob S. <keridee@jayco.net> wrote: > > > >>>The binary value is the same as the hex value. > >>>The binary representation is 000111110100, but > >>>unfortunately Python doesn't support binary in > >>>its string formatting(although it does in int()! > >> > >>Uh, question. Why not? It seems that all simple types should be included. > >>Since the computer stores it as binary, why shouldn't python be able to > >>display a > >>string of it in binary? That seems to be a short coming that should be added > >>to the > >>next release... IMHO of course. > >>Jacob Schmidt > >> > >>_______________________________________________ > >>Tutor maillist - Tutor@python.org > >>http://mail.python.org/mailman/listinfo/tutor > >> > > > > > > > > > > ------------------------------------------------------------------------ > > > > ###### > > # binString.py > > # by Liam Clarke > > #(Let me know when it's included in the standard library ;-)) > > ###### > > > > """Converts a integer base 10 to a string base 2""" > > > > def binary(decimalInt, bigEndian = True, bits = 32, truncExcess = False): > > """ > > Integer to be converted is essential, Endianess is an optional flag; > > me being a Win32 user, Endianess is big by default, defaults to a 32-bit > > representation, most integers in Python being 32 bit. truncExcess will > > strip place-holder zeros for succintness. > > > > Oh, and it will represent 11111111 as 256, as I'm not sure whether you want > > to start counting for zero with this. It's a simple matter to change.""" > > tempList = ['0' for x in range(bits)] > > > > for bitPlace in range(bits, -1, -1): > > if decimalInt - 2**bitPlace >= 0: > > tempList[bitPlace] = '1' > > decimalInt = decimalInt - 2**bitPlace > > if bigEndian: > > tempList.reverse() > > > > outPut = ''.join(tempList) > > > > if truncExcess: > > if bigEndian: > > outPut=outPut.lstrip('0') > > else: > > outPut=outPut.rstrip('0') > > > > return outPut > > > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cyresse at gmail.com Sun Feb 6 01:14:33 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sun Feb 6 01:14:37 2005 Subject: [Tutor] Re: variation of Unique items question In-Reply-To: <42038E81.4020906@tds.net> References: <dc4ecc9d050204055767d75e3a@mail.gmail.com> <42038E81.4020906@tds.net> Message-ID: <f2ff2d05020516141a5f4bce@mail.gmail.com> When someone joins the list, they shoudl receive a welcome email that contains - > - a clear description of what you want to do > - sample data > - desired results > - code that attempts to solve the problem as a helpful hint of how to ask questions. I have this bookmarked - http://catb.org/~esr/faqs/smart-questions.html "Never assume you are entitled to an answer. You are not; you aren't, after all, paying for the service. You will earn an answer, if you earn it, by asking a question that is substantial, interesting, and thought-provoking ? one that implicitly contributes to the experience of the community rather than merely passively demanding knowledge from others." "RTFM has a younger relative. If you get a reply that reads "STFW", the person who sent it thinks you should have Searched The F**king Web. He is almost certainly right. Go search it. (The milder version of this is when you are told "Google is your friend!")" "Q: My {program, configuration, SQL statement} doesn't work A: This is not a question, and I'm not interested in playing Twenty Questions to pry your actual question out of you ? I have better things to do. Q: How can I crack root/steal channel-ops privileges/read someone's email? A: You're a lowlife for wanting to do such things and a moron for asking a hacker to help you." Arrogant words of wisdom to ask help by. :- ) (But, some of them seem appropriate here from time to time.) Liam Clarke On Fri, 04 Feb 2005 10:02:25 -0500, Kent Johnson <kent37@tds.net> wrote: > I will give some credit to you for asking a clear question. You included > - a clear description of what you want to do > - sample data > - desired results > - code that attempts to solve the problem > > When all of these are present I am much more likely to respond. The first three elements especially > make a big difference. > > Kent > > Scott Melnyk wrote: > > Hello. > > > > Kent once again you have responded incredibly quickly in a most > > helpful manor. I sometimes wonder if the old reference to a > > "Kent-bot" has some truth to it. > > > > Thanks again, I will play with it and keep on going. > > > > Scott > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From sandip at lug-delhi.org Sun Feb 6 02:14:50 2005 From: sandip at lug-delhi.org (Sandip Bhattacharya) Date: Sun Feb 6 02:15:00 2005 Subject: [Tutor] Hex to Str - still an open issue In-Reply-To: <f2ff2d05020515523d4ebfc5@mail.gmail.com> References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> <041401c50ae9$63c21a50$68b78851@xp> <00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> <f2ff2d050205034498e84e@mail.gmail.com> <4204EAB1.2050206@tds.net> <f2ff2d05020515523d4ebfc5@mail.gmail.com> Message-ID: <42056F8A.7030205@lug-delhi.org> Liam Clarke wrote: > Sandip - > > Just looking at this - > i = 456 > s = '' > while i: > s = str(i % 2) + s > i/=2 > > This works, far simpler than mine, which is always infuriating, but my > question is, how exactly? > > if I have the number 15, when it divides by 2, it will become 7. Yet > no error is introduced into the binary. Argggg. Driving me nuts trying > to figure out how. I thought maybe a larger odd number would do it, > but no. > > i = 320977545 > s = 10011001000011011101010001001 > > Chuck that into ol' calc, and I get, 320977545. > > Can anyone shed some more light on this? If you imagine the number being displayed in binary inside your calculator, i % 2, gives us the rightmost bit of the number (has to be 0 or 1) 1/=2 just right shifts the number by one. So if you consider 15, a. i % 2 will give you "1". b. So even if 15/2 gives you 7, it is ok, as the odd bit has been taken care of in (a). - Sandip From ismaelgf at adinet.com.uy Sun Feb 6 04:55:00 2005 From: ismaelgf at adinet.com.uy (Ismael Garrido) Date: Sun Feb 6 04:54:14 2005 Subject: [Tutor] Hex to Str - still an open issue In-Reply-To: <f2ff2d05020515523d4ebfc5@mail.gmail.com> References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> <041401c50ae9$63c21a50$68b78851@xp> <00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> <f2ff2d050205034498e84e@mail.gmail.com> <4204EAB1.2050206@tds.net> <f2ff2d05020515523d4ebfc5@mail.gmail.com> Message-ID: <42059514.7000708@adinet.com.uy> Liam Clarke wrote: >Just looking at this - >i = 456 >s = '' >while i: > s = str(i % 2) + s > i/=2 > >This works, far simpler than mine, which is always infuriating, but my >question is, how exactly? > >if I have the number 15, when it divides by 2, it will become 7. Yet >no error is introduced into the binary. Argggg. Driving me nuts trying >to figure out how. I thought maybe a larger odd number would do it, >but no. > >Can anyone shed some more light on this? > > Let's step over it : i = 15 # = 1111b s = str(i % 2) + s # 15 % 2 = 1 so now s = "1" i = i / 2 # i = 7 where's the 1 missing? s has got it s = 7 % 2 = 1 so now s = "11" i = 7/2 = 3 ... and so on... Remember when you do the base-conversion by hand: (ASCII-ese graphics, use fixed font) 15 | 2 ---- 1 7 | 2 ---- 1 3 and so on... You're basically doing the same thing Perhaps that code could be improved by not using strings: ### Warning, untested code! ### i = 15 power = 0 f = 0 while i > 0: f = f+ (i%2)**power i /= 2 power += 1 I don't know if that's faster, but I see it as a more "mathematic" way to do it. Bye Ismael From alan.gauld at freenet.co.uk Sun Feb 6 09:44:42 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Feb 6 09:44:42 2005 Subject: [Tutor] Hex to Str - still an open issue References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com><041401c50ae9$63c21a50$68b78851@xp><00ae01c50b3b$6b55d390$215428cf@JSLAPTOP><f2ff2d050205034498e84e@mail.gmail.com> <4204EAB1.2050206@tds.net> <f2ff2d05020515523d4ebfc5@mail.gmail.com> Message-ID: <056f01c50c28$1ac59a30$68b78851@xp> Liam, > Just looking at this - > i = 456 > s = '' > while i: > s = str(i % 2) + s > i/=2 > > This works, far simpler than mine, which is always infuriating, but my > question is, how exactly? This is the classic math treatment of how to calculate a binary number. Just keep dividing by two and take the remainder into the number. Almost any math textbook will cover this approach. The snag is that from a computing point of view its pretty slow so computer texts usually highlught a lookup approach 8instead. Alan G. From cyresse at gmail.com Sun Feb 6 09:59:32 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sun Feb 6 09:59:35 2005 Subject: [Tutor] Hex to Str - still an open issue In-Reply-To: <056f01c50c28$1ac59a30$68b78851@xp> References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> <041401c50ae9$63c21a50$68b78851@xp> <00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> <f2ff2d050205034498e84e@mail.gmail.com> <4204EAB1.2050206@tds.net> <f2ff2d05020515523d4ebfc5@mail.gmail.com> <056f01c50c28$1ac59a30$68b78851@xp> Message-ID: <f2ff2d050206005943485d64@mail.gmail.com> Ah, yeah, gotta get me one of those textbooks. (Wait a minute, that would mean, my approach wasn't the textbook approach... /me salvages a little pride.) While I jest somewhat, that highlights a serious deficiency in my education that becomes more and more apparent, which is in maths. Sheesh, if I'd known I wanted to use maths for something I enjoyed, I would've paid attention in class. But the remainder thing - would this be why we read binary the way we do? 4 is 001 (on a continuum of 2^0 to 2^n), but using the above approach we get 100. Regards, Liam Clarke On Sun, 6 Feb 2005 08:44:42 -0000, Alan Gauld <alan.gauld@freenet.co.uk> wrote: > Liam, > > > Just looking at this - > > i = 456 > > s = '' > > while i: > > s = str(i % 2) + s > > i/=2 > > > > This works, far simpler than mine, which is always infuriating, but > my > > question is, how exactly? > > This is the classic math treatment of how to calculate a binary > number. > Just keep dividing by two and take the remainder into the number. > Almost any math textbook will cover this approach. > The snag is that from a computing point of view its pretty slow so > computer texts usually highlught a lookup approach 8instead. > > Alan G. > > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cyresse at gmail.com Sun Feb 6 12:57:35 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sun Feb 6 12:57:39 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <04fc01c50b61$01535960$68b78851@xp> References: <C4C644CF4ADA9448904C3E8BACC4B97C02E673B2@medexch1.medplus.com> <042601c50aea$e6edb410$68b78851@xp> <420404C7.2030409@pobox.com> <04fc01c50b61$01535960$68b78851@xp> Message-ID: <f2ff2d05020603572101f867@mail.gmail.com> Even more OT it would seem, but harking back to the original subject, Perl isn't looking too bad because I've been working through Java tonight. $j = <STDIN>; is relatively intuitive for a child of Unix, and it's also documented. BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in)); String j = keyboard.readline(); is not intuitive, and is hidden very well in the bowels of Sun's API's. Scary, when a language makes me think Perl would be nicer. : ) Heh. Oh, and whoever recommended Eclipse to me? Thank you very much. On Sat, 5 Feb 2005 08:59:30 -0000, Alan Gauld <alan.gauld@freenet.co.uk> wrote: > > > Surely you jest, Alan. :-) > > Smiley noted but... > > > Both perl and awk are turing complete, hence anything perl can do, > awk > > can do as well. > > This is a popular misconception. > > Being Turing complete simply means you can implement any algorithm. > But if the language doesn't provide I/O access for example it is > impossible to write a device driver, or a comms stack, or any of > a host of other low level programs. awk is non extendable (unless > you have the source code!) so you can't do those things. Perl is > not only extendable but actually comes wth a heap of those kinds > of features that awk just doesn't have. And no amount of clever > algorithms can compensate. Awk was designed for one task which it > does spectacularly well but it was never intended for general > purpose use. > > I/O is just one example, there are meny more... > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From kent37 at tds.net Sun Feb 6 13:27:34 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun Feb 6 13:27:39 2005 Subject: [Tutor] Hex to Str - still an open issue In-Reply-To: <f2ff2d050206005943485d64@mail.gmail.com> References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> <041401c50ae9$63c21a50$68b78851@xp> <00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> <f2ff2d050205034498e84e@mail.gmail.com> <4204EAB1.2050206@tds.net> <f2ff2d05020515523d4ebfc5@mail.gmail.com> <056f01c50c28$1ac59a30$68b78851@xp> <f2ff2d050206005943485d64@mail.gmail.com> Message-ID: <42060D36.8090500@tds.net> Liam Clarke wrote: > 4 is 001 (on a continuum of 2^0 to 2^n), but using the above approach > we get 100. ?? 4 (decimal) is 100 (binary). Not because of how the conversion algorithm works, but because that is how we write numbers. The least-significant digit is always the rightmost digit. 001 is 1 in every number base >= 2. Actually, generating the digits from the right complicates the algorithm quite a bit. It's hidden in the Python version, but s = str(i % 2) + s is a relatively expensive operation here - it has to copy all of s to make room for the new digit. Kent From maxnoel_fr at yahoo.fr Sun Feb 6 13:28:51 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Sun Feb 6 13:28:59 2005 Subject: [Tutor] Hex to Str - still an open issue In-Reply-To: <f2ff2d050206005943485d64@mail.gmail.com> References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> <041401c50ae9$63c21a50$68b78851@xp> <00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> <f2ff2d050205034498e84e@mail.gmail.com> <4204EAB1.2050206@tds.net> <f2ff2d05020515523d4ebfc5@mail.gmail.com> <056f01c50c28$1ac59a30$68b78851@xp> <f2ff2d050206005943485d64@mail.gmail.com> Message-ID: <5c246c73b673fe2ae8baaa9e7df08ac2@yahoo.fr> On Feb 6, 2005, at 08:59, Liam Clarke wrote: > Ah, yeah, gotta get me one of those textbooks. > (Wait a minute, that would mean, my approach wasn't the textbook > approach... /me salvages a little pride.) > > While I jest somewhat, that highlights a serious deficiency in my > education that becomes more and more apparent, which is in maths. > Sheesh, if I'd known I wanted to use maths for something I enjoyed, I > would've paid attention in class. > > But the remainder thing - would this be why we read binary the way we > do? > > 4 is 001 (on a continuum of 2^0 to 2^n), but using the above approach > we get 100. > > > Regards, > > Liam Clarke Yes, it is 100. The most significant bit (i.e. the highest power of 2) is on the left, just as the most significant digit (matching the highest power of 10) is on the left when representing base-10 numbers: 415 is 4*10^2 + 1*10^1 + 5*10^0. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From mark.kels at gmail.com Sun Feb 6 15:18:13 2005 From: mark.kels at gmail.com (Mark Kels) Date: Sun Feb 6 15:18:17 2005 Subject: [Tutor] The Tkinter Text widget and .get() Message-ID: <c225925305020606184248ffb9@mail.gmail.com> Hi all. As I understand, .get() has to get an index argument to get the text from the Text index... The problem is that I dont realy understand what is this index thing and what index do I need to give to the function so I'll get all the text in the widget. Any ideas ?? Thanks ! -- 1. The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners. 2. Unix is user friendly - it's just picky about it's friends. 3. Documentation is like sex: when it is good, it is very, very good. And when it is bad, it is better than nothing. - Dick Brandon From sigurd at 12move.de Sun Feb 6 15:23:27 2005 From: sigurd at 12move.de (Karl =?iso-8859-1?Q?Pfl=E4sterer?=) Date: Sun Feb 6 15:29:46 2005 Subject: [Tutor] Hex to Str - still an open issue In-Reply-To: <42060D36.8090500@tds.net> (Kent Johnson's message of "Sun, 06 Feb 2005 07:27:34 -0500") References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> <041401c50ae9$63c21a50$68b78851@xp> <00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> <f2ff2d050205034498e84e@mail.gmail.com> <4204EAB1.2050206@tds.net> <f2ff2d05020515523d4ebfc5@mail.gmail.com> <056f01c50c28$1ac59a30$68b78851@xp> <f2ff2d050206005943485d64@mail.gmail.com> <42060D36.8090500@tds.net> Message-ID: <umzuh7pt5.fsf@hamster.pflaesterer.de> On 6 Feb 2005, kent37@tds.net wrote: > Actually, generating the digits from the right complicates the algorithm quite > a bit. It's hidden in > the Python version, but s = str(i % 2) + s is a relatively expensive operation here - it has to copy > all of s to make room for the new digit. Because of that the standard answer is to write: s = [] s.append(...) return ''.join(s) Karl -- Please do *not* send copies of replies to me. I read the list From alan.gauld at freenet.co.uk Sun Feb 6 16:10:42 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Feb 6 16:10:27 2005 Subject: [Tutor] Hex to Str - still an open issue References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com><041401c50ae9$63c21a50$68b78851@xp><00ae01c50b3b$6b55d390$215428cf@JSLAPTOP><f2ff2d050205034498e84e@mail.gmail.com> <4204EAB1.2050206@tds.net><f2ff2d05020515523d4ebfc5@mail.gmail.com><056f01c50c28$1ac59a30$68b78851@xp> <f2ff2d050206005943485d64@mail.gmail.com> Message-ID: <058101c50c5e$0736faf0$68b78851@xp> > While I jest somewhat, that highlights a serious deficiency in my > education that becomes more and more apparent, which is in maths. Yes, its a sad fact. Good programming beyond basics does require a modicum of maths. You can learnn enough to do useful things without math, but there reaches a point when math becomes essential. Its no coincidence that at university Computing was traditionally (up till the late 70's at least) a branch of mathematics. > But the remainder thing - would this be why we read binary the way we do? > > 4 is 001 (on a continuum of 2^0 to 2^n), but using the above approach > we get 100. Not really. The reason we read 4 as 100 is the same reason we read 400 as 400 instead of 004 - we traditionally put the most significant part tothe left since we (in English at least) read from left to right. 400 = 4x10**2 + 0x10**1 + 0x10**0 110 = 1x2**2 + 0x2**1 + 0x2**0 But if we convert back again we can generate the number 400 from the value 400 by the same technique we saw for binary: 400/10 = 40 rem 0 40/10 = 4 rem 0 4/10 = 0 rem 4 So reading remainders bottom up we get 400, which is the decimal representation of 400! :-) So the algorithm is identical, we can write a generic function to convert a value into a representation if we pass in the value and base. Alan G. From askoose at sandia.gov Sun Feb 6 18:27:18 2005 From: askoose at sandia.gov (Kooser, Ara S) Date: Sun Feb 6 18:27:48 2005 Subject: [Tutor] Percolation model in python Message-ID: <A0CE32554BD73A4481FE85C3F39DB6FC0AEE6B@ES21SNLNT.srn.sandia.gov> Hello, I have been working with some high school students to create a model of small pox transmission. I am somewhat new to python (my programming experience is in f77) so I have borrowed parts of Danny's code that he posted for the Game of Life. I have included the code that we are using below. I have two questions. Once a MxN world is generated how would you search for nearest neighbors (to see who is connected) and then color the '*' so it's easier to see who is connected and who isn't. For a definition of percolation theory- http://en.wikipedia.org/wiki/Percolation_theory or for the wolfram fans http://mathworld.wolfram.com/PercolationTheory.html Thanks, Ara CODE STARTS HERE: print """ Please pick your option: 1) Percolation model for Small Pox 2) 3) Instructions 4) Exit """ option = raw_input("Which option[1,2,3,4]? ") if option == '1': import random perc = raw_input("Please enter a thresold between 0-1. ") perc = float(perc) ### PERSON, EMPTY = '*', '.' ### ### def percolation(perc): randval = random.random() if randval > perc: return EMPTY else: return PERSON def make_random_world(M, N): """Constructs a new random game world of size MxN.""" world = {} for j in range(N): for i in range(M): world[i, j] = percolation(perc) world['dimensions'] = (M, N) return world def print_world(world): """Prints out a string representation of a world.""" M, N = world['dimensions'] for j in range(N): for i in range(M): print world[i, j], print n = int(raw_input("Please enter a n dimension. ")) m = int(raw_input("Please enter a m dimension. ")) raw_input("Press return to make a world") print_world(make_random_world(n,m)) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050206/94af87cd/attachment.html From cyresse at gmail.com Sun Feb 6 19:52:02 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sun Feb 6 19:52:05 2005 Subject: [Tutor] Hex to Str - still an open issue In-Reply-To: <058101c50c5e$0736faf0$68b78851@xp> References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> <041401c50ae9$63c21a50$68b78851@xp> <00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> <f2ff2d050205034498e84e@mail.gmail.com> <4204EAB1.2050206@tds.net> <f2ff2d05020515523d4ebfc5@mail.gmail.com> <056f01c50c28$1ac59a30$68b78851@xp> <f2ff2d050206005943485d64@mail.gmail.com> <058101c50c5e$0736faf0$68b78851@xp> Message-ID: <f2ff2d050206105244a91c1d@mail.gmail.com> Ah, thanks all. I wasn't thinking of base 2 numbers like base 10 - when you describe it like that, I get i. (100 = 10^2 + 0*10^1 + 0*10^0) I was thinking strictly in terms of a base 10 number described by flags for each power of 2, which (to me) would logically start from 2^0 and go right. And yeah, I intend to study computer science as I can, so it's definitely the maths papers first. I'm working through my little brother's textbook on matrix algebra at the moment. Ick. Regards, Liam Clarke On Sun, 6 Feb 2005 15:10:42 -0000, Alan Gauld <alan.gauld@freenet.co.uk> wrote: > > While I jest somewhat, that highlights a serious deficiency in my > > education that becomes more and more apparent, which is in maths. > > Yes, its a sad fact. Good programming beyond basics does require a > modicum of maths. You can learnn enough to do useful things without > math, but there reaches a point when math becomes essential. Its > no coincidence that at university Computing was traditionally > (up till the late 70's at least) a branch of mathematics. > > > But the remainder thing - would this be why we read binary the way > we do? > > > > 4 is 001 (on a continuum of 2^0 to 2^n), but using the above > approach > > we get 100. > > Not really. The reason we read 4 as 100 is the same reason we > read 400 as 400 instead of 004 - we traditionally put the most > significant part tothe left since we (in English at least) read > from left to right. > > 400 = 4x10**2 + 0x10**1 + 0x10**0 > > 110 = 1x2**2 + 0x2**1 + 0x2**0 > > But if we convert back again we can generate the number 400 > from the value 400 by the same technique we saw for binary: > > 400/10 = 40 rem 0 > 40/10 = 4 rem 0 > 4/10 = 0 rem 4 > > So reading remainders bottom up we get 400, which is > the decimal representation of 400! :-) > > So the algorithm is identical, we can write a generic > function to convert a value into a representation if we > pass in the value and base. > > Alan G. > > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cyresse at gmail.com Sun Feb 6 19:58:34 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sun Feb 6 19:58:38 2005 Subject: [Tutor] The Tkinter Text widget and .get() In-Reply-To: <c225925305020606184248ffb9@mail.gmail.com> References: <c225925305020606184248ffb9@mail.gmail.com> Message-ID: <f2ff2d050206105826c058a6@mail.gmail.com> >From http://effbot.org/books/tkinterbook/text.htm "Indexes Indexes are used to point to positions within the text handled by the text widget. Like Python sequence indexes, text widget indexes correspond to positions between the actual characters. Tkinter provides a number of different index types: * line/column ("line.column") * line end ("line.end") * INSERT * CURRENT * END * user-defined marks * user-defined tags ("tag.first", "tag.last") * selection (SEL_FIRST, SEL_LAST) * window coordinate ("@x,y") * embedded object name (window, images) * expressions" I believe you want textWidget.get(1.0, END) But I seriously recommend the above book. 1.0 is line 1, column 0, to END of text. HTH Liam Clarke On Sun, 6 Feb 2005 16:18:13 +0200, Mark Kels <mark.kels@gmail.com> wrote: > Hi all. > > As I understand, .get() has to get an index argument to get the text > from the Text index... > The problem is that I dont realy understand what is this index thing > and what index do I need to give to the function so I'll get all the > text in the widget. > Any ideas ?? > > Thanks ! > -- > 1. The day Microsoft makes something that doesn't suck is probably the > day they start making vacuum cleaners. > 2. Unix is user friendly - it's just picky about it's friends. > 3. Documentation is like sex: when it is good, it is very, very good. > And when it is bad, it is better than nothing. - Dick Brandon > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From flaxeater at yahoo.com Sun Feb 6 19:59:11 2005 From: flaxeater at yahoo.com (Chad Crabtree) Date: Sun Feb 6 19:59:14 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: <20050206185911.85201.qmail@web54303.mail.yahoo.com> Jacob S. wrote: >> aFuncList=[] >> def x(): >> print "one" >> aFuncList.append(x) >> def x(): >> print "two" >> aFuncList.append(x) >> def x(): >> print "three" >> aFuncList.append(x) >> for item in aFuncList: >> item() > > > Okay, for this problem (it can be altered otherwise) > > def makefunct(stri): > def x(): > print stri > return x > aFuncList = [makefunct('one'),makefunct('two'),makefunct('three')] > for item in aFuncList: > item() > > It's shorter, it works and it looks cool. > Thanks to Jeff Shannon for the backbone of this example. My intent in showing the above code was not to really print one two three, but to show that a function doesn't care what it's called. __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From alan.gauld at freenet.co.uk Mon Feb 7 01:22:33 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Feb 7 01:22:15 2005 Subject: [Tutor] The Tkinter Text widget and .get() References: <c225925305020606184248ffb9@mail.gmail.com> Message-ID: <05a801c50cab$1e9e02e0$68b78851@xp> > As I understand, .get() has to get an index argument to get the text > from the Text index... Thats true. > The problem is that I dont realy understand what is this index thing Thats not surprising the Text widget index in Tk (its not really a Tkinter thing, its part of the underlying Tk toolkit...) is just a little bit weird! > and what index do I need to give to the function so I'll get all the > text in the widget. THe magic incantation (or one option, there are various ways) is: txt.get(1.0,END) Where 1.0 means first line, zeroth character (ie before the first!) is the starting position and END is the ending position. The index is a conceptual cursor that sits *between* characters. Thus for a line like: Here is a line If we only wanted the second word we'd use get(1.5, 1.7) This is explained in both the Tkinter documentation (but slightly vaguely), and,more precisely in the Tk documentation. AS with most things Python the best bet is to experiment at the >>> prompt till you get it right! There are some examples of using the Text widget in my tutorial in both the Event Driven Programming and Case Study topics. Specifically the doReset() method inthe case study uses indexing to delete the text in a Text box and doAnalyze shown text being appended (inserted at END). HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From reed at intersiege.com Mon Feb 7 07:58:57 2005 From: reed at intersiege.com (Reed L. O'Brien) Date: Mon Feb 7 07:59:42 2005 Subject: [Tutor] manipulating a file Message-ID: <cu73hp$7oj$1@sea.gmane.org> I want to read the httpd-access.log and remove any oversized log records I quickly tossed this script together. I manually mv-ed log to log.bak and touched a new logfile. running the following with print i uncommented does print each line to stdout. but it doesn't write to the appropriate file... a) what am I missing? b) is there a less expensive way to do it? c) I originally wanted to delete lines over 2085 in length but couldn't find a way to do that... did I miss it? Thanks #!/usr/local/bin/python import os srcfile = open('/var/log/httpd-access.log.bak', 'r') dstfile = open('/var/log/httpd-access.log', 'w') while 1: lines = srcfile.readlines() if not lines: break # print lines for i in lines: if len(i) < 2086: #print i dstfile.write(i) srcfile.close() dstfile.close() From dyoo at hkn.eecs.berkeley.edu Mon Feb 7 08:37:45 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Feb 7 08:37:50 2005 Subject: [Tutor] manipulating a file In-Reply-To: <cu73hp$7oj$1@sea.gmane.org> Message-ID: <Pine.LNX.4.44.0502062314380.12631-100000@hkn.eecs.berkeley.edu> On Mon, 7 Feb 2005, Reed L. O'Brien wrote: > I want to read the httpd-access.log and remove any oversized log records > > I quickly tossed this script together. I manually mv-ed log to log.bak > and touched a new logfile. > > running the following with print i uncommented does print each line to > stdout. but it doesn't write to the appropriate file... Hello! Let's take a look at the program again: ### import os srcfile = open('/var/log/httpd-access.log.bak', 'r') dstfile = open('/var/log/httpd-access.log', 'w') while 1: lines = srcfile.readlines() if not lines: break for i in lines: if len(i) < 2086: dstfile.write(i) srcfile.close() dstfile.close() ### > a) what am I missing? > b) is there a less expensive way to do it? Hmmm... I don't see anything offhand that prevents httpd-access.log from containing the lines you expect. Do you get any error messages, like permission problems, when you run the program? Can you show us how you are running the program, and how you are checking that the resulting file is empty? Addressing the question on efficiency and expense: yes. The program at the moment tries to read all lines into memory at once, and this is expensive if the file is large. Let's fix this. In recent versions of Python, we can modify file-handling code from: ### lines = somefile.readlines() for line in lines: ... ### to this: ### for line in somefile: ... ### That is, we don't need to extract a list of 'lines' out of a file. Python allows us to loop directly across a file object. We can find more details about this in the documentation on "Iterators" (PEP 234): http://www.python.org/peps/pep-0234.html Iterators are a good thing to know, since Python's iterators are deeply rooted in the language design. (Even if it they were retroactively embedded. *grin*) A few more comments: the while loop appears unnecessary, since on the second run-through the loop, we'll have already read all the lines out of the file. (I am assuming that nothing is writing to the backup file at the time.) If the body of a while loop just runs once, we don't need a loop. This simplifies the code down to: ### srcfile = open('/var/log/httpd-access.log.bak', 'r') dstfile = open('/var/log/httpd-access.log', 'w') for line in srcfile: if len(line) < 2086: dstfile.write(line) srcfile.close() dstfile.close() ### I don't see anything else here that causes the file writing to fail. If you can tell us more information on how you're checking the program's effectiveness, that may give us some more clues. Best of wishes to you! From tony at tcapp.com Mon Feb 7 10:03:08 2005 From: tony at tcapp.com (Tony Cappellini) Date: Mon Feb 7 10:03:28 2005 Subject: [Tutor] Iterating over multiple lists- options Message-ID: <6.1.2.0.0.20050207004003.01f59e78@mail.yamato.com> I'm trying to generate an HTML table, from multiple lists. There are 4 lists total, each of which *may* have a different length from the other lists. Each list has been stored in a master dictionary. North=[Bill, Bob, Sue, Mary] South=['Tim', ''Tom', 'Jim', 'John', 'Carl', 'Evan', 'Rich'] etc d1={'North':North, 'South':South, 'East':East, 'West':West] I want to iterate over all the lists a the same time, so I can populate an html table. This is approximately what the HTML table should look like, but the lists can be in any order, top to bottom, and left to right. South North East West Tim Bill May Ellen Tom Bob Mick Jim Sue Ron John Mary Keith Carl Joey Evan Rich Looking through my books on Python I've found examples for zip() and map() both of which have serious shortcomings That being, both of these functions can truncate the data, depending on certain conditions When iterating over multiple lists, it is fine if the mechanism returns an empty string , or None for a non-existing list item. I just wont display anything in the HTML table for missing items. I know how to create the HTML table, statically. The problem is being able to fill the table in one pass (preferably), which means my program would need to iterate over more than one list at the same time. Even using the range to generate an index has different effects, depending on the order in which the lists are referenced in the for loop. Are there any other options available for iterating over multiple lists ? From shitizb at yahoo.com Mon Feb 7 10:18:52 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Mon Feb 7 10:18:55 2005 Subject: [Tutor] manipulating a file In-Reply-To: <Pine.LNX.4.44.0502062314380.12631-100000@hkn.eecs.berkeley.edu> Message-ID: <20050207091852.87090.qmail@web53808.mail.yahoo.com> Hi, I do see a problem. The script is fine, the problem lies else where. Your script is trying to write log.bak to log, it should b other way round. i.e.... srcfile = open('/var/log/httpd-access.log', 'r') dstfile = open('/var/log/httpd-access.log.bak', 'w') hope that fixes it. About the efficiency, why do u need python at all... How abt a simple shell command.... cat httpd-access.log>>log.bak Shitiz --- Danny Yoo <dyoo@hkn.eecs.berkeley.edu> wrote: > > > On Mon, 7 Feb 2005, Reed L. O'Brien wrote: > > > I want to read the httpd-access.log and remove any > oversized log records > > > > I quickly tossed this script together. I manually > mv-ed log to log.bak > > and touched a new logfile. > > > > running the following with print i uncommented > does print each line to > > stdout. but it doesn't write to the appropriate > file... > > > Hello! > > Let's take a look at the program again: > > ### > import os > srcfile = open('/var/log/httpd-access.log.bak', 'r') > dstfile = open('/var/log/httpd-access.log', 'w') > while 1: > lines = srcfile.readlines() > if not lines: break > for i in lines: > if len(i) < 2086: > dstfile.write(i) > srcfile.close() > dstfile.close() > ### > > > a) what am I missing? > > b) is there a less expensive way to do it? > > Hmmm... I don't see anything offhand that prevents > httpd-access.log from > containing the lines you expect. Do you get any > error messages, like > permission problems, when you run the program? > > Can you show us how you are running the program, and > how you are checking > that the resulting file is empty? > > > Addressing the question on efficiency and expense: > yes. The program at > the moment tries to read all lines into memory at > once, and this is > expensive if the file is large. Let's fix this. > > > In recent versions of Python, we can modify > file-handling code from: > > ### > lines = somefile.readlines() > for line in lines: > ... > ### > > to this: > > ### > for line in somefile: > ... > ### > > That is, we don't need to extract a list of 'lines' > out of a file. > Python allows us to loop directly across a file > object. We can find more > details about this in the documentation on > "Iterators" (PEP 234): > > http://www.python.org/peps/pep-0234.html > > Iterators are a good thing to know, since Python's > iterators are deeply > rooted in the language design. (Even if it they > were retroactively > embedded. *grin*) > > > A few more comments: the while loop appears > unnecessary, since on the > second run-through the loop, we'll have already read > all the lines out of > the file. (I am assuming that nothing is writing to > the backup file at > the time.) If the body of a while loop just runs > once, we don't need a > loop. > > This simplifies the code down to: > > ### > srcfile = open('/var/log/httpd-access.log.bak', 'r') > dstfile = open('/var/log/httpd-access.log', 'w') > for line in srcfile: > if len(line) < 2086: > dstfile.write(line) > srcfile.close() > dstfile.close() > ### > > > I don't see anything else here that causes the file > writing to fail. If > you can tell us more information on how you're > checking the program's > effectiveness, that may give us some more clues. > > Best of wishes to you! > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > __________________________________ Do you Yahoo!? Yahoo! Mail - Helps protect you from nasty viruses. http://promotions.yahoo.com/new_mail From shitizb at yahoo.com Mon Feb 7 10:27:14 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Mon Feb 7 10:27:18 2005 Subject: [Tutor] Iterating over multiple lists- options In-Reply-To: <6.1.2.0.0.20050207004003.01f59e78@mail.yamato.com> Message-ID: <20050207092714.75163.qmail@web53807.mail.yahoo.com> Hi, My solution might raise purist's eyebrows but here it goes... How about using a try loop every time you read from the list. try: x=list[someno] except: x=nothing(or whatever) This goes on till the all lists start returning none. for shorter lists try throws an index out of range exception which is caught by except. Shitiz --- Tony Cappellini <tony@tcapp.com> wrote: > > > I'm trying to generate an HTML table, from multiple > lists. > > There are 4 lists total, each of which *may* have a > different length from > the other lists. > Each list has been stored in a master dictionary. > > > North=[Bill, Bob, Sue, Mary] > South=['Tim', ''Tom', 'Jim', 'John', 'Carl', 'Evan', > 'Rich'] > etc > > d1={'North':North, 'South':South, 'East':East, > 'West':West] > > > I want to iterate over all the lists a the same > time, so I can populate an > html table. > This is approximately what the HTML table should > look like, but the lists > can be in any order, top to bottom, and left to > right. > > South North East West > > Tim Bill May Ellen > Tom Bob Mick > Jim Sue Ron > John Mary Keith > Carl Joey > Evan > Rich > > > Looking through my books on Python I've found > examples for zip() and map() > both of which have serious shortcomings > That being, both of these functions can truncate the > data, depending on > certain conditions > > When iterating over multiple lists, it is fine if > the mechanism returns an > empty string , or None for a non-existing list item. > I just wont display anything in the HTML table for > missing items. > I know how to create the HTML table, statically. The > problem is being able > to fill the table in one pass (preferably), which > means my program would > need to iterate over > more than one list at the same time. > > Even using the range to generate an index has > different effects, depending > on the order in which the lists are referenced in > the for loop. > > Are there any other options available for iterating > over multiple lists ? > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > __________________________________ Do you Yahoo!? The all-new My Yahoo! - What will yours do? http://my.yahoo.com From dyoo at hkn.eecs.berkeley.edu Mon Feb 7 10:32:09 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Feb 7 10:32:13 2005 Subject: [Tutor] Iterating over multiple lists- options In-Reply-To: <6.1.2.0.0.20050207004003.01f59e78@mail.yamato.com> Message-ID: <Pine.LNX.4.44.0502070107290.5041-100000@hkn.eecs.berkeley.edu> On Mon, 7 Feb 2005, Tony Cappellini wrote: > There are 4 lists total, each of which *may* have a different length > from the other lists. Each list has been stored in a master dictionary. > > North=[Bill, Bob, Sue, Mary] > South=['Tim', ''Tom', 'Jim', 'John', 'Carl', 'Evan', 'Rich'] > etc > > I want to iterate over all the lists a the same time, so I can populate an > html table. [some text cut] > Looking through my books on Python I've found examples for zip() and map() > both of which have serious shortcomings Hi Tony, Out of curiosity, if it's not possible to run zip() directly on the lists that you have, can you bend the lists so that zip() will fit? Here's a quick function that should force a certain length on an iterator: ### def ipad(iterable, length, sentinel=None): """Returns a new iterator whose elements are taken from iterator. If there are fewer elements than 'length', we pad the rest with sentinels. Assumptions: len(iterator) <= length. The result from ipad never truncates the elements out of i, so the iterator always goes through all the elements in iterable. """ i = 0 for thing in iterable: yield thing i = i + 1 while i < length: yield sentinel i = i + 1 ### For example: ### >>> names = ['knuth', 'mcconnell', 'bentley', 'witten'] >>> for n in ipad(names, 7): ... print n ... knuth mcconnell bentley witten None None None >>> >>> >>> for n in ipad(names, 2): ... print n ... knuth mcconnell bentley witten ### So we could use something like ipad() to bring all the lists to the same length, and that should make it suitable for zip(). Hope this helps! From kent37 at tds.net Mon Feb 7 12:03:50 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Feb 7 12:03:55 2005 Subject: [Tutor] Iterating over multiple lists- options In-Reply-To: <6.1.2.0.0.20050207004003.01f59e78@mail.yamato.com> References: <6.1.2.0.0.20050207004003.01f59e78@mail.yamato.com> Message-ID: <42074B16.8080302@tds.net> Tony Cappellini wrote: > > > I'm trying to generate an HTML table, from multiple lists. > > There are 4 lists total, each of which *may* have a different length > from the other lists. > Each list has been stored in a master dictionary. > > > North=[Bill, Bob, Sue, Mary] > South=['Tim', ''Tom', 'Jim', 'John', 'Carl', 'Evan', 'Rich'] > etc > > d1={'North':North, 'South':South, 'East':East, 'West':West] > > > I want to iterate over all the lists a the same time, so I can populate > an html table. > This is approximately what the HTML table should look like, but the > lists can be in any order, top to bottom, and left to right. > > South North East West > > Tim Bill May Ellen > Tom Bob Mick > Jim Sue Ron > John Mary Keith > Carl Joey > Evan > Rich > > > Looking through my books on Python I've found examples for zip() and > map() both of which have serious shortcomings map(None, North, South, East West) does exactly what you want: >>> North=['Bill', 'Bob', 'Sue', 'Mary'] >>> South=['Tim', 'Tom', 'Jim', 'John', 'Carl', 'Evan', 'Rich'] >>> map(None, North, South) [('Bill', 'Tim'), ('Bob', 'Tom'), ('Sue', 'Jim'), ('Mary', 'John'), (None, 'Carl'), (None, 'Evan'), (None, 'Rich')] > That being, both of these functions can truncate the data, depending on > certain conditions I don't think that is true for map(); what conditions are you thinking of? Kent From ch_chandu9 at yahoo.com Mon Feb 7 12:09:14 2005 From: ch_chandu9 at yahoo.com (chandrasekhar cherukuri) Date: Mon Feb 7 12:09:18 2005 Subject: [Tutor] where do we use acquisition ? Message-ID: <20050207110914.12461.qmail@web21201.mail.yahoo.com> I completely understood what is acquisition. Now can some one explain me where it is useful and give some contextual examples where we can see the power of acquisition. regards chandu. __________________________________ Do you Yahoo!? Yahoo! Mail - Helps protect you from nasty viruses. http://promotions.yahoo.com/new_mail From kent37 at tds.net Mon Feb 7 13:37:26 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Feb 7 13:37:30 2005 Subject: [Tutor] where do we use acquisition ? In-Reply-To: <20050207110914.12461.qmail@web21201.mail.yahoo.com> References: <20050207110914.12461.qmail@web21201.mail.yahoo.com> Message-ID: <42076106.80806@tds.net> chandrasekhar cherukuri wrote: > I completely understood what is acquisition. I don't :-) Can you tell us what you mean by acquisition? I see Zope has something called acquisition; I can't think of anything by that name in standard Python... Kent Now can > some one explain me where it is useful and give some > contextual examples where we can see the power of > acquisition. > > regards > chandu. From kent37 at tds.net Mon Feb 7 14:00:15 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Feb 7 14:00:17 2005 Subject: [Tutor] where do we use acquisition ? In-Reply-To: <20050207125053.25163.qmail@web21201.mail.yahoo.com> References: <20050207125053.25163.qmail@web21201.mail.yahoo.com> Message-ID: <4207665F.5020908@tds.net> chandrasekhar cherukuri wrote: > http://zope.org/Documentation/Books/ZopeBook/2_6Edition/ScriptingZope.stx/Acquisition.stx > > http://zope.org/Members/crazybrett/acquisition > > Hope there is no sarcasm in this. No, none at all. A light irony, maybe. When I first read your post, I thought, "I have no idea what acquisition is". I thought it was funny that you completely understand it but I am clueless about it. I had to google 'python acquisition' to see that Zope uses that term. I hope someone else here has more of a clue than me. If not, you might want to try a Zope-specific mailing list. Kent > > > --- Kent Johnson <kent37@tds.net> wrote: > > >>chandrasekhar cherukuri wrote: >> >>>I completely understood what is acquisition. >> >>I don't :-) >>Can you tell us what you mean by acquisition? I see >>Zope has something called acquisition; I can't >>think of anything by that name in standard Python... >> >>Kent >> >>Now can >> >>>some one explain me where it is useful and give >> >>some >> >>>contextual examples where we can see the power of >>>acquisition. >>> >>>regards >>>chandu. >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> > > > > > > > __________________________________ > Do you Yahoo!? > Yahoo! Mail - You care about security. So do we. > http://promotions.yahoo.com/new_mail > From pierre.barbier at cirad.fr Mon Feb 7 14:09:50 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Mon Feb 7 14:07:51 2005 Subject: [Tutor] where do we use acquisition ? In-Reply-To: <4207665F.5020908@tds.net> References: <20050207125053.25163.qmail@web21201.mail.yahoo.com> <4207665F.5020908@tds.net> Message-ID: <4207689E.9010501@cirad.fr> I may say this is no subject for the Python _tutor_ list ! You'll at least want to post this message to the comp.lang.python newsgroup. Pierre Kent Johnson a ?crit : > chandrasekhar cherukuri wrote: > >> http://zope.org/Documentation/Books/ZopeBook/2_6Edition/ScriptingZope.stx/Acquisition.stx >> >> >> http://zope.org/Members/crazybrett/acquisition >> >> Hope there is no sarcasm in this. > > > No, none at all. A light irony, maybe. When I first read your post, I > thought, "I have no idea what acquisition is". I thought it was funny > that you completely understand it but I am clueless about it. I had to > google 'python acquisition' to see that Zope uses that term. > > I hope someone else here has more of a clue than me. If not, you might > want to try a Zope-specific mailing list. > > Kent > >> >> >> --- Kent Johnson <kent37@tds.net> wrote: >> >> >>> chandrasekhar cherukuri wrote: >>> >>>> I completely understood what is acquisition. >>> >>> >>> I don't :-) >>> Can you tell us what you mean by acquisition? I see >>> Zope has something called acquisition; I can't think of anything by >>> that name in standard Python... >>> >>> Kent >>> >>> Now can >>> >>>> some one explain me where it is useful and give >>> >>> >>> some >>> >>>> contextual examples where we can see the power of >>>> acquisition. >>>> >>>> regards >>>> chandu. >>> >>> >>> _______________________________________________ >>> Tutor maillist - Tutor@python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >> >> >> >> >> >> >> __________________________________ Do you Yahoo!? Yahoo! Mail - You >> care about security. So do we. http://promotions.yahoo.com/new_mail >> > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 From karen.leever at falw.vu.nl Mon Feb 7 14:40:06 2005 From: karen.leever at falw.vu.nl (Karen Leever) Date: Mon Feb 7 14:40:09 2005 Subject: [Tutor] calling subroutines into program Message-ID: <5.1.0.14.0.20050207140910.00bbe528@mailhost.geo.vu.nl> Hello, I've been writing some small python programs that basically do function analysis on the (x,y) output of a fortran code called COBRA. The COBRA output (basin.out) is the shape of a flexed beam, of which I calculate the 0-crossing, x and y of max. amplitude, and cross sectional area between function and y=0. I managed to make python calculate these things, so it actually works. No problems there. However, I'd like to make the format a bit more elegant. Each python program consists of several components, some of which occur in each of the programs. These components comprise: (1) reading the COBRA output file and write the contents to an array, (2) reading a second COBRA output file for reference values. See below for an example. How can I refer in my programs to these components without actually incorporating them in the program? I don't see how I could define them as functions. And "import 'component'.py" does not work either: I tried this but it will not recognize the array arr_xy (defined in 'component'.py) later on. thanks for suggestion or reference, Karen example of (1): --------------------------------------------------------- #this part of the program reads the file basin.out (the data we want to analyze) and changes its contents to the array arr_xy #layout of basin.out: #1 -950.00 10.00 200 > this line contains start, interval and number of x values; # 0.000000E+00 > remainder is a column of y values # -1.931787E-07 # -5.713295E-07 # -9.322559E-07 # -1.071361E-06 # -7.801342E-07 # ..... import re #open the (x,y) output file cobra_xy_file = open('/home/tecguest/leek/Suncobra/Screen/basin.out') #read first line and change it to a list so it can be read by the program firstline = cobra_xy_file.readline() p = re.compile(r'\s+') list = p.split(firstline) #from the list defined above, x-values have to be calculated. #the list contains strings that are converted to integers before they can be used in further calculations start = int(float(list[1])) interval = int(float(list[2])) n = int(float(list[3])) stop = start + n*interval arr_x = range(start, stop, interval) #the calculated x-values are stored in 1D array arr_x (note, fake array, is really a list) #the list of calculated x values, together with the y values in the cobra_xy_file have to be put in an array: arr_xy #first define the new array: arr_xy = [] #then fill the array with the x and y values: for i in range(0, len(arr_x)): sub_arr_xy = [] sub_arr_xy.append(arr_x[i]) sub_arr_xy.append(float(cobra_xy_file.readline())) arr_xy.append(sub_arr_xy) #print 'These are the first values from the x,y file:' #print arr_xy[:5] #print cobra_xy_file.close -------------------------------------------------------- >>> please note new phone and fax number <<< ---------------------------------------------------- Karen Leever Department of Tectonics Faculty of Earth and Life Sciences Vrije Universiteit Amsterdam De Boelelaan 1085 1081 HV Amsterdam The Netherlands tel: +31 20 598 7278 fax: +31 20 598 9943 @: karen.leever@falw.vu.nl ---------------------------------------------------- From cyresse at gmail.com Mon Feb 7 14:45:37 2005 From: cyresse at gmail.com (Liam Clarke) Date: Mon Feb 7 14:45:40 2005 Subject: [Tutor] calling subroutines into program In-Reply-To: <5.1.0.14.0.20050207140910.00bbe528@mailhost.geo.vu.nl> References: <5.1.0.14.0.20050207140910.00bbe528@mailhost.geo.vu.nl> Message-ID: <f2ff2d05020705459a81db9@mail.gmail.com> Hi Karen, if I have a file called foo.py = def la() return "la" x = 15 I can do the following in bar.py = import foo #Notice there's no .py extension! j = foo.la() print j print foo.x > la > 15 Hope that helps Liam Clarke On Mon, 07 Feb 2005 14:40:06 +0100, Karen Leever <karen.leever@falw.vu.nl> wrote: > Hello, > > I've been writing some small python programs that basically do function > analysis on the (x,y) output of a fortran code called COBRA. > The COBRA output (basin.out) is the shape of a flexed beam, of which I > calculate the 0-crossing, x and y of max. amplitude, and cross sectional > area between function and y=0. > > I managed to make python calculate these things, so it actually works. No > problems there. > However, I'd like to make the format a bit more elegant. Each python > program consists of several components, some of which occur in each of the > programs. These components comprise: (1) reading the COBRA output file and > write the contents to an array, (2) reading a second COBRA output file for > reference values. See below for an example. > > How can I refer in my programs to these components without actually > incorporating them in the program? > I don't see how I could define them as functions. > And "import 'component'.py" does not work either: I tried this but it will > not recognize the array arr_xy (defined in 'component'.py) later on. > > thanks for suggestion or reference, > > Karen > > example of (1): > --------------------------------------------------------- > #this part of the program reads the file basin.out (the data we want to > analyze) and changes its contents to the array arr_xy > #layout of basin.out: > #1 -950.00 10.00 200 > this line contains start, interval and > number of x values; > # 0.000000E+00 > remainder is a column of y values > # -1.931787E-07 > # -5.713295E-07 > # -9.322559E-07 > # -1.071361E-06 > # -7.801342E-07 > # ..... > > import re > > #open the (x,y) output file > cobra_xy_file = open('/home/tecguest/leek/Suncobra/Screen/basin.out') > > #read first line and change it to a list so it can be read by the program > firstline = cobra_xy_file.readline() > p = re.compile(r'\s+') > list = p.split(firstline) > > #from the list defined above, x-values have to be calculated. > #the list contains strings that are converted to integers before they can > be used in further calculations > start = int(float(list[1])) > interval = int(float(list[2])) > n = int(float(list[3])) > stop = start + n*interval > arr_x = range(start, stop, interval) #the calculated x-values are stored > in 1D array arr_x (note, fake array, is really a list) > > #the list of calculated x values, together with the y values in the > cobra_xy_file have to be put in an array: arr_xy > #first define the new array: > arr_xy = [] > > #then fill the array with the x and y values: > for i in range(0, len(arr_x)): > sub_arr_xy = [] > sub_arr_xy.append(arr_x[i]) > sub_arr_xy.append(float(cobra_xy_file.readline())) > arr_xy.append(sub_arr_xy) > > #print 'These are the first values from the x,y file:' > #print arr_xy[:5] > #print > > cobra_xy_file.close > -------------------------------------------------------- > > >>> please note new phone and fax number <<< > ---------------------------------------------------- > Karen Leever > Department of Tectonics > Faculty of Earth and Life Sciences > Vrije Universiteit Amsterdam > De Boelelaan 1085 > 1081 HV Amsterdam > The Netherlands > > tel: +31 20 598 7278 > fax: +31 20 598 9943 > @: karen.leever@falw.vu.nl > ---------------------------------------------------- > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cyresse at gmail.com Mon Feb 7 15:02:32 2005 From: cyresse at gmail.com (Liam Clarke) Date: Mon Feb 7 15:02:42 2005 Subject: [Tutor] calling subroutines into program In-Reply-To: <f2ff2d05020705459a81db9@mail.gmail.com> References: <5.1.0.14.0.20050207140910.00bbe528@mailhost.geo.vu.nl> <f2ff2d05020705459a81db9@mail.gmail.com> Message-ID: <f2ff2d05020706023b730c27@mail.gmail.com> Actually, if I may rewrite some sections of your code - > > example of (1): > > --------------------------------------------------------- > > #this part of the program reads the file basin.out (the data we want to > > analyze) and changes its contents to the array arr_xy > > #layout of basin.out: > > #1 -950.00 10.00 200 > this line contains start, interval and > > number of x values; > > # 0.000000E+00 > remainder is a column of y values > > # -1.931787E-07 > > # -5.713295E-07 > > # -9.322559E-07 > > # -1.071361E-06 > > # -7.801342E-07 > > # ..... So to clarify the first line has 4 values? Are they likely to be separated by whitespace characters other than space? If not, then you could just use a = firstline.split(" ") instead of > > p = re.compile(r'\s+') > > list = p.split(firstline) >start = int(float(list[1])) > interval = int(float(list[2])) > n = int(float(list[3])) list[1] is a string, so if I'm not missing something, start = int(list[1]) will do just fine. >>arr_x = range(start, stop, interval) #the calculated x-values are stored > > in 1D array arr_x (note, fake array, is really a list) > > > > #the list of calculated x values, together with the y values in the > > cobra_xy_file have to be put in an array: arr_xy > > #first define the new array: > > arr_xy = [] > > > > #then fill the array with the x and y values: > > for i in range(0, len(arr_x)): > > sub_arr_xy = [] > > sub_arr_xy.append(arr_x[i]) > > sub_arr_xy.append(float(cobra_xy_file.readline())) > > arr_xy.append(sub_arr_xy) arr_xy=[] for i in range(start, stop, interval): sub_arr_xy = [] sub_arr_xy.append(i) sub_arr_xy.append(float(cobra_xy_file.readline() ) ) arr_xy.append(sub_arr_xy) Should do the same thing. Good luck, Liam Clarke -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From kent37 at tds.net Mon Feb 7 15:04:54 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Feb 7 15:04:56 2005 Subject: [Tutor] calling subroutines into program In-Reply-To: <5.1.0.14.0.20050207140910.00bbe528@mailhost.geo.vu.nl> References: <5.1.0.14.0.20050207140910.00bbe528@mailhost.geo.vu.nl> Message-ID: <42077586.3080900@tds.net> Karen, Put all of your code into a function, maybe called import_cobra(). The function should take the path to the basic.out file as a parameter and return the array of data. So it will look something like this: def import_cobra(basicPath): cobra_xy_file = open(basicPath) # All the same code as below all the way to... cobra_xy_file.close() # Oops, you were missing parentheses here! # End with a return statement that passes the array back to the caller return arr_xy If you put this in a file called component.py (you might want to think of a more descriptive name, maybe CobraUtils.py?), then in a client program you can do this: from component import import_cobra arr_xy = import_cobra Now you can do what you want with arr_xy. Kent Karen Leever wrote: > Hello, > > I've been writing some small python programs that basically do function > analysis on the (x,y) output of a fortran code called COBRA. > The COBRA output (basin.out) is the shape of a flexed beam, of which I > calculate the 0-crossing, x and y of max. amplitude, and cross sectional > area between function and y=0. > > I managed to make python calculate these things, so it actually works. > No problems there. > However, I'd like to make the format a bit more elegant. Each python > program consists of several components, some of which occur in each of > the programs. These components comprise: (1) reading the COBRA output > file and write the contents to an array, (2) reading a second COBRA > output file for reference values. See below for an example. > > How can I refer in my programs to these components without actually > incorporating them in the program? > I don't see how I could define them as functions. > And "import 'component'.py" does not work either: I tried this but it > will not recognize the array arr_xy (defined in 'component'.py) later on. > > thanks for suggestion or reference, > > Karen > > > example of (1): > --------------------------------------------------------- > #this part of the program reads the file basin.out (the data we want to > analyze) and changes its contents to the array arr_xy > #layout of basin.out: > #1 -950.00 10.00 200 > this line contains start, interval and > number of x values; > # 0.000000E+00 > remainder is a column of y values > # -1.931787E-07 > # -5.713295E-07 > # -9.322559E-07 > # -1.071361E-06 > # -7.801342E-07 > # ..... > > import re > > #open the (x,y) output file > cobra_xy_file = open('/home/tecguest/leek/Suncobra/Screen/basin.out') > > > #read first line and change it to a list so it can be read by the program > firstline = cobra_xy_file.readline() > p = re.compile(r'\s+') > list = p.split(firstline) > > > #from the list defined above, x-values have to be calculated. > #the list contains strings that are converted to integers before they > can be used in further calculations > start = int(float(list[1])) > interval = int(float(list[2])) > n = int(float(list[3])) > stop = start + n*interval > arr_x = range(start, stop, interval) #the calculated x-values are > stored in 1D array arr_x (note, fake array, is really a list) > > > #the list of calculated x values, together with the y values in the > cobra_xy_file have to be put in an array: arr_xy > #first define the new array: > arr_xy = [] > > #then fill the array with the x and y values: > for i in range(0, len(arr_x)): > sub_arr_xy = [] > sub_arr_xy.append(arr_x[i]) > sub_arr_xy.append(float(cobra_xy_file.readline())) > arr_xy.append(sub_arr_xy) > > #print 'These are the first values from the x,y file:' > #print arr_xy[:5] > #print > > cobra_xy_file.close > -------------------------------------------------------- > > > > > >>> please note new phone and fax number <<< > ---------------------------------------------------- > Karen Leever > Department of Tectonics > Faculty of Earth and Life Sciences > Vrije Universiteit Amsterdam > De Boelelaan 1085 > 1081 HV Amsterdam > The Netherlands > > tel: +31 20 598 7278 > fax: +31 20 598 9943 > @: karen.leever@falw.vu.nl > ---------------------------------------------------- > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From jsmith at medplus.com Mon Feb 7 15:14:55 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Mon Feb 7 15:15:19 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: <C4C644CF4ADA9448904C3E8BACC4B97C02E67461@medexch1.medplus.com> Alan, No use beating this dead horse...I guess that's why there are so many languages in the first place. Different people are comfortable with different things. (I did warn you that I like both Lisp and Prolog and only wish I had more of a reason to use them :-) As an aside, I did try to create a lambda based solution but was unable. Let me know what's wrong: ftable = { 'a' : lambda: print 'a', 'b' : lambda: print 'b or c', 'c' : lambda: print 'b or c', 'd' : lambda: pass } ftable.get(var, lambda: print 'default case')() File "C:\scratch\Script1.py", line 2 ftable = { 'a' : lambda: print 'a', ^ SyntaxError: invalid syntax Jeff -----Original Message----- From: Alan Gauld [mailto:alan.gauld@freenet.co.uk] Sent: Friday, February 04, 2005 6:39 PM To: Smith, Jeff; Jacob S.; Nicholas.Montpetit@deluxe.com; tutor@python.org Subject: Re: [Tutor] Are you allowed to shoot camels? [kinda OT] > Now who's joking? :-) > Are you saying that > > switch var: > case 'a': > print 'a' > ... > default: > print 'default case' > > Is less clear and maintainable than I don;tthink I said (certainly didn't mean) less clear, but yes it is less maintainable. But then... > def do_this_function(): > print 'a' > .... > ftable = { 'a' : do_this_function, > 'b' : do_that_function, > 'c' : do_that_function, > 'd' : do_pass_function } > ftable.get(var, do_default_function)() I did also say that it was best with proper lambdas ftable = {'a' : lambda: print 'a', 'b' : lambda: print 'b' etc/// and I'd code the calling section: try: ftable[value]() except KeyError: doDefaultFunction() Its more maintainable because even if the switches proliferates as they tend to do, the dictionary stays in one place and the calling code never needs changing. So the changes are much more localised. And of course the more complex the case actions are, the more effective the dictionary/function approach becomes. Alan G. From hornak at csb.sunysb.edu Mon Feb 7 15:27:56 2005 From: hornak at csb.sunysb.edu (Viktor Hornak) Date: Mon Feb 7 15:28:33 2005 Subject: [Tutor] python lists to C arrays and vice versa Message-ID: <42077AEC.5060007@csb.sunysb.edu> Hello All, I've been trying to find more resources/documentation about how to convert python lists to C arrays (and vice versa) when writing a python extension. Surprisingly, there's very little one can find about this even though it must be a fairly common procedure. I looked through official python guide on "Extending and Embedding the Python Interpreter" but it's very terse on examples and the important topic on reference counting is still not very clear. I also found one or two examples of similar operations on this list postings (from 6 years ago!) but they didn't quite explain all I need to know. Here is the code I was trying to use to convert two lists (one is a list of strings with the same length and the other is a list of doubles) to C arrays in a C extension: typedef char Name[5]; extern void parseMask(int, char*, Name *, double *); /* this is the function I am trying to wrap */ static PyObject *print_sel(PyObject *self, PyObject *args) { PyObject *anamestr, *xdbl; PyObject *pylist; /* return list of 0/1 */ PyObject *item; int nat; int i, k; Name *aname; double *x; PyArg_ParseTuple(args,"iOO", &nat, &anamestr, &xdbl); if (!PySequence_Check(anamestr) || !PySequence_Check(xdbl)) { PyErr_SetString(PyExc_TypeError, "expected sequence"); return NULL; } /* create dynamic C arrays */ aname = (Name *) malloc(sizeof(Name)*nat); x = (double *) malloc(sizeof(double)*nat); for (i = 0; i < nat; i++) { /* get the element from the list*/ item = PySequence_GetItem(anamestr,i); /* check that item != NULL, i.e. make sure it is Python string */ if (!PyString_Check(item)) { free(aname); /* free up the memory before leaving */ free(x); PyErr_SetString(PyExc_TypeError, "expected sequence of strings"); return NULL; } /* assign to the C array */ strcpy(aname[i], PyString_AsString(item)); Py_DECREF(item); item = PySequence_GetItem(xdbl,i); if (!PyFloat_Check(item)) { free(aname); free(x); PyErr_SetString(PyExc_TypeError, "expected sequence of integers"); return NULL; } x[i] = PyFloat_AsDouble(item); Py_DECREF(item); } Then I call the function "parseMask" (which I am trying to wrap in this extension) which returns a C array (integer array, elements are either 0 or 1). Now I need to convert this integer array to python list and return it back to python. Here is the code for that: result = (int *) malloc(sizeof(int) * nat); parseMask(...) -> returns int array result pylist = PyTuple_New(nat); for (i = 0; i < nat; i++) { /* convert resulting array [0/1] to PyObject */ if (result[i] == 0) item = PyInt_FromLong(0); else item = PyInt_FromLong(1); PyTuple_SetItem(pylist, i, item); Py_DECREF(item); } /* free up all arrays before leaving */ free((void *) aname); free((void *) x); free((void *) result); return pylist; I was wondering if some 'extension guru' (or whoever has experience with writing extensions :-)) could see if the above code is correct, especially with respect to reference counting. When I use this extension from Python (on Fedora Core 3, Python2.3) I get the following error: *** glibc detected *** double free or corruption (out): 0x09f724e8 *** Aborted This is supposed to mean some deeper memory allocation/deallocation error. I suspect I am not creating or releasing python objects in my C extension above correctly. Of course, it is also possible that the C function I am wrapping (parseMask()) is not allocating memory properly, but it works without problem when I call it from a C program. I am sorry for this looong post, but I didn't see a way to make it shorter and still be very specific about what I am trying to do... Many thanks for any help, -Viktor Hornak From kent37 at tds.net Mon Feb 7 15:36:02 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Feb 7 15:36:03 2005 Subject: [Tutor] calling subroutines into program In-Reply-To: <f2ff2d05020706023b730c27@mail.gmail.com> References: <5.1.0.14.0.20050207140910.00bbe528@mailhost.geo.vu.nl> <f2ff2d05020705459a81db9@mail.gmail.com> <f2ff2d05020706023b730c27@mail.gmail.com> Message-ID: <42077CD2.5040107@tds.net> Liam Clarke wrote: >>>example of (1): >>>--------------------------------------------------------- >>>#this part of the program reads the file basin.out (the data we want to >>>analyze) and changes its contents to the array arr_xy >>>#layout of basin.out: >>>#1 -950.00 10.00 200 > this line contains start, interval and >>>number of x values; >>># 0.000000E+00 > remainder is a column of y values >>># -1.931787E-07 >>># -5.713295E-07 >>># -9.322559E-07 >>># -1.071361E-06 >>># -7.801342E-07 >>># ..... >>start = int(float(list[1])) >>interval = int(float(list[2])) >>n = int(float(list[3])) > > > list[1] is a string, so if I'm not missing something, start = > int(list[1]) will do just fine. No, because list[1] is '-950.00' which will not parse as an int. Kent From bgailer at alum.rpi.edu Mon Feb 7 15:47:33 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon Feb 7 15:42:03 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <C4C644CF4ADA9448904C3E8BACC4B97C02E67461@medexch1.medplus. com> References: <C4C644CF4ADA9448904C3E8BACC4B97C02E67461@medexch1.medplus.com> Message-ID: <6.1.2.0.0.20050207074342.034cec58@mail.mric.net> At 07:14 AM 2/7/2005, Smith, Jeff wrote: >Alan, > >No use beating this dead horse...I guess that's why there are so many >languages in the first place. Different people are comfortable with >different things. (I did warn you that I like both Lisp and Prolog and >only wish I had more of a reason to use them :-) > >As an aside, I did try to create a lambda based solution but was unable. >Let me know what's wrong: > >ftable = { 'a' : lambda: print 'a', > 'b' : lambda: print 'b or c', > 'c' : lambda: print 'b or c', > 'd' : lambda: pass } >ftable.get(var, lambda: print 'default case')() From the docs: lambda arguments: expression print 'a' is not an expression > File "C:\scratch\Script1.py", line 2 > ftable = { 'a' : lambda: print 'a', > ^ >SyntaxError: invalid syntax Bob Gailer mailto:bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From jsmith at medplus.com Mon Feb 7 15:43:07 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Mon Feb 7 15:43:13 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: <C4C644CF4ADA9448904C3E8BACC4B97C02E67470@medexch1.medplus.com> That's kinda what I thought but a couple of people suggested that I used lambdas to make it clearer that I figured I was doing something wrong... Jeff -----Original Message----- From: Bob Gailer [mailto:bgailer@alum.rpi.edu] Sent: Monday, February 07, 2005 9:48 AM To: Smith, Jeff; tutor@python.org Subject: RE: [Tutor] Are you allowed to shoot camels? [kinda OT] At 07:14 AM 2/7/2005, Smith, Jeff wrote: >Alan, > >No use beating this dead horse...I guess that's why there are so many >languages in the first place. Different people are comfortable with >different things. (I did warn you that I like both Lisp and Prolog and >only wish I had more of a reason to use them :-) > >As an aside, I did try to create a lambda based solution but was >unable. Let me know what's wrong: > >ftable = { 'a' : lambda: print 'a', > 'b' : lambda: print 'b or c', > 'c' : lambda: print 'b or c', > 'd' : lambda: pass } >ftable.get(var, lambda: print 'default case')() From the docs: lambda arguments: expression print 'a' is not an expression > File "C:\scratch\Script1.py", line 2 > ftable = { 'a' : lambda: print 'a', > ^ >SyntaxError: invalid syntax Bob Gailer mailto:bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From bgailer at alum.rpi.edu Mon Feb 7 16:09:57 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon Feb 7 16:04:26 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <C4C644CF4ADA9448904C3E8BACC4B97C02E67470@medexch1.medplus. com> References: <C4C644CF4ADA9448904C3E8BACC4B97C02E67470@medexch1.medplus.com> Message-ID: <6.1.2.0.0.20050207080358.0347faf8@mail.mric.net> At 07:43 AM 2/7/2005, Smith, Jeff wrote: >That's kinda what I thought but a couple of people suggested that I used >lambdas to make it clearer that I figured I was doing something wrong... Well you can use lambdas. Have them return an expression which you print after retrieving: ftable = { 'a' : lambda: 'a', 'b' : lambda: 'b or c', 'c' : lambda: 'b or c', 'd' : lambda: ''} print ftable.get(var, lambda: 'default case')() But it would be clearer to store just the expressions: ftable = { 'a' : 'a', 'b' : 'b or c', 'c' : 'b or c', 'd' : ''} print ftable.get(var, 'default case') Bob Gailer mailto:bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From jsmith at medplus.com Mon Feb 7 16:06:10 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Mon Feb 7 16:06:15 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: <C4C644CF4ADA9448904C3E8BACC4B97C02E67477@medexch1.medplus.com> Bob, Unfortunately, that doesn't do the same thing. In the 'd' case, you get a print rather than a pass for instance. It was also just happenstance that I chose to print on each switch rather than do something like increment a counter. Jeff -----Original Message----- From: Bob Gailer [mailto:bgailer@alum.rpi.edu] Sent: Monday, February 07, 2005 10:10 AM To: Smith, Jeff; tutor@python.org Subject: RE: [Tutor] Are you allowed to shoot camels? [kinda OT] At 07:43 AM 2/7/2005, Smith, Jeff wrote: >That's kinda what I thought but a couple of people suggested that I >used lambdas to make it clearer that I figured I was doing something >wrong... Well you can use lambdas. Have them return an expression which you print after retrieving: ftable = { 'a' : lambda: 'a', 'b' : lambda: 'b or c', 'c' : lambda: 'b or c', 'd' : lambda: ''} print ftable.get(var, lambda: 'default case')() But it would be clearer to store just the expressions: ftable = { 'a' : 'a', 'b' : 'b or c', 'c' : 'b or c', 'd' : ''} print ftable.get(var, 'default case') Bob Gailer mailto:bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From kent37 at tds.net Mon Feb 7 16:16:12 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Feb 7 16:16:14 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <6.1.2.0.0.20050207074342.034cec58@mail.mric.net> References: <C4C644CF4ADA9448904C3E8BACC4B97C02E67461@medexch1.medplus.com> <6.1.2.0.0.20050207074342.034cec58@mail.mric.net> Message-ID: <4207863C.2030109@tds.net> Bob Gailer wrote: > At 07:14 AM 2/7/2005, Smith, Jeff wrote: > >> Alan, >> >> No use beating this dead horse...I guess that's why there are so many >> languages in the first place. Different people are comfortable with >> different things. (I did warn you that I like both Lisp and Prolog and >> only wish I had more of a reason to use them :-) >> >> As an aside, I did try to create a lambda based solution but was unable. >> Let me know what's wrong: >> >> ftable = { 'a' : lambda: print 'a', >> 'b' : lambda: print 'b or c', >> 'c' : lambda: print 'b or c', >> 'd' : lambda: pass } >> ftable.get(var, lambda: print 'default case')() > > > From the docs: lambda arguments: expression > print 'a' is not an expression As a workaround to use print in a lambda you can use sys.stdout.write() instead. Kent From sandip at lug-delhi.org Mon Feb 7 16:09:27 2005 From: sandip at lug-delhi.org (Sandip Bhattacharya) Date: Mon Feb 7 16:44:45 2005 Subject: [Tutor] want recommendations for interfacing with postgresql Message-ID: <1107788967.29067.5.camel@pluto.home> Hi! I am planning to work with postgresql and python for one of my projects. Which library module would you recommend for the job? I have seen: 1. http://www.pygresql.org (pgdb module) 2. http://initd.org/projects/psycopg1 Thanks, Sandip -- Sandip Bhattacharya * Puroga Technologies * sandip@puroga.com Work: http://www.puroga.com * Home/Blog: http://www.sandipb.net/blog PGP/GPG Signature: 51A4 6C57 4BC6 8C82 6A65 AE78 B1A1 2280 A129 0FF3 From sandip at lug-delhi.org Mon Feb 7 17:01:15 2005 From: sandip at lug-delhi.org (Sandip Bhattacharya) Date: Mon Feb 7 16:53:12 2005 Subject: [Tutor] Fwd: want recommendations for interfacing with postgresql Message-ID: <1107792075.29067.10.camel@pluto.home> [Reposting. Didnt make it the first time - Sandip] -------- Forwarded Message -------- From: Sandip Bhattacharya <sandip@lug-delhi.org> To: Python Tutor Mailing List <tutor@python.org> Subject: want recommendations for interfacing with postgresql Date: Mon, 07 Feb 2005 20:39:27 +0530 Hi! I am planning to work with postgresql and python for one of my projects. Which library module would you recommend for the job? I have seen: 1. http://www.pygresql.org (pgdb module) 2. http://initd.org/projects/psycopg1 Thanks, Sandip -- Sandip Bhattacharya * Puroga Technologies * sandip@puroga.com Work: http://www.puroga.com * Home/Blog: http://www.sandipb.net/blog PGP/GPG Signature: 51A4 6C57 4BC6 8C82 6A65 AE78 B1A1 2280 A129 0FF3 -- Sandip Bhattacharya * Puroga Technologies * sandip@puroga.com Work: http://www.puroga.com * Home/Blog: http://www.sandipb.net/blog PGP/GPG Signature: 51A4 6C57 4BC6 8C82 6A65 AE78 B1A1 2280 A129 0FF3 From tony at tcapp.com Mon Feb 7 19:32:57 2005 From: tony at tcapp.com (Tony Cappellini) Date: Mon Feb 7 19:30:42 2005 Subject: [Tutor] Iterating over multiple lists- options In-Reply-To: <Pine.LNX.4.44.0502070107290.5041-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0502070107290.5041-100000@hkn.eecs.berkeley.edu> Message-ID: <20050207102429.O90909@yamato.yamato.com> > Out of curiosity, if it's not possible to run zip() directly on the lists > that you have, can you bend the lists so that zip() will fit? It is possible, however zip() truncates the longer list, based on the size of the smaller list, so it's just not feasible in my case. > Here's a quick function that should force a certain length on an iterator: > > ### > def ipad(iterable, length, sentinel=None): > """Returns a new iterator whose elements are taken from iterator. If > there are fewer elements than 'length', we pad the rest with > sentinels. > > Assumptions: len(iterator) <= length. The result from ipad never > truncates the elements out of i, so the iterator always goes through > all the elements in iterable. > """ > i = 0 > for thing in iterable: > yield thing > i = i + 1 > while i < length: > yield sentinel > i = i + 1 > ### > > > For example: > > ### > >>> names = ['knuth', 'mcconnell', 'bentley', 'witten'] > >>> for n in ipad(names, 7): > ... print n > ... > knuth > mcconnell > bentley > witten > None > None > None > >>> > >>> > >>> for n in ipad(names, 2): > ... print n > ... > knuth > mcconnell > bentley > witten > ### > > > So we could use something like ipad() to bring all the lists to the same > length, and that should make it suitable for zip(). > > > Hope this helps! > > I see- yes it does. And since it's my first use of generators, without really having to understand them, I'm more inclined to use this approach :-) I will just pad the short lists with the lenght of the longest list. However, this brings up a question about map() ing over lists of different lengths (which is what I started to use), but I'll post that in a different message. BTW, is your def ipad() function the 20gb, 40gb, or 60gb model ? :-) Thanks From alan.gauld at freenet.co.uk Mon Feb 7 20:28:34 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Feb 7 20:28:04 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <C4C644CF4ADA9448904C3E8BACC4B97C02E67461@medexch1.medplus.com> Message-ID: <05ad01c50d4b$37c1c040$68b78851@xp> > As an aside, I did try to create a lambda based solution but was unable. > Let me know what's wrong: > > ftable = { 'a' : lambda: print 'a', > SyntaxError: invalid syntax I did say "if Python had *proper* lambdas..." Unfortunately Python insists on only having *expressions* as lambdas and since print is a command not a function you can't use it in Python lambdas! Dumb or what??! So you are stuck with predefining a bunch of one liner functions and then creating a dictionary or going back to if/elif chains, which is where we came in... :-) HTH, Alan G. From alan.gauld at freenet.co.uk Mon Feb 7 20:49:24 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Feb 7 20:50:20 2005 Subject: [Tutor] manipulating a file References: <cu73hp$7oj$1@sea.gmane.org> Message-ID: <05d401c50d4e$2058fc40$68b78851@xp> > running the following with print i uncommented does print each line to > stdout. but it doesn't write to the appropriate file... Does it do anything? BTW YOu don;t need to touch a file, the 'w' parameter will create a new file if one doesn't exist. > c) I originally wanted to delete lines over 2085 in length but couldn't > find a way to do that... did I miss it? deleting files from a file aint so easy, its much simpler to just create a new file with the lines you want, as you do here. > srcfile = open('/var/log/httpd-access.log.bak', 'r') > dstfile = open('/var/log/httpd-access.log', 'w') > while 1: > lines = srcfile.readlines() > if not lines: break > for i in lines: This is much easier with: for i in srcfile: It will automatically detect and stop at the end of the file. > if len(i) < 2086: > #print i > dstfile.write(i) You should add a newline character otherwise you will just get one enormously long line! dstfile.write(i+'\n') > srcfile.close() > dstfile.close() But I don't see anything obviously wrong. What exactly does happen? A single line as explained above? Or just a blank file? Alan G. From alan.gauld at freenet.co.uk Mon Feb 7 20:53:05 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Feb 7 20:52:28 2005 Subject: [Tutor] manipulating a file References: <20050207091852.87090.qmail@web53808.mail.yahoo.com> Message-ID: <05dd01c50d4e$a404df00$68b78851@xp> > About the efficiency, why do u need python at all... > How abt a simple shell command.... > cat httpd-access.log>>log.bak > Because that would be a copy, well actually an append... cp httpd-access.log log.bak would be better! But the OP wanted to strip out long lines in transit not just copy... Alan G. From alan.gauld at freenet.co.uk Mon Feb 7 20:56:41 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Feb 7 20:56:06 2005 Subject: [Tutor] Iterating over multiple lists- options References: <20050207092714.75163.qmail@web53807.mail.yahoo.com> Message-ID: <05e201c50d4f$25213d40$68b78851@xp> > How about using a try loop every time you read from > the list. try is not a loop. > try: > x=list[someno] > except: > x=nothing(or whatever) > > This goes on till the all lists start returning none. No, sorry it just does it once. try/except is for detecting errors not a looping construct. > for shorter lists try throws an index out of range > exception which is caught by except. This much is true. But to do as you suggest the try/except would need to be placed inside a for or while loop. However that would be an interesting approach. I don't know if it would be faster than comparing the len(), I suspect not, but try/except is fairly fast so it just might be. Alan G. From jsmith at medplus.com Mon Feb 7 20:58:03 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Mon Feb 7 20:58:10 2005 Subject: [Tutor] manipulating a file Message-ID: <C4C644CF4ADA9448904C3E8BACC4B97C02E674CC@medexch1.medplus.com> -----Original Message----- From: Alan Gauld [mailto:alan.gauld@freenet.co.uk] Sent: Monday, February 07, 2005 2:49 PM To: Reed L. O'Brien; tutor@python.org Subject: Re: [Tutor] manipulating a file >You should add a newline character otherwise you will just >get one enormously long line! > > dstfile.write(i+'\n') In these cases, I've taken to doing print >> dstfile, I ...hmmm starting to look like Perl's many ways to accomplish the same thing approach :-) Jeff From alan.gauld at freenet.co.uk Mon Feb 7 21:06:28 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Feb 7 21:05:55 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <C4C644CF4ADA9448904C3E8BACC4B97C02E67470@medexch1.medplus.com> Message-ID: <062001c50d50$82d50330$68b78851@xp> > That's kinda what I thought but a couple of people suggested > that I used lambdas to make it clearer I suggested that if we had proper lambdas we could use 'em... But of course you can still use lambdas just put the print at the client side: def p(): pass ftable = { 'a' : lambda: 'a', 'b' : lambda: 'b or c', 'c' : lambda: 'b or c', 'd' : lambda: p} print ftable.get(var, lambda: 'default case')() But I still had to use a def for the pass... :-( Alan G. From alan.gauld at freenet.co.uk Mon Feb 7 21:08:04 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Feb 7 21:07:35 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <C4C644CF4ADA9448904C3E8BACC4B97C02E67470@medexch1.medplus.com> <6.1.2.0.0.20050207080358.0347faf8@mail.mric.net> Message-ID: <062501c50d50$bc2715b0$68b78851@xp> > Well you can use lambdas. Have them return an expression which you print > after retrieving: > ftable = { 'a' : lambda: 'a', > 'b' : lambda: 'b or c', > But it would be clearer to store just the expressions: > ftable = { 'a' : 'a', > 'b' : 'b or c', True for this special case, but where the lambda has to do some calculation it starts to make sense! :-) Alan G. From jsmith at medplus.com Mon Feb 7 21:08:59 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Mon Feb 7 21:09:05 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: <C4C644CF4ADA9448904C3E8BACC4B97C02E674D3@medexch1.medplus.com> Alan, That's actually worse than you might think. Try this: var = 'd' def p(): pass ftable = { 'a' : lambda: 'a', 'b' : lambda: 'b or c', 'c' : lambda: 'b or c', 'd' : lambda: p} print ftable.get(var, lambda: 'default case')() And what you get is: <function p at 0x009BDFB0> That's hardly a pass :-) Jeff -----Original Message----- From: Alan Gauld [mailto:alan.gauld@freenet.co.uk] Sent: Monday, February 07, 2005 3:06 PM To: Smith, Jeff; Bob Gailer; tutor@python.org Subject: Re: [Tutor] Are you allowed to shoot camels? [kinda OT] > That's kinda what I thought but a couple of people suggested > that I used lambdas to make it clearer I suggested that if we had proper lambdas we could use 'em... But of course you can still use lambdas just put the print at the client side: def p(): pass ftable = { 'a' : lambda: 'a', 'b' : lambda: 'b or c', 'c' : lambda: 'b or c', 'd' : lambda: p} print ftable.get(var, lambda: 'default case')() But I still had to use a def for the pass... :-( Alan G. From dyoo at hkn.eecs.berkeley.edu Mon Feb 7 21:30:59 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Feb 7 21:31:03 2005 Subject: [Tutor] Iterating over multiple lists- options In-Reply-To: <20050207102429.O90909@yamato.yamato.com> Message-ID: <Pine.LNX.4.44.0502071047370.31432-100000@hkn.eecs.berkeley.edu> On Mon, 7 Feb 2005, Tony Cappellini wrote: > > Here's a quick function that should force a certain length on an > > iterator: > > > > ### > > def ipad(iterable, length, sentinel=None): > > i = 0 > > for thing in iterable: > > yield thing > > i = i + 1 > > while i < length: > > yield sentinel > > i = i + 1 > > ### > > BTW, is your def ipad() function the 20gb, 40gb, or 60gb model ? :-) Hi Tony, Oh, I had some terrible puns I was going to use in the last message. Here's one, just for your amusement: ### import sys def ipad_maxi(iterable, sentinel=None): """Applies a maximum ipad()ding on a given iterable.""" return ipad(iterable, sys.maxint, sentinel) ### But getting back on topic: I like Kent's solution with map() much better than my own. I had completely forgotten that map() had a special case that applies directly to what you're trying to do. Best of wishes to you! From dyoo at hkn.eecs.berkeley.edu Mon Feb 7 21:43:42 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Feb 7 21:43:47 2005 Subject: [Tutor] where do we use acquisition ? In-Reply-To: <4207689E.9010501@cirad.fr> Message-ID: <Pine.LNX.4.44.0502071231240.20554-100000@hkn.eecs.berkeley.edu> Hi Chandu, Ah, so you're looking into "environmental acquisition". I think the reason you're asking about on Tutor is because one of the most visible deployments of acquisition has been in the Zope web framework. But just because Zope is written in Python doesn't mean that acquisition is a concept that's exclusive to Python. If you would like to learn more, here's a link to a really nice web site on acquisition: http://www.ccs.neu.edu/home/lorenz/research/acquisition/ It appears to house a lot of the accumulated knowledge on acquisition. Because this topic is very specialized, we probably won't be able to do any justice to it on Python-tutor. The acquisition web site linked above should give you references for why it's cool, and what communities you can talk with to learn more about it. Best of wishes to you! From shitizb at yahoo.com Mon Feb 7 22:01:29 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Mon Feb 7 22:01:32 2005 Subject: [Tutor] manipulating a file In-Reply-To: <05dd01c50d4e$a404df00$68b78851@xp> Message-ID: <20050207210129.83279.qmail@web53801.mail.yahoo.com> How about cat log|grep -v -E [[:alnum]]'{2096}'>> log.bak The issue is - will unix shell command be any more efficient than a python script?? Also i used append because i gathered that the user will not want to erase the previous logs. He is free to use a single > if he does. --- Alan Gauld <alan.gauld@freenet.co.uk> wrote: > > About the efficiency, why do u need python at > all... > > How abt a simple shell command.... > > cat httpd-access.log>>log.bak > > > > Because that would be a copy, well actually an > append... > > cp httpd-access.log log.bak > > would be better! > > But the OP wanted to strip out long lines in transit > not just copy... > > Alan G. > > > __________________________________ Do you Yahoo!? Yahoo! Mail - Find what you need with new enhanced search. http://info.mail.yahoo.com/mail_250 From cyresse at gmail.com Mon Feb 7 22:12:00 2005 From: cyresse at gmail.com (Liam Clarke) Date: Mon Feb 7 22:12:03 2005 Subject: [Tutor] calling subroutines into program In-Reply-To: <42077CD2.5040107@tds.net> References: <5.1.0.14.0.20050207140910.00bbe528@mailhost.geo.vu.nl> <f2ff2d05020705459a81db9@mail.gmail.com> <f2ff2d05020706023b730c27@mail.gmail.com> <42077CD2.5040107@tds.net> Message-ID: <f2ff2d050207131220e1f627@mail.gmail.com> oh? Is is the negative? On Mon, 07 Feb 2005 09:36:02 -0500, Kent Johnson <kent37@tds.net> wrote: > Liam Clarke wrote: > >>>example of (1): > >>>--------------------------------------------------------- > >>>#this part of the program reads the file basin.out (the data we want to > >>>analyze) and changes its contents to the array arr_xy > >>>#layout of basin.out: > >>>#1 -950.00 10.00 200 > this line contains start, interval and > >>>number of x values; > >>># 0.000000E+00 > remainder is a column of y values > >>># -1.931787E-07 > >>># -5.713295E-07 > >>># -9.322559E-07 > >>># -1.071361E-06 > >>># -7.801342E-07 > >>># ..... > >>start = int(float(list[1])) > >>interval = int(float(list[2])) > >>n = int(float(list[3])) > > > > > > list[1] is a string, so if I'm not missing something, start = > > int(list[1]) will do just fine. > > No, because list[1] is '-950.00' which will not parse as an int. > > Kent > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From kent37 at tds.net Mon Feb 7 22:21:38 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Feb 7 22:21:44 2005 Subject: [Tutor] calling subroutines into program In-Reply-To: <f2ff2d050207131220e1f627@mail.gmail.com> References: <5.1.0.14.0.20050207140910.00bbe528@mailhost.geo.vu.nl> <f2ff2d05020705459a81db9@mail.gmail.com> <f2ff2d05020706023b730c27@mail.gmail.com> <42077CD2.5040107@tds.net> <f2ff2d050207131220e1f627@mail.gmail.com> Message-ID: <4207DBE2.6000109@tds.net> Liam Clarke wrote: > oh? Is is the negative? No, the decimal fraction. It's easy enough to try it: >>> int('950') 950 >>> int('-950') -950 >>> int('950.00') Traceback (most recent call last): File "<stdin>", line 1, in ? ValueError: invalid literal for int(): 950.00 >>> int('-950.00') Traceback (most recent call last): File "<stdin>", line 1, in ? ValueError: invalid literal for int(): -950.00 Kent > > > On Mon, 07 Feb 2005 09:36:02 -0500, Kent Johnson <kent37@tds.net> wrote: >>No, because list[1] is '-950.00' which will not parse as an int. >> >>Kent >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> > > > From lumbricus at gmx.net Mon Feb 7 22:09:48 2005 From: lumbricus at gmx.net (Joerg Woelke) Date: Mon Feb 7 22:27:23 2005 Subject: [Tutor] manipulating a file In-Reply-To: <20050207210129.83279.qmail@web53801.mail.yahoo.com> References: <05dd01c50d4e$a404df00$68b78851@xp> <20050207210129.83279.qmail@web53801.mail.yahoo.com> Message-ID: <20050207210948.GB19208@laplace> On Mon, Feb 07, 2005 at 01:01:29PM -0800, Shitiz Bansal wrote: > > How about > cat log|grep -v -E [[:alnum]]'{2096}'>> log.bak UUOC (Useless Use Of Cat) SCNR J"o! -- You're at the end of the road again. From ternary at gmail.com Mon Feb 7 22:37:47 2005 From: ternary at gmail.com (Mike Bell) Date: Mon Feb 7 22:37:50 2005 Subject: [Tutor] manipulating a file In-Reply-To: <C4C644CF4ADA9448904C3E8BACC4B97C02E674CC@medexch1.medplus.com> References: <C4C644CF4ADA9448904C3E8BACC4B97C02E674CC@medexch1.medplus.com> Message-ID: <82975b0c050207133779e71018@mail.gmail.com> without the explicit newlines in file.write(i), could it be that the file was closed before the write buffer was ever flushed? mike On Mon, 7 Feb 2005 14:58:03 -0500, Smith, Jeff <jsmith@medplus.com> wrote: > -----Original Message----- > From: Alan Gauld [mailto:alan.gauld@freenet.co.uk] > Sent: Monday, February 07, 2005 2:49 PM > To: Reed L. O'Brien; tutor@python.org > Subject: Re: [Tutor] manipulating a file > > >You should add a newline character otherwise you will just > >get one enormously long line! > > > > dstfile.write(i+'\n') > > In these cases, I've taken to doing > print >> dstfile, I > > ...hmmm starting to look like Perl's many ways to accomplish the same > thing approach :-) > > Jeff > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo at hkn.eecs.berkeley.edu Mon Feb 7 22:48:24 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Feb 7 22:48:28 2005 Subject: [Tutor] python lists to C arrays and vice versa In-Reply-To: <42077AEC.5060007@csb.sunysb.edu> Message-ID: <Pine.LNX.4.44.0502071334190.20554-100000@hkn.eecs.berkeley.edu> On Mon, 7 Feb 2005, Viktor Hornak wrote: > I've been trying to find more resources/documentation about how to > convert python lists to C arrays (and vice versa) when writing a python > extension. Hi Viktor, There was a post back in 1999 that might be useful for you: http://mail.python.org/pipermail/tutor/1999-November/000758.html I'm not positive if there is a nicer helper function to do this. > I also found one or two examples of similar operations on this list > postings (from 6 years ago!) but they didn't quite explain all I need > to know. Ah, so you did see that posting then. *grin* Ok, good. What parts of their explanation were incomplete? Maybe one of us here can help fill in more details for you. > Here is the code I was trying to use to convert two lists (one > is a list of strings with the same length and the other is a list of > doubles) to C arrays in a C extension: [Some code cut] The code there seems sorta ok: you might want to add a string length check in there somewhere: the code expects that names are at most 4 characters long, but that condition isn't being checked by strcpy(). > Then I call the function "parseMask" (which I am trying to wrap in this > extension) which returns a C array (integer array, elements are either 0 > or 1). Now I need to convert this integer array to python list and > return it back to python. Here is the code for that: > > result = (int *) malloc(sizeof(int) * nat); > parseMask(...) -> returns int array result > > pylist = PyTuple_New(nat); > for (i = 0; i < nat; i++) { > /* convert resulting array [0/1] to PyObject */ > if (result[i] == 0) > item = PyInt_FromLong(0); > else > item = PyInt_FromLong(1); > > PyTuple_SetItem(pylist, i, item); > Py_DECREF(item); /** <-- (dyoo): bug located */ > } Ah! Got it. Don't call Py_DECREF() here: PyTuple_SetItem will already "steal" the reference, according to the documentation: http://docs.python.org/api/tupleObjects.html#l2h-576 so there's no need to decrement the reference count here. By the way, if you're really going to do more C extension stuff, take a look at Pyrex or SWIG: http://nz.cosc.canterbury.ac.nz/~greg/python/Pyrex/ http://www.swig.org/ Coding C wrappers by hand is painful: use these tools to make your life easier. *grin* Best of wishes! From kent37 at tds.net Mon Feb 7 22:59:56 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Feb 7 23:00:00 2005 Subject: [Tutor] manipulating a file In-Reply-To: <cu73hp$7oj$1@sea.gmane.org> References: <cu73hp$7oj$1@sea.gmane.org> Message-ID: <4207E4DC.3000908@tds.net> Reed L. O'Brien wrote: > I want to read the httpd-access.log and remove any oversized log records > > I quickly tossed this script together. I manually mv-ed log to log.bak > and touched a new logfile. > > running the following with print i uncommented does print each line to > stdout. but it doesn't write to the appropriate file... Is the log open for writing in another application? Kent > > a) what am I missing? > b) is there a less expensive way to do it? > c) I originally wanted to delete lines over 2085 in length but couldn't > find a way to do that... did I miss it? > > Thanks > > #!/usr/local/bin/python > > import os > > srcfile = open('/var/log/httpd-access.log.bak', 'r') > dstfile = open('/var/log/httpd-access.log', 'w') > while 1: > lines = srcfile.readlines() > if not lines: break > # print lines > for i in lines: > if len(i) < 2086: > #print i > dstfile.write(i) > > srcfile.close() > dstfile.close() > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at freenet.co.uk Tue Feb 8 00:15:23 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Feb 8 00:14:46 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <C4C644CF4ADA9448904C3E8BACC4B97C02E674D3@medexch1.medplus.com> Message-ID: <062e01c50d6a$e6eaa900$68b78851@xp> That's actually worse than you might think. Try this: > def p(): pass > ftable = { 'a' : lambda: 'a', > 'd' : lambda: p} That should be: 'd': p} ie No lambda used at all. I wish Python had real lambdas! > And what you get is: > <function p at 0x009BDFB0> Yep, coz the lambda returns a function object! Which it should, I just shouldn't have used lambda there. My bad, Alan G. From missive at hotmail.com Tue Feb 8 00:48:36 2005 From: missive at hotmail.com (Lee Harr) Date: Tue Feb 8 00:49:05 2005 Subject: [Tutor] Re: Percolation model in python Message-ID: <BAY2-F26A4BFE81A524FBC87C060B1730@phx.gbl> > I have two questions. Once a MxN world is generated how would you >search for nearest neighbors (to see who is connected) and then color Does this help? import random PERSON, EMPTY = '*', '.' def get_threshold(): perc = raw_input("Please enter a thresold between 0-1. ") perc = float(perc) return perc def make_random_world(M, N): """Constructs a new random game world of size MxN.""" perc = get_threshold() world = {} for j in range(N): for i in range(M): world[i, j] = percolation(perc) world['dimensions'] = (M, N) return world def percolation(perc): randval = random.random() if randval > perc: return EMPTY else: return PERSON def neighbors(world, x, y): M, N = world['dimensions'] nxmin = max(0, x-1) nxmax = min(M, x+1) nymin = max(0, y-1) nymax = min(N, y+1) r = [] for nx in range(nxmin, nxmax+1): for ny in range(nymin, nymax+1): if nx != x or ny != y: r.append((nx, ny)) return r def print_world(world): """Prints out a string representation of a world.""" M, N = world['dimensions'] for j in range(N): for i in range(M): print world[i, j], print def make_world_option(): m = int(raw_input("Please enter a m dimension. ")) n = int(raw_input("Please enter a n dimension. ")) raw_input("Press return to make a world") return make_random_world(m, n) def show_neighbors_option(world): x = int(raw_input("Please enter an x coord. ")) y = int(raw_input("Please enter a y coord. ")) print neighbors(world, x, y) def menu(): print """ Please pick your option: 1) Percolation model for Small Pox 2) Show world 3) Instructions 4) Show neighbors 5) Exit """ option = int(raw_input("Which option[1,2,3,4,5]? ")) return option if __name__ == '__main__': option = None while option != 5: if option == 1: world = make_world_option() elif option == 2: print_world(world) elif option == 4: show_neighbors_option(world) option = menu() _________________________________________________________________ Don't just search. Find. Check out the new MSN Search! http://search.msn.com/ From alan.gauld at freenet.co.uk Tue Feb 8 00:53:46 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Feb 8 00:53:09 2005 Subject: [Tutor] manipulating a file References: <20050207210129.83279.qmail@web53801.mail.yahoo.com> Message-ID: <067701c50d70$43e31160$68b78851@xp> > How about > cat log|grep -v -E [[:alnum]]'{2096}'>> log.bak OK< but you can miss the cat out grep -v -E [[:alnum]]'{2096}' log >> log.bak But I confess I've no idea how that works, I've never seen that notation in a grep before! Checking man reveals an "extended regex" which I interpret as: any alphanumeric repeated 2096 times? But I'm not sure about my interpretation... > The issue is - will unix shell command be any more > efficient than a python script?? Usually, if you only use a single process like grep because they are written in C. But when you pipeline with cat it might slow it down enough to make Python competitive. Process startup tends to be the limiting factor in shell pipelines. > Also i used append because i gathered that the user > will not want to erase the previous logs. He is free > to use a single > if he does. Interesting, I assumed he would want to delete the old logs... As you say, whichever is appropriate is easily controlled. Alan G. From alan.gauld at freenet.co.uk Tue Feb 8 00:55:27 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Feb 8 00:54:49 2005 Subject: [Tutor] manipulating a file References: <C4C644CF4ADA9448904C3E8BACC4B97C02E674CC@medexch1.medplus.com> <82975b0c050207133779e71018@mail.gmail.com> Message-ID: <068201c50d70$801a4270$68b78851@xp> > without the explicit newlines in file.write(i), could it be that the > file was closed before the write buffer was ever flushed? No because close() was called explicitly, which does a flush first... Alan G. From flaxeater at yahoo.com Tue Feb 8 00:55:33 2005 From: flaxeater at yahoo.com (Chad Crabtree) Date: Tue Feb 8 00:55:37 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: <20050207235533.16392.qmail@web54307.mail.yahoo.com> Alan Gauld wrote: >ie No lambda used at all. > >I wish Python had real lambdas! > > If python had real lambda's then it would be lisp or schema. __________________________________ Do you Yahoo!? Yahoo! Mail - now with 250MB free storage. Learn more. http://info.mail.yahoo.com/mail_250 From shitizb at yahoo.com Tue Feb 8 01:30:25 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Tue Feb 8 01:30:28 2005 Subject: [Tutor] manipulating a file In-Reply-To: <20050207210129.83279.qmail@web53801.mail.yahoo.com> Message-ID: <20050208003025.88618.qmail@web53808.mail.yahoo.com> I aplogise for a typo... Please read the command as: cat log|grep -v -E [[:alnum]]'{2096,}'>> log.bak note the missing comma in the previous command. --- Shitiz Bansal <shitizb@yahoo.com> wrote: > > How about > cat log|grep -v -E [[:alnum]]'{2096}'>> log.bak > > The issue is - will unix shell command be any more > efficient than a python script?? > > Also i used append because i gathered that the user > will not want to erase the previous logs. He is free > to use a single > if he does. > > > --- Alan Gauld <alan.gauld@freenet.co.uk> wrote: > > > > About the efficiency, why do u need python at > > all... > > > How abt a simple shell command.... > > > cat httpd-access.log>>log.bak > > > > > > > Because that would be a copy, well actually an > > append... > > > > cp httpd-access.log log.bak > > > > would be better! > > > > But the OP wanted to strip out long lines in > transit > > not just copy... > > > > Alan G. > > > > > > > > > > > __________________________________ > Do you Yahoo!? > Yahoo! Mail - Find what you need with new enhanced > search. > http://info.mail.yahoo.com/mail_250 > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From tony at tcapp.com Tue Feb 8 01:59:56 2005 From: tony at tcapp.com (Tony Cappellini) Date: Tue Feb 8 01:57:37 2005 Subject: [Tutor] Iterating over multiple lists- options In-Reply-To: <Pine.LNX.4.44.0502071047370.31432-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0502071047370.31432-100000@hkn.eecs.berkeley.edu> Message-ID: <20050207165704.M96328@yamato.yamato.com> LOL > Here's one, just for your amusement: > > But getting back on topic: I like Kent's solution with map() much better > than my own. I had completely forgotten that map() had a special case > that applies directly to what you're trying to do. I havne't seen Kent's reply yet- will have to look when I get home from work. But I 've found some inconsistnacies with map, depending on which order the args were passed in. If the shorter list was passed to map first, as in map(shortlist, longerlist), it behaved one way. If I reversed the order of the args, as in map(longerlist, shortlist), map() behaved slighlty different. Almost like what zip() did. Perhaps Kent's suggestion addresses this. I will see later. Thanks! From jeff at ccvcorp.com Tue Feb 8 03:18:40 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue Feb 8 03:17:32 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <05ad01c50d4b$37c1c040$68b78851@xp> References: <C4C644CF4ADA9448904C3E8BACC4B97C02E67461@medexch1.medplus.com> <05ad01c50d4b$37c1c040$68b78851@xp> Message-ID: <42082180.4040907@ccvcorp.com> Alan Gauld wrote: >>As an aside, I did try to create a lambda based solution but was >>unable. Let me know what's wrong: >> >>ftable = { 'a' : lambda: print 'a', >>SyntaxError: invalid syntax > > I did say "if Python had *proper* lambdas..." > > Unfortunately Python insists on only having *expressions* as > lambdas and since print is a command not a function you can't > use it in Python lambdas! Dumb or what??! > > So you are stuck with predefining a bunch of one liner > functions and then creating a dictionary or going back > to if/elif chains, which is where we came in... :-) Well, in this particular case, if one really wants to use lambdas then one could (after importing sys, of course) replace the print statement with a call to sys.stdout.write() -- ftable = { 'a': lambda: sys.stdout.write('a\n'), ... } Note that sys.stdout.write() will *not* automatically add the newline that print does (which is why I've specified it in the above sample). Indeed, print can do all sorts of odd things with whitespace, leaving sys.stdout.write() as the best way to have real control over your output anyhow... Jeff Shannon Technician/Programmer Credit International From kent37 at tds.net Tue Feb 8 04:32:06 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Feb 8 04:32:11 2005 Subject: [Tutor] Iterating over multiple lists- options In-Reply-To: <20050207165704.M96328@yamato.yamato.com> References: <Pine.LNX.4.44.0502071047370.31432-100000@hkn.eecs.berkeley.edu> <20050207165704.M96328@yamato.yamato.com> Message-ID: <420832B6.2070909@tds.net> Tony Cappellini wrote: > I havne't seen Kent's reply yet- will have to look when I get home from > work. > But I 've found some inconsistnacies with map, depending on which order > the args were passed in. > If the shorter list was passed to map first, as in map(shortlist, > longerlist), it behaved one way. The first argument to map() is a function or None, not one of the lists. You should try map(None, shortlist, longerlist). Kent From tony at tcapp.com Tue Feb 8 07:12:08 2005 From: tony at tcapp.com (Tony Cappellini) Date: Tue Feb 8 07:12:22 2005 Subject: [Tutor] Iterating over multiple lists- options Message-ID: <6.1.2.0.0.20050207215900.01b30de8@mail.yamato.com> map(None, North, South, East West) does exactly what you want: >>> North=['Bill', 'Bob', 'Sue', 'Mary'] >>> South=['Tim', 'Tom', 'Jim', 'John', 'Carl', 'Evan', 'Rich'] >>> map(None, North, South) [('Bill', 'Tim'), ('Bob', 'Tom'), ('Sue', 'Jim'), ('Mary', 'John'), (None, 'Carl'), (None, 'Evan'), (None, 'Rich')] > That being, both of these functions can truncate the data, depending on > certain conditions >>I don't think that is true for map(); what conditions are you thinking of? Well, I've tried duplicating what I was seeing last night when I posted the message, and it's not happening the same now. Maybe I was up too later working on this problem... What I *thought* I was seeing was map() would return a list of a certain length when I called it like this map(None, North, South) and returned a list of a different length when I called it like this map(None, South, North) However, trying that now basically returns the a list that appears to be the same length, for both calls. I think this will work after all. I'll add it to my program . Thanks for your quick replies From johan at accesstel.co.za Tue Feb 8 08:28:35 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Tue Feb 8 08:30:12 2005 Subject: [Tutor] CRC-16 calculation Message-ID: <1107847715.4673.9.camel@KMA.accesstel> Hi everybody, I have a data packet in Hex values and need to determine how to calculate the CRC-16 bit checksum for these values. Eg.: 0x55,0x00,0x0A,0x01,0x01, 0x01,0xFF,0x00,0xDC,0xCC Sync| Lenght |source addr|dest. adr |Data| CRC check| This example shows me the CRC chechsum, but if I change the source addr, this chechsum is no longer valid. Any suggestions on how to calculate that? Thanks Johan -- This E-Mail has been scanned. Enjoy Your Day. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050208/3c07fe23/attachment.htm From kohlerj at ukzn.ac.za Tue Feb 8 08:58:37 2005 From: kohlerj at ukzn.ac.za (Johan Kohler) Date: Tue Feb 8 08:58:56 2005 Subject: [Tutor] Have I run into a limitation of Pickle? Message-ID: <opslvcfzdga89mar@condor> Hi, In the attached code, I'm trying to pickle and unpickle (1) an object containing a list of dictionaries. (2) an object containing a list objects each containing a dictionary. Case (1) seems to work (printing succesfully), ----- Running '/home/johan/prog/ratings/testpickle2.py' ... {'tel': 1234, 'name': 'Johan'} {'tel': 12454, 'name': 'Elize'} {'tel': 1234, 'name': 'Johan'} {'tel': 12454, 'name': 'Elize'} but (2) fails with the following error: <__main__.User instance at 0x41a56fac> <__main__.User instance at 0x41a56f2c> Traceback (most recent call last): File "/usr/lib/python2.3/site-packages/sm/scriptutils.py", line 49, in run exec codeObject in mainDict File "<source>", line 87, in ? File "<source>", line 79, in loadbroken File "<source>", line 33, in readfromfile File "/usr/lib/python2.3/pickle.py", line 1390, in load return Unpickler(file).load() File "/usr/lib/python2.3/pickle.py", line 872, in load dispatch[key](self) File "/usr/lib/python2.3/pickle.py", line 1083, in load_inst klass = self.find_class(module, name) File "/usr/lib/python2.3/pickle.py", line 1140, in find_class klass = getattr(mod, name) AttributeError: 'module' object has no attribute 'User' Exception raised while running script <source> --- I hope this is not a limitation of Pickle, because that would mean I have to change a large section of my code :-( Any help will be greatly appreciated Johan -- Using Opera's revolutionary e-mail client: http://www.opera.com/m2/ -------------------------------------------------------------------- Please find our disclaimer at http://www.ukzn.ac.za/disclaimer -------------------------------------------------------------------- <<<<gwavasig>>>> -------------- next part -------------- A non-text attachment was scrubbed... Name: testpickle2.py Type: application/octet-stream Size: 1952 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050208/04c5983f/testpickle2-0001.obj From johan at accesstel.co.za Tue Feb 8 11:03:04 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Tue Feb 8 11:04:08 2005 Subject: [Tutor] Hex to Str - still an open issue In-Reply-To: <4204EAB1.2050206@tds.net> References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> <041401c50ae9$63c21a50$68b78851@xp> <00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> <f2ff2d050205034498e84e@mail.gmail.com> <4204EAB1.2050206@tds.net> Message-ID: <1107856983.4603.6.camel@KMA.accesstel> Hi everybody, I used binary.py and is a bit puzzled by the results I get when comparing the binary of decimal 2 and the value I get when I convert the binary to an int. >>> binary(2) '00000000000000000000000000000010' >>> int(00000000000000000000000000000010) 8 >>> Isn't the int value of this binary string supposd to be '2' and not '8'? Johan On Sat, 2005-02-05 at 17:48, Kent Johnson wrote: > Liam, > > I think you misunderstand what endianness is. > > Big-endian and little-endian refer to the way a number is stored as bytes in the underlying memory > of the computer. This is not something you generally need to worry about in a Python program. > > For example, consider the number 0x12345678. On most modern computers this will be stored in four > consecutive bytes of computer memory. The individual bytes will contain the values 0x12, 0x34, 0x56, > 0x78. The question is, what is the order of those bytes in memory? On a big-endian computer, the > most significant byte - 0x12 - is stored at the lowest memory address, so the sequence of bytes will > be 0x12, 0x34, 0x56, 0x78. On a little-endian computer, the least-significant byte is stored at the > lowest address, and the order will be reversed: 0x78, 0x56, 0x34, 0x12. > > Most programming languages will hide this detail from you most of the time. Even in assembly > language, you generally load and store integers without worrying about endianness. Math operations > just do the right thing so you don't have to worry about it. > > Endianness becomes an issue when you want to convert between representations, and when binary data > is shared between computers which may have different endianness. > > For example in a C program you might want to get the high byte of an integer when you know the > address of the integer. The desired byte will be at (address+0) or (address+3) depending on the > endianness of the hardware. > > Similarly, if an array of integers is written to a file in a binary representation (not as ASCII > strings representing the integers, but as 32-bit values), then to correctly read the file you have > to know the endianness of the data in the file. > > > OK, so what does this have to do with converting a number to binary in Python? Well, nothing, > actually. First, note that 'binary representation' can mean two different things. In the description > above, I was talking about the actual bit pattern stored in the computer. Python works with binary > numbers all the time, in this sense, but it is under the hood. The other meaning of 'binary > representation' is that of a base-2 string representation of a number. > > So if you ask, "How do I convert a number to binary?" you can mean either of these. > > The first one is trivial. If you have a decimal string representation of the number, use int() to > convert it to binary. If you have an integer already, it's already *in* binary, so you don't have to > do anything! > > So, "How do I convert a number to binary?", to be interesting, must mean "How do I convert an > integer to a base-2 string representation?" And how do you do this? Well, you figured out one way > using the mathematical properties of integers. These operations are independent of endianness, and > so is the desired result. > > The base-2 string representation of the number (whose base-16 string representation is) 0x1234 is > '0001001000110100'. The order of digits here is determined by our convention of writing the most > significant digits on the left, not by the endianness of the underlying computer. > > OK, this is long enough, I hope I have shed some light... > Kent > > > > Liam Clarke wrote: > > Jacob - just for you, begin your agitation for the next release please ;) > > > > binstring.py, as attached. > > (also pasted up - http://www.rafb.net/paste/results/5feItM57.html) > > > > Creating this, was just a brain teaser, but I was thinking 'what if I > > wanted to make this for the standard library.' > > > > And so you can see, I had to include a flag for endianess. But that > > was really a cheap trick. If this was going into a standard library, > > I'd want to query the OS for endianess. As for the bits, once again, > > 32 bit is the norm, but 64 bit is here and spreading. > > > > Also, should it display 11111111 as 255 or 256? Both are valid, > > depending on context. > > > > Thirdly, if I can do it in 2 minutes, (well, the main part), then > > should they bother putting it in the standard library considering > > also, > > > > - How often, really, are you going to need to present a decimal or hex > > as a binary string. > > > > Lastly - this only does base 10 to base 2. Should I include a base 6 > > to base 2, base 8 to base 2, base 10 to 6, 10 to 8, 8 to 6? > > > > I wouldn't like to write for the standard library, because you can > > never please everyone. > > > > But yeah, feel free to use the above, just keep my doc strings and comments. > > > > Regards, > > > > Liam Clarke > > > > On Fri, 4 Feb 2005 23:30:19 -0500, Jacob S. <keridee@jayco.net> wrote: > > > >>>The binary value is the same as the hex value. > >>>The binary representation is 000111110100, but > >>>unfortunately Python doesn't support binary in > >>>its string formatting(although it does in int()! > >> > >>Uh, question. Why not? It seems that all simple types should be included. > >>Since the computer stores it as binary, why shouldn't python be able to > >>display a > >>string of it in binary? That seems to be a short coming that should be added > >>to the > >>next release... IMHO of course. > >>Jacob Schmidt > >> > >>_______________________________________________ > >>Tutor maillist - Tutor@python.org > >>http://mail.python.org/mailman/listinfo/tutor > >> > > > > > > > > > > ------------------------------------------------------------------------ > > > > ###### > > # binString.py > > # by Liam Clarke > > #(Let me know when it's included in the standard library ;-)) > > ###### > > > > """Converts a integer base 10 to a string base 2""" > > > > def binary(decimalInt, bigEndian = True, bits = 32, truncExcess = False): > > """ > > Integer to be converted is essential, Endianess is an optional flag; > > me being a Win32 user, Endianess is big by default, defaults to a 32-bit > > representation, most integers in Python being 32 bit. truncExcess will > > strip place-holder zeros for succintness. > > > > Oh, and it will represent 11111111 as 256, as I'm not sure whether you want > > to start counting for zero with this. It's a simple matter to change.""" > > tempList = ['0' for x in range(bits)] > > > > for bitPlace in range(bits, -1, -1): > > if decimalInt - 2**bitPlace >= 0: > > tempList[bitPlace] = '1' > > decimalInt = decimalInt - 2**bitPlace > > if bigEndian: > > tempList.reverse() > > > > outPut = ''.join(tempList) > > > > if truncExcess: > > if bigEndian: > > outPut=outPut.lstrip('0') > > else: > > outPut=outPut.rstrip('0') > > > > return outPut > > > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- This E-Mail has been scanned. Enjoy Your Day. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050208/ca1ef0df/attachment.htm From pierre.barbier at cirad.fr Tue Feb 8 11:12:22 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Tue Feb 8 11:10:27 2005 Subject: [Tutor] Hex to Str - still an open issue In-Reply-To: <1107856983.4603.6.camel@KMA.accesstel> References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> <041401c50ae9$63c21a50$68b78851@xp> <00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> <f2ff2d050205034498e84e@mail.gmail.com> <4204EAB1.2050206@tds.net> <1107856983.4603.6.camel@KMA.accesstel> Message-ID: <42089086.8010407@cirad.fr> MMmmhh ... no ! The number you wrote is equivalent to '010' and any number beginning by '0' and not followed by "x" will be considered octal. So "10" in base 8 is ... 8 :) If you want to convert a number from base 2 to base 10 write : >>> int("0000000010", 2) 2 Pierre Johan Geldenhuys a ?crit : > Hi everybody, > I used binary.py and is a bit puzzled by the results I get when > comparing the binary of decimal 2 and the value I get when I convert the > binary to an int. > > >>>>binary(2) > > '00000000000000000000000000000010' > >>>>int(00000000000000000000000000000010) > > 8 > > > Isn't the int value of this binary string supposd to be '2' and not '8'? > > Johan > On Sat, 2005-02-05 at 17:48, Kent Johnson wrote: > > >>Liam, >> >>I think you misunderstand what endianness is. >> >>Big-endian and little-endian refer to the way a number is stored as bytes in the underlying memory >>of the computer. This is not something you generally need to worry about in a Python program. >> >>For example, consider the number 0x12345678. On most modern computers this will be stored in four >>consecutive bytes of computer memory. The individual bytes will contain the values 0x12, 0x34, 0x56, >>0x78. The question is, what is the order of those bytes in memory? On a big-endian computer, the >>most significant byte - 0x12 - is stored at the lowest memory address, so the sequence of bytes will >>be 0x12, 0x34, 0x56, 0x78. On a little-endian computer, the least-significant byte is stored at the >>lowest address, and the order will be reversed: 0x78, 0x56, 0x34, 0x12. >> >>Most programming languages will hide this detail from you most of the time. Even in assembly >>language, you generally load and store integers without worrying about endianness. Math operations >>just do the right thing so you don't have to worry about it. >> >>Endianness becomes an issue when you want to convert between representations, and when binary data >>is shared between computers which may have different endianness. >> >>For example in a C program you might want to get the high byte of an integer when you know the >>address of the integer. The desired byte will be at (address+0) or (address+3) depending on the >>endianness of the hardware. >> >>Similarly, if an array of integers is written to a file in a binary representation (not as ASCII >>strings representing the integers, but as 32-bit values), then to correctly read the file you have >>to know the endianness of the data in the file. >> >> >>OK, so what does this have to do with converting a number to binary in Python? Well, nothing, >>actually. First, note that 'binary representation' can mean two different things. In the description >>above, I was talking about the actual bit pattern stored in the computer. Python works with binary >>numbers all the time, in this sense, but it is under the hood. The other meaning of 'binary >>representation' is that of a base-2 string representation of a number. >> >>So if you ask, "How do I convert a number to binary?" you can mean either of these. >> >>The first one is trivial. If you have a decimal string representation of the number, use int() to >>convert it to binary. If you have an integer already, it's already *in* binary, so you don't have to >>do anything! >> >>So, "How do I convert a number to binary?", to be interesting, must mean "How do I convert an >>integer to a base-2 string representation?" And how do you do this? Well, you figured out one way >>using the mathematical properties of integers. These operations are independent of endianness, and >>so is the desired result. >> >>The base-2 string representation of the number (whose base-16 string representation is) 0x1234 is >>'0001001000110100'. The order of digits here is determined by our convention of writing the most >>significant digits on the left, not by the endianness of the underlying computer. >> >>OK, this is long enough, I hope I have shed some light... >>Kent >> >> >> >>Liam Clarke wrote: >> >>>Jacob - just for you, begin your agitation for the next release please ;) >>> >>>binstring.py, as attached. >>>(also pasted up - http://www.rafb.net/paste/results/5feItM57.html) >>> >>>Creating this, was just a brain teaser, but I was thinking 'what if I >>>wanted to make this for the standard library.' >>> >>>And so you can see, I had to include a flag for endianess. But that >>>was really a cheap trick. If this was going into a standard library, >>>I'd want to query the OS for endianess. As for the bits, once again, >>>32 bit is the norm, but 64 bit is here and spreading. >>> >>>Also, should it display 11111111 as 255 or 256? Both are valid, >>>depending on context. >>> >>>Thirdly, if I can do it in 2 minutes, (well, the main part), then >>>should they bother putting it in the standard library considering >>>also, >>> >>>- How often, really, are you going to need to present a decimal or hex >>>as a binary string. >>> >>>Lastly - this only does base 10 to base 2. Should I include a base 6 >>>to base 2, base 8 to base 2, base 10 to 6, 10 to 8, 8 to 6? >>> >>>I wouldn't like to write for the standard library, because you can >>>never please everyone. >>> >>>But yeah, feel free to use the above, just keep my doc strings and comments. >>> >>>Regards, >>> >>>Liam Clarke >>> >>>On Fri, 4 Feb 2005 23:30:19 -0500, Jacob S. <keridee@jayco.net> wrote: >>> >>> >>>>>The binary value is the same as the hex value. >>>>>The binary representation is 000111110100, but >>>>>unfortunately Python doesn't support binary in >>>>>its string formatting(although it does in int()! >>>> >>>>Uh, question. Why not? It seems that all simple types should be included. >>>>Since the computer stores it as binary, why shouldn't python be able to >>>>display a >>>>string of it in binary? That seems to be a short coming that should be added >>>>to the >>>>next release... IMHO of course. >>>>Jacob Schmidt >>>> >>>>_______________________________________________ >>>>Tutor maillist - Tutor@python.org >>>>http://mail.python.org/mailman/listinfo/tutor >>>> >>> >>> >>> >>> >>>------------------------------------------------------------------------ >>> >>>###### >>># binString.py >>># by Liam Clarke >>>#(Let me know when it's included in the standard library ;-)) >>>###### >>> >>>"""Converts a integer base 10 to a string base 2""" >>> >>>def binary(decimalInt, bigEndian = True, bits = 32, truncExcess = False): >>> """ >>>Integer to be converted is essential, Endianess is an optional flag; >>>me being a Win32 user, Endianess is big by default, defaults to a 32-bit >>>representation, most integers in Python being 32 bit. truncExcess will >>>strip place-holder zeros for succintness. >>> >>>Oh, and it will represent 11111111 as 256, as I'm not sure whether you want >>>to start counting for zero with this. It's a simple matter to change.""" >>> tempList = ['0' for x in range(bits)] >>> >>> for bitPlace in range(bits, -1, -1): >>> if decimalInt - 2**bitPlace >= 0: >>> tempList[bitPlace] = '1' >>> decimalInt = decimalInt - 2**bitPlace >>> if bigEndian: >>> tempList.reverse() >>> >>> outPut = ''.join(tempList) >>> >>> if truncExcess: >>> if bigEndian: >>> outPut=outPut.lstrip('0') >>> else: >>> outPut=outPut.rstrip('0') >>> >>> return outPut >>> >>> >>>------------------------------------------------------------------------ >>> >>>_______________________________________________ >>>Tutor maillist - Tutor@python.org >>>http://mail.python.org/mailman/listinfo/tutor >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 From dyoo at hkn.eecs.berkeley.edu Tue Feb 8 11:18:10 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Feb 8 11:18:43 2005 Subject: [Tutor] CRC-16 calculation In-Reply-To: <1107847715.4673.9.camel@KMA.accesstel> Message-ID: <Pine.LNX.4.44.0502080122340.19826-100000@hkn.eecs.berkeley.edu> On Tue, 8 Feb 2005, Johan Geldenhuys wrote: > I have a data packet in Hex values and need to determine how to > calculate the CRC-16 bit checksum for these values: > > 0x55,0x00,0x0A,0x01,0x01, 0x01,0xFF,0x00,0xDC,0xCC > Sync| Lenght |source addr|dest. adr |Data| CRC check| > > This example shows me the CRC checksum, but if I change the source addr, > this chechsum is no longer valid. Hi Johan, I'm not exactly sure what you are asking: are you looking for an implementation of the CRC-16 algorithm in Python? Or are you asking how it actually works? If you'd like to learn how CRC error detection works, the web site: http://www.ross.net/crc/crcpaper.html has a nice tutorial that explain their fundamentals. If you are looking for a CRC-16 implementation, there appears to be one here: http://mail.python.org/pipermail/python-list/2004-January/204983.html From alan.gauld at freenet.co.uk Tue Feb 8 11:28:30 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Feb 8 11:28:32 2005 Subject: [Tutor] (no subject) References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com><041401c50ae9$63c21a50$68b78851@xp><00ae01c50b3b$6b55d390$215428cf@JSLAPTOP><f2ff2d050205034498e84e@mail.gmail.com> <4204EAB1.2050206@tds.net> <1107856983.4603.6.camel@KMA.accesstel>X-Antivirus: avast! (VPS 0505-2, 05/02/2005), Outbound message Message-ID: <06c601c50dc9$05883f90$68b78851@xp> Subject: Re: [Tutor] Hex to Str - still an open issue Date: Tue, 8 Feb 2005 10:29:07 -0000 MIME-Version: 1.0 Content-Type: text/plain; charset="UTF-8" Content-Transfer-Encoding: 7bit X-Priority: 3 X-MSMail-Priority: Normal X-Mailer: Microsoft Outlook Express 6.00.2800.1437 X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2800.1441 > >>> binary(2) > '00000000000000000000000000000010' > >>> int(00000000000000000000000000000010) > 8 In Python (and most C based languages) a number starting with 0 is assumed to be in octal. so 010 in octal is 8 in decimal. Alan g. From jsmith at medplus.com Tue Feb 8 14:37:31 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Tue Feb 8 14:37:37 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: <C4C644CF4ADA9448904C3E8BACC4B97C02E6750F@medexch1.medplus.com> Alan, That's no good. You still get something printed out. In this case: None Jeff -----Original Message----- From: Alan Gauld [mailto:alan.gauld@freenet.co.uk] Sent: Monday, February 07, 2005 6:15 PM To: Smith, Jeff; Bob Gailer; tutor@python.org Subject: Re: [Tutor] Are you allowed to shoot camels? [kinda OT] That's actually worse than you might think. Try this: > def p(): pass > ftable = { 'a' : lambda: 'a', > 'd' : lambda: p} That should be: 'd': p} ie No lambda used at all. I wish Python had real lambdas! > And what you get is: > <function p at 0x009BDFB0> Yep, coz the lambda returns a function object! Which it should, I just shouldn't have used lambda there. My bad, Alan G. From javier at ruere.com.ar Tue Feb 8 14:26:45 2005 From: javier at ruere.com.ar (Javier Ruere) Date: Tue Feb 8 14:42:03 2005 Subject: [Tutor] Re: Have I run into a limitation of Pickle? In-Reply-To: <opslvcfzdga89mar@condor> References: <opslvcfzdga89mar@condor> Message-ID: <cuaed1$hs9$1@sea.gmane.org> Johan Kohler wrote: > Hi, > In the attached code, I'm trying to pickle and unpickle > (1) an object containing a list of dictionaries. > (2) an object containing a list objects each containing a dictionary. > [successful usecase] > > but (2) fails with the following error: > > <__main__.User instance at 0x41a56fac> > <__main__.User instance at 0x41a56f2c> > Traceback (most recent call last): > File "/usr/lib/python2.3/site-packages/sm/scriptutils.py", line 49, > in run > exec codeObject in mainDict > File "<source>", line 87, in ? > File "<source>", line 79, in loadbroken > File "<source>", line 33, in readfromfile > File "/usr/lib/python2.3/pickle.py", line 1390, in load > return Unpickler(file).load() > File "/usr/lib/python2.3/pickle.py", line 872, in load > dispatch[key](self) > File "/usr/lib/python2.3/pickle.py", line 1083, in load_inst > klass = self.find_class(module, name) > File "/usr/lib/python2.3/pickle.py", line 1140, in find_class > klass = getattr(mod, name) > AttributeError: 'module' object has no attribute 'User' > Exception raised while running script <source> > --- > > I hope this is not a limitation of Pickle, because that would mean I > have to change a large section of my code :-( Pickle can handle any object but it needs the definition of the class of the object to be available in order to unpickle. For example: .>>> class A: pass .... .>>> a = A() .>>> import pickle .>>> s = pickle.dumps(a) .>>> s '(i__main__\nA\np0\n(dp1\nb.' .>>> pickle.loads(s) <__main__.A instance at 0x403fdcec> .>>> del A .>>> pickle.loads(s) Traceback (most recent call last): File "<stdin>", line 1, in ? File "/usr/lib/python2.3/pickle.py", line 1394, in loads return Unpickler(file).load() File "/usr/lib/python2.3/pickle.py", line 872, in load dispatch[key](self) File "/usr/lib/python2.3/pickle.py", line 1083, in load_inst klass = self.find_class(module, name) File "/usr/lib/python2.3/pickle.py", line 1140, in find_class klass = getattr(mod, name) AttributeError: 'module' object has no attribute 'A' The tracebacks are similar. It seems class User is not available when unpickling in the second case. Javier PS: I have not actually looked at the code so YMMV. :p From jsmith at medplus.com Tue Feb 8 14:42:54 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Tue Feb 8 14:43:04 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: <C4C644CF4ADA9448904C3E8BACC4B97C02E67510@medexch1.medplus.com> Jeff, It looks like that finally is the simplest expression of the original switch statement: import sys def p(): pass ftable = { 'a' : lambda: sys.stdout.write('a\n'), 'b' : lambda: sys.stdout.write('b or c\n'), 'c' : lambda: sys.stdout.write('b or c\n'), 'd' : p } ftable.get(var, lambda: sys.stdout.write('default case\n'))() I do note that it took this group of experienced programmers several tries to impliment this simple switch statement without actually using switch. I dare say with standard switch syntax we would've had it right the first time :-) Jeff -----Original Message----- From: Jeff Shannon [mailto:jeff@ccvcorp.com] Sent: Monday, February 07, 2005 9:19 PM To: tutor@python.org Subject: Re: [Tutor] Are you allowed to shoot camels? [kinda OT] Alan Gauld wrote: >>As an aside, I did try to create a lambda based solution but was >>unable. Let me know what's wrong: >> >>ftable = { 'a' : lambda: print 'a', >>SyntaxError: invalid syntax > > I did say "if Python had *proper* lambdas..." > > Unfortunately Python insists on only having *expressions* as lambdas > and since print is a command not a function you can't use it in Python > lambdas! Dumb or what??! > > So you are stuck with predefining a bunch of one liner functions and > then creating a dictionary or going back to if/elif chains, which is > where we came in... :-) Well, in this particular case, if one really wants to use lambdas then one could (after importing sys, of course) replace the print statement with a call to sys.stdout.write() -- ftable = { 'a': lambda: sys.stdout.write('a\n'), ... } Note that sys.stdout.write() will *not* automatically add the newline that print does (which is why I've specified it in the above sample). Indeed, print can do all sorts of odd things with whitespace, leaving sys.stdout.write() as the best way to have real control over your output anyhow... Jeff Shannon Technician/Programmer Credit International _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From tktucker at gmail.com Tue Feb 8 16:34:32 2005 From: tktucker at gmail.com (Tom Tucker) Date: Tue Feb 8 16:34:37 2005 Subject: [Tutor] Match on current line and next line. Possible? Message-ID: <2a278ffe05020807347045c8ad@mail.gmail.com> Hello! How can I instruct Python to match on the current line and the next line? Assumptions; - We are reading in one line at a time BROKEN EXAMPLE (discussion) ###################### file = open('/somefile','r').readlines() for line in file: match_one = re.search('^Python', line) match_two = re.search('^\tBLAH', line) if match_one and nextline == match_two: do_something() Maybe this just isn't possible, since we are working line by line. Any suggestions? Tom From kent37 at tds.net Tue Feb 8 16:53:00 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Feb 8 16:52:57 2005 Subject: [Tutor] Match on current line and next line. Possible? In-Reply-To: <2a278ffe05020807347045c8ad@mail.gmail.com> References: <2a278ffe05020807347045c8ad@mail.gmail.com> Message-ID: <4208E05C.9080301@tds.net> Tom Tucker wrote: > Hello! How can I instruct Python to match on the current line and the > next line? > BROKEN EXAMPLE (discussion) > ###################### > file = open('/somefile','r').readlines() > for line in file: > match_one = re.search('^Python', line) > match_two = re.search('^\tBLAH', line) > if match_one and nextline == match_two: > do_something() > match_one = None for line in open(...): match_two = re.search('^\tBLAH', line) if match_one and match_two: do_something() match_one = re.search('^Python', line) Add a last_line variable as well if do_something() needs access to the line data. Kent From pierre.barbier at cirad.fr Tue Feb 8 16:55:36 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Tue Feb 8 16:53:42 2005 Subject: [Tutor] Match on current line and next line. Possible? In-Reply-To: <2a278ffe05020807347045c8ad@mail.gmail.com> References: <2a278ffe05020807347045c8ad@mail.gmail.com> Message-ID: <4208E0F8.1030508@cirad.fr> MMmh ... one way to do that : Py> file_content = open('/somefile', 'r').readlines() Py> next_file_content = iter(file_content) Py> next_file_content.next() Py> for (line, next_line) in izip(file_content, next_file_content): Py> match_one = re.search('^Python', line) Py> match_two = re.search('^\tBLAH', line) Py> if match_one and nextline == match_two: Py> do_something() Pierre Tom Tucker a ?crit : > Hello! How can I instruct Python to match on the current line and the > next line? > > > Assumptions; > - We are reading in one line at a time > > > BROKEN EXAMPLE (discussion) > ###################### > file = open('/somefile','r').readlines() > for line in file: > match_one = re.search('^Python', line) > match_two = re.search('^\tBLAH', line) > if match_one and nextline == match_two: > do_something() > > > Maybe this just isn't possible, since we are working line by line. > > Any suggestions? > > > Tom > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 From kent37 at tds.net Tue Feb 8 17:16:36 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Feb 8 17:16:31 2005 Subject: [Tutor] Match on current line and next line. Possible? In-Reply-To: <4208E0F8.1030508@cirad.fr> References: <2a278ffe05020807347045c8ad@mail.gmail.com> <4208E0F8.1030508@cirad.fr> Message-ID: <4208E5E4.7060300@tds.net> Hmm, this would be a good use of itertools.tee() (Python 2.4 only): import itertools iter1, iter2 = itertools.tee(open('/somefile', 'r')) iter2.next() for line, next_line in izip(iter1, iter2): ... Kent Pierre Barbier de Reuille wrote: > MMmh ... one way to do that : > > Py> file_content = open('/somefile', 'r').readlines() > Py> next_file_content = iter(file_content) > Py> next_file_content.next() > Py> for (line, next_line) in izip(file_content, next_file_content): > Py> match_one = re.search('^Python', line) > Py> match_two = re.search('^\tBLAH', line) > Py> if match_one and nextline == match_two: > Py> do_something() > > Pierre > > Tom Tucker a ?crit : > >> Hello! How can I instruct Python to match on the current line and the >> next line? >> >> >> Assumptions; >> - We are reading in one line at a time >> >> >> BROKEN EXAMPLE (discussion) >> ###################### >> file = open('/somefile','r').readlines() >> for line in file: >> match_one = re.search('^Python', line) >> match_two = re.search('^\tBLAH', line) >> if match_one and nextline == match_two: >> do_something() >> >> >> Maybe this just isn't possible, since we are working line by line. >> Any suggestions? >> >> Tom >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> > From WilliTf at dshs.wa.gov Tue Feb 8 18:49:51 2005 From: WilliTf at dshs.wa.gov (Williams, Thomas) Date: Tue Feb 8 18:50:04 2005 Subject: [Tutor] executing SAS and passing parameters Message-ID: <592E8923DB6EA348BE8E33FCAADEFFFC0B13DC2E@dshs-exch2.dshs.wa.lcl> Greetings, I am trying to use python to run a SAS program by passing the needed parameters. I am able to start SAS, but unable to start the correct SAS program with its parameters. Any assistance you could provide will be appreciated. Tom Williams DSHS - Research and Data Analysis Division 14th and Jefferson, MS: 45204 Olympia, WA 98504-5204 360.902.0764 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050208/cb30e823/attachment.html From alan.gauld at freenet.co.uk Tue Feb 8 19:24:29 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Feb 8 19:26:30 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <C4C644CF4ADA9448904C3E8BACC4B97C02E6750F@medexch1.medplus.com> Message-ID: <06d601c50e0b$6e1b9e20$68b78851@xp> > That's no good. You still get something printed out. In this case: > > None Of course, silly me, p will return the default value None, you need to replace the pass with return '' or, I guess use the lambda... > ftable = { 'a' : lambda: 'a',... > 'd' : lambda: ''} Now it should work and is consistent again! But only for this trivial case of printing a label... Alan G. From john.ertl at fnmoc.navy.mil Tue Feb 8 19:31:32 2005 From: john.ertl at fnmoc.navy.mil (Ertl, John) Date: Tue Feb 8 19:30:20 2005 Subject: [Tutor] What is in the traceback object Message-ID: <E338ADD616B66043824B9ABF5CA6EF2332C513@lanexc107p.fnmoc.navy.mil> I have a bit of code that uses a module and I am trying to get more info on the error. I am using this bit of code: try: rhfill = Ngl.contour(wks,rhisobar,rh_res) except: execType,value,tracebak = sys.exc_info()[:3] print execType print value print tracebak In the log file I get this: exceptions.SystemError error return without exception set <traceback object at 0xb6cf2c84> How do I get the actual traceback so I can read it? Thanks, John Ertl -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050208/0e92e952/attachment.html From jsmith at medplus.com Tue Feb 8 19:32:57 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Tue Feb 8 19:33:08 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: <C4C644CF4ADA9448904C3E8BACC4B97C02E67580@medexch1.medplus.com> Not to be nit-picky but it's still not the same. The switch would give no output but yours would give a newline. I think the sys write solution would be the closest equivalent...and took a lot longer for us to code correctly :-) Jeff -----Original Message----- From: Alan Gauld [mailto:alan.gauld@freenet.co.uk] Sent: Tuesday, February 08, 2005 1:24 PM To: Smith, Jeff; Bob Gailer; tutor@python.org Subject: Re: [Tutor] Are you allowed to shoot camels? [kinda OT] > That's no good. You still get something printed out. In this case: > > None Of course, silly me, p will return the default value None, you need to replace the pass with return '' or, I guess use the lambda... > ftable = { 'a' : lambda: 'a',... > 'd' : lambda: ''} Now it should work and is consistent again! But only for this trivial case of printing a label... Alan G. From dyoo at hkn.eecs.berkeley.edu Tue Feb 8 19:39:03 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Feb 8 19:39:07 2005 Subject: [Tutor] What is in the traceback object In-Reply-To: <E338ADD616B66043824B9ABF5CA6EF2332C513@lanexc107p.fnmoc.navy.mil> Message-ID: <Pine.LNX.4.44.0502081036430.8292-100000@hkn.eecs.berkeley.edu> On Tue, 8 Feb 2005, Ertl, John wrote: > I have a bit of code that uses a module and I am trying to get more info > on the error. > > I am using this bit of code: > > try: > rhfill = Ngl.contour(wks,rhisobar,rh_res) > except: > execType,value,tracebak = sys.exc_info()[:3] > print execType > print value > print tracebak > > In the log file I get this: > > exceptions.SystemError > error return without exception set > <traceback object at 0xb6cf2c84> > > How do I get the actual traceback so I can read it? Hi John, You can use the 'traceback' module: http://www.python.org/doc/lib/module-traceback.html Use the traceback.print_exc() function within the except block: it'll automatically pull information from sys.exc_info() for you: ###### try: rhfill = Ngl.contour(wks,rhisobar,rh_res) except: traceback.print_exc() ###### Best of wishes to you! From john.ertl at fnmoc.navy.mil Tue Feb 8 19:42:27 2005 From: john.ertl at fnmoc.navy.mil (Ertl, John) Date: Tue Feb 8 19:41:18 2005 Subject: [Tutor] What is in the traceback object Message-ID: <E338ADD616B66043824B9ABF5CA6EF2332C514@lanexc107p.fnmoc.navy.mil> Danny, That is great...every time I have a problem someone has already solved it...the other problem is finding that solution...Thanks again. John Ertl -----Original Message----- From: Danny Yoo [mailto:dyoo@hkn.eecs.berkeley.edu] Sent: Tuesday, February 08, 2005 10:39 To: Ertl, John Cc: 'tutor@python.org' Subject: Re: [Tutor] What is in the traceback object On Tue, 8 Feb 2005, Ertl, John wrote: > I have a bit of code that uses a module and I am trying to get more info > on the error. > > I am using this bit of code: > > try: > rhfill = Ngl.contour(wks,rhisobar,rh_res) > except: > execType,value,tracebak = sys.exc_info()[:3] > print execType > print value > print tracebak > > In the log file I get this: > > exceptions.SystemError > error return without exception set > <traceback object at 0xb6cf2c84> > > How do I get the actual traceback so I can read it? Hi John, You can use the 'traceback' module: http://www.python.org/doc/lib/module-traceback.html Use the traceback.print_exc() function within the except block: it'll automatically pull information from sys.exc_info() for you: ###### try: rhfill = Ngl.contour(wks,rhisobar,rh_res) except: traceback.print_exc() ###### Best of wishes to you! From askoose at sandia.gov Tue Feb 8 21:03:50 2005 From: askoose at sandia.gov (Kooser, Ara S) Date: Tue Feb 8 21:04:22 2005 Subject: [Tutor] Printing columns of data Message-ID: <A0CE32554BD73A4481FE85C3F39DB6FC0B05F4@ES21SNLNT.srn.sandia.gov> Hello all, I am writing a program to take a data file, divide it up into columns and print the information back with headers. The data files looks like this 0.0 -3093.44908 -3084.59762 387.64329 26.38518 0.3902434E+00 -0.6024320E-04 0.4529416E-05 1.0 -3094.09209 -3084.52987 391.42288 105.55994 0.3889897E+00 -0.2290866E-03 0.4187074E-03 2.0 -3094.59358 -3084.88826 373.64911 173.44885 0.3862430E+00 -0.4953443E-03 0.2383621E-02 etc... 10.0 ... So I wrote the program included below and it only prints the last line of the file. Timestep PE 10.0 -3091.80609 I have one question. Do I need to put ts and pe into a list before I print then to screen or I am just missing something. Thanks. Ara import string inp = open("fort.44","r") all_file = inp.readlines() inp.close() outp = open("out.txt","w") cols = map(string.split,all_file) ##print cols Data = {} for line in cols: ts = line[0] # print line[0] pe = line[1] # print line[1] print """ Timestep PE""" print "%s %s " % (ts,pe) outp.close() -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050208/3ba3b3ec/attachment.htm From jeff at ccvcorp.com Tue Feb 8 21:41:26 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue Feb 8 21:40:33 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <C4C644CF4ADA9448904C3E8BACC4B97C02E67510@medexch1.medplus.com> References: <C4C644CF4ADA9448904C3E8BACC4B97C02E67510@medexch1.medplus.com> Message-ID: <420923F6.6050103@ccvcorp.com> Smith, Jeff wrote: > Jeff, > > It looks like that finally is the simplest expression of the original > switch statement: > > import sys > def p(): > pass > ftable = { 'a' : lambda: sys.stdout.write('a\n'), > 'b' : lambda: sys.stdout.write('b or c\n'), > 'c' : lambda: sys.stdout.write('b or c\n'), > 'd' : p } > ftable.get(var, lambda: sys.stdout.write('default case\n'))() > > I do note that it took this group of experienced programmers several > tries to impliment this simple switch statement without actually using > switch. I dare say with standard switch syntax we would've had it right > the first time :-) I wasn't following this thread all the way through, but to be honest, I'd have solved this differently -- that may be the best "direct translation" of some switch statement, but that doesn't mean it's the best-fit solution here. ISTM that, given the desire to print some text (or nothing) based on the contents of a variable, I would *not* handle the output inside the "switch" -- that is, I'd (conditionally) print a value from a string-containing dictionary, rather than use a table of functions that print strings. table = { 'a': 'a', 'b': 'b or c', 'c': 'b or c', 'd': None } result = table.get(var, 'default case') if result: print result This, to my mind, is much cleaner -- you're factoring out the repeated code, whether print statement or call to sys.stdout.write(), reducing the complexity of the dict. You're making flow control much more straightforward. You're making the whole thing easier to read. The key, here, is that instead of saying "I want a switch, how can I implement that in Python?", I've taken the approach of "The end result I want is ***; what tools does Python offer to achieve that?" This conceptual shift is, IMHO, *the* most important mental hurdle in learning a [second/third/n-th] language. Jeff Shannon Technician/Programmer Credit International From kent37 at tds.net Tue Feb 8 21:49:21 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Feb 8 21:49:24 2005 Subject: [Tutor] Printing columns of data In-Reply-To: <A0CE32554BD73A4481FE85C3F39DB6FC0B05F4@ES21SNLNT.srn.sandia.gov> References: <A0CE32554BD73A4481FE85C3F39DB6FC0B05F4@ES21SNLNT.srn.sandia.gov> Message-ID: <420925D1.3050809@tds.net> Kooser, Ara S wrote: > Hello all, > > I am writing a program to take a data file, divide it up into columns > and print the information back with headers. The data files looks like this > > 0.0 -3093.44908 -3084.59762 387.64329 26.38518 0.3902434E+00 > -0.6024320E-04 0.4529416E-05 > 1.0 -3094.09209 -3084.52987 391.42288 105.55994 0.3889897E+00 > -0.2290866E-03 0.4187074E-03 > 2.0 -3094.59358 -3084.88826 373.64911 173.44885 0.3862430E+00 > -0.4953443E-03 0.2383621E-02 > etc? > 10.0 ... > > So I wrote the program included below and it only prints the last line > of the file. > > Timestep PE > 10.0 -3091.80609 > > I have one question. Do I need to put ts and pe into a list before I > print then to screen or I am just missing something. Thanks. You should print the header before the loop, and the contents inside the loop. So: print """ Timestep PE""" for line in cols: ts = line[0] # print line[0] pe = line[1] # print line[1] # The next line is indented so it is included in the loop: print "%s %s " % (ts,pe) You probably will want to set the field width in the print format so the columns all line up, something like this (just guessing on the widths): print "%10s %10" % (ts,pe) You might be interested in this recipe which does a very slick job of pretty-printing a table: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/267662 Kent > > Ara > > import string > > inp = open("fort.44","r") > all_file = inp.readlines() > inp.close() > > outp = open("out.txt","w") > > cols = map(string.split,all_file) > ##print cols > > Data = {} > for line in cols: > ts = line[0] > # print line[0] > pe = line[1] > # print line[1] > > print """ > > Timestep PE""" > print "%s %s " % (ts,pe) > > > outp.close() > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at freenet.co.uk Tue Feb 8 21:51:39 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Feb 8 21:50:50 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <C4C644CF4ADA9448904C3E8BACC4B97C02E67580@medexch1.medplus.com> Message-ID: <06db01c50e1f$fd1e65d0$68b78851@xp> > Not to be nit-picky but it's still not the same. The switch would give > no output but yours would give a newline. I think the sys write > solution would be the closest equivalent...and took a lot longer for us > to code correctly :-) I can't really argue with that! :-) Me, I'm blaming the lambdas! Alan g. From bgailer at alum.rpi.edu Tue Feb 8 21:57:33 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue Feb 8 21:52:03 2005 Subject: [Tutor] Printing columns of data In-Reply-To: <A0CE32554BD73A4481FE85C3F39DB6FC0B05F4@ES21SNLNT.srn.sandi a.gov> References: <A0CE32554BD73A4481FE85C3F39DB6FC0B05F4@ES21SNLNT.srn.sandia.gov> Message-ID: <6.1.2.0.0.20050208135547.03615ff0@mail.mric.net> At 01:03 PM 2/8/2005, Kooser, Ara S wrote: >Content-class: urn:content-classes:message >Content-Type: multipart/alternative; > boundary="----_=_NextPart_001_01C50E19.4E45912A" > >Hello all, > > I am writing a program to take a data file, divide it up into columns > and print the information back with headers. The data files looks like this > > 0.0 -3093.44908 -3084.59762 387.64329 26.38518 0.3902434E+00 > -0.6024320E-04 0.4529416E-05 > 1.0 -3094.09209 -3084.52987 391.42288 105.55994 0.3889897E+00 > -0.2290866E-03 0.4187074E-03 > 2.0 -3094.59358 -3084.88826 373.64911 173.44885 0.3862430E+00 > -0.4953443E-03 0.2383621E-02 > etc > 10.0 ... > >So I wrote the program included below and it only prints the last line of >the file. > >Timestep PE >10.0 -3091.80609 > >I have one question. Do I need to put ts and pe into a list before I print >then to screen or I am just missing something. Thanks. > >Ara > >import string > >inp = open("fort.44","r") >all_file = inp.readlines() >inp.close() > >outp = open("out.txt","w") > >cols = map(string.split,all_file) >##print cols > >Data = {} >for line in cols: > ts = line[0] ># print line[0] > pe = line[1] ># print line[1] > >print """ > >Timestep PE""" >print "%s %s " % (ts,pe) > >outp.close() Put the print statement in the for loop. for line in cols: ... print "%s %s " % (ts,pe) Bob Gailer mailto:bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050208/03a98ee6/attachment.htm From alan.gauld at freenet.co.uk Tue Feb 8 22:51:51 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Feb 8 22:50:55 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <C4C644CF4ADA9448904C3E8BACC4B97C02E67510@medexch1.medplus.com> Message-ID: <06fa01c50e28$65ebcc80$68b78851@xp> As one last option... (And I confess I've kind of got off the original thread here, this is just catching my interest now! :-) try: ftable = { 'a' : lambda: 'a', 'b' : lambda: 'b or c', 'c' : lambda: 'b or c' } print ftable[var] except KeyError: pass Which is actually how I would probably code it if I wqs using a dictionary (well actually I'd miss out the lambdas in this case, but let's imagine we are doing something just a tad more exciting!) Using the get() method actrually makes it more complex in this case. But if we really do want a specific 'd' that does nothing (or more specifically a default that does *something*, then we are back to that bad ol' def p() again.) Now lets look at a putative switch version: switch var: case 'a' : print 'a' case 'b' : case 'c' : print 'b or c' else : pass It is one line less, but is not reusable, so if the switch needs to be used more than once - as is often the case in label printing scenarios particularly - the dictionary wins. But for a one-off the switch wins. The switch also, by using drop through has the advantage of only a single message for 'b or c' - a maintenance win. (But that can be ameliorated by having the messages in a separate table someplace - which is good practice anyhow for multi lingual code.) The final option is the if/elif option: if var == 'a': print 'a' elif var == 'b' or var == 'c': print 'b or c' Which is the shortest of all of them and for simple label printing is probably the best option too! But once the number of cases increases, performance starts to wane and we go back to a dictionary or our missing switch... What does all of this tell us? Probably only that the old adage KISS is right: Keep It Simple Stupid! :-) > I do note that it took this group of experienced programmers several > tries to impliment this simple switch statement without actually using > switch. I dare say with standard switch syntax we would've had it right > the first time :-) Oh I dunno, I've seen some pretty weird switch code. But if the switch didn't allow drop through it might've worked first time ;-) Alan G. From alan.gauld at freenet.co.uk Tue Feb 8 22:56:30 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Feb 8 22:55:39 2005 Subject: [Tutor] executing SAS and passing parameters References: <592E8923DB6EA348BE8E33FCAADEFFFC0B13DC2E@dshs-exch2.dshs.wa.lcl> Message-ID: <071001c50e29$0ca16940$68b78851@xp> > I am trying to use python to run a SAS program by passing the needed > parameters. I am able to start SAS, but unable to start the correct SAS > program with its parameters. Not being familiar with SAS or its parameters we'll need more clues... > Any assistance you could provide will be appreciated. Can you show us what you used to start SAS? Can you tell us exactly what happened? - any errors etc? Can you show us how you'd do it outside of Python? Can you tell us which OS you are using? With that info we should be able to make a stab at it. Alan G. From alan.gauld at freenet.co.uk Tue Feb 8 23:02:01 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Feb 8 23:02:01 2005 Subject: [Tutor] Printing columns of data References: <A0CE32554BD73A4481FE85C3F39DB6FC0B05F4@ES21SNLNT.srn.sandia.gov> Message-ID: <073801c50e29$d1c3b840$68b78851@xp> > So I wrote the program included below and it only prints the last line > of the file. > I have one question. Do I need to put ts and pe into a list before I > print then to screen or I am just missing something. Thanks. You just need to indent your last print statement so it is inside the loop and put the heading print statement before the loop. print """ Timestep PE""" for line in cols: ts = line[0] pe = line[1] print "%s %s " % (ts,pe) You might also like to use stroing formatting to force column widths to be constant: print "%20s%20s" % (ts,pe) should illustrate...adjust the size to suit. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Tue Feb 8 23:04:59 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Feb 8 23:04:05 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <C4C644CF4ADA9448904C3E8BACC4B97C02E67510@medexch1.medplus.com> <420923F6.6050103@ccvcorp.com> Message-ID: <073d01c50e2a$3c1128e0$68b78851@xp> > table = { 'a': 'a', 'b': 'b or c', 'c': 'b or c', 'd': None } > result = table.get(var, 'default case') > if result: > print result > > This, to my mind, is much cleaner -- you're factoring out the repeated > code, whether print statement or call to sys.stdout.write(), reducing > the complexity of the dict. You're making flow control much more > straightforward. You're making the whole thing easier to read. Yep, the lambda stuff etc is there on the assumption that we are trying to do something a tad more interesting than just print the label - but as it happens printing the label has been hard enough!! :-) Alan G. From WilliTf at dshs.wa.gov Tue Feb 8 23:04:43 2005 From: WilliTf at dshs.wa.gov (Williams, Thomas) Date: Tue Feb 8 23:05:00 2005 Subject: [Tutor] executing SAS and passing parameters Message-ID: <592E8923DB6EA348BE8E33FCAADEFFFC0B13DC31@dshs-exch2.dshs.wa.lcl> I'll do my best to answer these questions for you. I am able to start the SAS executable from python, but not the specific SAS program in question. When this executable is executed, the typical SAS environment is displayed (SAS editor Window, SAS libraries, and the output and log windows). I want to have a specific SAS program executing with the assigned parameters that will be read into a SAS macro. This SAS program was originally called from an AML (Arc Macro Language), again, with the parameters passed to it. OS: WindowsNT Let me know if you need further information. Thanks again, Tom -----Original Message----- From: Alan Gauld [mailto:alan.gauld@freenet.co.uk] Sent: Tuesday, February 08, 2005 1:57 PM To: Williams, Thomas; tutor@python.org Subject: Re: [Tutor] executing SAS and passing parameters > I am trying to use python to run a SAS program by passing the needed > parameters. I am able to start SAS, but unable to start the correct SAS > program with its parameters. Not being familiar with SAS or its parameters we'll need more clues... > Any assistance you could provide will be appreciated. Can you show us what you used to start SAS? Can you tell us exactly what happened? - any errors etc? Can you show us how you'd do it outside of Python? Can you tell us which OS you are using? With that info we should be able to make a stab at it. Alan G. From carroll at tjc.com Wed Feb 9 01:31:42 2005 From: carroll at tjc.com (Terry Carroll) Date: Wed Feb 9 01:31:47 2005 Subject: [Tutor] executing SAS and passing parameters In-Reply-To: <592E8923DB6EA348BE8E33FCAADEFFFC0B13DC31@dshs-exch2.dshs.wa.lcl> Message-ID: <Pine.LNX.4.44.0502081628550.7610-100000@violet.rahul.net> Ah, SAS. I used that a lot in the early '80s for general programming. I felt a lot about SAS then as I do about Python now. Enough of that. Can you show your python code that invokes SAS; and can you also show what you type at a command line that makes SAS run the way you want? Given the command line, it should be pretty straightforward to move the command line invocation into Python. On Tue, 8 Feb 2005, Williams, Thomas wrote: > I'll do my best to answer these questions for you. > > I am able to start the SAS executable from python, but not the specific SAS > program in question. When this executable is executed, the typical SAS > environment is displayed (SAS editor Window, SAS libraries, and the output > and log windows). I want to have a specific SAS program executing with the > assigned parameters that will be read into a SAS macro. > > This SAS program was originally called from an AML (Arc Macro Language), > again, with the parameters passed to it. > > OS: WindowsNT > > Let me know if you need further information. > > Thanks again, > Tom > > > -----Original Message----- > From: Alan Gauld [mailto:alan.gauld@freenet.co.uk] > Sent: Tuesday, February 08, 2005 1:57 PM > To: Williams, Thomas; tutor@python.org > Subject: Re: [Tutor] executing SAS and passing parameters > > > I am trying to use python to run a SAS program by passing the needed > > parameters. I am able to start SAS, but unable to start the correct > SAS > > program with its parameters. > > Not being familiar with SAS or its parameters we'll need more clues... > > > Any assistance you could provide will be appreciated. > > Can you show us what you used to start SAS? > Can you tell us exactly what happened? - any errors etc? > Can you show us how you'd do it outside of Python? > Can you tell us which OS you are using? > > With that info we should be able to make a stab at it. > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From keridee at jayco.net Wed Feb 9 03:17:21 2005 From: keridee at jayco.net (Jacob S.) Date: Wed Feb 9 03:22:15 2005 Subject: [Tutor] calling subroutines into program References: <5.1.0.14.0.20050207140910.00bbe528@mailhost.geo.vu.nl> <f2ff2d05020705459a81db9@mail.gmail.com> <f2ff2d05020706023b730c27@mail.gmail.com><42077CD2.5040107@tds.net><f2ff2d050207131220e1f627@mail.gmail.com> <4207DBE2.6000109@tds.net> Message-ID: <004b01c50e4e$3dab4680$935328cf@JSLAPTOP> > Liam Clarke wrote: >> oh? Is is the negative? > > No, the decimal fraction. It's easy enough to try it: Not exactly, it's a combination of string *and* decimal fraction. >>> int('-945') -945 >>> int('-945.0') Traceback (most recent call last): File "<stdin>", line 1, in ? ValueError: invalid literal for int(): -945.0 >>> int(-945.0) -945 >>> Jacob > >>> int('950') > 950 > >>> int('-950') > -950 > >>> int('950.00') > Traceback (most recent call last): > File "<stdin>", line 1, in ? > ValueError: invalid literal for int(): 950.00 > >>> int('-950.00') > Traceback (most recent call last): > File "<stdin>", line 1, in ? > ValueError: invalid literal for int(): -950.00 > > Kent > From keridee at jayco.net Wed Feb 9 05:12:46 2005 From: keridee at jayco.net (Jacob S.) Date: Wed Feb 9 05:12:26 2005 Subject: [Tutor] manipulating a file References: <cu73hp$7oj$1@sea.gmane.org> Message-ID: <008301c50e5d$a15a8a60$935328cf@JSLAPTOP> > import os > > srcfile = open('/var/log/httpd-access.log.bak', 'r') > dstfile = open('/var/log/httpd-access.log', 'w') > while 1: > lines = srcfile.readlines() > if not lines: break > # print lines > for i in lines: > if len(i) < 2086: > #print i > dstfile.write(i) > > srcfile.close() > dstfile.close() Okay, so how about... a = '/var/log/httpd-access.log' srcfile = open(a,'r') dstfile = open(a+'.bak,'w') for x in srcfile: try: x[2086] except: print >> dstfile, x srcfile.close() dstfile.close() 1) Put filename in seperate variable because I'm lazy and didn't want to type it twice. 2) Implemented the file iteration technique. 3) Odd alternative way for line check. Remeber, there's more than one way to do it! 4) Implemented the cool redirection of print statement Not bad, what do you thing, Reed? Does anybody have any input on alternative length check technique? Will it be less efficient than just using len()? HTH, Jacob From keridee at jayco.net Wed Feb 9 05:29:39 2005 From: keridee at jayco.net (Jacob S.) Date: Wed Feb 9 05:29:46 2005 Subject: [Tutor] Match on current line and next line. Possible? References: <2a278ffe05020807347045c8ad@mail.gmail.com> Message-ID: <00b901c50e60$09d1a270$935328cf@JSLAPTOP> It's getting late, so if someone already suggested something like this, just pretend to smack me across the face, and I'll flinch later... import re fi = open('/somefile','r') ## Don't do readlines and bring the whole file in memory... match1 = re.compile('^Python') match2 = re.compile('^/tBLAH') prevline = '' for line in fi: if match1.search(line) and match2.search(line): do_something() prevline = line fi.close() HTH, Jacob > Hello! How can I instruct Python to match on the current line and the > next line? > > > Assumptions; > - We are reading in one line at a time > > > BROKEN EXAMPLE (discussion) > ###################### > file = open('/somefile','r').readlines() > for line in file: > match_one = re.search('^Python', line) > match_two = re.search('^\tBLAH', line) > if match_one and nextline == match_two: > do_something() > > > Maybe this just isn't possible, since we are working line by line. > > Any suggestions? > > > Tom > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From james2dope at yahoo.com Wed Feb 9 05:35:39 2005 From: james2dope at yahoo.com (james middendorff) Date: Wed Feb 9 05:35:43 2005 Subject: [Tutor] help Message-ID: <20050209043539.36808.qmail@web31004.mail.mud.yahoo.com> I want to use mysqldb to add people into a database, but when I ask for the certain fields like Name, PhoneNumber and such, I cannot get it to put them in as a string? I am not sure what I am doing wrong but here is my code thanks to anyone who helps: import MySQLdb username = raw_input("what is your username? ") password = raw_input("what is the password? ") database = raw_input("what database do you want to enter? ") conn = MySQLdb.connect(host='127.0.0.1', user=username, passwd=password, db=database) c = conn.cursor() Name = raw_input("what is the name you want to add? ") PhoneNumber = input("what is the phone number for the person you are adding? ") Address = raw_input("what is the address for the person you are adding? ") EmailAddress = raw_input("what is the email address of the person you are adding? ") BirthDate = raw_input("what is the birthdate of the person you are adding? year-month-day") c.execute (""" INSERT INTO people () VALUES ('%s','%s','%s','%s','%s'); """)% (Name, PhoneNumber, Address, EmailAddress, BirthDate) print "%d rows were inserted" % c.rowcount ===== "I would kill everyone in this room for a drop of sweet beer." ----Homer Simpson---- __________________________________ Do you Yahoo!? The all-new My Yahoo! - What will yours do? http://my.yahoo.com From reed at intersiege.com Wed Feb 9 06:13:37 2005 From: reed at intersiege.com (Reed L. O'Brien) Date: Wed Feb 9 06:14:30 2005 Subject: [Tutor] Re: manipulating a file In-Reply-To: <20050207091852.87090.qmail@web53808.mail.yahoo.com> References: <Pine.LNX.4.44.0502062314380.12631-100000@hkn.eecs.berkeley.edu> <20050207091852.87090.qmail@web53808.mail.yahoo.com> Message-ID: <cuc648$8ta$1@sea.gmane.org> Shitiz Bansal wrote: > Hi, > I do see a problem. > The script is fine, the problem lies else where. > > Your script is trying to write log.bak to log, it > should b other way round. > > i.e.... > srcfile = open('/var/log/httpd-access.log', 'r') > dstfile = open('/var/log/httpd-access.log.bak', 'w') > > hope that fixes it. > > About the efficiency, why do u need python at all... > How abt a simple shell command.... > cat httpd-access.log>>log.bak > > Shitiz > > --- Danny Yoo <dyoo@hkn.eecs.berkeley.edu> wrote: > > >> >>On Mon, 7 Feb 2005, Reed L. O'Brien wrote: >> >> >>>I want to read the httpd-access.log and remove any >> >>oversized log records >> >>>I quickly tossed this script together. I manually >> >>mv-ed log to log.bak >> >>>and touched a new logfile. >>> >>>running the following with print i uncommented >> >>does print each line to >> >>>stdout. but it doesn't write to the appropriate >> >>file... >> >> >>Hello! >> >>Let's take a look at the program again: >> >>### >>import os >>srcfile = open('/var/log/httpd-access.log.bak', 'r') >>dstfile = open('/var/log/httpd-access.log', 'w') >>while 1: >> lines = srcfile.readlines() >> if not lines: break >> for i in lines: >> if len(i) < 2086: >> dstfile.write(i) >>srcfile.close() >>dstfile.close() >>### >> >> >>>a) what am I missing? >>>b) is there a less expensive way to do it? >> >>Hmmm... I don't see anything offhand that prevents >>httpd-access.log from >>containing the lines you expect. Do you get any >>error messages, like >>permission problems, when you run the program? >> >>Can you show us how you are running the program, and >>how you are checking >>that the resulting file is empty? >> >> >>Addressing the question on efficiency and expense: >>yes. The program at >>the moment tries to read all lines into memory at >>once, and this is >>expensive if the file is large. Let's fix this. >> >> >>In recent versions of Python, we can modify >>file-handling code from: >> >>### >>lines = somefile.readlines() >>for line in lines: >> ... >>### >> >>to this: >> >>### >>for line in somefile: >> ... >>### >> >>That is, we don't need to extract a list of 'lines' >>out of a file. >>Python allows us to loop directly across a file >>object. We can find more >>details about this in the documentation on >>"Iterators" (PEP 234): >> >> http://www.python.org/peps/pep-0234.html >> >>Iterators are a good thing to know, since Python's >>iterators are deeply >>rooted in the language design. (Even if it they >>were retroactively >>embedded. *grin*) >> >> >>A few more comments: the while loop appears >>unnecessary, since on the >>second run-through the loop, we'll have already read >>all the lines out of >>the file. (I am assuming that nothing is writing to >>the backup file at >>the time.) If the body of a while loop just runs >>once, we don't need a >>loop. >> >>This simplifies the code down to: >> >>### >>srcfile = open('/var/log/httpd-access.log.bak', 'r') >>dstfile = open('/var/log/httpd-access.log', 'w') >>for line in srcfile: >> if len(line) < 2086: >> dstfile.write(line) >>srcfile.close() >>dstfile.close() >>### >> >> >>I don't see anything else here that causes the file >>writing to fail. If >>you can tell us more information on how you're >>checking the program's >>effectiveness, that may give us some more clues. >> >>Best of wishes to you! >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> > > > > > > __________________________________ > Do you Yahoo!? > Yahoo! Mail - Helps protect you from nasty viruses. > http://promotions.yahoo.com/new_mail > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > I am actually mv log to bak and write the non offening entries back to log. I can not be working on log as it needs to be able to accept new entries as the webserver is accessed. Plus I am learning python, I could have sh scripted it easy but am broadening my horizons... reed From nixonron at yahoo.com Wed Feb 9 06:36:55 2005 From: nixonron at yahoo.com (Ron Nixon) Date: Wed Feb 9 06:37:02 2005 Subject: [Tutor] print out lines that start with a word Message-ID: <20050209053656.60027.qmail@web20326.mail.yahoo.com> Can anyone tell me what I've done wrong in this script. I'm trying to get only the lines that start with "This" for a text file. Here's what I wrote: >>> import re >>> f = open('c:/lines.txt').readlines() >>> for line in f: match = re.search('^This',f) if line == match: print match here's the error message I got: Traceback (most recent call last): File "<pyshell#34>", line 2, in -toplevel- match = re.search('^This',f) File "C:\Python24\lib\sre.py", line 134, in search return _compile(pattern, flags).search(string) TypeError: expected string or buffer Thanks in advance __________________________________ Do you Yahoo!? Read only the mail you want - Yahoo! Mail SpamGuard. http://promotions.yahoo.com/new_mail From dyoo at hkn.eecs.berkeley.edu Wed Feb 9 08:15:03 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Feb 9 08:15:09 2005 Subject: [Tutor] Re: manipulating a file In-Reply-To: <cuc648$8ta$1@sea.gmane.org> Message-ID: <Pine.LNX.4.44.0502082252020.32760-100000@hkn.eecs.berkeley.edu> > >>This simplifies the code down to: > >> > >>### > >>srcfile = open('/var/log/httpd-access.log.bak', 'r') > >>dstfile = open('/var/log/httpd-access.log', 'w') > >>for line in srcfile: > >> if len(line) < 2086: > >> dstfile.write(line) > >>srcfile.close() > >>dstfile.close() > >>### > >> > >> > I am actually mv log to bak and write the non offening entries back to > log. Hi Reed, Oh, so the web server is still continuing to write things onto the open log file then. Out of curiosity, what web server are you using? One remote possiblility for the weirdness might depend on how your web server writes new log messages into the file: perhaps it can automatically detect log file rotation, and may be overwriting http-access.log? It's very hard to say. I'll talk about this a little more below. > I can not be working on log as it needs to be able to accept new entries > as the webserver is accessed. Plus I am learning python, I could have > sh scripted it easy but am broadening my horizons... Sure, I think that's perfectly fine. I think there was some confusion on the list earlier, so I'm glad you cleared that up. I'm still trying to figure out what could be causing the problem. You mentioned that you were running the programs as root, so permission problems are probably not an issue. I don't think we have enough information to debug this, and I hate shooting arrows in random directions. I feel a little nervous programs that try to do 'in-place' changes. Conceptually, we're trying to swap out httpd_access out from underneath the httpd process's nose, and that might not work. If you're doing a 'mv', then the log messages should continue to log to the backup file, if I understand how apache works. Let's test something. Can you try writing the truncated log to another file, like '/var/log/http-access.truncated.log'? This at least should prevent any wacky writing conflicst between the httpd process and our log-filtering program. Also, what happens if instead of opening up explicit files you use standard input and output? Here's a modified program that uses sys.stdin and sys.stdout: ###### """Cut really long lines out of the output.""" import sys for line in sys.stdin: if len(line) < 2086: sys.stdout.write(line) sys.stdin.close() sys.stdout.close() ###### This can be equivalent to the previous program if we use the shell's file redirection. It also allows us to run the program on different input and output files with ease. Try it on some other files first and see that it does work on regular files first. Best of wishes to you! From cyresse at gmail.com Wed Feb 9 08:18:48 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed Feb 9 08:18:52 2005 Subject: [Tutor] print out lines that start with a word In-Reply-To: <20050209053656.60027.qmail@web20326.mail.yahoo.com> References: <20050209053656.60027.qmail@web20326.mail.yahoo.com> Message-ID: <f2ff2d05020823187fbf796b@mail.gmail.com> H Ron, >>> import re >>> f = open('c:/lines.txt').readlines() >>> for line in f: match = re.search('^This',f) if line == match: print match Hi Ron, Welcome to the wonderful world of Python. from re.search.__doc__ ; "Scan through string looking for a match to the pattern, returning a match object, or None if no match was found." OK, so if there's a match, you get an object returned, otherwise it returns None. So, you can boolean test this. I'm guessing you want to print lines that start with this. import re f = file('c:/lines.txt) #Also, you can iterate over a file for line in f: match = re.search('^This', line) #you want to search line by line? if match: print line else: print "No match" Or, you could store all the lines in a list to use afterwards - lineStore =[] for line in f: match = re.search('^This', line) #you want to search line by line? if match: lineStore.append(line) else: print "No match" On Tue, 8 Feb 2005 21:36:55 -0800 (PST), Ron Nixon <nixonron@yahoo.com> wrote: > Can anyone tell me what I've done wrong in this > script. > > I'm trying to get only the lines that start with > "This" for a text file. > > Here's what I wrote: > > >>> import re > >>> f = open('c:/lines.txt').readlines() > >>> for line in f: > match = re.search('^This',f) > if line == match: > print match > > here's the error message I got: > > Traceback (most recent call last): > File "<pyshell#34>", line 2, in -toplevel- > match = re.search('^This',f) > File "C:\Python24\lib\sre.py", line 134, in search > return _compile(pattern, flags).search(string) > TypeError: expected string or buffer > > Thanks in advance > > > __________________________________ > Do you Yahoo!? > Read only the mail you want - Yahoo! Mail SpamGuard. > http://promotions.yahoo.com/new_mail > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From dyoo at hkn.eecs.berkeley.edu Wed Feb 9 08:33:22 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Feb 9 08:33:27 2005 Subject: [Tutor] help In-Reply-To: <20050209043539.36808.qmail@web31004.mail.mud.yahoo.com> Message-ID: <Pine.LNX.4.44.0502082315340.32760-100000@hkn.eecs.berkeley.edu> On Tue, 8 Feb 2005, james middendorff wrote: > I want to use mysqldb to add people into a database, but when I ask for > the certain fields like Name, PhoneNumber and such, I cannot get it to > put them in as a string? I am not sure what I am doing wrong but here is > my code thanks to anyone who helps: Hi James, Ok, I see a few things in the execute statement that can be fixed. Let's first take a look at the code: > c.execute (""" > INSERT INTO people () > VALUES > ('%s','%s','%s','%s','%s'); > """)% (Name, PhoneNumber, Address, > EmailAddress, BirthDate) The SQL here has an empty column list: INSERT into people () ^^ and this is probably not a good idea: instead, list out the field names explicitely. The reason is because SQL tables don't necessarily imply a specific order. The empty column list approach is also not robust to SQL table changes in the future: if you add a new column into people, your existing code will certainly break since the number of values don't match the number of columns. More than that, though, is a silly syntax issue that's related to string interpolation. Let's pretend for the moment that we do fix the SQL column issue: ### c.execute (""" INSERT INTO people (name, phone_number, address, email_address, birthdate) VALUES ('%s','%s','%s','%s','%s'); """) % (Name, PhoneNumber, Address, EmailAddress, BirthDate) ### Brace yourself: you're not going to like this. One of the parenthesis is misplaced. You meant to write: ### c.execute (""" INSERT INTO people (name, phone_number, address, email_address, birthdate) VALUES ('%s','%s','%s','%s','%s'); """ % (Name, PhoneNumber, Address, EmailAddress, BirthDate) ) ### Don't worry, we all do this sometimes. *grin* Which brings up the point: at the moment, you're doing explicit string interpolation, but there are some special cases that the code above isn't considering. In particular, what happens if one of the names that get entered looks like: "D'Artagnan" Then all of the quotes get unbalanced, and we get a really messed up SQL statement. *grin* Most database systems provide a system to automatically do robust interpolation of values into a statement. Here's your execute(), using the robust approach: ### c.execute (""" INSERT INTO people (name, phone_number, address, email_address, birthdate) VALUES (%s,%s,%s,%s,%s); """, (Name, PhoneNumber, Address, EmailAddress, BirthDate) ) ### Not much changes here syntactically, but semanically, this is nicer: the cursor's execute() statement itself takes the tuple of values, and does the interpolation itself. Notice that there's no more quotes around the string values: the execute() will add them in for you. If you have more questions, please feel free to ask. Good luck to you! From kraus at hagen-partner.de Wed Feb 9 09:00:52 2005 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Wed Feb 9 09:01:06 2005 Subject: [Tutor] Re: print out lines that start with a word In-Reply-To: <20050209053656.60027.qmail@web20326.mail.yahoo.com> References: <20050209053656.60027.qmail@web20326.mail.yahoo.com> Message-ID: <cucfsm$ra7$1@sea.gmane.org> Ron Nixon wrote: > Can anyone tell me what I've done wrong in this > script. > > I'm trying to get only the lines that start with > "This" for a text file. > > Here's what I wrote: > > >>>>import re >>>>f = open('c:/lines.txt').readlines() >>>>for line in f: > > match = re.search('^This',f) > if line == match: > print match > > Pardon my ignorance, but why is everybody fond of regexps ;-) ? Are they faster? What about good ol' startswith(): http://docs.python.org/lib/string-methods.html#l2h-204 Untested: f = open('c:/lines.txt').readlines() for line in f: if line.startswith('This'): print line # Or whatever match is, no regexp-expert here, sorry Wondering, Wolfram From cyresse at gmail.com Wed Feb 9 09:05:00 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed Feb 9 09:05:03 2005 Subject: [Tutor] Re: print out lines that start with a word In-Reply-To: <cucfsm$ra7$1@sea.gmane.org> References: <20050209053656.60027.qmail@web20326.mail.yahoo.com> <cucfsm$ra7$1@sea.gmane.org> Message-ID: <f2ff2d05020900056e962b89@mail.gmail.com> regexes are common across a lot of languages, even Java has them. Though the pain that would be I daren't not imagine. So the syntax is familiar, whereas string methods may not be. On Wed, 09 Feb 2005 09:00:52 +0100, Wolfram Kraus <kraus@hagen-partner.de> wrote: > Ron Nixon wrote: > > Can anyone tell me what I've done wrong in this > > script. > > > > I'm trying to get only the lines that start with > > "This" for a text file. > > > > Here's what I wrote: > > > > > >>>>import re > >>>>f = open('c:/lines.txt').readlines() > >>>>for line in f: > > > > match = re.search('^This',f) > > if line == match: > > print match > > > > > Pardon my ignorance, but why is everybody fond of regexps ;-) ? Are they > faster? What about good ol' startswith(): > http://docs.python.org/lib/string-methods.html#l2h-204 > Untested: > > f = open('c:/lines.txt').readlines() > for line in f: > if line.startswith('This'): > print line # Or whatever match is, no regexp-expert here, sorry > > Wondering, > Wolfram > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From kraus at hagen-partner.de Wed Feb 9 09:30:09 2005 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Wed Feb 9 09:30:24 2005 Subject: [Tutor] Re: print out lines that start with a word In-Reply-To: <f2ff2d05020900056e962b89@mail.gmail.com> References: <20050209053656.60027.qmail@web20326.mail.yahoo.com> <cucfsm$ra7$1@sea.gmane.org> <f2ff2d05020900056e962b89@mail.gmail.com> Message-ID: <cuchjg$vc3$1@sea.gmane.org> Liam Clarke wrote: > regexes are common across a lot of languages, even Java has them. > Though the pain that would be I daren't not imagine. So the syntax is > familiar, whereas string methods may not be. But IMHO string methods are (more) explicit and readable, the name tells you what the method is doing. I know that sometimes regexp are really fine, e.g. extracting something from html or maybe speed issues (can anyone enlighten me on that one?), but for simple task like the OP's problem I'd always use string methods. Wolfram From pierre.barbier at cirad.fr Wed Feb 9 09:44:15 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Wed Feb 9 09:42:19 2005 Subject: [Tutor] Re: print out lines that start with a word In-Reply-To: <cuchjg$vc3$1@sea.gmane.org> References: <20050209053656.60027.qmail@web20326.mail.yahoo.com> <cucfsm$ra7$1@sea.gmane.org> <f2ff2d05020900056e962b89@mail.gmail.com> <cuchjg$vc3$1@sea.gmane.org> Message-ID: <4209CD5F.3090705@cirad.fr> Wolfram Kraus a ?crit : > Liam Clarke wrote: > >> regexes are common across a lot of languages, even Java has them. >> Though the pain that would be I daren't not imagine. So the syntax is >> familiar, whereas string methods may not be. > > But IMHO string methods are (more) explicit and readable, the name tells > you what the method is doing. I know that sometimes regexp are really > fine, e.g. extracting something from html or maybe speed issues (can > anyone enlighten me on that one?), but for simple task like the OP's > problem I'd always use string methods. > > Wolfram I completely agree ! Then, it will very probably be more efficient. And the methods (or functions) like "startwith" are avalaible in almost every string library ! Pierre -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 From cyresse at gmail.com Wed Feb 9 10:42:34 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed Feb 9 10:42:38 2005 Subject: [Tutor] Re: print out lines that start with a word In-Reply-To: <4209CD5F.3090705@cirad.fr> References: <20050209053656.60027.qmail@web20326.mail.yahoo.com> <cucfsm$ra7$1@sea.gmane.org> <f2ff2d05020900056e962b89@mail.gmail.com> <cuchjg$vc3$1@sea.gmane.org> <4209CD5F.3090705@cirad.fr> Message-ID: <f2ff2d0502090142625594f@mail.gmail.com> >>> x= ["Dude", 'How is it going man', ' '] >>> print x ['Dude', 'How is it going man', ' '] >>> j=[] >>> for item in x: ... if re.search('\S+',item): ... j.append(item) >>> print j ['Dude', 'How is it going man'] Now, I first did that in a Perl script, but it easily comes across to Python. \S+ will usually mean 'one or more non-whitespace characters'. Brilliant for when your first Perl script accidentally appended \n to everything, even \n and \t. *embarassed* Whereas, while I'm sure there is a string method that can do that, I'm not sure what it is. Also - say you have a list of words - j = " bag apple tomato cheese *marmite* sausages *scones*" and you wanted to pick up each word that was asterisked. I did this as a string method then a regex. >>> try: ... indexes=[] ... lastIndex = 0 ... while 1: ... x = j.index("*", lastIndex + 1) ... indexes.append(x) ... lastIndex = x ... except ValueError: ... pass ... >>> print indexes [4, 10] >>>myString = j[5:10] Now the regular expression - >>> x = re.finditer("\*(?P<myString>.*?)\*", j) >>> a = x.next() >>> print a.group('myString') apple Now, while the regEx syntax is a big harsh to begin with, once you get the hang of it, it's OK, and the string method version I used felt too 'hacky' for me. Of course, both only work with pairs of asterisks, so I guess that makes them both hacky. : ) That's my 2c, I use string methods for stuff like that .startswith, .endswith, if 'foo' in x stuff is good as well. But sometimes, a regex is the right tool for the job. Regards, Liam Clarke PS Pierre, my wife asked if you could write something in French so that she could try and read it, as she's trying to pick up her French again. If you don't mind. On Wed, 09 Feb 2005 09:44:15 +0100, Pierre Barbier de Reuille <pierre.barbier@cirad.fr> wrote: > Wolfram Kraus a ?crit : > > Liam Clarke wrote: > > > >> regexes are common across a lot of languages, even Java has them. > >> Though the pain that would be I daren't not imagine. So the syntax is > >> familiar, whereas string methods may not be. > > > > But IMHO string methods are (more) explicit and readable, the name tells > > you what the method is doing. I know that sometimes regexp are really > > fine, e.g. extracting something from html or maybe speed issues (can > > anyone enlighten me on that one?), but for simple task like the OP's > > problem I'd always use string methods. > > > > Wolfram > > I completely agree ! Then, it will very probably be more efficient. And > the methods (or functions) like "startwith" are avalaible in almost > every string library ! > > Pierre > > -- > Pierre Barbier de Reuille > > INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP > Botanique et Bio-informatique de l'Architecture des Plantes > TA40/PSII, Boulevard de la Lironde > 34398 MONTPELLIER CEDEX 5, France > > tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From kraus at hagen-partner.de Wed Feb 9 11:08:40 2005 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Wed Feb 9 11:08:56 2005 Subject: [Tutor] Re: print out lines that start with a word In-Reply-To: <f2ff2d0502090142625594f@mail.gmail.com> References: <20050209053656.60027.qmail@web20326.mail.yahoo.com> <cucfsm$ra7$1@sea.gmane.org> <f2ff2d05020900056e962b89@mail.gmail.com> <cuchjg$vc3$1@sea.gmane.org> <4209CD5F.3090705@cirad.fr> <f2ff2d0502090142625594f@mail.gmail.com> Message-ID: <cucnbu$ep5$1@sea.gmane.org> Liam Clarke wrote: >>>>x= ["Dude", 'How is it going man', ' '] >>>>print x > > ['Dude', 'How is it going man', ' '] > > >>>>j=[] >>>>for item in x: > > ... if re.search('\S+',item): > ... j.append(item) > > >>>>print j > > ['Dude', 'How is it going man'] What about: x= ["Dude", 'How is it going man', ' '] print [a for a in x if a.strip()] > Now, I first did that in a Perl script, but it easily comes across to > Python. \S+ will usually mean 'one or more non-whitespace characters'. > Brilliant for when your first Perl script accidentally appended \n to > everything, even \n and \t. *embarassed* > > Whereas, while I'm sure there is a string method that can do that, I'm > not sure what it is. Well the documentation on that is not sooo big ;-) > Also - say you have a list of words - > j = " bag apple tomato cheese *marmite* sausages *scones*" > > and you wanted to pick up each word that was asterisked. > I did this as a string method then a regex. > > > >>>>try: > > ... indexes=[] > ... lastIndex = 0 > ... while 1: > ... x = j.index("*", lastIndex + 1) > ... indexes.append(x) > ... lastIndex = x > ... except ValueError: > ... pass > ... > >>>>print indexes > > [4, 10] > >>>>myString = j[5:10] > That gives me [25, 33, 45, 52], propably a C&P bug? > Now the regular expression - > > >>>>x = re.finditer("\*(?P<myString>.*?)\*", j) >>>>a = x.next() >>>>print a.group('myString') > > apple Same error as above? And you said you want _all_ asteriksed words! How about this cute lil list comprehension: print [w for w in j.split() if words[0] == '*' and words[-1] == '*'] > Now, while the regEx syntax is a big harsh to begin with, once you get > the hang of it, it's OK, and the string method version I used felt too > 'hacky' for me. Of course, both only work with pairs of asterisks, so > I guess that makes them both hacky. : ) > > That's my 2c, I use string methods for stuff like that .startswith, .endswith, > if 'foo' in x stuff is good as well. But sometimes, a regex is the > right tool for the job. I didn't say that they are useless (and don't wanna troll or start a flameware), but IMHO they are a PITA when it comes to debugging. Ever touched a regexp after one year ;-)? > Regards, > > > Liam Clarke Greetings, Wolfram From kraus at hagen-partner.de Wed Feb 9 11:26:40 2005 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Wed Feb 9 11:28:08 2005 Subject: [Tutor] Re: print out lines that start with a word In-Reply-To: <cucnbu$ep5$1@sea.gmane.org> References: <20050209053656.60027.qmail@web20326.mail.yahoo.com> <cucfsm$ra7$1@sea.gmane.org> <f2ff2d05020900056e962b89@mail.gmail.com> <cuchjg$vc3$1@sea.gmane.org> <4209CD5F.3090705@cirad.fr> <f2ff2d0502090142625594f@mail.gmail.com> <cucnbu$ep5$1@sea.gmane.org> Message-ID: <cucodl$hg8$1@sea.gmane.org> Damn! C&P-bug here to! Is this a virus? ;-) > print [w for w in j.split() if words[0] == '*' and words[-1] == '*'] Should be: print [w for w in j.split() if w[0] == '*' and w[-1] == '*'] From cyresse at gmail.com Wed Feb 9 11:32:51 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed Feb 9 11:32:54 2005 Subject: [Tutor] Re: print out lines that start with a word In-Reply-To: <cucodl$hg8$1@sea.gmane.org> References: <20050209053656.60027.qmail@web20326.mail.yahoo.com> <cucfsm$ra7$1@sea.gmane.org> <f2ff2d05020900056e962b89@mail.gmail.com> <cuchjg$vc3$1@sea.gmane.org> <4209CD5F.3090705@cirad.fr> <f2ff2d0502090142625594f@mail.gmail.com> <cucnbu$ep5$1@sea.gmane.org> <cucodl$hg8$1@sea.gmane.org> Message-ID: <f2ff2d05020902323268e051@mail.gmail.com> print [w for w in j.split() if w[0] == '*' and w[-1] == '*'] Wouldn't that only work if it was bug *car* jeff? I can imagine bug*car*jeff would throw it. Cheers, Liam Clarke -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From kraus at hagen-partner.de Wed Feb 9 11:48:23 2005 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Wed Feb 9 11:48:36 2005 Subject: [Tutor] Re: print out lines that start with a word In-Reply-To: <f2ff2d05020902323268e051@mail.gmail.com> References: <20050209053656.60027.qmail@web20326.mail.yahoo.com> <cucfsm$ra7$1@sea.gmane.org> <f2ff2d05020900056e962b89@mail.gmail.com> <cuchjg$vc3$1@sea.gmane.org> <4209CD5F.3090705@cirad.fr> <f2ff2d0502090142625594f@mail.gmail.com> <cucnbu$ep5$1@sea.gmane.org> <cucodl$hg8$1@sea.gmane.org> <f2ff2d05020902323268e051@mail.gmail.com> Message-ID: <cucpmb$kvj$1@sea.gmane.org> Liam Clarke wrote: > print [w for w in j.split() if w[0] == '*' and w[-1] == '*'] > > > Wouldn't that only work if it was bug *car* jeff? > > I can imagine bug*car*jeff would throw it. > > Cheers, > > Liam Clarke x = 'bug*car*jeff*foo*bar' [x.split('*')[a] for a in range(1,len(x.split('*')), 2)] When you mix * and spaces I will give up ;-)! Wolfram From WilliTf at dshs.wa.gov Wed Feb 9 16:49:55 2005 From: WilliTf at dshs.wa.gov (Williams, Thomas) Date: Wed Feb 9 16:50:11 2005 Subject: [Tutor] executing SAS and passing parameters Message-ID: <592E8923DB6EA348BE8E33FCAADEFFFC0B13DC34@dshs-exch2.dshs.wa.lcl> Here is the code I am using to invoke SAS: import os import sys shell = os.environ.get('COMSPEC') if shell is None: shell = os.environ.get('SHELL') if shell is None: shell = 'an unknown command processor' print 'Running under', shell os.execl('C:\Program Files\SAS Institute\SAS\V8\SAS.exe') However, the program in question is c:\work\run_ratios.sas, with 2 parameters: incov, and outcov. This program was initially invoked from an aml program. The code that invoked SAS from this aml is: &SYSTEM %.SASLOC% -SYSPARM %sas_parm% -log ~ %.ARCLOC%\ratios\log\%.file%.log -SYSIN ~ %.ARCLOC%\sas_code\ratios\new_ratio.sas %.SASLOC%: the SAS executable file ('C:\Program Files\SAS Institute\SAS\V8\SAS.exe') %sas_parm%: the list of parameters to be passed onto SAS %.file%: the name of the log file that is generated during the execution of the SAS program. %.ARCLOC%: directory of the SAS program (c:\work) I think this is an excellent forum to share ideas and solve problems. Thank you ever so much for your assistance with this. From bgailer at alum.rpi.edu Wed Feb 9 19:56:24 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed Feb 9 19:50:47 2005 Subject: [Tutor] help In-Reply-To: <20050209043539.36808.qmail@web31004.mail.mud.yahoo.com> References: <20050209043539.36808.qmail@web31004.mail.mud.yahoo.com> Message-ID: <6.1.2.0.0.20050209115519.0335a370@mail.mric.net> At 09:35 PM 2/8/2005, james middendorff wrote: >I want to use mysqldb to add people into a database, >but when I ask for the certain fields like Name, >PhoneNumber and such, I cannot get it to put them in >as a string? You can increase your chances of getting help by telling us what happens when you execute this code. >I am not sure what I am doing wrong but >here is my code thanks to anyone who helps: >import MySQLdb > >username = raw_input("what is your username? ") >password = raw_input("what is the password? ") >database = raw_input("what database do you want to >enter? ") >conn = MySQLdb.connect(host='127.0.0.1', >user=username, passwd=password, db=database) > >c = conn.cursor() > >Name = raw_input("what is the name you want to add? ") >PhoneNumber = input("what is the phone number for the >person you are adding? ") >Address = raw_input("what is the address for the >person you are adding? ") >EmailAddress = raw_input("what is the email address of >the person you are adding? ") >BirthDate = raw_input("what is the birthdate of the >person you are adding? year-month-day") > > >c.execute (""" > INSERT INTO people () > VALUES > ('%s','%s','%s','%s','%s'); > """)% (Name, PhoneNumber, Address, >EmailAddress, BirthDate) > >print "%d rows were inserted" % c.rowcount > >===== >"I would kill everyone in this room > for a drop of sweet beer." > ----Homer Simpson---- > > > >__________________________________ >Do you Yahoo!? >The all-new My Yahoo! - What will yours do? >http://my.yahoo.com >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor Bob Gailer mailto:bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From jfs.world at gmail.com Wed Feb 9 21:14:05 2005 From: jfs.world at gmail.com (Jeffrey Lim) Date: Wed Feb 9 21:14:10 2005 Subject: [Tutor] python's default argument value handling in functions - weird syntax? problem grappling with the concept Message-ID: <4b3125cc050209121418102fbb@mail.gmail.com> hey folks, i'm a relative newbie to python itself, and I am currently learning by making my way through the tutorial found within the docs of 2.4 (http://www.python.org/doc/2.4/tut/tut.html). I am currently having a problem dealing with the concept of the "default argument value" in python functions, and just how python handles this. Now http://www.python.org/doc/2.4/tut/node6.html#SECTION006710000000000000000 makes the statement that "the default value is evaluated only once". While that is fine, what I don't really get is how the solution given can even make sense - either syntactically, or conceptually. First of all, let me quote what the doc says: =========== Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls: def f(a, L=[]): L.append(a) return L print f(1) print f(2) print f(3) This will print [1] [1, 2] [1, 2, 3] If you don't want the default to be shared between subsequent calls, you can write the function like this instead: def f(a, L=None): if L is None: L = [] L.append(a) return L ======== This leads me to at first conclude several things: 1. 'L' in this case (or by extension, all function arguments for which a default is given in the function definition) is "static" (see 'C' language definition). This is my conclusion, seeing as how 'L' can seem to retain its value even though it has gone out of scope after the 'f' function returns. Correct me if i'm wrong here, guys. 2. (*Now this is where I start to get confused. I think the best way to illustrate how I am having problems is to illustrate with a few examples. The basic problem that I am having is, "Which L is which L?") My examples... Example 1 >>> def f(a,L=[]): ... if L==[5]: ... print 'L==[5] caught' ... print L ... print 'resetting L...' ... L=[] ... L.append(a) ... return L ... >>> f(5) [5] >>> f(5) L==[5] caught [5] resetting L... [5] >>> f(2) L==[5] caught [5] resetting L... [2] Example 2 >>> def f(a,L=None): ... if L==[5]: ... print 'caught, printing, resetting' ... print L ... L=[] ... else: ... L=[] ... L.append(a) ... return L ... >>> f(5) [5] >>> f(6) [6] >>> f(6) So when the default value for 'L' is an empty list, the test condition, _once triggered_, *always* catches? But when the default value for 'L' is none, the 'if' never catches? How is this possible? Or even consider the example given - def f(a, L=None): if L is None: L = [] L.append(a) return L How is 'L == None' even possible all the time, given that for def f(a, L=[]): L.append(a) return L , L isn't even [] except for the first call to 'f'? -jf From bgailer at alum.rpi.edu Wed Feb 9 22:12:30 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed Feb 9 22:06:51 2005 Subject: e-mail address change (was Re: [Tutor] python's default argument value handling in functions - weird syntax? problem grappling with the concept) In-Reply-To: <4b3125cc050209121418102fbb@mail.gmail.com> References: <4b3125cc050209121418102fbb@mail.gmail.com> Message-ID: <6.1.2.0.0.20050209140553.026fc810@mail.mric.net> At 01:14 PM 2/9/2005, Jeffrey Lim wrote: >hey folks, i'm a relative newbie to python itself, and I am currently >learning by making my way through the tutorial found within the docs >of 2.4 (http://www.python.org/doc/2.4/tut/tut.html). > >I am currently having a problem dealing with the concept of the >"default argument value" in python functions, and just how python >handles this. > >Now http://www.python.org/doc/2.4/tut/node6.html#SECTION006710000000000000000 >makes the statement that "the default value is evaluated only once". >While that is fine, what I don't really get is how the solution given >can even make sense - either syntactically, or conceptually. > >First of all, let me quote what the doc says: > >=========== >Important warning: The default value is evaluated only once. This >makes a difference when the default is a mutable object such as a >list, dictionary, or instances of most classes. For example, the >following function accumulates the arguments passed to it on >subsequent calls: > >def f(a, L=[]): > L.append(a) > return L > >print f(1) >print f(2) >print f(3) > >This will print > >[1] >[1, 2] >[1, 2, 3] > >If you don't want the default to be shared between subsequent calls, >you can write the function like this instead: > >def f(a, L=None): > if L is None: > L = [] > L.append(a) > return L >======== > >This leads me to at first conclude several things: > >1. 'L' in this case (or by extension, all function arguments for which >a default is given in the function definition) is "static" (see 'C' >language definition). This is my conclusion, seeing as how 'L' can >seem to retain its value even though it has gone out of scope after >the 'f' function returns. > >Correct me if i'm wrong here, guys. > >2. (*Now this is where I start to get confused. I think the best way >to illustrate how I am having problems is to illustrate with a few >examples. The basic problem that I am having is, "Which L is which >L?") > >My examples... > >Example 1 > >>> def f(a,L=[]): >... if L==[5]: >... print 'L==[5] caught' >... print L >... print 'resetting L...' >... L=[] >... L.append(a) >... return L >... > >>> f(5) >[5] > >>> f(5) >L==[5] caught >[5] >resetting L... >[5] > >>> f(2) >L==[5] caught >[5] >resetting L... >[2] That works as expected. I assume you are happy with the results. >Example 2 > >>> def f(a,L=None): >... if L==[5]: >... print 'caught, printing, resetting' >... print L >... L=[] >... else: >... L=[] >... L.append(a) >... return L >... > >>> f(5) >[5] > >>> f(6) >[6] > >>> f(6) That also works as expected. I assume you are happy with the results. >So when the default value for 'L' is an empty list, the test >condition, _once triggered_, *always* catches? No. What leads you to think that is happening? This code empties the list each time you invoke it. >But when the default value for 'L' is none, the 'if' never catches? > >How is this possible? > >Or even consider the example given - >def f(a, L=None): > if L is None: > L = [] > L.append(a) > return L > >How is 'L == None' even possible all the time, given that for >def f(a, L=[]): > L.append(a) > return L >, L isn't even [] except for the first call to 'f'? From the 1st reference you cited above: 'The default values are evaluated at the point of function definition" Bob Gailer mailto:bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From ternary at gmail.com Wed Feb 9 22:12:22 2005 From: ternary at gmail.com (Mike Bell) Date: Wed Feb 9 22:12:28 2005 Subject: [Tutor] python's default argument value handling in functions - weird syntax? problem grappling with the concept In-Reply-To: <4b3125cc050209121418102fbb@mail.gmail.com> References: <4b3125cc050209121418102fbb@mail.gmail.com> Message-ID: <82975b0c050209131271b13ffa@mail.gmail.com> The function's local variable L is not static, but "default argument value" is, which is what the documentation means when it says that it will evaluate these only once. When the default value is a list (in your code, not "the empty list" but a list which happens to be empty when the default arguments are being evaluated), that same object is used every time the function is called. mike From jfs.world at gmail.com Wed Feb 9 22:19:11 2005 From: jfs.world at gmail.com (Jeffrey Lim) Date: Wed Feb 9 22:19:14 2005 Subject: e-mail address change (was Re: [Tutor] python's default argument value handling in functions - weird syntax? problem grappling with the concept) In-Reply-To: <6.1.2.0.0.20050209140553.026fc810@mail.mric.net> References: <4b3125cc050209121418102fbb@mail.gmail.com> <6.1.2.0.0.20050209140553.026fc810@mail.mric.net> Message-ID: <4b3125cc050209131917b2cfe7@mail.gmail.com> On Wed, 09 Feb 2005 14:12:30 -0700, Bob Gailer <bgailer@alum.rpi.edu> wrote: > At 01:14 PM 2/9/2005, Jeffrey Lim wrote: > > > >Example 1 > > >>> def f(a,L=[]): > >... if L==[5]: > >... print 'L==[5] caught' > >... print L > >... print 'resetting L...' > >... L=[] > >... L.append(a) > >... return L > >... > > >>> f(5) > >[5] > > >>> f(5) > >L==[5] caught > >[5] > >resetting L... > >[5] > > >>> f(2) > >L==[5] caught > >[5] > >resetting L... > >[2] > > That works as expected. I assume you are happy with the results. did you even read what i gave as an example properly? So tell me then - why are you happy with the results when 'f(2)' is called? I am not happy with the results. Calling function 'f' with argument 2 should not (unless u are satisfied with such a result) get caught in the 'if L==[5]' > >So when the default value for 'L' is an empty list, the test > >condition, _once triggered_, *always* catches? > > No. What leads you to think that is happening? This code empties the list > each time you invoke it. > pls read http://www.python.org/doc/2.4/tut/node6.html#SECTION006710000000000000000 for the whole context to my questions. Read also my quotes from the doc in my original post. I assume that you can cope with the level of the presentation of my questions. > > > >How is this possible? > > > >Or even consider the example given - > >def f(a, L=None): > > if L is None: > > L = [] > > L.append(a) > > return L > > > >How is 'L == None' even possible all the time, given that for > >def f(a, L=[]): > > L.append(a) > > return L > >, L isn't even [] except for the first call to 'f'? > > From the 1st reference you cited above: 'The default values are evaluated > at the point of function definition" > perhaps you might like to explain that further, seeing as how you seem to be adopting a "I am smarter than you" attitude. -jf From jfs.world at gmail.com Wed Feb 9 22:22:00 2005 From: jfs.world at gmail.com (Jeffrey Lim) Date: Wed Feb 9 22:22:05 2005 Subject: e-mail address change (was Re: [Tutor] python's default argument value handling in functions - weird syntax? problem grappling with the concept) In-Reply-To: <4b3125cc050209131917b2cfe7@mail.gmail.com> References: <4b3125cc050209121418102fbb@mail.gmail.com> <6.1.2.0.0.20050209140553.026fc810@mail.mric.net> <4b3125cc050209131917b2cfe7@mail.gmail.com> Message-ID: <4b3125cc05020913227e0c5e88@mail.gmail.com> and have the Common Courtesy to stop hijacking or rewriting other people's thread titles unnecessarily pls. (Like when was this thread ever about the change of email address change on your part???) -jf From bgailer at alum.rpi.edu Wed Feb 9 22:51:42 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed Feb 9 22:46:02 2005 Subject: e-mail address change (was Re: [Tutor] python's default argument value handling in functions - weird syntax? problem grappling with the concept) In-Reply-To: <4b3125cc05020913227e0c5e88@mail.gmail.com> References: <4b3125cc050209121418102fbb@mail.gmail.com> <6.1.2.0.0.20050209140553.026fc810@mail.mric.net> <4b3125cc050209131917b2cfe7@mail.gmail.com> <4b3125cc05020913227e0c5e88@mail.gmail.com> Message-ID: <6.1.2.0.0.20050209144944.0331dd48@mail.mric.net> At 02:22 PM 2/9/2005, Jeffrey Lim wrote: >and have the Common Courtesy to stop hijacking or rewriting other >people's thread titles unnecessarily pls. (Like when was this thread >ever about the change of email address change on your part???) I have no idea how this happened. My computer started acting funny. I had to reboot it.. First I knew of the problem was when I saw the posting you are referring to. Perhaps my box has a virus. Bob Gailer mailto:bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From jfs.world at gmail.com Wed Feb 9 22:56:01 2005 From: jfs.world at gmail.com (Jeffrey Lim) Date: Wed Feb 9 22:56:49 2005 Subject: [Tutor] python's default argument value handling in functions - weird syntax? problem grappling with the concept In-Reply-To: <82975b0c050209131271b13ffa@mail.gmail.com> References: <4b3125cc050209121418102fbb@mail.gmail.com> <82975b0c050209131271b13ffa@mail.gmail.com> Message-ID: <4b3125cc0502091356730da149@mail.gmail.com> On Wed, 9 Feb 2005 13:12:22 -0800, Mike Bell <ternary@gmail.com> wrote: > The function's local variable L is not static, but "default argument > value" is, which is what the documentation means when it says that it > will evaluate these only once. When the default value is a list (in > your code, not "the empty list" but a list which happens to be empty > when the default arguments are being evaluated), that same object is > used every time the function is called. > ah, thanks for the clarification! I more or less get it now (the key was to think of everything in terms of object references). Would you mind explaining to me in a bit more detail about how the '==['a list']' operation works then? Frankly, the code and results i get below nearly stumbled me... >>> def f(a,L=[]): ... if L==[5]: ... print "'if L==[5]' caught - printing, and then resetting L..." ... print L ... L = [] ... L.append(a) ... return L ... >>> f(5) [5] >>> f(34) 'if L==[5]' caught - printing, and then resetting L... [5] [34] >>> f('fjskl') 'if L==[5]' caught - printing, and then resetting L... [5] ['fjskl'] >>> My questions: - is the '==' operation a 'list' comparison - rather than a pointer comparison? (my experiments seem to indicate that it is a 'list' comparison) - if this is the case, then why does the 'if L==[5]' test still catch later on, when the 'L' should no longer be a '[5]' list? - if this is *not* the case then, then how do you determine the '==' is supposed to match? - or is this a matter of 'compare by value' first, then after we get a match, we 'compare by reference' later on??? thanks for your time, -jf From alan.gauld at freenet.co.uk Wed Feb 9 23:05:15 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Feb 9 23:05:05 2005 Subject: [Tutor] help References: <20050209043539.36808.qmail@web31004.mail.mud.yahoo.com> Message-ID: <078801c50ef3$700477f0$68b78851@xp> > PhoneNumber and such, I cannot get it to put them in > as a string? I can't help in general but I did notice... > PhoneNumber = input("what is the phone number for the > person you are adding? ") You shouldn't store phone numbers as numbers. People often include spaces or hyphens or parentheses etc when entering them, eg: +44 (0) 1234 567890 (542) 123 4567 0121-553-2609 etc etc... And of course you get the alpha numerics: 0172 TAXICAB So strings are the best solution (and they should be 24 characters long to handle the worst case international standard phone number!) Alan G. Who works for the phone company! :-) From dyoo at hkn.eecs.berkeley.edu Wed Feb 9 23:05:23 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Feb 9 23:05:33 2005 Subject: e-mail address change (was Re: [Tutor] python's default argument value handling in functions - weird syntax? problem grappling with the concept) In-Reply-To: <4b3125cc050209131917b2cfe7@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0502091344050.10744-100000@hkn.eecs.berkeley.edu> On Thu, 10 Feb 2005, Jeffrey Lim wrote: > > > > > >Example 1 > > > >>> def f(a,L=[]): > > >... if L==[5]: > > >... print 'L==[5] caught' > > >... print L > > >... print 'resetting L...' > > >... L=[] > > >... L.append(a) > > >... return L > > >... Hi Jeffery, At the beginning of a function call, if a function has default parameter values, then the parameters get aimed at those default values. So every time through the call to f() here, L will initially refer to that list value. I liked your experiments in your earlier post. Let's run through your example, and see if our explanation matches with reality. *grin* To make talking abou this a little less confusing, do you mind if I change the definition slightly, to this? ### initialList = [] def f(a,L=initialList): if L==[5]: print 'L==[5] caught' print L print 'resetting L...' L=[] L.append(a) return L ### It should have about the same effect as your previous code, but with the advantage of letting us poke around at the list that's being used as the default value. Ok, let's try this out. ### >>> f(5) [5] ### Ok, at this point, the 'default value' that initialList refers to should also be [5]. Let's check this. ### >>> initialList [5] ### Ok, good. Now we call f(5) again: ### >>> f(5) L==[5] caught [5] resetting L... [5] ### The reassignment to L in the 'if' block: if L==[5]: print 'L==[5] caught' print L print 'resetting L...' L=[] doesn't do any mutation on the actual default value. L is just a name that can be aimed at values: rebinding L through assignment doesn't "mutate" the list value. We'll talk about this again later in this post. We can look at the default value again by peeking at it through initialValue again: ### >>> initialList [5] ### So if we call f() again, since L is always bound to the default value, Let's call f(2) one more time. ### >>> f(2) L==[5] caught [5] resetting L... [2] ### Yup. The reassignment of L still doesn't do anything to the value that L is referring to, so subsequent calls to f() should continue to say "resetting L". Does this make sense so far? Please feel free to ask questions on any part that seems wacky, and we'll try to make sense out of it. *grin* Looking back at the program, I think that you meant to write: ### initialList = [] def f(a,L=initialList): if L==[5]: print 'L==[5] caught' print L print 'resetting L...' del L[:] ## Resets the initial value to the empty list L.append(a) return L ### The change here is the commented line: del L[:] ## Resets the initial value to the empty list which causes the list that we refer to as "L" to shrink down to the empty list. There are a few tricky subtleties here, and we have to keep in mind the distinction between a "name" and a "value". 'names' are like fingers that point at 'values'. Python handles default parameters by pointing the parameter name to a default value when it enters a function. So if we want to do things that make the default parameter appear to "change", we have to mutate the value that the parameter is pointed at. Hope this helps! From alan.gauld at freenet.co.uk Wed Feb 9 23:07:17 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Feb 9 23:07:14 2005 Subject: [Tutor] print out lines that start with a word References: <20050209053656.60027.qmail@web20326.mail.yahoo.com> Message-ID: <078f01c50ef3$b89a02f0$68b78851@xp> > I'm trying to get only the lines that start with > "This" for a text file. > > Here's what I wrote: > > >>> import re > >>> f = open('c:/lines.txt').readlines() > >>> for line in f: > match = re.search('^This',f) > if line == match: > print match try if line.startwith('This'): its easier! But your problem above is that match returns a match object which is not a string. So you can't compare directly you need to extract the string from inside the match object! HTH Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From bvande at po-box.mcgill.ca Wed Feb 9 23:05:44 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed Feb 9 23:07:22 2005 Subject: [Tutor] help with refactoring needed -- which approach is more Pythonic? Message-ID: <420A8938.5040604@po-box.mcgill.ca> Hi all, I have data files with a format that can be scheamatized as: File Header Contents . . . File Header End Tag Node Header Contents . . . Node Header End Tag Node Contents . . . Node End Tag [Repeat Node elements until end of file] I'm refactoring the heck out of a file conversion utility I wrote for this format back when I knew even less than I do now =:-0 The main change in refactoring is moving it to OOP. I have a method that serves as the entry point for parsing the files. It separates the file header content and the nodes (or body content), sending them each to appropriate methods to be processed. I want the body parser to accept a list of lines corresponding to the nodes portions of my file, separate out each node (everything between node end tags, the bottommost end tag included in the node), and send each node's contents to a further method for processing. What I have now works and is a big improvement on what I had before. But, I know that I tend to employ while loops more than I perhaps ought, and much of the style of OOP has yet to sink in. So, any suggestions on how to make this method more Pythonic would be most welcome. (body_contents is a list of file lines, with all file header lines removed.) . def body_parser(self, body_contents): . . while body_contents: . . count = 0 . current_node_contents = [] . . for line in body_contents: . current_node_contents.append(line) . count += 1 . if line == node_end_tag: # node_end_tag elsewhere . break # defined and includes '\n' . . self.node_parser(current_node_contents) . body_contents = body_contents[count:] Another alternative has occurred to me, but seems to compensate for the avoidance of while by being ugly. Untested code: . def alt_body_parser(self, body_contents): . . body_contents = ''.join(body_contents) . body_contents = body_contents.split(node_end_tag) . . # ugly lives here -- having removed node_end_tag's . # with split, I need to put them back on: . count = 0 . for i in body_contents: . body_contents[count] = i + node_end_tag . count += 1 . # (The sub-alternative of having the node_parser method . # put them back, while easier, also seems a dangerous . # separation of responsibility for the integrity of the data . # format.) . . for i in body_contents: . self.node_parser(i) So, which of these 2 (and a half) ways seems most Pythonic to the more experienced? Any better ways I've overlooked? Thanks, and best to all, Brian vdB From jfs.world at gmail.com Wed Feb 9 23:03:36 2005 From: jfs.world at gmail.com (Jeffrey Lim) Date: Wed Feb 9 23:11:08 2005 Subject: e-mail address change (was Re: [Tutor] python's default argument value handling in functions - weird syntax? problem grappling with the concept) In-Reply-To: <6.1.2.0.0.20050209144944.0331dd48@mail.mric.net> References: <4b3125cc050209121418102fbb@mail.gmail.com> <6.1.2.0.0.20050209140553.026fc810@mail.mric.net> <4b3125cc050209131917b2cfe7@mail.gmail.com> <4b3125cc05020913227e0c5e88@mail.gmail.com> <6.1.2.0.0.20050209144944.0331dd48@mail.mric.net> Message-ID: <4b3125cc050209140354a1ec83@mail.gmail.com> On Wed, 09 Feb 2005 14:51:42 -0700, Bob Gailer <bgailer@alum.rpi.edu> wrote: > At 02:22 PM 2/9/2005, Jeffrey Lim wrote: > >and have the Common Courtesy to stop hijacking or rewriting other > >people's thread titles unnecessarily pls. (Like when was this thread > >ever about the change of email address change on your part???) > > I have no idea how this happened. My computer started acting funny. I had > to reboot it.. First I knew of the problem was when I saw the posting you > are referring to. Perhaps my box has a virus. > I will let all of posterity decide this for themselves (they will, anyway). I have never seen a virus act this way, nor should i think it would ever have reason to - without at least an attachment of itself. As it is, I will be so kind enough as to give you the benefit of the doubt, and to be courteous and friendly enough, and "equal-level footing perspective enough" to you in answering your implied question. -jf From alan.gauld at freenet.co.uk Wed Feb 9 23:18:07 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Feb 9 23:18:00 2005 Subject: [Tutor] executing SAS and passing parameters References: <592E8923DB6EA348BE8E33FCAADEFFFC0B13DC34@dshs-exch2.dshs.wa.lcl> Message-ID: <07c301c50ef5$3c180270$68b78851@xp> > os.execl('C:\Program Files\SAS Institute\SAS\V8\SAS.exe') You might find that os.system() is all you need here, but if execl works don't worry too much. > However, the program in question is c:\work\run_ratios.sas, with 2 > parameters: incov, and outcov. This program was initially invoked from an > aml program. The code that invoked SAS from this aml is: Wacky stuff it remindss me of JCL on an MVS mainframe. What exactly is AML? Is it a SAS specific thing? > &SYSTEM %.SASLOC% -SYSPARM %sas_parm% -log ~ > %.ARCLOC%\ratios\log\%.file%.log -SYSIN ~ > %.ARCLOC%\sas_code\ratios\new_ratio.sas I'm assuming the ~ characters are line continuations? So the above is effectively one long line? If so translating it becomes: <path>/sas.exe -<params> -log <path>/%file%.log -f(?) <path>new_ratio.sas If so, you could try that from your command prompt. If it works just build the string and insert it into an os.system() call. I think the real issue here is extracting the actuial command line from the AML code (and probably the SAS documentation for startup parameters). Once you've got it working from an interactive command line (ie Cmd.exe Box in NT) then getting Python to replicate that should be straighforward. Alan G. From alan.gauld at freenet.co.uk Wed Feb 9 23:32:07 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Feb 9 23:33:11 2005 Subject: [Tutor] python's default argument value handling in functions -weird syntax? problem grappling with the concept References: <4b3125cc050209121418102fbb@mail.gmail.com> Message-ID: <07ca01c50ef7$30c70ef0$68b78851@xp> > This leads me to at first conclude several things: > > 1. 'L' in this case (or by extension, all function arguments for which > a default is given in the function definition) is "static" Pretty close, yes. Especially if the parameter is mutable. > language definition). This is my conclusion, seeing as how 'L' can > seem to retain its value even though it has gone out of scope after > the 'f' function returns. Thats right, the default value is evaluated once only, it keeps that initial value for all future invocations. But if it is mutable the list object(in the example) is the same list but the content of the list can be changed on each invocation. > 2. (*Now this is where I start to get confused. I think the best way > to illustrate how I am having problems is to illustrate with a few > examples. The basic problem that I am having is, "Which L is which > L?") > > My examples... > > Example 1 > >>> def f(a,L=[]): > ... if L==[5]: > ... print 'L==[5] caught' > ... print L > ... print 'resetting L...' > ... L=[] Here you reassign L to a completely new list, but the original default one is still lurking i the background complete with the changes you made earlier. > ... L.append(a) > ... return L You now return your new list. > >>> f(5) > [5] > >>> f(5) > L==[5] caught > [5] > resetting L... > [5] > >>> f(2) > L==[5] caught So we go back to the original default > [5] > resetting L... And you create another new list > [2] And return it. > Example 2 > >>> def f(a,L=None): > ... if L==[5]: > ... print 'caught, printing, resetting' > ... print L Should never happen unless you call f(a,[5]) that is never triggered for the default value. > ... L=[] but now creates a brand new L regardless of what was passed in > ... else: > ... L=[] Create another new L > ... L.append(a) > ... return L And modify and return the new list. > ... > >>> f(5) > [5] > >>> f(6) > [6] So in both cases you return a new list, the original default None is still there but you ignore it! > So when the default value for 'L' is an empty list, the test > condition, _once triggered_, *always* catches? No, it only catches if you pass in a value otherwise the default will still be None. Notice your if branch was not executed in either case above, only the return value is shown. > But when the default value for 'L' is none, the 'if' never catches? Because the default is None, the if only catches if you override the default with a matching list. > Or even consider the example given - > def f(a, L=None): > if L is None: > L = [] > L.append(a) > return L > > How is 'L == None' even possible all the time, given that for Because the value is only evaluated *once*. The default is set forever to None which is *immutable* - you cant change it, only overwrite it. > def f(a, L=[]): > L.append(a) > return L > , L isn't even [] except for the first call to 'f'? The value is set only once, the list is created and the same list object is used each time. But because list objects are *mutable* you can change the *contents* of the list, but you can never change the default list itself. Its just as the docs say. BUt don;t try to hard to think in terms of C. This is Python not C and it works differently. In C parameters etc are locations on the memory stack. In Python they are entries in a dictionary. Very different concepts and they result in very different behaviour! HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Wed Feb 9 23:38:20 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Feb 9 23:38:23 2005 Subject: [Tutor] python's default argument value handling in functions -weird syntax? problem grappling with the concept References: <4b3125cc050209121418102fbb@mail.gmail.com><82975b0c050209131271b13ffa@mail.gmail.com> <4b3125cc0502091356730da149@mail.gmail.com> Message-ID: <07df01c50ef8$0f972890$68b78851@xp> > > My questions: > - is the '==' operation a 'list' comparison - rather than a pointer > comparison? (my experiments seem to indicate that it is a 'list' > comparison) Forget pointers and all you ever knew of them from C. Trying to think of Python in terms of Pointers is ultimately an excercise in frustration. Python uses dictionaries for its indirection not memory addresses. > - if this is the case, then why does the 'if L==[5]' test still catch > later on, when the 'L' should no longer be a '[5]' list? It shouldn't! Are you absolutely sue about that? I didn't see a case in your examples where the [5] case would fail... > - if this is *not* the case then, then how do you determine the '==' > is supposed to match? It should match if both are [5] > - or is this a matter of 'compare by value' first, then after we get a > match, we 'compare by reference' later on??? The actual semanics of omparisons for all Pythons types are described in the Language reference. But mostly you can ignore it and it will just work... Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From jfs.world at gmail.com Wed Feb 9 23:30:59 2005 From: jfs.world at gmail.com (Jeffrey Lim) Date: Wed Feb 9 23:49:49 2005 Subject: e-mail address change (was Re: [Tutor] python's default argument value handling in functions - weird syntax? problem grappling with the concept) In-Reply-To: <Pine.LNX.4.44.0502091344050.10744-100000@hkn.eecs.berkeley.edu> References: <4b3125cc050209131917b2cfe7@mail.gmail.com> <Pine.LNX.4.44.0502091344050.10744-100000@hkn.eecs.berkeley.edu> Message-ID: <4b3125cc0502091430eba2810@mail.gmail.com> On Wed, 9 Feb 2005 14:05:23 -0800 (PST), Danny Yoo <dyoo@hkn.eecs.berkeley.edu> wrote: > > [snip] > > Does this make sense so far? YES!!! Most perfectly!!! Thanks for your detailed step-by-step analysis man - it was very helpful, and much appreciated... > > Looking back at the program, I think that you meant to write: > > ### > initialList = [] > def f(a,L=initialList): > if L==[5]: > print 'L==[5] caught' > print L > print 'resetting L...' > del L[:] ## Resets the initial value to the empty list > L.append(a) > return L > ### > yeah man - i guess i was just still stuck in the "non-object-oriented" thinking rut... I believe you have just about clarified all the doubts that i've had about the whole thing which prompted my question to the list in the first place! thanks a lot... -jf From abli at freemail.hu Wed Feb 9 23:50:49 2005 From: abli at freemail.hu (Abel Daniel) Date: Wed Feb 9 23:50:24 2005 Subject: [Tutor] Re: python's default argument value handling in functions - weird syntax? problem grappling with the concept In-Reply-To: <4b3125cc050209121418102fbb@mail.gmail.com> (Jeffrey Lim's message of "Thu, 10 Feb 2005 04:14:05 +0800") References: <4b3125cc050209121418102fbb@mail.gmail.com> Message-ID: <E1Cz0fZ-0001gc-K2@localhost.localdomain> quoted lines are from Jeffrey Lim [... I have rearranged the order of the quotes ...] > How is 'L == None' even possible all the time, given that for > def f(a, L=[]): > L.append(a) > return L > , L isn't even [] except for the first call to 'f'? This is the important point. You see, its true that L != [] for those calls, but despite this, L _is_ []. I guess this sounds wierd, so I'll clarify it: Lets try it with a little modification. Instead of "def f(a, L=[])", we will use "def f(a, L=l)", where l is an empty list. This surely shouldn't cause any difference, should it? >>> l=[] >>> def f(a, L=l): ... L.append(a) ... return L ... >>> f(1) [1] >>> f(2) [1, 2] >>> f(3) [1, 2, 3] So far, so good. Now lets see whether L is [] or not: >>> a=f(4) # so now a is whatever L was inside the function >>> a == l True and: >>> a is l True So L _is_ [], isn't it? How can this happen? After all, by now L is [1,2,3,4], right? And l is an empty list, right? Well, wrong: >>> l [1, 2, 3, 4] So the strange thing is that even though L is _not_ [] (as in, its not an empty list) it _is_ [] in some sence. That is, it is the _same_ list which was [] once. This second sentence might sound pretty wierd. You have to keep in mind, that every time you type [], python will create a _new_, empty list. This means that: >>> [] is [] False The big difference between the "def f(a, L=[])" and "def f(a, L=None)" cases is that in the first, L is a list, and lists are mutable. In the second, L is None and obviously, None is not mutable. In both cases you give an object as a default value. In both cases, L will _allways_ be this object at the first line of the function when you call the function. The difference is that in the first case, although you can't change the _identity_ of the default value, you can change its _content_ . And thats what you do with the line "L.append(a)". Keep in mind that L=[] does _not_ copy the list. In fact, in python even a=5 does not copy anything. In C, variables might be thought of as little drawers that have something in them. When you say a=b, the contents of b get copied to a. In python, however, variables are better thought of as labels. When you say a=5, you put a label on the number 5 object. Its like saying "I want to be able to call that number a". When doing a=b, there is no copying, what happens is that the label 'a' gets moved to the object which has the label 'b' on it. In the previous paragraph, I have written "when you say a=5, you put a label on the number 5 object". Maybe I should have written "you put a label on a number 5 object". Notice the difference? For numbers, one could claim that there is no difference. After all, there is only one number 5, right? However, as we have seen above, for lists, you can't claim the same. There is no _the_ []. Every '[]' will create a new one. If you think of variables as labels on objects, and objects as having content and identity, everything should become clear. ('==' compares by value, that is, by content, 'is' compares by identity. Make sure not to mix identity with eguality.) Recommended reading: http://www.effbot.org/zone/python-objects.htm (understanding python objects, pretty short) http://starship.python.net/crew/mwh/hacks/objectthink.html ("variables as labels", a bit longer) ps. For extra wierdness, in python "there is only one number 5" isn't true for large numbers: >>> a=100 >>> b=100 >>> a is b False Using a large number is important: integers up to 99 are cached, so they _are_ unique (we would get True above). For larger numbers, the cacheing is more subtle, for example: >>> a, b = 100, 100 >>> a is b True -- Abel Daniel From jfs.world at gmail.com Wed Feb 9 23:57:54 2005 From: jfs.world at gmail.com (Jeffrey Lim) Date: Wed Feb 9 23:57:56 2005 Subject: [Tutor] python's default argument value handling in functions -weird syntax? problem grappling with the concept In-Reply-To: <07df01c50ef8$0f972890$68b78851@xp> References: <4b3125cc050209121418102fbb@mail.gmail.com> <82975b0c050209131271b13ffa@mail.gmail.com> <4b3125cc0502091356730da149@mail.gmail.com> <07df01c50ef8$0f972890$68b78851@xp> Message-ID: <4b3125cc0502091457f1eedd9@mail.gmail.com> On Wed, 9 Feb 2005 22:38:20 -0000, Alan Gauld <alan.gauld@freenet.co.uk> wrote: > > > > My questions: > > > > [snip] > > [snip] > > HTH, yes it did! I've already gotten it - but your explanation was just simply beautiful (it really is). Thanks for the note about "not in think in terms of C" as well - I'll have to remember that! Appreciate it, -jf ps. sorry for the double send, Alan - i forgot to send to the list as well. From jfs.world at gmail.com Thu Feb 10 00:22:02 2005 From: jfs.world at gmail.com (Jeffrey Lim) Date: Thu Feb 10 00:28:49 2005 Subject: [Tutor] Re: python's default argument value handling in functions - weird syntax? problem grappling with the concept In-Reply-To: <E1Cz0fZ-0001gc-K2@localhost.localdomain> References: <4b3125cc050209121418102fbb@mail.gmail.com> <E1Cz0fZ-0001gc-K2@localhost.localdomain> Message-ID: <4b3125cc0502091522316346aa@mail.gmail.com> On Wed, 09 Feb 2005 23:50:49 +0100, Abel Daniel <abli@freemail.hu> wrote: > > quoted lines are from Jeffrey Lim > [... I have rearranged the order of the quotes ...] > thanks, Abel! Especially for the part on the 'C' concept of variables, vs that of Python's (and the links, as well). appreciated it, and thanks, all, for such a great "first-time tutor list experience" already, -jf From dyoo at hkn.eecs.berkeley.edu Thu Feb 10 00:58:39 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Feb 10 00:58:43 2005 Subject: [Tutor] help with refactoring needed -- which approach is more Pythonic? In-Reply-To: <420A8938.5040604@po-box.mcgill.ca> Message-ID: <Pine.LNX.4.44.0502091540360.28687-100000@hkn.eecs.berkeley.edu> On Wed, 9 Feb 2005, Brian van den Broek wrote: > Hi all, > > I have data files with a format that can be scheamatized as: > > File Header Contents > . . . > File Header End Tag > Node Header Contents > . . . > Node Header End Tag > Node Contents > . . . > Node End Tag > [Repeat Node elements until end of file] [some text cut] > . def body_parser(self, body_contents): > . while body_contents: > . count = 0 > . current_node_contents = [] > . for line in body_contents: > . current_node_contents.append(line) > . count += 1 > . if line == node_end_tag: # node_end_tag elsewhere > . break # defined and includes '\n' > . self.node_parser(current_node_contents) > . body_contents = body_contents[count:] Hi Brian, Ah, this looks like the perfect place for helper functions. *grin* Conceptually, the code applies the method 'self.node_parser'() on a sequence of nodes. We can reshape the code above so it works like this: ### def partition_node_content(body_contents): """Returns a sequence of node-element content.""" pass ## FIXME: fill me in def body_parser(self, body_contents): for node_content in partition_node_content(body_contents): self.node_parser(node_content) ### Helper functions are key to making this look nicer. We let our 'partition_node_content()' function handle the bundling up of lines for us. We can yank out part of the original code to write partition_node_content(), like this: ### def partition_node_content(body_contents): partitions = [] while body_contents: count = 0 current_node_contents = [] for line in body_contents: current_node_contents.append(line) count += 1 if line == node_end_tag: # node_end_tag elsewhere break # defined and includes '\n' partitions.append(current_node_content) body_contents = body_contents[count:] return partitions ### But we can make this even nicer; some of the stuff that deals with 'count' --- and the while loop too! --- can dissolve if we iterate directly across the elements of body_contents: ### def partition_node_content(self, body_contents): """Splits apart body_contents into a bunch of node_content lists.""" partitions = [] current_node_contents = [] for line in body_contents: if line == node_end_tag: partitions.append(current_node_contents) current_node_contents = [] return partitions ### If we want to be fancy, we can also take advantage of Python's generator support to avoid constructing an explicit list: ### def partition_node_content(self, body_contents): """Returns an iterator whose contents are a bunch of node_content lists.""" current_node_contents = [] for line in body_contents: if line == node_end_tag: yield current_node_contents current_node_contents = [] ### This generator behaves similarly, and can potentially save on memory use, since it streams chunks of node content back. Best of wishes to you! From dyoo at hkn.eecs.berkeley.edu Thu Feb 10 01:06:25 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Feb 10 01:06:30 2005 Subject: [Tutor] help with refactoring needed -- which approach is more Pythonic? In-Reply-To: <Pine.LNX.4.44.0502091540360.28687-100000@hkn.eecs.berkeley.edu> Message-ID: <Pine.LNX.4.44.0502091600500.28687-100000@hkn.eecs.berkeley.edu> > If we want to be fancy, we can also take advantage of Python's generator > support to avoid constructing an explicit list: > > ### > def partition_node_content(self, body_contents): > """Returns an iterator whose contents are a bunch of > node_content lists.""" > current_node_contents = [] > for line in body_contents: > if line == node_end_tag: > yield current_node_contents > current_node_contents = [] > ### Hi Brian, Oh good grief. *grin* That last snippet won't work; I had forgotten about appending lines into current_node_contents. Here's a revision of the silly code: ### def partition_node_content(self, body_contents): """Returns an iterator whose contents are a bunch of node_content lists.""" current_node_contents = [] for line in body_contents: current_node_contents.append(line) if line == node_end_tag: yield current_node_contents current_node_contents = [] ### I wanted to add that the generator approach should have the same performance characteristic as your original code. Your original code's approach interleaved the bundling of the body_content with calls to the node parser. The approach with the separate list bundling behaves a little bit differently: it tries to build a list of all the node_content chunks, and then processes that list element by element. The generator approach, like your original code, interleaves the bundling with the node_content parsing. My apologies! From bvande at po-box.mcgill.ca Thu Feb 10 01:52:18 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Thu Feb 10 01:52:37 2005 Subject: [Tutor] help with refactoring needed -- which approach is more Pythonic? In-Reply-To: <Pine.LNX.4.44.0502091600500.28687-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0502091600500.28687-100000@hkn.eecs.berkeley.edu> Message-ID: <420AB042.1070300@po-box.mcgill.ca> Danny Yoo said unto the world upon 2005-02-09 19:06: >>If we want to be fancy, we can also take advantage of Python's generator >>support to avoid constructing an explicit list: >> <SNIP code like that below but missing the .append()> > > Hi Brian, > > > Oh good grief. *grin* > > That last snippet won't work; I had forgotten about appending lines into > current_node_contents. Here's a revision of the silly code: > > > ### > def partition_node_content(self, body_contents): > """Returns an iterator whose contents are a bunch of > node_content lists.""" > current_node_contents = [] > for line in body_contents: > current_node_contents.append(line) > if line == node_end_tag: > yield current_node_contents > current_node_contents = [] > ### > > > I wanted to add that the generator approach should have the same > performance characteristic as your original code. > > Your original code's approach interleaved the bundling of the body_content > with calls to the node parser. The approach with the separate list > bundling behaves a little bit differently: it tries to build a list of all > the node_content chunks, and then processes that list element by element. > The generator approach, like your original code, interleaves the bundling > with the node_content parsing. > > > My apologies! Hi Danny, Apologies, while nice, aren't needed; catching your small thinko was the easy part of the generator code. :-) (Of the parts of Python about which I am still fuzzy, generators are among the fuzziest.) And thank you for the replies. Given that in my application, neither performance nor memory use matter too much, are there are grounds (beyond bare personal preference) to choose amongst the approaches? (Having rejected personal preference and performance as criterion, one might well wonder what's left? I mean something like community consensus about which is more elegant, etc. where there is enough agreement to take it out of the realm of pure personal preference. And, seeing how I've phrased it, I think `that's unanswerable' might well be a perfectly acceptable answer. :-) ) Alternatively, of the two ways you gave (the generator above and the helper function route), which seems better? All I have to guide me is unfamiliarity with generators, and that isn't the best compass. Thanks again, Brian vdB From carroll at tjc.com Thu Feb 10 02:41:33 2005 From: carroll at tjc.com (Terry Carroll) Date: Thu Feb 10 02:41:37 2005 Subject: [Tutor] executing SAS and passing parameters In-Reply-To: <592E8923DB6EA348BE8E33FCAADEFFFC0B13DC34@dshs-exch2.dshs.wa.lcl> Message-ID: <Pine.LNX.4.44.0502091628170.20869-100000@violet.rahul.net> I'd echo what Alan said. It sounds more like you're having trouble finding out what the command line to SAS should look like, rather than invoking it with Python. (I'm going to quote some of your message out-of-order to better facilitate my approach to this. I will, I trust, not misrepresent the context.) On Wed, 9 Feb 2005, Williams, Thomas wrote: > However, the program in question is c:\work\run_ratios.sas, with 2 > parameters: incov, and outcov. This program was initially invoked from an > aml program. The code that invoked SAS from this aml is: > > &SYSTEM %.SASLOC% -SYSPARM %sas_parm% -log ~ > %.ARCLOC%\ratios\log\%.file%.log -SYSIN ~ > %.ARCLOC%\sas_code\ratios\new_ratio.sas > > %.SASLOC%: the SAS executable file ('C:\Program Files\SAS > Institute\SAS\V8\SAS.exe') > %sas_parm%: the list of parameters to be passed onto SAS > %.file%: the name of the log file that is generated during the execution of > the SAS program. > %.ARCLOC%: directory of the SAS program (c:\work) First, something's not jibing here: you say the program to run is c:\work\run_ratios.sas , but none of the variables under AML appear to have "run_ratios" in it. (Not that I know what AML is). My expectation is that this code: > &SYSTEM %.SASLOC% -SYSPARM %sas_parm% -log ~ > %.ARCLOC%\ratios\log\%.file%.log -SYSIN ~ > %.ARCLOC%\sas_code\ratios\new_ratio.sas Expands to an invocation of this: """ C:\Program Files\SAS Institute\SAS\V8\SAS.exe -SYSPARM incov outcov -log c:\work\ratios\log\[logfilename].log -SYSIN c:\work\sas_code\ratios\new_ratio.sas """ (where [logfilename] is actually replaced with the name of your logfile.) As I said, no reference to "c:\work\run_ratios.sas" in this; so confirm this. My suggestion is that you open up an MSDOS window, and try variations on this until you find one that works. Once you find one that works, you know your command; and that's going to be 95% of the battle. In your Python code: > os.execl('C:\Program Files\SAS Institute\SAS\V8\SAS.exe') First, as Alan points out, try os.system() instead. I would also very much encourage a piece of advice he gave that might have slipped through, which is: build a string, first, and pass that string to os.system(). That way, you can do some debugging by making sure your string represents the command you cane up with earlier. I'd also recommend using forward slashes rather than backslashes, which saves you some escape heartache. Forward slashes should still work. You can also do something along the same lines your AML took, if you like: SAS_location = "C:/Program Files/SAS Institute/SAS/V8/SAS.exe" sas_parm = "incov outcov" ARC_location = "c:/work/" logfile = "ratios/mylog.log" SAS_SYSIN = "sas_code/ratios/new_ratio.sas" command_line = "%s -SYSPARM %s -log %s%s -SYSIN %s%s" % (SAS_location, sas_parm, ARC_location, logfile, ARC_location, SAS_SYSIN) print command_line # above line verifies the command matches what you determined from the # earlier testing from the MS-DOS command line os.system(command_line) # invoke SAS From ismaelgf at adinet.com.uy Thu Feb 10 04:07:11 2005 From: ismaelgf at adinet.com.uy (Ismael Garrido) Date: Thu Feb 10 04:06:47 2005 Subject: e-mail address change (was Re: [Tutor] python's default argument value handling in functions - weird syntax? problem grappling with the concept) In-Reply-To: <Pine.LNX.4.44.0502091344050.10744-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0502091344050.10744-100000@hkn.eecs.berkeley.edu> Message-ID: <420ACFDF.2080402@adinet.com.uy> Danny Yoo wrote: >### > >def f(a,L=[]): > if L==[5]: > print 'L==[5] caught' > print L > print 'resetting L...' > L=[] > L.append(a) > return L > > >### > Now I'm dizzy... I can't understand why there are two "L"! L is a local variable of the function, right? (I can't imagine it being anything else) Then if I reassign L to something, why doesn't it keep that change till next run? At least, it keeps the values in the list.. so it should keep the reassignation, no? I'm completly puzzled :-S Ismael From maxnoel_fr at yahoo.fr Thu Feb 10 04:26:06 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu Feb 10 04:26:13 2005 Subject: e-mail address change (was Re: [Tutor] python's default argument value handling in functions - weird syntax? problem grappling with the concept) In-Reply-To: <420ACFDF.2080402@adinet.com.uy> References: <Pine.LNX.4.44.0502091344050.10744-100000@hkn.eecs.berkeley.edu> <420ACFDF.2080402@adinet.com.uy> Message-ID: <022b560bc49cafd2091f0ea260eb08c6@yahoo.fr> On Feb 10, 2005, at 03:07, Ismael Garrido wrote: > Danny Yoo wrote: > >> ### >> >> def f(a,L=[]): >> if L==[5]: >> print 'L==[5] caught' >> print L >> print 'resetting L...' >> L=[] >> L.append(a) >> return L >> >> ### >> > Now I'm dizzy... I can't understand why there are two "L"! > L is a local variable of the function, right? (I can't imagine it > being anything else) Then if I reassign L to something, why doesn't it > keep that change till next run? At least, it keeps the values in the > list.. so it should keep the reassignation, no? > I'm completly puzzled :-S It's not L you have to look at but the default value itself. L is local to the function and recreated each time you run it. The default value, however (which has no name, so I'm gonna call it "defVal"), is static (in the Java/C++ sense of the word -- it's only created once). The first time you run the function, defVal is set to [] and then it is assigned to L (as in, L = defVal). Since defVal is a list, L and defVal are actually two names for the same variable. Thus, when you append something to L, it is appended to defVal as well. However, when you do L = [], you're binding the name L to another variable (which you create on the spot). But the name defVal is still bound to the same variable! Thus, when you run the function again, you get defVal as you left it. # Let's consider that defVal == [5] (say, you've already called f(5)) and call f(10): if L == [5]: # L == defVal == [5] (they are the same variable) L = [] # Re-binding the name: a new var is created. L == []; defVal == [5] L.append(a) # L == [10]; defVal == [5]. See what I mean? -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From johan at accesstel.co.za Thu Feb 10 06:43:04 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Thu Feb 10 06:45:01 2005 Subject: [Tutor] Hex to Str - still an open issue In-Reply-To: <42089086.8010407@cirad.fr> References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> <041401c50ae9$63c21a50$68b78851@xp> <00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> <f2ff2d050205034498e84e@mail.gmail.com> <4204EAB1.2050206@tds.net> <1107856983.4603.6.camel@KMA.accesstel> <42089086.8010407@cirad.fr> Message-ID: <1108014184.4623.1.camel@KMA.accesstel> I am not so clued up on the 'base 2' and 'base 8' stuff. Care to explain that a little? Johan On Tue, 2005-02-08 at 12:12, Pierre Barbier de Reuille wrote: > MMmmhh ... no ! > > The number you wrote is equivalent to '010' and any number beginning by > '0' and not followed by "x" will be considered octal. So "10" in base 8 > is ... 8 :) > > If you want to convert a number from base 2 to base 10 write : > > >>> int("0000000010", 2) > 2 > > Pierre > > Johan Geldenhuys a ?crit : > > Hi everybody, > > I used binary.py and is a bit puzzled by the results I get when > > comparing the binary of decimal 2 and the value I get when I convert the > > binary to an int. > > > > > >>>>binary(2) > > > > '00000000000000000000000000000010' > > > >>>>int(00000000000000000000000000000010) > > > > 8 > > > > > > Isn't the int value of this binary string supposd to be '2' and not '8'? > > > > Johan > > On Sat, 2005-02-05 at 17:48, Kent Johnson wrote: > > > > > >>Liam, > >> > >>I think you misunderstand what endianness is. > >> > >>Big-endian and little-endian refer to the way a number is stored as bytes in the underlying memory > >>of the computer. This is not something you generally need to worry about in a Python program. > >> > >>For example, consider the number 0x12345678. On most modern computers this will be stored in four > >>consecutive bytes of computer memory. The individual bytes will contain the values 0x12, 0x34, 0x56, > >>0x78. The question is, what is the order of those bytes in memory? On a big-endian computer, the > >>most significant byte - 0x12 - is stored at the lowest memory address, so the sequence of bytes will > >>be 0x12, 0x34, 0x56, 0x78. On a little-endian computer, the least-significant byte is stored at the > >>lowest address, and the order will be reversed: 0x78, 0x56, 0x34, 0x12. > >> > >>Most programming languages will hide this detail from you most of the time. Even in assembly > >>language, you generally load and store integers without worrying about endianness. Math operations > >>just do the right thing so you don't have to worry about it. > >> > >>Endianness becomes an issue when you want to convert between representations, and when binary data > >>is shared between computers which may have different endianness. > >> > >>For example in a C program you might want to get the high byte of an integer when you know the > >>address of the integer. The desired byte will be at (address+0) or (address+3) depending on the > >>endianness of the hardware. > >> > >>Similarly, if an array of integers is written to a file in a binary representation (not as ASCII > >>strings representing the integers, but as 32-bit values), then to correctly read the file you have > >>to know the endianness of the data in the file. > >> > >> > >>OK, so what does this have to do with converting a number to binary in Python? Well, nothing, > >>actually. First, note that 'binary representation' can mean two different things. In the description > >>above, I was talking about the actual bit pattern stored in the computer. Python works with binary > >>numbers all the time, in this sense, but it is under the hood. The other meaning of 'binary > >>representation' is that of a base-2 string representation of a number. > >> > >>So if you ask, "How do I convert a number to binary?" you can mean either of these. > >> > >>The first one is trivial. If you have a decimal string representation of the number, use int() to > >>convert it to binary. If you have an integer already, it's already *in* binary, so you don't have to > >>do anything! > >> > >>So, "How do I convert a number to binary?", to be interesting, must mean "How do I convert an > >>integer to a base-2 string representation?" And how do you do this? Well, you figured out one way > >>using the mathematical properties of integers. These operations are independent of endianness, and > >>so is the desired result. > >> > >>The base-2 string representation of the number (whose base-16 string representation is) 0x1234 is > >>'0001001000110100'. The order of digits here is determined by our convention of writing the most > >>significant digits on the left, not by the endianness of the underlying computer. > >> > >>OK, this is long enough, I hope I have shed some light... > >>Kent > >> > >> > >> > >>Liam Clarke wrote: > >> > >>>Jacob - just for you, begin your agitation for the next release please ;) > >>> > >>>binstring.py, as attached. > >>>(also pasted up - http://www.rafb.net/paste/results/5feItM57.html) > >>> > >>>Creating this, was just a brain teaser, but I was thinking 'what if I > >>>wanted to make this for the standard library.' > >>> > >>>And so you can see, I had to include a flag for endianess. But that > >>>was really a cheap trick. If this was going into a standard library, > >>>I'd want to query the OS for endianess. As for the bits, once again, > >>>32 bit is the norm, but 64 bit is here and spreading. > >>> > >>>Also, should it display 11111111 as 255 or 256? Both are valid, > >>>depending on context. > >>> > >>>Thirdly, if I can do it in 2 minutes, (well, the main part), then > >>>should they bother putting it in the standard library considering > >>>also, > >>> > >>>- How often, really, are you going to need to present a decimal or hex > >>>as a binary string. > >>> > >>>Lastly - this only does base 10 to base 2. Should I include a base 6 > >>>to base 2, base 8 to base 2, base 10 to 6, 10 to 8, 8 to 6? > >>> > >>>I wouldn't like to write for the standard library, because you can > >>>never please everyone. > >>> > >>>But yeah, feel free to use the above, just keep my doc strings and comments. > >>> > >>>Regards, > >>> > >>>Liam Clarke > >>> > >>>On Fri, 4 Feb 2005 23:30:19 -0500, Jacob S. <keridee@jayco.net> wrote: > >>> > >>> > >>>>>The binary value is the same as the hex value. > >>>>>The binary representation is 000111110100, but > >>>>>unfortunately Python doesn't support binary in > >>>>>its string formatting(although it does in int()! > >>>> > >>>>Uh, question. Why not? It seems that all simple types should be included. > >>>>Since the computer stores it as binary, why shouldn't python be able to > >>>>display a > >>>>string of it in binary? That seems to be a short coming that should be added > >>>>to the > >>>>next release... IMHO of course. > >>>>Jacob Schmidt > >>>> > >>>>_______________________________________________ > >>>>Tutor maillist - Tutor@python.org > >>>>http://mail.python.org/mailman/listinfo/tutor > >>>> > >>> > >>> > >>> > >>> > >>>------------------------------------------------------------------------ > >>> > >>>###### > >>># binString.py > >>># by Liam Clarke > >>>#(Let me know when it's included in the standard library ;-)) > >>>###### > >>> > >>>"""Converts a integer base 10 to a string base 2""" > >>> > >>>def binary(decimalInt, bigEndian = True, bits = 32, truncExcess = False): > >>> """ > >>>Integer to be converted is essential, Endianess is an optional flag; > >>>me being a Win32 user, Endianess is big by default, defaults to a 32-bit > >>>representation, most integers in Python being 32 bit. truncExcess will > >>>strip place-holder zeros for succintness. > >>> > >>>Oh, and it will represent 11111111 as 256, as I'm not sure whether you want > >>>to start counting for zero with this. It's a simple matter to change.""" > >>> tempList = ['0' for x in range(bits)] > >>> > >>> for bitPlace in range(bits, -1, -1): > >>> if decimalInt - 2**bitPlace >= 0: > >>> tempList[bitPlace] = '1' > >>> decimalInt = decimalInt - 2**bitPlace > >>> if bigEndian: > >>> tempList.reverse() > >>> > >>> outPut = ''.join(tempList) > >>> > >>> if truncExcess: > >>> if bigEndian: > >>> outPut=outPut.lstrip('0') > >>> else: > >>> outPut=outPut.rstrip('0') > >>> > >>> return outPut > >>> > >>> > >>>------------------------------------------------------------------------ > >>> > >>>_______________________________________________ > >>>Tutor maillist - Tutor@python.org > >>>http://mail.python.org/mailman/listinfo/tutor > >> > >>_______________________________________________ > >>Tutor maillist - Tutor@python.org > >>http://mail.python.org/mailman/listinfo/tutor > > > > > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > -- > Pierre Barbier de Reuille > > INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP > Botanique et Bio-informatique de l'Architecture des Plantes > TA40/PSII, Boulevard de la Lironde > 34398 MONTPELLIER CEDEX 5, France > > tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 -- This E-Mail has been scanned. Enjoy Your Day. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050210/2fbaef82/attachment.htm From dyoo at hkn.eecs.berkeley.edu Thu Feb 10 07:26:38 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Feb 10 07:26:44 2005 Subject: e-mail address change (was Re: [Tutor] python's default argument value handling in functions - weird syntax? problem grappling with the concept) In-Reply-To: <420ACFDF.2080402@adinet.com.uy> Message-ID: <Pine.LNX.4.44.0502092220490.16545-100000@hkn.eecs.berkeley.edu> On Thu, 10 Feb 2005, Ismael Garrido wrote: > Danny Yoo wrote: > > >### > > > >def f(a,L=[]): > > if L==[5]: > > print 'L==[5] caught' > > print L > > print 'resetting L...' > > L=[] > > L.append(a) > > return L > >### > > > Now I'm dizzy... I can't understand why there are two "L"! Hi Ismael, Ok, let's ignore the default argument stuff for the moment. Let's change the program slightly, to the following: ### someList = [] def f(a): L = someList if L == [5]: print "L == [5] caught" print L print "Resetting L..." L = [] L.append(a) return L ### Try out Jeffrey's experiments, and see if you see anything unusual. Does what you see make sense to you, or is it still baffling? Please feel free to ask questions, and we'll go from there. Best of wishes to you! From alan.gauld at freenet.co.uk Thu Feb 10 08:58:58 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Feb 10 08:58:48 2005 Subject: [Tutor] help with refactoring needed -- which approach is morePythonic? References: <420A8938.5040604@po-box.mcgill.ca> Message-ID: <07fe01c50f46$60d84240$68b78851@xp> > The main change in refactoring is moving it to OOP. I have a method > that serves as the entry point for parsing the files. Not an object? If you are thinking terms of what the methods do its probably not OOP... I would expect to see an object for the File, another for the Header, a third for the Body and another for the Node. The first (containing a header and bosdy object) is responsible for cracking open the file and reading the lines, recognising where it has a header and sending those lines to the header object and the rest to the bosy object. The body object then reades those lines and creates a Node object per node feeding it lines as appropriate... > I want the body parser to accept a list of lines corresponding to the > nodes portions of my file, separate out each node (everything between > node end tags, the bottommost end tag included in the node), and > send each node's contents to a further method for processing. Or to another object? Nouns are objects, verbs are methods. > . def body_parser(self, body_contents): Pseudo code: class Body: def __init__(self,content): self.contents = contents self.nodes = [] def parse(self): for line in self.contents: if line == NodeStartTag: node = Node() if line == NodeEndTag: self.nodes.append(node) node.append(line) def __del__(self): del self.nodes > . self.node_parser(current_node_contents) class Node: def __init__(self,lines=[]): self.lines = lines def append(self,item): self.lines.append(item) def parse(self): # your parsing method here. Whats the advantage? If you have different node types you can easily subclass Node and not change the File or Body classes, just write a slightl'y different line parser. That way your code remains more stable - you never need to change working code to add a new node type... Just an alternative to consider.... Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Thu Feb 10 09:14:04 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Feb 10 09:13:45 2005 Subject: e-mail address change (was Re: [Tutor] python's default argumentvalue handling in functions - weird syntax? problem grappling withthe concept) References: <Pine.LNX.4.44.0502091344050.10744-100000@hkn.eecs.berkeley.edu> <420ACFDF.2080402@adinet.com.uy> Message-ID: <083101c50f48$7ce065b0$68b78851@xp> > >def f(a,L=[]): > > if L==[5]: > > print 'L==[5] caught' > > print L > > print 'resetting L...' > > L=[] > > L.append(a) > > return L > > > > > >### > > > Now I'm dizzy... I can't understand why there are two "L"! > L is a local variable of the function, right? L is a parameter if the function with a default value. That means its a special type of local variable that has a life outside the function. But while inside the function it acts just like a local variable. > anything else) Then if I reassign L to something, why doesn't it keep > that change till next run? Because local variables die and their contents are garbage collected at the end of the function. L goes back to its external life which points at the original default L. > so it should keep the reassignation, no? No, the whole point of this thread is that Python, as the documentation said, only evaluates the default value once, at function definition time, you *cannot* change it. After each function invocation all local changes are lost and it reverts to the ioriginal value. Alan G. From alan.gauld at freenet.co.uk Thu Feb 10 09:24:24 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Feb 10 09:24:30 2005 Subject: [Tutor] Hex to Str - still an open issue References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com><041401c50ae9$63c21a50$68b78851@xp><00ae01c50b3b$6b55d390$215428cf@JSLAPTOP><f2ff2d050205034498e84e@mail.gmail.com> <4204EAB1.2050206@tds.net><1107856983.4603.6.camel@KMA.accesstel> <42089086.8010407@cirad.fr> <1108014184.4623.1.camel@KMA.accesstel> Message-ID: <084b01c50f49$ee57d510$68b78851@xp> > I am not so clued up on the 'base 2' and 'base 8' stuff. > Care to explain that a little? base 2 is binary, base 8 is octal. We normally use base 10 decimal. The base refers to the biggest number that can be represented by a single digit. (Actually one less than the base because we start with zero!) Thus in base 10 we have digits 0,1,2...,8,9 In base 8 we have 0,1,2...,6,7 and in binary 0,1 When we need a number bigger than a single digit can represent we add another column, so 9+1 = 10, that is 1 ten plus zero units. Similarly in base 8 & + 1 = 10 ie one eight and no units and in base 2, 1+1 = 10 ie one two and zero units. So the same principles hold as we are used to in decimal but they just kick in at different points. But these are just representational issues, the underlying value is the same in each of the following cases: 9 - base 10 11 - base 8 1001 -base 2 You might also find base 16 - hexadecimal, or more commonly just hex. There the numbers between 10 and 15 are represented by letters: 0,1,....9,A,B,C,D,E,F So the decimal number 27 is represented in hex as 1B And to make it clear which base is being used computer languages adopt a simple convention of prefixing the digit in ambiguous cases: 012 = implies 12 in base 8 (because of the leading 0 0x12 = implies 12 in hex because of the leading 0x 12 = implies decimal 12, no prefix. HTH, A web search on 'number bases' or 'binary numbers' should throw up much more detailed info Alan G. From maxnoel_fr at yahoo.fr Thu Feb 10 09:27:38 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu Feb 10 09:28:37 2005 Subject: [Tutor] Hex to Str - still an open issue In-Reply-To: <1108014184.4623.1.camel@KMA.accesstel> References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> <041401c50ae9$63c21a50$68b78851@xp> <00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> <f2ff2d050205034498e84e@mail.gmail.com> <4204EAB1.2050206@tds.net> <1107856983.4603.6.camel@KMA.accesstel> <42089086.8010407@cirad.fr> <1108014184.4623.1.camel@KMA.accesstel> Message-ID: <26038a44985aebb1c871c2272f25ebc4@yahoo.fr> On Feb 10, 2005, at 05:43, Johan Geldenhuys wrote: > I am not so clued up on the 'base 2' and 'base 8' stuff. > Care to explain that a little? Usually, we use base 10 numbers, that is, numbers that can be represented with 10 symbols (0, 1, 2, 3, 4, 5, 6, 7, 8, 9). Binary, or base 2, represents all the numbers with only 2 symbols (0 and 1), whereas octal (base 8) uses 8 (0 to 7) and hexadecimal (base 16) uses 16 (0 to 9 then A to F). In binary, 0b10 = 2, and 0b100 = 4. In octal, 010 = 8 and 0100 = 64. In hexadecimal, 0x10 = 16 and 0x100 = 256. Is that clearer now? -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From bvande at po-box.mcgill.ca Thu Feb 10 09:34:42 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Thu Feb 10 09:35:16 2005 Subject: [Tutor] Hex to Str - still an open issue In-Reply-To: <1108014184.4623.1.camel@KMA.accesstel> References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> <041401c50ae9$63c21a50$68b78851@xp> <00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> <f2ff2d050205034498e84e@mail.gmail.com> <4204EAB1.2050206@tds.net> <1107856983.4603.6.camel@KMA.accesstel> <42089086.8010407@cirad.fr> <1108014184.4623.1.camel@KMA.accesstel> Message-ID: <420B1CA2.7080404@po-box.mcgill.ca> Johan Geldenhuys said unto the world upon 2005-02-10 00:43: > I am not so clued up on the 'base 2' and 'base 8' stuff. > Care to explain that a little? > > Johan > On Tue, 2005-02-08 at 12:12, Pierre Barbier de Reuille wrote: <SNIP much quoting of thread on bases among other things> Hi Johan, here's a go: We have 10 fingers. Not coincidentally, we have a base 10 number system. OK, what's that mean? Well, we have 10 primitive numerical symbols {0,1,2,3,4,5,6,7,8,9}. So, say we have 7 widgets and then we get another. No problem -- 8 widgets. Another -- 9. One more? Well, we are out of primitive symbols. 9 means nine units. If we add another to 9, we end up with one tens and zero units: 10. Each additional place gives us a new multiple of 10. So 10342 is one ten-thousands, zero thousands, three hundreds, four tens and two units. And, you might be thinking `Jeeze! I know all that.' Fair enough. Here's the switch: Say we had a number system with only 8 numerical primitives: {0,1,2,3,4,5,6,7). That is a base 8 system. (It isn't really the reason, but you can think of `base' as "how many primitive symbols is the number system based upon" and not be too far off.) If we have seven widgets, that's 7 as before. Add one. Well, there is no '8' symbol. So, 7 + 1 is one eights and zero units or 10 (010 in Pythonic notation but put that aside for now). Twenty four is 30 in base 8 -- 3 eights and zero units. Likewise base 8 763 is 7 sixtyfours + 6 eights + 3 units or 499 in base 10 or decimal notation. Base 2 is where we have just the two primitive symbols 0 and 1. So, 11010 in binary notation is one sixteens+ one eights + zero fours + one twos + zero units or 26 in decimal. Likewise 14 is one eights and one fours and one twos and zero units or 1110. The general principle is in a base X number system, you have only X primitives. To represent more than X - 1 things ('0' being one of the primitives) you move a place to the left, and consider the symbols in that place as representing X times as many things as the previous place. I hope I've shed more light than shadows :-) Best, brian vdB From bvande at po-box.mcgill.ca Thu Feb 10 10:43:02 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Thu Feb 10 10:46:32 2005 Subject: [Tutor] help with refactoring needed -- which approach is morePythonic? In-Reply-To: <07fe01c50f46$60d84240$68b78851@xp> References: <420A8938.5040604@po-box.mcgill.ca> <07fe01c50f46$60d84240$68b78851@xp> Message-ID: <420B2CA6.50807@po-box.mcgill.ca> Alan Gauld said unto the world upon 2005-02-10 02:58: >>The main change in refactoring is moving it to OOP. I have a method >>that serves as the entry point for parsing the files. > > > Not an object? If you are thinking terms of what the methods > do its probably not OOP... Hi Alan, That may well be :-) What I've done is have a class File_in_the_format, and have all the parsing work going on in methods of the class. My class is called with a filepath, the __init__ method calls the _master_parser method which breaks things into head and body, calling appropriate methods and so on. I was thinking it was OOP even with just the one class as I am making use of encapsulation and the class namespace to avoid passing parameters about. > I would expect to see an object for the File, another for the Header, > a third for the Body and another for the Node. The first (containing > a header and bosdy object) is responsible for cracking open the file > and reading the lines, recognising where it has a header and sending > those lines to the header object and the rest to the bosy object. > > The body object then reades those lines and creates a Node object > per node feeding it lines as appropriate... I originally tried to see how to do it that way, but got stuck. I'll point to where by using your pseudo code below. <SNIP> > Pseudo code: > class Body: > def __init__(self,content): > self.contents = contents > self.nodes = [] > > def parse(self): > for line in self.contents: > if line == NodeStartTag: > node = Node() # Stuck here -- BvdB > if line == NodeEndTag: > self.nodes.append(node) > node.append(line) > > def __del__(self): del self.nodes > <SNIP> I got stuck at the place where I added a comment above. I didn't see how I could do that, since I didn't yet have all of the node lines in hand when it would be time to build a node. > class Node: > def __init__(self,lines=[]): > self.lines = lines > def append(self,item): # Bing! -- BvdB > self.lines.append(item) > def parse(self): > # your parsing method here. Well, that flipped a switch! I *knew in the abstract* that I can define interfaces [?] like .append and .__add__. The puzzle pieces just hadn't come together yet. They aren't all there yet either, but a half an hour in the interpreter has already cleared away much puzzlement over how to pull this off. So, thanks a lot for the push! > > Whats the advantage? If you have different node types you > can easily subclass Node and not change the File or Body > classes, just write a slightl'y different line parser. > That way your code remains more stable - you never need > to change working code to add a new node type... Well, I don't *think* these considerations are going to enter into my particular task. I'm working with a well documented text format for a shareware app I have where the developer has recently changed the file format to an undocumented binary format. So, I can be fairly confident that my particular target is one I have complete knowledge about. But, I absolutely see the point for the general case. I'm off to scrap the code that made me happy :-( and redo it this way to learn better habits :-) Thanks again, Brian vdB From kent37 at tds.net Thu Feb 10 11:52:51 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Feb 10 11:52:56 2005 Subject: [Tutor] help with refactoring needed -- which approach is morePythonic? In-Reply-To: <07fe01c50f46$60d84240$68b78851@xp> References: <420A8938.5040604@po-box.mcgill.ca> <07fe01c50f46$60d84240$68b78851@xp> Message-ID: <420B3D03.2020301@tds.net> Alan Gauld wrote: >>The main change in refactoring is moving it to OOP. I have a method >>that serves as the entry point for parsing the files. > > > Not an object? If you are thinking terms of what the methods > do its probably not OOP... > > I would expect to see an object for the File, another for the Header, > a third for the Body and another for the Node. The first (containing > a header and bosdy object) is responsible for cracking open the file > and reading the lines, recognising where it has a header and sending > those lines to the header object and the rest to the bosy object. > > The body object then reades those lines and creates a Node object > per node feeding it lines as appropriate... This is a reasonable approach. Having the Body and Node classes gives a handy place to put functions to do something with that data. But I tend to take the Extreme Programming position of You Aren't Going To Need It. I would probably stick with the list representation of Node, for example, until I had some real work for the Node class to do. It's definitely a judgement call when to introduce classes, there isn't a right way and a wrong way. Some problems cry out for classes, some clearly have no need, and then there is a gray area in the middle. > Pseudo code: > class Body: > def __init__(self,content): > self.contents = contents > self.nodes = [] > > def parse(self): > for line in self.contents: > if line == NodeStartTag: > node = Node() > if line == NodeEndTag: > self.nodes.append(node) > node.append(line) > > def __del__(self): del self.nodes Why is 'del self.nodes' needed? When the Body is del'ed the reference to self.nodes should be lost and the nodes list will be GC'd. Or am I missing something? > class Node: > def __init__(self,lines=[]): > self.lines = lines > def append(self,item): > self.lines.append(item) > def parse(self): > # your parsing method here. You might want to extend list so a Node automatically has the behavior of a list. Kent From amonroe at columbus.rr.com Thu Feb 10 12:45:41 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Thu Feb 10 12:46:18 2005 Subject: [Tutor] Hex to Str - still an open issue In-Reply-To: <1108014184.4623.1.camel@KMA.accesstel> References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> <041401c50ae9$63c21a50$68b78851@xp> <00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> <f2ff2d050205034498e84e@mail.gmail.com> <4204EAB1.2050206@tds.net> <1107856983.4603.6.camel@KMA.accesstel> <42089086.8010407@cirad.fr> <1108014184.4623.1.camel@KMA.accesstel> Message-ID: <150916134541.20050210064541@columbus.rr.com> > I am not so clued up on the 'base 2' and 'base 8' stuff. > Care to explain that a little? Easy. Imagine the numerals 2,3,4,5,6,7,8,9 were never invented. You'd start counting at 0. Next would come 1. Now you've maxed out your first column so you have to carry to the next column, so next would come 10. Alan From jsmith at medplus.com Thu Feb 10 16:22:51 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Thu Feb 10 16:22:54 2005 Subject: [Tutor] Perl Symbology (was: Are you allowed to shoot camels?) Message-ID: <C4C644CF4ADA9448904C3E8BACC4B97C02E676DF@medexch1.medplus.com> To all those who talked about hating the symbology in Perl and the suggestion that it should be removed from a later version. I just remembered what you get for that symbology that I really do like about Perl: variable interpolation in strings: C: sprintf(newstr,"%s %d %f",s,n,r); Becomes a little nicer in Python with: newstr = '%s %d %f' % (s,n,r) Although it's worse with: newstr = s + ' ' + str(n) + ' ' + str(r) But in my mind nothing beats the Perl statement: newstr = "$s $n $r"; for clarity, ease of use, and maintainability. Jeff From bill.mill at gmail.com Thu Feb 10 16:43:28 2005 From: bill.mill at gmail.com (Bill Mill) Date: Thu Feb 10 16:43:32 2005 Subject: [Tutor] Perl Symbology (was: Are you allowed to shoot camels?) In-Reply-To: <C4C644CF4ADA9448904C3E8BACC4B97C02E676DF@medexch1.medplus.com> References: <C4C644CF4ADA9448904C3E8BACC4B97C02E676DF@medexch1.medplus.com> Message-ID: <797fe3d40502100743651ad144@mail.gmail.com> Jeff, I get the impression that many pythonistas don't like string interpolation. I've never seen a clear definition of why. Anyway, it's easy enough to add with the Itpl [1] module: >>> import Itpl, sys >>> sys.stdout = Itpl.filter() >>> s, n, r = 0, 0, 0 >>> print "$s $n $r" 0 0 0 >>> x = Itpl.itpl("$s $n $r") >>> x '0 0 0' And, of course, you can give Itpl.itpl a nicer name; I usually call it pp(). If you don't need to change the behavior of the "print" statement, then you don't need the Itpl.filter() line. [1] http://lfw.org/python/Itpl.py Peace Bill Mill bill.mill at gmail.com On Thu, 10 Feb 2005 10:22:51 -0500, Smith, Jeff <jsmith@medplus.com> wrote: > To all those who talked about hating the symbology in Perl and the > suggestion that it should be removed from a later version. I just > remembered what you get for that symbology that I really do like about > Perl: variable interpolation in strings: > > C: > sprintf(newstr,"%s %d %f",s,n,r); > > Becomes a little nicer in Python with: > newstr = '%s %d %f' % (s,n,r) > > Although it's worse with: > newstr = s + ' ' + str(n) + ' ' + str(r) > > But in my mind nothing beats the Perl statement: > newstr = "$s $n $r"; > > for clarity, ease of use, and maintainability. > > Jeff > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From bill.mill at gmail.com Thu Feb 10 16:46:43 2005 From: bill.mill at gmail.com (Bill Mill) Date: Thu Feb 10 16:46:47 2005 Subject: [Tutor] Perl Symbology (was: Are you allowed to shoot camels?) In-Reply-To: <797fe3d40502100743651ad144@mail.gmail.com> References: <C4C644CF4ADA9448904C3E8BACC4B97C02E676DF@medexch1.medplus.com> <797fe3d40502100743651ad144@mail.gmail.com> Message-ID: <797fe3d405021007466c71f46c@mail.gmail.com> Sorry for the double post; I forgot one thing: On Thu, 10 Feb 2005 10:43:28 -0500, Bill Mill <bill.mill@gmail.com> wrote: > Jeff, > > I get the impression that many pythonistas don't like string > interpolation. I've never seen a clear definition of why. Anyway, it's > easy enough to add with the Itpl [1] module: > > >>> import Itpl, sys > >>> sys.stdout = Itpl.filter() > >>> s, n, r = 0, 0, 0 > >>> print "$s $n $r" > 0 0 0 > >>> x = Itpl.itpl("$s $n $r") > >>> x > '0 0 0' > This works with arbitrary data types too, to be truer to your example: >>> s, n, r = '0', 12, 3.4 >>> x = Itpl.itpl("$s $n $r") >>> x '0 12 3.4' Peace Bill Mill bill.mill at gmail.com From abli at freemail.hu Thu Feb 10 18:22:30 2005 From: abli at freemail.hu (Abel Daniel) Date: Thu Feb 10 18:21:59 2005 Subject: [Tutor] Re: Perl Symbology In-Reply-To: <797fe3d40502100743651ad144@mail.gmail.com> (Bill Mill's message of "Thu, 10 Feb 2005 10:43:28 -0500") References: <C4C644CF4ADA9448904C3E8BACC4B97C02E676DF@medexch1.medplus.com> <797fe3d40502100743651ad144@mail.gmail.com> Message-ID: <E1CzI1O-0000rq-Au@localhost.localdomain> Bill Mill writes: > I get the impression that many pythonistas don't like string > interpolation. I've never seen a clear definition of why. >From "import this": Explicit is better than implicit. And doesn't perl's method mean that you have to escape _every_ _single_ '$' in strings? I think having to escape '\' is bad enough. From bgailer at alum.rpi.edu Thu Feb 10 18:33:56 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu Feb 10 18:28:16 2005 Subject: ****SPAM(10.2)**** [Tutor] Re: python's default argument value handling in functions - weird syntax? problem grappling with the concept In-Reply-To: <4b3125cc0502091522316346aa@mail.gmail.com> References: <4b3125cc050209121418102fbb@mail.gmail.com> <E1Cz0fZ-0001gc-K2@localhost.localdomain> <4b3125cc0502091522316346aa@mail.gmail.com> Message-ID: <6.1.2.0.0.20050210103104.0345bbb8@mail.mric.net> I regret my original answer since it led to frustration. I missed the point that the local variable is pointed to the once-created default object, and that reassigning to that name does NOT affect the once-created default object. I am glad for a community in which we can cover each other's blind spots. Bob Gailer mailto:bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From bill.mill at gmail.com Thu Feb 10 19:04:48 2005 From: bill.mill at gmail.com (Bill Mill) Date: Thu Feb 10 19:32:06 2005 Subject: [Tutor] Re: Perl Symbology In-Reply-To: <E1CzI1O-0000rq-Au@localhost.localdomain> References: <C4C644CF4ADA9448904C3E8BACC4B97C02E676DF@medexch1.medplus.com> <797fe3d40502100743651ad144@mail.gmail.com> <E1CzI1O-0000rq-Au@localhost.localdomain> Message-ID: <797fe3d405021010046d1710e7@mail.gmail.com> On Thu, 10 Feb 2005 18:22:30 +0100, Abel Daniel <abli@freemail.hu> wrote: > Bill Mill writes: > > > I get the impression that many pythonistas don't like string > > interpolation. I've never seen a clear definition of why. > >From "import this": > > Explicit is better than implicit. > > And doesn't perl's method mean that you have to escape _every_ > _single_ '$' in strings? I think having to escape '\' is bad enough. Abel, You've provided me with what is approximately the eleventy-seventh explanation I've gotten as to why string interpolation is bad. I don't think that any of them are "stupid", per se, but neither do I think that any of them are strong enough to be convincing. In my perfect language, string interpolation would be on by default. That said, there are enough reasons to think that it's a bad idea that it is warranted to avoid turning it on by default. I don't mind typing pp("interpolate $mystring"), and although I do wish python standardized it before version 2.4 [1], I hardly even feel that it's a wart in the language. I just wanted to tell the person who wanted string interpolation that it's easy to add into the language and easy to use. One should not take python out of consideration if one feels that string interpolation is a killer feature. Peace Bill Mill bill.mill at gmail.com [1] http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/335308 From kent37 at tds.net Thu Feb 10 19:43:21 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Feb 10 19:43:22 2005 Subject: [Tutor] Perl Symbology In-Reply-To: <797fe3d40502100743651ad144@mail.gmail.com> References: <C4C644CF4ADA9448904C3E8BACC4B97C02E676DF@medexch1.medplus.com> <797fe3d40502100743651ad144@mail.gmail.com> Message-ID: <420BAB49.6070100@tds.net> Python 2.4 includes a string.Template class which does much the same thing as Itpl.itpl(): >>> from string import Template >>> s, n, r = '0', 12, 3.4 >>> x = Template("$s $n $r") >>> x.substitute(locals()) '0 12 3.4' If you want to bundle this up in a pp() function you have to do some magic to get the locals() of the caller. This seems to work: >>> import sys >>> def pp(s): ... loc = sys._getframe(1).f_locals ... print Template(s).substitute(loc) ... >>> pp("$s $n $r") 0 12 3.4 Kent Bill Mill wrote: > Jeff, > > I get the impression that many pythonistas don't like string > interpolation. I've never seen a clear definition of why. Anyway, it's > easy enough to add with the Itpl [1] module: > > >>>>import Itpl, sys >>>>sys.stdout = Itpl.filter() >>>>s, n, r = 0, 0, 0 >>>>print "$s $n $r" > > 0 0 0 > >>>>x = Itpl.itpl("$s $n $r") >>>>x > > '0 0 0' > > And, of course, you can give Itpl.itpl a nicer name; I usually call it > pp(). If you don't need to change the behavior of the "print" > statement, then you don't need the Itpl.filter() line. > > [1] http://lfw.org/python/Itpl.py > > Peace > Bill Mill > bill.mill at gmail.com > > > On Thu, 10 Feb 2005 10:22:51 -0500, Smith, Jeff <jsmith@medplus.com> wrote: > >>To all those who talked about hating the symbology in Perl and the >>suggestion that it should be removed from a later version. I just >>remembered what you get for that symbology that I really do like about >>Perl: variable interpolation in strings: >> >>C: >>sprintf(newstr,"%s %d %f",s,n,r); >> >>Becomes a little nicer in Python with: >>newstr = '%s %d %f' % (s,n,r) >> >>Although it's worse with: >>newstr = s + ' ' + str(n) + ' ' + str(r) >> >>But in my mind nothing beats the Perl statement: >>newstr = "$s $n $r"; >> >>for clarity, ease of use, and maintainability. >> >>Jeff >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From jsmith at medplus.com Thu Feb 10 19:59:04 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Thu Feb 10 19:59:17 2005 Subject: [Tutor] Re: Perl Symbology Message-ID: <C4C644CF4ADA9448904C3E8BACC4B97C02E6777B@medexch1.medplus.com> Abel, No, you don't have to escape them all. Perl treats single and double quotes differently. Single-quoted strings don't do interpolation and double-quoted strings do. Jeff -----Original Message----- From: Abel Daniel [mailto:abli@freemail.hu] Sent: Thursday, February 10, 2005 12:23 PM To: tutor@python.org Subject: [Tutor] Re: Perl Symbology Bill Mill writes: > I get the impression that many pythonistas don't like string >interpolation. I've never seen a clear definition of why. From "import >this": Explicit is better than implicit. And doesn't perl's method mean that you have to escape _every_ _single_ '$' in strings? I think having to escape '\' is bad enough. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From bill.mill at gmail.com Thu Feb 10 19:59:58 2005 From: bill.mill at gmail.com (Bill Mill) Date: Thu Feb 10 20:00:02 2005 Subject: [Tutor] Perl Symbology In-Reply-To: <420BAB49.6070100@tds.net> References: <C4C644CF4ADA9448904C3E8BACC4B97C02E676DF@medexch1.medplus.com> <797fe3d40502100743651ad144@mail.gmail.com> <420BAB49.6070100@tds.net> Message-ID: <797fe3d405021010597afb4ff1@mail.gmail.com> Kent, On Thu, 10 Feb 2005 13:43:21 -0500, Kent Johnson <kent37@tds.net> wrote: > Python 2.4 includes a string.Template class which does much the same thing as Itpl.itpl(): > > >>> from string import Template > >>> s, n, r = '0', 12, 3.4 > >>> x = Template("$s $n $r") > >>> x.substitute(locals()) > '0 12 3.4' > > If you want to bundle this up in a pp() function you have to do some magic to get the locals() of > the caller. This seems to work: > > >>> import sys > >>> def pp(s): > ... loc = sys._getframe(1).f_locals > ... print Template(s).substitute(loc) > ... > >>> pp("$s $n $r") > 0 12 3.4 > I just didn't want to give an answer that only works in python 2.4, and one furthermore which I have not tested. You can also find a recipe to make pp() easy to make at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/335308 . This function may or may not be better than yours; I haven't used either. the Itpl module has worked fine for me (and for the author of ipython) for quite a while. Peace Bill Mill bill.mill at gmail.com From kent37 at tds.net Thu Feb 10 20:22:52 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Feb 10 20:22:53 2005 Subject: [Tutor] Perl Symbology In-Reply-To: <797fe3d405021010597afb4ff1@mail.gmail.com> References: <C4C644CF4ADA9448904C3E8BACC4B97C02E676DF@medexch1.medplus.com> <797fe3d40502100743651ad144@mail.gmail.com> <420BAB49.6070100@tds.net> <797fe3d405021010597afb4ff1@mail.gmail.com> Message-ID: <420BB48C.3020003@tds.net> Bill Mill wrote: > Kent, > > On Thu, 10 Feb 2005 13:43:21 -0500, Kent Johnson <kent37@tds.net> wrote: > >>Python 2.4 includes a string.Template class which does much the same thing as Itpl.itpl(): > > I just didn't want to give an answer that only works in python 2.4, > and one furthermore which I have not tested. > > You can also find a recipe to make pp() easy to make at > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/335308 . This > function may or may not be better than yours; I haven't used either. It's better, it looks at locals() and globals() as well as allowing dict and keyword args do pp() directly. > the Itpl module has worked fine for me (and for the author of ipython) > for quite a while. I certainly didn't mean to cast any doubt on Itpl, I just thought it was worth pointing out that there is some support in the standard library now. Kent From alan.gauld at freenet.co.uk Thu Feb 10 20:28:26 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Feb 10 20:28:10 2005 Subject: [Tutor] Perl Symbology (was: Are you allowed to shoot camels?) References: <C4C644CF4ADA9448904C3E8BACC4B97C02E676DF@medexch1.medplus.com> Message-ID: <087d01c50fa6$b1debec0$68b78851@xp> > Although it's worse with: > newstr = s + ' ' + str(n) + ' ' + str(r) You could try: newstr = s + ' ' + `n` + ' ' + `r` if you think thats better. But `` is different to str() for some types. Personally I prefer the formatting approach. > But in my mind nothing beats the Perl statement: > newstr = "$s $n $r"; Perl is king of string processing in modern scripting, without a doubt. But even here the $ prefix could have been used for that specific purpose without insisting it be used everywhere else! BTW Anyone recall how Ruby does this? Alan G. Too lazy to look it up! From bill.mill at gmail.com Thu Feb 10 20:50:34 2005 From: bill.mill at gmail.com (Bill Mill) Date: Thu Feb 10 20:50:38 2005 Subject: [Tutor] Perl Symbology (was: Are you allowed to shoot camels?) In-Reply-To: <087d01c50fa6$b1debec0$68b78851@xp> References: <C4C644CF4ADA9448904C3E8BACC4B97C02E676DF@medexch1.medplus.com> <087d01c50fa6$b1debec0$68b78851@xp> Message-ID: <797fe3d40502101150552f5cf4@mail.gmail.com> On Thu, 10 Feb 2005 19:28:26 -0000, Alan Gauld <alan.gauld@freenet.co.uk> wrote: > > Although it's worse with: > > newstr = s + ' ' + str(n) + ' ' + str(r) > > You could try: > > newstr = s + ' ' + `n` + ' ' + `r` > > if you think thats better. > But `` is different to str() for some types. > > Personally I prefer the formatting approach. > > > But in my mind nothing beats the Perl statement: > > newstr = "$s $n $r"; > > Perl is king of string processing in modern scripting, > without a doubt. But even here the $ prefix could have > been used for that specific purpose without insisting > it be used everywhere else! > > BTW Anyone recall how Ruby does this? I don't know ruby at all, but a quick google and 30 interpreter seconds later: irb(main):001:0> x = 12 => 12 irb(main):002:0> '$x' => "$x" irb(main):003:0> "$x" => "$x" irb(main):004:0> "#{$x}" => "" irb(main):005:0> "#{x}" => "12" irb(main):006:0> '#{x}' => "#{x}" so "#{<variable}" seems to do it. The googling shows that there are a myriad of other ways, which I haven't even looked at. They all seem to involve #{[symbol]<variable>} . Peace Bill Mill bill.mill at gmail.com From maxnoel_fr at yahoo.fr Thu Feb 10 20:58:55 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu Feb 10 20:59:02 2005 Subject: [Tutor] Perl Symbology (was: Are you allowed to shoot camels?) In-Reply-To: <797fe3d40502101150552f5cf4@mail.gmail.com> References: <C4C644CF4ADA9448904C3E8BACC4B97C02E676DF@medexch1.medplus.com> <087d01c50fa6$b1debec0$68b78851@xp> <797fe3d40502101150552f5cf4@mail.gmail.com> Message-ID: <214aeeb0995e82517f33ca6c5895a688@yahoo.fr> On Feb 10, 2005, at 19:50, Bill Mill wrote: > so "#{<variable}" seems to do it. The googling shows that there are a > myriad of other ways, which I haven't even looked at. They all seem to > involve #{[symbol]<variable>} . Here, [symbol] refers to the scope(?) of the variable. See the discussion between me and Alan on this topic a while ago -- the use of these symbols being his main criticism of Ruby. foo is a local variable $foo is a global variable @foo is an instance variable @@foo is a class variable FOO is a constant (which can be modded into global, instance or class with the appropriate use of $, @ or @@) -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From hugonz-lists at h-lab.net Thu Feb 10 18:31:50 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Thu Feb 10 23:06:34 2005 Subject: [Tutor] Perl Symbology (was: Are you allowed to shoot camels?) In-Reply-To: <C4C644CF4ADA9448904C3E8BACC4B97C02E676DF@medexch1.medplus.com> References: <C4C644CF4ADA9448904C3E8BACC4B97C02E676DF@medexch1.medplus.com> Message-ID: <420B9A86.5000804@h-lab.net> Smith, Jeff wrote: > But in my mind nothing beats the Perl statement: > newstr = "$s $n $r"; > > for clarity, ease of use, and maintainability. Only a little ease of use is lost with the following in Python, clarity and maintainability are kept, and it even will let you format the output (as in # of decimal places) newstr = "%{s}s %(n)s %(r)s"%locals() If you cannot assume a type you can always just use %s... Hugo From cyresse at gmail.com Fri Feb 11 08:09:10 2005 From: cyresse at gmail.com (Liam Clarke) Date: Fri Feb 11 08:09:13 2005 Subject: [Tutor] Data storage, SQL? Message-ID: <f2ff2d05021023093bb965ef@mail.gmail.com> Hi, I'm looking to create a prog that will store disparate bits of info all linked together, i.e. address details for a person, transaction records, specific themes, and the ability to search by certain criteria, so I'm pretty sure I want a database. Can anyone recommend a useful database library for Python that's not too complex? Also, I keep hearing about SQL, would this be the best way to go? I don't know much about databases. Regards, Liam Clarke -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From bvande at po-box.mcgill.ca Fri Feb 11 09:04:27 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri Feb 11 09:06:03 2005 Subject: [Tutor] default argument frustration In-Reply-To: <07fe01c50f46$60d84240$68b78851@xp> References: <420A8938.5040604@po-box.mcgill.ca> <07fe01c50f46$60d84240$68b78851@xp> Message-ID: <420C670B.4070209@po-box.mcgill.ca> Alan Gauld said unto the world upon 2005-02-10 02:58: > class Node: > def __init__(self,lines=[]): # here's the zowie BvdB > self.lines = lines > def append(self,item): > self.lines.append(item) > def parse(self): > # your parsing method here. Hi all, I've been following the general approach that Alan suggested and have been happily making much headway. (The code is about twice as long as before and does about 4 times as many things :-) ) At first, I ended up with every single node being a copy of the first one processed. A bit of weeping later, I realized that this is from the feature [?] of Python that default arguments are evaluated just once. (Note the comment added above.) Happily, I didn't need the default argument. And even if I did, there's the work around from the tutorial <http://docs.python.org/tut/node6.html#SECTION006720000000000000000> that's been under recent discussion in the python's default argument value handling in functions - weird syntax? problem grappling with the concept thread. I may have missed the discussion in that thread but: <venting> FOR THE LOVE OF MIKE can someone tell me even one reason why this isn't a misfeature?!?! </venting> Sorry for the shouting, but this issue seems to come up a lot. Officially, I do know about it, but it often takes me considerable frustration to realize it's what's ruining my day. I'd be far happier if I could see that there was a good reason for this behaviour. (There'd even be a chance that I'd remember more readily--I hope so, these keyboards are getting expensive.) I'm sure there is one, as I don't believe that Dutchman are particularly given to sadism. Thanks, and best to all, Brian vdB From kent37 at tds.net Fri Feb 11 12:00:34 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Feb 11 12:00:41 2005 Subject: [Tutor] Data storage, SQL? In-Reply-To: <f2ff2d05021023093bb965ef@mail.gmail.com> References: <f2ff2d05021023093bb965ef@mail.gmail.com> Message-ID: <420C9052.2070009@tds.net> Liam Clarke wrote: > Hi, > > I'm looking to create a prog that will store disparate bits of info > all linked together, i.e. address details for a person, transaction > records, specific themes, and the ability to search by certain > criteria, so I'm pretty sure I want a database. > > Can anyone recommend a useful database library for Python that's not > too complex? Most Python database access modules implement the Python DB-API. This is a standard API created by the Python community. As a result most Python database libraries are pretty similar from the programmer's point of view. See the Database Topic Guide for the DB-API spec and links to modules that support it. http://www.python.org/topics/database/ > Also, I keep hearing about SQL, would this be the best way to go? I > don't know much about databases. SQL is a standardized language for giving commands to databases. Most (all?) industrial-strength databases use SQL as their command language. (DB-API is actually a wrapper around SQL - it standardizes the API to issue a SQL command and read the results.) SQL is kind of a strange beast and has a style and learning curve all its own. It is worth learning if you expect to be using databases much in your future. There are some light-weight databases that don't use SQL (KirbyBase and MetaKit are two) but all of the major ones do. A couple of pages that might help you make a choice: http://www.python.org/moin/DatabaseInterfaces http://www.python.org/moin/ChoosingDatabase Note that DB-API and SQL don't provide 100% portability between databases; there are differences in the details that can trip you up. Kent > > Regards, > > Liam Clarke From matthew.williams at cancer.org.uk Fri Feb 11 12:29:38 2005 From: matthew.williams at cancer.org.uk (Matt Williams) Date: Fri Feb 11 12:29:45 2005 Subject: [Tutor] Database In-Reply-To: <20050211110157.8EB271E400E@bag.python.org> References: <20050211110157.8EB271E400E@bag.python.org> Message-ID: <1108121378.2916.14.camel@dhcp0320.acl.icnet.uk> I would recommend KirbyBase as a quick starter - it's nice and simple, and outputs text files, so you can always check things manually. http://www.netpromi.com/kirbybase.html Matt From kent37 at tds.net Fri Feb 11 13:34:41 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Feb 11 13:34:45 2005 Subject: [Tutor] Data storage, SQL? In-Reply-To: <420C9052.2070009@tds.net> References: <f2ff2d05021023093bb965ef@mail.gmail.com> <420C9052.2070009@tds.net> Message-ID: <420CA661.8080900@tds.net> Kent Johnson wrote: > SQL is a standardized language for giving commands to databases. Most > (all?) industrial-strength databases use SQL as their command language. > (DB-API is actually a wrapper around SQL - it standardizes the API to > issue a SQL command and read the results.) > > SQL is kind of a strange beast and has a style and learning curve all > its own. It is worth learning if you expect to be using databases much > in your future. There are some light-weight databases that don't use SQL > (KirbyBase and MetaKit are two) but all of the major ones do. I don't know any good on-line resources for learning SQL - maybe others have a recommendation. A book I like is "The Practical SQL Handbook" by Judith Bowman, Sandra Emerson, Marcy Darnovsky http://www.bookpool.com/ss?qs=Practical+SQL+Handbook&x=0&y=0 Kent From kent37 at tds.net Fri Feb 11 14:04:20 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Feb 11 14:04:23 2005 Subject: [Tutor] default argument frustration In-Reply-To: <420C670B.4070209@po-box.mcgill.ca> References: <420A8938.5040604@po-box.mcgill.ca> <07fe01c50f46$60d84240$68b78851@xp> <420C670B.4070209@po-box.mcgill.ca> Message-ID: <420CAD54.2020509@tds.net> Brian van den Broek wrote: > At first, I ended up with every single node being a copy of the first > one processed. A bit of weeping later, I realized that this is from the > feature [?] of Python that default arguments are evaluated just once. > (Note the comment added above.) > > <venting> > FOR THE LOVE OF MIKE can someone tell me even one reason why this isn't > a misfeature?!?! > </venting> I will guess...because historically it was useful, and because the alternative is problematic. Before Python 2.1, when nested scopes were introduced, default arguments were widely used as a way to bind values from the local environment into a function. For example, suppose I want to write a function of one argument that returns a function of one argument that adds the two arguments together. Today, I can write >>> def makeAdder(n): ... def f(x): ... return x+n ... return f ... >>> add5 = makeAdder(5) >>> add5(2) 7 In Python 2.0 this doesn't work, add5 will not know the value of n. The common workaround was to provide n as a default argument to f: >>> def makeAdder2(n): ... def f(x, n=n): ... return x+n ... return f Now n is bound as a default argument when f is created, and makeAdder2() works the same as makeAdder(). OK, now imagine what would happen to makeAdder2() if the default argument was evaluated at the point of call? It would use whatever value of n was in scope at the time. This could be confusing - n might well not even be defined! What this really does is make variables in default arguments be dynamically scoped. Since other variables in Python are lexically scoped, this would be kind of strange. http://en.wikipedia.org/wiki/Dynamic_scoping http://en.wikipedia.org/wiki/Lexical_variable_scoping Kent From kent37 at tds.net Fri Feb 11 14:05:29 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Feb 11 14:05:31 2005 Subject: [Tutor] Data storage, SQL? In-Reply-To: <420CA661.8080900@tds.net> References: <f2ff2d05021023093bb965ef@mail.gmail.com> <420C9052.2070009@tds.net> <420CA661.8080900@tds.net> Message-ID: <420CAD99.2030404@tds.net> Kent Johnson wrote: > I don't know any good on-line resources for learning SQL The Wikipedia entry for SQL has links to quite a few tutorials: http://en.wikipedia.org/wiki/Sql Kent From jsmith at medplus.com Fri Feb 11 15:28:35 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Fri Feb 11 15:28:38 2005 Subject: [Tutor] Simple question on creating a filter Message-ID: <C4C644CF4ADA9448904C3E8BACC4B97C02E677FB@medexch1.medplus.com> I'm sorry to both with such a simple question but I've looked in the normal places and don't see the quick and dirty answer I know must exist. I want to write a simple line selection filter that could be used like: filter < file In Perl I would do: while (<>) { print if line meets selection criteria; } I've tried what I thought would be the Python equivalent but it doesn't work: for line in sys.stdin: if line meets selection criteria: print line I get the following at runtime: Traceback (most recent call last): File "U:\TimeKeeper\mine.py", line 2, in ? for line in sys.stdin: IOError: [Errno 9] Bad file descriptor This is with Python 2.4 on Windows. Jeff From bill.mill at gmail.com Fri Feb 11 15:38:01 2005 From: bill.mill at gmail.com (Bill Mill) Date: Fri Feb 11 15:38:05 2005 Subject: [Tutor] Simple question on creating a filter In-Reply-To: <C4C644CF4ADA9448904C3E8BACC4B97C02E677FB@medexch1.medplus.com> References: <C4C644CF4ADA9448904C3E8BACC4B97C02E677FB@medexch1.medplus.com> Message-ID: <797fe3d405021106387fe92acf@mail.gmail.com> On Fri, 11 Feb 2005 09:28:35 -0500, Smith, Jeff <jsmith@medplus.com> wrote: > I'm sorry to both with such a simple question but I've looked in the > normal places and don't see the quick and dirty answer I know must > exist. > No worries; that's what this list is for. > I want to write a simple line selection filter that could be used like: > > filter < file > > In Perl I would do: > > while (<>) > { > print if line meets selection criteria; > } > > I've tried what I thought would be the Python equivalent but it doesn't > work: > > for line in sys.stdin: > if line meets selection criteria: > print line > > I get the following at runtime: > > Traceback (most recent call last): > File "U:\TimeKeeper\mine.py", line 2, in ? > for line in sys.stdin: > IOError: [Errno 9] Bad file descriptor > I'm not quite sure how you're getting that "bad file dscriptor" error. My code, also on windows (and cygwin) with python2.4: /d/code/python$ cat test.py import sys for line in sys.stdin: if line.startswith('a'): print line.strip() /d/code/python$ cat test_in aline1 bline2 aline3 cline4 /d/code/python$ python test.py < test_in aline1 aline3 Try to run it like I did, and let me know if it gives you the same thing; that'll give us a common point of reference. Peace Bll Mill bill.mill at gmail.com > This is with Python 2.4 on Windows. > > Jeff > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From maitj at vianet.ca Fri Feb 11 16:03:30 2005 From: maitj at vianet.ca (Jeffrey Maitland) Date: Fri Feb 11 16:03:37 2005 Subject: [Tutor] Might be a silly question! Message-ID: <20050211150330.24150.qmail@mail.vianet.ca> Hello all, I am drawing a blank right now and can't seem to find anything on it and I am sure this issue has been addressed before, so here is the question. Can and if you can how do you set a variable as a constant? Example of what I mean: (this is loose and not python since variable type declaration is not needed in python) CONST int gamma = 5 This would mean in my little mind that the variable gamma which is an integer of 5 can not be changed in the code and would throw an error if you tried. Just wondering if there is a way of doing this in Python. This is just to clear this up in my mind it means nothing to my code since the way I write variable names any variable I want to remain unchanged I use caps to help distinguish easily. Thanks. Jeff "They say the quickest way between to 2 points is a straight line, however where is the fun in that?" From jsmith at medplus.com Fri Feb 11 16:26:50 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Fri Feb 11 16:26:55 2005 Subject: [Tutor] Simple question on creating a filter Message-ID: <C4C644CF4ADA9448904C3E8BACC4B97C02FFC797@medexch1.medplus.com> Good catch Bill, I was using assoc and ftype to allow me to run my filter.py directly as a command and using: filter < file Unfortunately, Windows doesn't handle this properly and I had to do C:\Python24\python filter.py < file To get it to work. Thanks, Jeff P.S. In retrospect, I've had the same problem with Perl but because of my newbie status I assumed I was doin' something wrong :-) -----Original Message----- From: Bill Mill [mailto:bill.mill@gmail.com] Sent: Friday, February 11, 2005 9:38 AM To: Smith, Jeff Cc: tutor@python.org Subject: Re: [Tutor] Simple question on creating a filter On Fri, 11 Feb 2005 09:28:35 -0500, Smith, Jeff <jsmith@medplus.com> wrote: > I'm sorry to both with such a simple question but I've looked in the > normal places and don't see the quick and dirty answer I know must > exist. > No worries; that's what this list is for. > I want to write a simple line selection filter that could be used > like: > > filter < file > > In Perl I would do: > > while (<>) > { > print if line meets selection criteria; > } > > I've tried what I thought would be the Python equivalent but it > doesn't > work: > > for line in sys.stdin: > if line meets selection criteria: > print line > > I get the following at runtime: > > Traceback (most recent call last): > File "U:\TimeKeeper\mine.py", line 2, in ? > for line in sys.stdin: > IOError: [Errno 9] Bad file descriptor > I'm not quite sure how you're getting that "bad file dscriptor" error. My code, also on windows (and cygwin) with python2.4: /d/code/python$ cat test.py import sys for line in sys.stdin: if line.startswith('a'): print line.strip() /d/code/python$ cat test_in aline1 bline2 aline3 cline4 /d/code/python$ python test.py < test_in aline1 aline3 Try to run it like I did, and let me know if it gives you the same thing; that'll give us a common point of reference. Peace Bll Mill bill.mill at gmail.com > This is with Python 2.4 on Windows. > > Jeff > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From bill.mill at gmail.com Fri Feb 11 16:38:57 2005 From: bill.mill at gmail.com (Bill Mill) Date: Fri Feb 11 16:39:02 2005 Subject: [Tutor] Might be a silly question! In-Reply-To: <20050211150330.24150.qmail@mail.vianet.ca> References: <20050211150330.24150.qmail@mail.vianet.ca> Message-ID: <797fe3d405021107383f191157@mail.gmail.com> Jeff, On Fri, 11 Feb 2005 10:03:30 -0500, Jeffrey Maitland <maitj@vianet.ca> wrote: > > Hello all, > > I am drawing a blank right now and can't seem to find anything on it and I > am sure this issue has been addressed before, so here is the question. > > Can and if you can how do you set a variable as a constant? > > Example of what I mean: (this is loose and not python since variable type > declaration is not needed in python) > > CONST int gamma = 5 > > This would mean in my little mind that the variable gamma which is an > integer of 5 can not be changed in the code and would throw an error if you > tried. Just wondering if there is a way of doing this in Python. There is no real way to guarantee this in Python. > This is > just to clear this up in my mind it means nothing to my code since the way I > write variable names any variable I want to remain unchanged I use caps to > help distinguish easily. Constants are enforced by convention in Python. Any variable with a name in ALL CAPS is considered to be a constant, and it is considered bad programming style to change it. While it sounds like a weak system, and I'm sure there have been problems with it, I've never heard of one. Remember to only import the names you need from the classes you import, and you should be fine. Peace Bill Mill bill.mill at gmail.com From maitj at vianet.ca Fri Feb 11 16:47:42 2005 From: maitj at vianet.ca (Jeffrey Maitland) Date: Fri Feb 11 16:47:45 2005 Subject: [Tutor] Re: Might be a silly question! In-Reply-To: <797fe3d405021107383f191157@mail.gmail.com> References: <20050211150330.24150.qmail@mail.vianet.ca> <797fe3d405021107383f191157@mail.gmail.com> Message-ID: <20050211154742.30487.qmail@mail.vianet.ca> Thanks that's what I thought. Wasn't 100% sure that is what prompted me to ask the question in here. As for the CAPS thing for constants, I generally try and practice (to the best of my knowledge) proper programming consepts/styles/standards. However I have been reading code written before me (mind you it's C++) and the authors seemed to follow what ever style they wished to that day. Oh well that's the nature of the beast. Thanks again for clearing that up for me. Jeff Bill Mill writes: > Jeff, > > On Fri, 11 Feb 2005 10:03:30 -0500, Jeffrey Maitland <maitj@vianet.ca> wrote: >> >> Hello all, >> >> I am drawing a blank right now and can't seem to find anything on it and I >> am sure this issue has been addressed before, so here is the question. >> >> Can and if you can how do you set a variable as a constant? >> >> Example of what I mean: (this is loose and not python since variable type >> declaration is not needed in python) >> >> CONST int gamma = 5 >> >> This would mean in my little mind that the variable gamma which is an >> integer of 5 can not be changed in the code and would throw an error if you >> tried. Just wondering if there is a way of doing this in Python. > > There is no real way to guarantee this in Python. > >> This is >> just to clear this up in my mind it means nothing to my code since the way I >> write variable names any variable I want to remain unchanged I use caps to >> help distinguish easily. > > Constants are enforced by convention in Python. Any variable with a > name in ALL CAPS is considered to be a constant, and it is considered > bad programming style to change it. While it sounds like a weak > system, and I'm sure there have been problems with it, I've never > heard of one. Remember to only import the names you need from the > classes you import, and you should be fine. > > Peace > Bill Mill > bill.mill at gmail.com From mark.brown at rogers.com Fri Feb 11 16:52:03 2005 From: mark.brown at rogers.com (Mark Brown) Date: Fri Feb 11 16:52:13 2005 Subject: [Tutor] Negative IF conditions Message-ID: <420CD4A3.6040105@rogers.com> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050211/f769586e/attachment.html From zanesdad at bellsouth.net Fri Feb 11 17:04:11 2005 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Fri Feb 11 17:05:45 2005 Subject: [Tutor] Negative IF conditions In-Reply-To: <420CD4A3.6040105@rogers.com> References: <420CD4A3.6040105@rogers.com> Message-ID: <420CD77B.2050106@bellsouth.net> Mark Brown wrote: > Hi, > I'm a newbie and was wondering which of these IF conditions is better > structure: > > 1. if not os.path.exists('filename'): > 2. if os.path.exists('filename') == False: > My preference would be the first (if not os.path.exists). os.path.exists returns a boolean (I think), so the "if" will directly check that rather than having to setup a second truth statement (== False) for "if" to check. It's more readable to me and just "feels better." > They both work so if one preferred over the other? > Thanks > Mark Brown > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > Jeremy Jones -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050211/97fb3f68/attachment.htm From bvande at po-box.mcgill.ca Fri Feb 11 17:15:25 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri Feb 11 17:16:32 2005 Subject: [Tutor] help with refactoring needed -- which approach is morePythonic? In-Reply-To: <07fe01c50f46$60d84240$68b78851@xp> References: <420A8938.5040604@po-box.mcgill.ca> <07fe01c50f46$60d84240$68b78851@xp> Message-ID: <420CDA1D.5040204@po-box.mcgill.ca> Alan Gauld said unto the world upon 2005-02-10 02:58: > Pseudo code: > class Body: > def __init__(self,content): > self.contents = contents > self.nodes = [] > > def parse(self): > for line in self.contents: > if line == NodeStartTag: > node = Node() > if line == NodeEndTag: > self.nodes.append(node) > node.append(line) > > class Node: > def __init__(self,lines=[]): > self.lines = lines > def append(self,item): > self.lines.append(item) > def parse(self): > # your parsing method here. Hi all, YAQ (Yet Another Question): Following the general pattern, I end up with a Body object which has an attribute .nodes that consists of a list of Node objects. So, something like: My Example Body Node List Node the first Node the second Is there any way to make methods of the Node class access attributes of `parents' of instances? I would like a Node instance such as Node the first above to be aware just what it is a node of and what its siblings are. Does this make sense? Best to all, Brian vdB PS Thanks for the reply to my venting question, Kent. From zanesdad at bellsouth.net Fri Feb 11 17:27:37 2005 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Fri Feb 11 17:29:05 2005 Subject: [Tutor] help with refactoring needed -- which approach is morePythonic? In-Reply-To: <420CDA1D.5040204@po-box.mcgill.ca> References: <420A8938.5040604@po-box.mcgill.ca> <07fe01c50f46$60d84240$68b78851@xp> <420CDA1D.5040204@po-box.mcgill.ca> Message-ID: <420CDCF9.8000603@bellsouth.net> Brian van den Broek wrote: > Alan Gauld said unto the world upon 2005-02-10 02:58: > >> Pseudo code: >> class Body: >> def __init__(self,content): >> self.contents = contents >> self.nodes = [] >> >> def parse(self): >> for line in self.contents: >> if line == NodeStartTag: >> node = Node() >> if line == NodeEndTag: >> self.nodes.append(node) >> node.append(line) >> >> class Node: >> def __init__(self,lines=[]): >> self.lines = lines >> def append(self,item): >> self.lines.append(item) >> def parse(self): >> # your parsing method here. > > > Hi all, > > YAQ (Yet Another Question): > > Following the general pattern, I end up with a Body object which has > an attribute .nodes that consists of a list of Node objects. > > So, something like: > > My Example Body > Node List > Node the first > Node the second > > Is there any way to make methods of the Node class access attributes > of `parents' of instances? I would like a Node instance such as Node > the first above to be aware just what it is a node of and what its > siblings are. > > Does this make sense? I think so. I haven't tested this (pseudo) code which I took from your above post and just modified it, but I think you want something like this: Pseudo code: class Body: def __init__(self,content): self.contents = contents self.nodes = [] def parse(self): for line in self.contents: if line == NodeStartTag: node = Node(self) #when you create a node, pass in the parent object like this if line == NodeEndTag: self.nodes.append(node) node.append(line) class Node: def __init__(self, parent, lines=[]): self.lines = lines self.parent = parent #and store the parent like this def append(self,item): self.lines.append(item) def parse(self): # your parsing method here. def show_siblings(self): print self.parent.nodes # and you can access the parent kinda like this. You don't want to get too carried away with something like this, though. You may want to read up on the Law of Demeter. This (in my opinion) is fine, though. > > Best to all, > > Brian vdB > > PS Thanks for the reply to my venting question, Kent. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > Jeremy Jones From kent37 at tds.net Fri Feb 11 17:34:02 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Feb 11 17:34:07 2005 Subject: [Tutor] help with refactoring needed -- which approach is morePythonic? In-Reply-To: <420CDA1D.5040204@po-box.mcgill.ca> References: <420A8938.5040604@po-box.mcgill.ca> <07fe01c50f46$60d84240$68b78851@xp> <420CDA1D.5040204@po-box.mcgill.ca> Message-ID: <420CDE7A.3010408@tds.net> Brian van den Broek wrote: > Alan Gauld said unto the world upon 2005-02-10 02:58: > >> Pseudo code: >> class Body: >> def __init__(self,content): >> self.contents = contents >> self.nodes = [] >> >> def parse(self): >> for line in self.contents: >> if line == NodeStartTag: >> node = Node() >> if line == NodeEndTag: >> self.nodes.append(node) >> node.append(line) >> >> class Node: >> def __init__(self,lines=[]): >> self.lines = lines >> def append(self,item): >> self.lines.append(item) >> def parse(self): >> # your parsing method here. > > > Hi all, > > YAQ (Yet Another Question): > > Following the general pattern, I end up with a Body object which has an > attribute .nodes that consists of a list of Node objects. > > So, something like: > > My Example Body > Node List > Node the first > Node the second > > Is there any way to make methods of the Node class access attributes of > `parents' of instances? I would like a Node instance such as Node the > first above to be aware just what it is a node of and what its siblings > are. You have to tell it the parent. ("Explicit is better than implicit.") For example you could pass a reference to Body to the Node in the constructor: def parse(self): for line in self.contents: if line == NodeStartTag: node = Node(self) # HERE if line == NodeEndTag: self.nodes.append(node) node.append(line) In general I think this is a bad design. I try to avoid telling components about their parents in any kind of containment hierarchy. If the component knows about its parent, then the component can't be reused in a different context and it can't be tested without creating the expected context. Is there another way you could accomplish what you want? Kent > > Does this make sense? > > Best to all, > > Brian vdB > > PS Thanks for the reply to my venting question, Kent. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From ryan at acceleration.net Fri Feb 11 18:39:40 2005 From: ryan at acceleration.net (Ryan Davis) Date: Fri Feb 11 18:39:46 2005 Subject: [Tutor] Larger program organization Message-ID: <20050211173944.07AAC1E4008@bag.python.org> I'm starting to make a code-generation suite in python, customized to the way we ASP.NET at my company, and I'm having some trouble finding a good way to organize all the code. I keep writing it, but it feels more and more spaghetti-ish every day. I'm going to look at the other stuff in site-packages to see if I can glean any wisdom, and have googled a bit, coming up mostly blank or with trivial examples. Are there any helpful links or advice anyone has for building larger systems? My background is mostly C#, so I'm used to the ridiculous rigidity of strongly-typed languages. I have been using python for helper apps for a few months now, so am pretty familiar with the syntax now, but I don't know any of the patterns yet. My nefarious goal is to supplant C#/ASP.NET with Python, but I need to figure out how to make programs clients want to pay for before I can make any reasonable argument. Thanks, Ryan ---- Ryan Davis Director of Programming Services http://www.acceleration.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050211/05b2eaec/attachment.html From alan.gauld at freenet.co.uk Fri Feb 11 19:21:25 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 11 19:20:44 2005 Subject: [Tutor] Data storage, SQL? References: <f2ff2d05021023093bb965ef@mail.gmail.com> Message-ID: <001901c51066$80ad0b20$31d78751@xp> > I'm looking to create a prog that will store disparate bits of info > all linked together, i.e. address details for a person, transaction > records, specific themes, and the ability to search by certain > criteria, so I'm pretty sure I want a database. Sounds a lot like it! > Can anyone recommend a useful database library for Python that's not > too complex? MYSql gets a lot of fans. PostGres is also popular and both are free. My personal favourite although I'm not sure the free version is still available is Borland's Interbase (and there was an open source spinoff too - Firebird - not to be confused with the mail tool! I just checked and Interbvase is still free to download. A comparison of all 3 can be found here: http://www.skippingdot.net/2002/02/01 > Also, I keep hearing about SQL, would this be the best way to go? I > don't know much about databases. You should learn SQL. Its a very powerful and useful tool for any kind of serious data work and is fairly portable between databases from MS Access on a PC to IBMs DB2 on a mainframe. Basic use is very easy: SELECT FIELD1,FIELD2,... FROM TABLE1,TABLE2 WHERE TABLE.FIELD <CONDITION> VALUE ORDER BY FIELD And you can abbreviate it as needed and add extra complexity too. Here is a more concrete example: SELECT Name, Age FROM Student WHERE Age > 30 ORDER by Name Will return a tuple of Name, Age pairs for all records in the Student table where the age is greater than 30 and sorted by student name. Now think about how much Python code youd need to do that from a flat file... Doable but much harder work. Now lets start linking data together: SELECT Name, Age, Course.Name FROM Student, Course WHERE Age > 30 AND Student.CourseID = Course.CourseID ORDER BY Name Here we are linking the course table with the student table so we can see which courses our mature students are studying. There are lots of other things you can do including nesting select statements, only having unique values output etc. The other advantage is that if you just want to explore your data most databases will provide an interactive prompt (like Pythons >>>) where you can interactively type SQL queries so the development style is very like Python and the two can be used together very easily and naturally. (Maybe I could do a SQL primer as part of my advanced topics section in the tutorial... hmm. An intro to SQL then the next topic showing how to use the Python DBAPI to link SQL and Python - any takers for that idea?) Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Fri Feb 11 19:30:17 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 11 19:29:35 2005 Subject: [Tutor] default argument frustration References: <420A8938.5040604@po-box.mcgill.ca><07fe01c50f46$60d84240$68b78851@xp> <420C670B.4070209@po-box.mcgill.ca> Message-ID: <001e01c51067$bd0478f0$31d78751@xp> > <venting> > FOR THE LOVE OF MIKE can someone tell me even one reason why this > isn't a misfeature?!?! > </venting> :-) Its the only sane way to implement default arguments. The whole point of function definitions is that they provide a single concise interface. The function should return the same result each time you call it with the same input. The only way to achieve that is to have the default calculated once. The problem is that the default value can be a mutable object (and that aspect could be argued as a mis-feature) which leads to apparently different behaviour for the same input as the recent thread illustrated. But in fact the same object is being returnd its just the internal content that changes... And of course this behaviour is exploited regularly in Python in the same way that static variables are exploited in C. But I agree that it can be confusing when the default is mutable but since the only reasonable option would have been to restrict default values to immutable types I think I prefer the confusion... Alan G. From alan.gauld at freenet.co.uk Fri Feb 11 19:35:54 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 11 19:35:18 2005 Subject: [Tutor] Data storage, SQL? References: <f2ff2d05021023093bb965ef@mail.gmail.com><420C9052.2070009@tds.net> <420CA661.8080900@tds.net> Message-ID: <003501c51068$85c32890$31d78751@xp> > I don't know any good on-line resources for learning SQL I like http://www.sqlcourse.com/ Its got a live SQL prompt so you can practice with their database and see the results. It seems fairly clearly written too. Caveat: I'#ve only gone through a few of the pages to check it out, I haven't followeed it to completion - and I already know SQL which always helps! But its best to get a book that focuses on the specific dialect used by your database in the longer term. Alan G. From alan.gauld at freenet.co.uk Fri Feb 11 19:39:27 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 11 19:39:40 2005 Subject: [Tutor] Simple question on creating a filter References: <C4C644CF4ADA9448904C3E8BACC4B97C02E677FB@medexch1.medplus.com> Message-ID: <004401c51069$254904c0$31d78751@xp> > In Perl I would do: > > while (<>) > { > print if line meets selection criteria; > } You may want to check out the fileinput module. It takes care of multiple files being passed as input and such like too. > for line in sys.stdin: > if line meets selection criteria: > print line > for line in sys.stdin: > IOError: [Errno 9] Bad file descriptor Sorry, I'm stumped - you did import sys I assume? Alan G. From alan.gauld at freenet.co.uk Fri Feb 11 19:42:02 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 11 19:41:24 2005 Subject: [Tutor] Might be a silly question! References: <20050211150330.24150.qmail@mail.vianet.ca> Message-ID: <004501c51069$60abf5e0$31d78751@xp> > Can and if you can how do you set a variable as a constant? Only by resorting to tricks involving classes and properties. There is a cookbook recipe if I recall correctly. Vanilla Python doesn't have the concept of constants other than as a naming convention (all uppercase). Its part of the "we are all consenting adults" approach. Alan G. From alan.gauld at freenet.co.uk Fri Feb 11 19:44:18 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 11 19:43:40 2005 Subject: [Tutor] Re: Might be a silly question! References: <20050211150330.24150.qmail@mail.vianet.ca><797fe3d405021107383f191157@mail.gmail.com> <20050211154742.30487.qmail@mail.vianet.ca> Message-ID: <005901c51069$b1d08350$31d78751@xp> > I have been reading code written before me (mind you it's C++) and the > authors seemed to follow what ever style they wished to that day. And that's C++ style, it has no single standard approach... > that's the nature of the beast. How very true. Alan G. From alan.gauld at freenet.co.uk Fri Feb 11 19:45:51 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 11 19:50:26 2005 Subject: [Tutor] Negative IF conditions References: <420CD4A3.6040105@rogers.com> Message-ID: <005e01c51069$e92f0330$31d78751@xp> > I'm a newbie and was wondering which of these IF conditions is better structure: > 1.. if not os.path.exists('filename'): > 2.. if os.path.exists('filename') == False: Which one reads easiest? I'd say the first one personally. But both are OK. Alan G. From alan.gauld at freenet.co.uk Fri Feb 11 19:51:19 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 11 19:50:47 2005 Subject: [Tutor] help with refactoring needed -- which approach ismorePythonic? References: <420A8938.5040604@po-box.mcgill.ca><07fe01c50f46$60d84240$68b78851@xp> <420CDA1D.5040204@po-box.mcgill.ca> Message-ID: <006d01c5106a$ad0bb2d0$31d78751@xp> > My Example Body > Node List > Node the first > Node the second > > Is there any way to make methods of the Node class access attributes > of `parents' of instances? I would like a Node instance such as Node > the first above to be aware just what it is a node of and what its > siblings are. Pass a reference to the container into the constructor of Node class Body: .... def parse(self): for line in self.contents: if line == NodeStartTag: node = Node(self) if line == NodeEndTag: self.nodes.append(node) node.append(line) And modify the Node constructor to accept and assign the value to self.parent. This is the same approach used in Tkinter to navigate between GUI components such as buttons and theor containing frame. (And to pick up on someone else's question this is why you should put in a __del__ to tidy up the Node list when Body is destructed - otherwise you get circular references which can cause memory leaks by confusing the garbage collector! HTH Alan G. From kent37 at tds.net Fri Feb 11 20:19:14 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Feb 11 20:19:14 2005 Subject: [Tutor] help with refactoring needed -- which approach ismorePythonic? In-Reply-To: <006d01c5106a$ad0bb2d0$31d78751@xp> References: <420A8938.5040604@po-box.mcgill.ca><07fe01c50f46$60d84240$68b78851@xp> <420CDA1D.5040204@po-box.mcgill.ca> <006d01c5106a$ad0bb2d0$31d78751@xp> Message-ID: <420D0532.9050800@tds.net> Alan Gauld wrote: > (And to pick up on someone else's question this is why you should > put in a __del__ to tidy up the Node list when Body is destructed > - otherwise you get circular references which can cause memory > leaks by confusing the garbage collector! CPython has been able to GC cycles since version 2.0. http://www.amk.ca/python/2.0/index.html#SECTION000900000000000000000 AFAIK Java has always been able to GC cycles so Jython should be OK too. Kent From billk at fastmail.fm Fri Feb 11 20:29:51 2005 From: billk at fastmail.fm (Bill Kranec) Date: Fri Feb 11 20:29:46 2005 Subject: [Tutor] Data storage, SQL? In-Reply-To: <001901c51066$80ad0b20$31d78751@xp> References: <f2ff2d05021023093bb965ef@mail.gmail.com> <001901c51066$80ad0b20$31d78751@xp> Message-ID: <420D07AF.3050505@fastmail.fm> I also recommend learning SQL. It is not very hard to learn, and sometimes it may be advantageous to do data manipulation directly in the database, rather than with Python. As far as databases go, I would recommend Firebird, as I have found that it has a good number of features, is free, and yet is also fairly easy to install and run, even on Windows (I could never get MySQL to work quite right). FlameRobin (http://flamerobin.sourceforge.net/) is a nice GUI interface for Firebird. >(Maybe I could do a SQL primer as part of my advanced >topics section in the tutorial... hmm. An intro to SQL then >the next topic showing how to use the Python DBAPI to >link SQL and Python - any takers for that idea?) > >Alan G > I would love to read an in depth explanation of the Python DBAPI. The only thing preventing me from connecting my Python and SQL programs is a lack of understanding of the API, which boils down to ( I think ): 1. How to actually pass SQL code to the database using the API (A good example is all I really need). 2. Why does the API use cursor objects to pass commands to the database? Isn't this inefficient from the SQL point of view? 3. What is the best way to deal with the returned result set? Can I assign it to a list or dictionary? I apologize if any of these questions are overly ignorant, and would be very appreciative for any help. Bill From dyoo at hkn.eecs.berkeley.edu Fri Feb 11 20:35:41 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Feb 11 20:35:49 2005 Subject: [Tutor] Simple question on creating a filter In-Reply-To: <C4C644CF4ADA9448904C3E8BACC4B97C02E677FB@medexch1.medplus.com> Message-ID: <Pine.LNX.4.44.0502111127010.17698-100000@hkn.eecs.berkeley.edu> On Fri, 11 Feb 2005, Smith, Jeff wrote: > I'm sorry to both with such a simple question but I've looked in the > normal places and don't see the quick and dirty answer I know must > exist. > > I want to write a simple line selection filter that could be used like: > > filter < file > > I get the following at runtime: > > Traceback (most recent call last): > File "U:\TimeKeeper\mine.py", line 2, in ? > for line in sys.stdin: > IOError: [Errno 9] Bad file descriptor Hi Jeff, Ok there might be a problem with Windows; I see: http://mail.python.org/pipermail/python-list/2002-May/104962.html which sounds really similar to the problem you're seeing. here appears to be a bug in the Windows shell that you may need to work around. The most common workaround I see is wrapping the program with a 'cmd' file. So you can do write a "mine.cmd" program with the following content: ### mine.cmd @python mine.py %* ### After which, you should be able to say: mine < file and things should work again. There's a thread about this issue here: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/c5c687b31434a168/e6e6da312e7b18c6#e6e6da312e7b18c6 Best of wishes to you! From zen45800 at zen.co.uk Sat Feb 12 05:21:12 2005 From: zen45800 at zen.co.uk (Lobster) Date: Fri Feb 11 21:21:00 2005 Subject: [Tutor] Idle needles Message-ID: <420D8438.7050208@zen.co.uk> Hi Just started with Idle and Python :-) The tutorials I am accessing with Firefox and there seems to be a conflict in which the Idle editor is trying to (or reported as accessing the Net but does not (according to the literature and warning) More seriously I can not run Idle and Firefox together Not quite sure what to do other than download the whole web sites? Any help or solutions most welcome. Very pleased with what I have learned so far :-) I am using Win98 Python 2.4 and Zone Alarm Ed Jason From bgailer at alum.rpi.edu Fri Feb 11 21:28:34 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri Feb 11 21:23:08 2005 Subject: [Tutor] Negative IF conditions In-Reply-To: <420CD4A3.6040105@rogers.com> References: <420CD4A3.6040105@rogers.com> Message-ID: <6.1.2.0.0.20050211132646.03558d68@mail.mric.net> At 08:52 AM 2/11/2005, Mark Brown wrote: >Hi, >I'm a newbie and was wondering which of these IF conditions is better >structure: if not os.path.exists('filename'): IMHO the above is preferable to the below. It is much more "intuitive". if os.path.exists('filename') == False: Bob Gailer mailto:bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050211/5d0a0236/attachment.htm From bgailer at alum.rpi.edu Fri Feb 11 21:34:14 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri Feb 11 21:32:35 2005 Subject: ****SPAM(11.2)**** [Tutor] Larger program organization In-Reply-To: <20050211173944.07AAC1E4008@bag.python.org> References: <20050211173944.07AAC1E4008@bag.python.org> Message-ID: <6.1.2.0.0.20050211132921.036258d8@mail.mric.net> At 10:39 AM 2/11/2005, Ryan Davis wrote: >I'm starting to make a code-generation suite in python, customized to the >way we ASP.NET at my company, and I'm having some trouble finding a good >way to organize all the code. My take on doing that in Python: Organize things into modules. Especially with an eye to potential reuse. Look at the module index in the docs to see how most of the "standard" modules focus on doing one thing well. Within a module create classes for every conceivable object. Whenever you find yourself writing an if statement ask whether this would be better handled by subclasses. Whenever you find yourself about to write a global statement, consider making the variables properties of a class. Within classes create methods applicable to those classes. Within subclasses create methods applicable to those subclasses. >I keep writing it, but it feels more and more spaghetti-ish every day. > >I'm going to look at the other stuff in site-packages to see if I can >glean any wisdom, and have googled a bit, coming up mostly blank or with >trivial examples. Are there any helpful links or advice anyone has for >building larger systems? > >My background is mostly C#, so I'm used to the ridiculous rigidity of >strongly-typed languages. I have been using python for helper apps for a >few months now, so am pretty familiar with the syntax now, but I don't >know any of the patterns yet. My nefarious goal is to supplant C#/ASP.NET >with Python, but I need to figure out how to make programs clients want to >pay for before I can make any reasonable argument. > >Thanks, >Ryan >---- >Ryan Davis >Director of Programming Services ><http://www.acceleration.net/>http://www.acceleration.net/ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor Bob Gailer mailto:bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050211/cea801ea/attachment.html From project5 at redrival.net Fri Feb 11 20:07:23 2005 From: project5 at redrival.net (Andrei) Date: Fri Feb 11 21:34:05 2005 Subject: [Tutor] Re: Negative IF conditions In-Reply-To: <420CD4A3.6040105@rogers.com> References: <420CD4A3.6040105@rogers.com> Message-ID: <cuivlo$ju2$1@sea.gmane.org> Mark Brown wrote: > I'm a newbie and was wondering which of these IF conditions is better > structure: > > 1. if not os.path.exists('filename'): > 2. if os.path.exists('filename') == False: I prefer the "if not" variety. Yours, Andrei From kent37 at tds.net Fri Feb 11 21:38:18 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Feb 11 21:38:15 2005 Subject: [Tutor] Negative IF conditions In-Reply-To: <420CD4A3.6040105@rogers.com> References: <420CD4A3.6040105@rogers.com> Message-ID: <420D17BA.80909@tds.net> Mark Brown wrote: > Hi, > I'm a newbie and was wondering which of these IF conditions is better > structure: > > 1. if not os.path.exists('filename'): I prefer the above. > 2. if os.path.exists('filename') == False: > > They both work so if one preferred over the other? Note that in Python in general, 'not x' and 'x == False' are not equivalent; 'not x' will be true for many more values than just False. For example not 0 not 0.0 not [] not {} are all True. Kent > Thanks > Mark Brown > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From bgailer at alum.rpi.edu Fri Feb 11 22:09:00 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri Feb 11 22:03:24 2005 Subject: [Tutor] Negative IF conditions In-Reply-To: <420D17BA.80909@tds.net> References: <420CD4A3.6040105@rogers.com> <420D17BA.80909@tds.net> Message-ID: <6.1.2.0.0.20050211140749.0337a438@mail.mric.net> At 01:38 PM 2/11/2005, Kent Johnson wrote: >Mark Brown wrote: >>Hi, >>I'm a newbie and was wondering which of these IF conditions is better >>structure: >> 1. if not os.path.exists('filename'): > >I prefer the above. > >> 2. if os.path.exists('filename') == False: >>They both work so if one preferred over the other? > >Note that in Python in general, 'not x' and 'x == False' are not >equivalent; 'not x' will be true for many more values than just False. For >example >not 0 >not 0.0 >not [] >not {} > >are all True. Oops. 0 and 0.0 do == False. Bob Gailer mailto:bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From kent37 at tds.net Fri Feb 11 22:11:05 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Feb 11 22:11:02 2005 Subject: [Tutor] Negative IF conditions In-Reply-To: <6.1.2.0.0.20050211140749.0337a438@mail.mric.net> References: <420CD4A3.6040105@rogers.com> <420D17BA.80909@tds.net> <6.1.2.0.0.20050211140749.0337a438@mail.mric.net> Message-ID: <420D1F69.2020805@tds.net> Bob Gailer wrote: > At 01:38 PM 2/11/2005, Kent Johnson wrote: >> Note that in Python in general, 'not x' and 'x == False' are not >> equivalent; 'not x' will be true for many more values than just False. >> For example >> not 0 >> not 0.0 >> not [] >> not {} >> >> are all True. > > > Oops. 0 and 0.0 do == False. Uh, right. Thanks! Kent From bgailer at alum.rpi.edu Fri Feb 11 22:06:26 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri Feb 11 22:24:06 2005 Subject: [Tutor] Negative IF conditions In-Reply-To: <420D17BA.80909@tds.net> References: <420CD4A3.6040105@rogers.com> <420D17BA.80909@tds.net> Message-ID: <6.1.2.0.0.20050211140608.036243d0@mail.mric.net> At 01:38 PM 2/11/2005, Kent Johnson wrote: >Mark Brown wrote: >>Hi, >>I'm a newbie and was wondering which of these IF conditions is better >>structure: >> 1. if not os.path.exists('filename'): > >I prefer the above. > >> 2. if os.path.exists('filename') == False: >>They both work so if one preferred over the other? > >Note that in Python in general, 'not x' and 'x == False' are not >equivalent; 'not x' will be true for many more values than just False. For >exampl >not 0 >not 0.0 >not [] >not {} > >are all True. > >Kent > >>Thanks >>Mark Brown >> >>------------------------------------------------------------------------ >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor Bob Gailer mailto:bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From dyoo at hkn.eecs.berkeley.edu Fri Feb 11 22:36:37 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Feb 11 22:36:41 2005 Subject: [Tutor] Idle needles In-Reply-To: <420D8438.7050208@zen.co.uk> Message-ID: <Pine.LNX.4.44.0502111333230.17698-100000@hkn.eecs.berkeley.edu> On Fri, 11 Feb 2005, Lobster wrote: > The tutorials I am accessing with Firefox and there seems to be a > conflict in which the Idle editor is trying to (or reported as accessing > the Net but does not (according to the literature and warning) Hello! IDLE does use network connections to talk to itself --- namely, whenever we execute a program in IDLE, it creates a new program process and runs our program in that new process. The IDLE environment talks to that new process through a network socket, so all the communication is in-house, but you might still see something from ZoneAlarm warning about that communication. There's a note about this here: http://www.python.org/2.4/bugs.html It's not really a bug; but it is something unexpected for folks who are using ZoneAlarm. > More seriously I can not run Idle and Firefox together Not quite sure > what to do other than download the whole web sites? What happens if you try running both of them together? Do either of them fail to start up? Firefox and IDLE should not conflict; if you can tell us more details, we'll try to figure out what's going wrong. Best of wishes to you! From dyoo at hkn.eecs.berkeley.edu Fri Feb 11 22:38:47 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Feb 11 22:38:54 2005 Subject: ****SPAM(11.2)**** [Tutor] Larger program organization In-Reply-To: <6.1.2.0.0.20050211132921.036258d8@mail.mric.net> Message-ID: <Pine.LNX.4.44.0502111337020.17698-100000@hkn.eecs.berkeley.edu> > >way we ASP.NET at my company, and I'm having some trouble finding a good > >way to organize all the code. > > My take on doing that in Python: > > Organize things into modules. Especially with an eye to potential reuse. > Look at the module index in the docs to see how most of the "standard" > modules focus on doing one thing well. Hi Ryan, And just making sure; are you using packages? http://www.python.org/doc/tut/node8.html#SECTION008400000000000000000 Most large Python programs that I've seen will first partition their functionality into modules, and if that's not enough, then they further break themselves down into packages. Best of wishes to you! From sigurd at 12move.de Fri Feb 11 22:44:30 2005 From: sigurd at 12move.de (Karl =?iso-8859-1?Q?Pfl=E4sterer?=) Date: Fri Feb 11 22:47:25 2005 Subject: [Tutor] default argument frustration In-Reply-To: <001e01c51067$bd0478f0$31d78751@xp> (Alan Gauld's message of "Fri, 11 Feb 2005 18:30:17 -0000") References: <420A8938.5040604@po-box.mcgill.ca> <07fe01c50f46$60d84240$68b78851@xp> <420C670B.4070209@po-box.mcgill.ca> <001e01c51067$bd0478f0$31d78751@xp> Message-ID: <ud5v6hlh8.fsf@hamster.pflaesterer.de> On 11 Feb 2005, alan.gauld@freenet.co.uk wrote: >> FOR THE LOVE OF MIKE can someone tell me even one reason why this >> isn't a misfeature?!?! > Its the only sane way to implement default arguments. The whole > point of function definitions is that they provide a single concise > interface. The function should return the same result each time > you call it with the same input. The only way to achieve that > is to have the default calculated once. IBTD. With full lexical scope you only need to calculate the default argument in the lexical scope it was defined in. Look at a languale like Common Lisp. Here is first an example in Python: .>>> def mutate_list (L=list()): .... L.append(1) .... return L .... .>>> mutate_list() .[1] .>>> mutate_list() .[1, 1] .>> Now the same in Common Lisp: [17]> (defun dont-mutate (&optional (L (list))) (push 1 L)) DONT-MUTATE [18]> (dont-mutate) (1) [19]> (dont-mutate) (1) As you can see here I defined an optional argument L and as default value a list (the same as in Python). But the difference is: each call of that function evaluates the default argument in the lexical environment it was defined in (`push' is a destructive function). To make that clearer here is a second version where I shadow the definition of `list' (with labels I can shadow the lexical function binding of a symbol (here the symbol `list')). After the labels form is closed the old binding of `list' is restored. [20]> (labels ((list (&optional &rest args) (apply 'list 'shadow args))) (defun dont-mutate-with-shadowed-list (&optional (L (list))) (push 1 L))) DONT-MUTATE-WITH-SHADOWED-LIST [21]> (dont-mutate-with-shadowed-list) (1 SHADOW) [22]> (dont-mutate-with-shadowed-list) (1 SHADOW) [23]> (list 1 2) (1 2) So these functions return the same result each time you call them with the same arguments (even with mutable default arguments). [...] > But I agree that it can be confusing when the default is mutable > but since the only reasonable option would have been to restrict > default values to immutable types I think I prefer the confusion... You see it can be done different (I'm not sure which version is better; both will have their advantages). Karl -- Please do *not* send copies of replies to me. I read the list From reg at plaguerats.net Fri Feb 11 22:52:20 2005 From: reg at plaguerats.net (Matt Dimmic) Date: Fri Feb 11 22:52:40 2005 Subject: [Tutor] References in loops Message-ID: <000a01c51083$f9ef0ac0$8eaaec84@CuriousGeorge> In Python, one bug that often bites me is this: (example A) aList = [1,2,3] for i in aList: i += 1 print aList --> [1,2,3] This goes against my intuition, which is that aList == [2,3,4], probably because so much in Python is passed by reference and not by value. Of course I can always use range() or enumerate(): (example B) aList = [1,2,3] for i in range(len(aList)): aList[i] += 1 print aList --> [4,5,6] But example A seems more elegant, if only it did what I wanted it to do. :) So pardon my ignorance if the answer is obvious, but what is the simplest way in Python to get a reference to an element in a list? Is it really Example B? Thanks, Matt (My apologies if this double-posts; I accidentally sent it previously from a non-subscribed address. Moderator, please deny the other copy.) From tegmine at gmail.com Fri Feb 11 22:53:40 2005 From: tegmine at gmail.com (Luis N) Date: Fri Feb 11 22:53:43 2005 Subject: [Tutor] elementtree, lists, and dictionaries Message-ID: <77bfa81a050211135376b1843f@mail.gmail.com> Hi, This code works, but I don't like it much: def authenticateAuthor(author, password): authorxml = 'author.xml' path = os.path.join(xml, authorxml) try: if not os.path.exists(path): authorfile = False else: authorfile = True tree = E.ElementTree(file=path) u = tree.getiterator('user') p = tree.getiterator('password') ul = [] pl = [] for unode in u: ul.append(unode.text) for pnode in p: pl.append(pnode.text) d = {} for i in range(len(ul)): d[ul[i]] = pl[i] if d.has_key(author): if d.get(author) == password: auth = True else: auth = False return auth, authorfile It assumes a great deal, such as that there is no chance that there will be more users then there are passwords, etc. given an xml document format such as: <root> <author> <user>authorname</user> <password>authorpassword</password> </author> </root> I don't like how I'm making two lists and then turning them into a dictionary. It seems unpythonic. Suggestions are appreciated. From dyoo at hkn.eecs.berkeley.edu Fri Feb 11 23:32:49 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Feb 11 23:32:57 2005 Subject: [Tutor] References in loops In-Reply-To: <000a01c51083$f9ef0ac0$8eaaec84@CuriousGeorge> Message-ID: <Pine.LNX.4.44.0502111405420.17698-100000@hkn.eecs.berkeley.edu> On Fri, 11 Feb 2005, Matt Dimmic wrote: > In Python, one bug that often bites me is this: > > (example A) > aList = [1,2,3] > for i in aList: > i += 1 > print aList > --> [1,2,3] > > This goes against my intuition, which is that aList == [2,3,4], probably > because so much in Python is passed by reference and not by value. Hi Matt, Yes. If we "unroll" the loop, we can better see what's going on: ### aList = [1, 2, 3] i = aList[0] i += 1 i = aList[1] i += 1 i = aList[2] i += 1 print aList ### This has the same meaning as Example A, and it should be clearer why the assignment to 'i' has no affect. 'i' is just a regular local variable, just like any other local variable. Assignment is not the same thing as value mutation; it's actually the same issue that we talked about earlier with the default argument thread. *grin* When I see something like: ### x = 42 y = x y = y + 1 ### My visual model of this is that variable names are "arrows" to values: -------------------------------------------------- x -----------> 42 ## x = 42 ---------------------------------------------------- x -----------> 42 ## y = x ^ / y -----------/ ---------------------------------------------------- x -----------> 42 ## y = y + 1 y -----------> 43 ---------------------------------------------------- That being said, we can do something here with a little indirection: ### >>> def box(x): ... """Put a mutable wrapper around the value x.""" ... return [x] ... >>> def unbox(boxedValue): ... """Grab the value in the box.""" ... return boxedValue[0] ... >>> def incr(boxedValue): ... """Increment the value in the box.""" ... boxedValue[0] += 1 ... >>> >>> >>> aList = [box(1), box(2), box(3)] >>> map(unbox, aList) [1, 2, 3] >>> for b in aList: ... incr(b) ... >>> map(unbox, aList) [2, 3, 4] ### This might be overkill, though. *grin* But this shows that, if we really needed to, we could "box" everything in some kind of mutable container. I don't recommend this for normal Python programming, though. > Of course I can always use range() or enumerate(): > > (example B) > aList = [1,2,3] > for i in range(len(aList)): > aList[i] += 1 > print aList > --> [4,5,6] > > But example A seems more elegant, if only it did what I wanted it to do. > :) So pardon my ignorance if the answer is obvious, but what is the > simplest way in Python to get a reference to an element in a list? Is it > really Example B? A variation of Example B, with enumerate(), is probably the most straightforward way to do in-place mutation on the list in Python: ### aList = [1, 2, 3] for i, x in enumerate(aList): aList[i] = x + 1 print aList ### There are languages that magically allow us to do mutation on a list without making it look like list mutation. Perl is one of those languages that adds magic syntactic sugar for doing in-place list stuff. But Python has no special mechanisms for doing this. The main issue that I think people are running against is that, in Python, numeric values are "immutable" --- they can't be changed. When we do things like addition: ### >>> x = 7 >>> x = x + 1 ### we are not changing the value of '7': we're just "re-aiming" or directing 'x' to the new value '8'. If you have more questions, please feel free to ask! From alan.gauld at freenet.co.uk Sat Feb 12 00:50:54 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Feb 12 00:50:13 2005 Subject: [Tutor] help with refactoring needed -- whichapproach ismorePythonic? References: <420A8938.5040604@po-box.mcgill.ca><07fe01c50f46$60d84240$68b78851@xp> <420CDA1D.5040204@po-box.mcgill.ca><006d01c5106a$ad0bb2d0$31d78751@xp> <420D0532.9050800@tds.net> Message-ID: <00a201c51094$87226670$31d78751@xp> > > - otherwise you get circular references which can cause memory > > leaks by confusing the garbage collector! > > CPython has been able to GC cycles since version 2.0. Yep but it takes a lot longer. The cycle detection sweep only occurs periodically if I remember rightly, and if you are doing a lot of processing you can still get process growth. So as a matter of course I tend to add a __del__ any time I create a list of objects inside another object. Maybe its just my C++ paranoia showing through! :-) Alan G. From cyresse at gmail.com Sat Feb 12 01:05:52 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sat Feb 12 01:05:55 2005 Subject: [Tutor] Re: Might be a silly question! In-Reply-To: <005901c51069$b1d08350$31d78751@xp> References: <20050211150330.24150.qmail@mail.vianet.ca> <797fe3d405021107383f191157@mail.gmail.com> <20050211154742.30487.qmail@mail.vianet.ca> <005901c51069$b1d08350$31d78751@xp> Message-ID: <f2ff2d05021116056952f714@mail.gmail.com> I suppose, you could do it like this - gamma = 5, and access with gamma[0]. But, there'd be nothing to stop you reassigning gamma. On Fri, 11 Feb 2005 18:44:18 -0000, Alan Gauld <alan.gauld@freenet.co.uk> wrote: > > I have been reading code written before me (mind you it's C++) and > the > > authors seemed to follow what ever style they wished to that day. > > And that's C++ style, it has no single standard approach... > > > that's the nature of the beast. > > How very true. > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From project5 at redrival.net Sat Feb 12 01:38:18 2005 From: project5 at redrival.net (Andrei) Date: Sat Feb 12 01:38:37 2005 Subject: [Tutor] Re: References in loops In-Reply-To: <000a01c51083$f9ef0ac0$8eaaec84@CuriousGeorge> References: <000a01c51083$f9ef0ac0$8eaaec84@CuriousGeorge> Message-ID: <cujj2b$jig$1@sea.gmane.org> Matt Dimmic wrote: > In Python, one bug that often bites me is this: > > (example A) > aList = [1,2,3] > for i in aList: > i += 1 > print aList > --> [1,2,3] Numbers are immutable, so the element 1 can't change into a 2 inside the list. If 1 was not immutable, e.g. a list you could modify it and then it would be "updated" in the original list too. > This goes against my intuition, which is that aList == [2,3,4], probably > because so much in Python is passed by reference and not by value. Of > course I can always use range() or enumerate(): I tend to use list comprehensions for this: aList = [elem+1 for elem in aList] but it's barely shorter than the explicit loop, so not necessarily an improvement from that point of view. But at least it prevents the bug from biting :). Yours, Andrei From keridee at jayco.net Sat Feb 12 03:13:13 2005 From: keridee at jayco.net (Jacob S.) Date: Sat Feb 12 03:14:03 2005 Subject: [Tutor] References in loops References: <Pine.LNX.4.44.0502111405420.17698-100000@hkn.eecs.berkeley.edu> Message-ID: <004401c510a8$8246b7f0$105428cf@JSLAPTOP> Of all the odd quirks of python, this is the only thing that has bitten be in the butt. And several, several times. List comprehensions have similar limitations as python lambdas, however, so I guess the only way to execute several expressions on the item in the list would be to pass the item to a function and return the changed item? Thoughts, Jacob > On Fri, 11 Feb 2005, Matt Dimmic wrote: > >> In Python, one bug that often bites me is this: >> >> (example A) >> aList = [1,2,3] >> for i in aList: >> i += 1 >> print aList >> --> [1,2,3] >> >> This goes against my intuition, which is that aList == [2,3,4], probably >> because so much in Python is passed by reference and not by value. > > > Hi Matt, > > > Yes. If we "unroll" the loop, we can better see what's going on: > > ### > aList = [1, 2, 3] > i = aList[0] > i += 1 > i = aList[1] > i += 1 > i = aList[2] > i += 1 > print aList > ### > > This has the same meaning as Example A, and it should be clearer why the > assignment to 'i' has no affect. 'i' is just a regular local variable, > just like any other local variable. > > Assignment is not the same thing as value mutation; it's actually the same > issue that we talked about earlier with the default argument thread. > *grin* > > > > When I see something like: > > ### > x = 42 > y = x > y = y + 1 > ### > > > My visual model of this is that variable names are "arrows" to values: > > -------------------------------------------------- > > x -----------> 42 ## x = 42 > > ---------------------------------------------------- > > x -----------> 42 ## y = x > ^ > / > y -----------/ > > ---------------------------------------------------- > > x -----------> 42 ## y = y + 1 > > y -----------> 43 > > ---------------------------------------------------- > > > > That being said, we can do something here with a little indirection: > > ### >>>> def box(x): > ... """Put a mutable wrapper around the value x.""" > ... return [x] > ... >>>> def unbox(boxedValue): > ... """Grab the value in the box.""" > ... return boxedValue[0] > ... >>>> def incr(boxedValue): > ... """Increment the value in the box.""" > ... boxedValue[0] += 1 > ... >>>> >>>> >>>> aList = [box(1), box(2), box(3)] >>>> map(unbox, aList) > [1, 2, 3] >>>> for b in aList: > ... incr(b) > ... >>>> map(unbox, aList) > [2, 3, 4] > ### > > This might be overkill, though. *grin* > > But this shows that, if we really needed to, we could "box" everything in > some kind of mutable container. I don't recommend this for normal Python > programming, though. > > > >> Of course I can always use range() or enumerate(): >> >> (example B) >> aList = [1,2,3] >> for i in range(len(aList)): >> aList[i] += 1 >> print aList >> --> [4,5,6] >> >> But example A seems more elegant, if only it did what I wanted it to do. >> :) So pardon my ignorance if the answer is obvious, but what is the >> simplest way in Python to get a reference to an element in a list? Is it >> really Example B? > > A variation of Example B, with enumerate(), is probably the most > straightforward way to do in-place mutation on the list in Python: > > ### > aList = [1, 2, 3] > for i, x in enumerate(aList): > aList[i] = x + 1 > print aList > ### > > There are languages that magically allow us to do mutation on a list > without making it look like list mutation. Perl is one of those languages > that adds magic syntactic sugar for doing in-place list stuff. But Python > has no special mechanisms for doing this. > > > The main issue that I think people are running against is that, in Python, > numeric values are "immutable" --- they can't be changed. When we do > things like addition: > > ### >>>> x = 7 >>>> x = x + 1 > ### > > we are not changing the value of '7': we're just "re-aiming" or directing > 'x' to the new value '8'. > > > If you have more questions, please feel free to ask! > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From nbbalane at gmail.com Sat Feb 12 03:17:01 2005 From: nbbalane at gmail.com (jrlen balane) Date: Sat Feb 12 03:17:04 2005 Subject: [Tutor] What does this mean Message-ID: <2cad2090050211181719a6834e@mail.gmail.com> what does (*args, **kwargs) mean??? i'm sort of a bit confused... thanks. From zanesdad at bellsouth.net Sat Feb 12 03:39:46 2005 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Sat Feb 12 03:38:43 2005 Subject: [Tutor] What does this mean In-Reply-To: <2cad2090050211181719a6834e@mail.gmail.com> References: <2cad2090050211181719a6834e@mail.gmail.com> Message-ID: <420D6C72.4030404@bellsouth.net> jrlen balane wrote: >what does (*args, **kwargs) mean??? i'm sort of a bit confused... thanks. >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > *args is notation for list of arguments. **kwargs is notation for keyword arguments. Here is an example: ####################### In [1]: def foo(bar, *args, **kwargs): ...: print "bar", bar ...: print "args", args ...: print "kwargs", kwargs ...: In [2]: foo('1') bar 1 args () kwargs {} In [3]: foo('1', 1, 2, 3) bar 1 args (1, 2, 3) kwargs {} In [4]: foo('1', 1, 2, 3, bam=1, baz=2, boo=3) bar 1 args (1, 2, 3) kwargs {'bam': 1, 'baz': 2, 'boo': 3} ####################### In the definition (at prompt [1]), I only stated 3 arguments to pass in: bar, args, and kwargs. At prompt [2], I pass in a "1" string as my only argument, which gets assigned to "bar". At prompt [3], I pass in "1", 1, 2, 3. "1" gets assigned to foo as in the previous example. (1,2,3) gets assigned to args. The *args notations says, "Assign any following arguments to the args variable." At prompt [4], I pass in the same thing as at [3], but pass in keyword arguments (bam=1, baz=2, boo=3). Everything gets assigned as it did at [3] except kwargs is a dictionary with keys 'bam', 'baz', and 'boo' with respective values 1,2,3. The **kwargs notations says, "Assign any subsequent keyword arguments to kwargs." NOTE - you don't have to use *args and **kwargs. You just have to use the * and **. Jeremy Jones From kent37 at tds.net Sat Feb 12 04:28:55 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat Feb 12 04:28:59 2005 Subject: [Tutor] elementtree, lists, and dictionaries In-Reply-To: <77bfa81a050211135376b1843f@mail.gmail.com> References: <77bfa81a050211135376b1843f@mail.gmail.com> Message-ID: <420D77F7.6090609@tds.net> If you iterate over the author nodes you can check the user name and password of each in turn. Not tested code! def authenticateAuthor(author, password): authorxml = 'author.xml' path = os.path.join(xml, authorxml) if not os.path.exists(path): return False, False else: tree = E.ElementTree(file=path) for authorNode in tree.getiterator('author'): user = authorNode.find('user').text pass = authorNode.find('password').text if author == user: if password == pass: return True, True else: return False, True return False, True Luis N wrote: > Hi, > > This code works, but I don't like it much: > > def authenticateAuthor(author, password): > authorxml = 'author.xml' > path = os.path.join(xml, authorxml) > try: if not os.path.exists(path): > authorfile = False > else: > authorfile = True > tree = E.ElementTree(file=path) > u = tree.getiterator('user') > p = tree.getiterator('password') Here you could say d = dict( (unode.text, pnode.text) for unode, pnode in zip(u, p)) > ul = [] > pl = [] > for unode in u: > ul.append(unode.text) > for pnode in p: > pl.append(pnode.text) > d = {} > for i in range(len(ul)): > d[ul[i]] = pl[i] > if d.has_key(author): > if d.get(author) == password: > auth = True > else: > auth = False or try: if d[author] == password: auth = True except KeyError: auth = False or, if you are sure password will not be None, just skip the has_key(): if d.get(author) == password: ... (I hate using has_key() followed by a get()... > return auth, authorfile > > It assumes a great deal, such as that there is no chance that there > will be more users then there are passwords, etc. given an xml > document format such as: > > <root> > <author> > <user>authorname</user> > <password>authorpassword</password> > </author> > </root> > > I don't like how I'm making two lists and then turning them into a > dictionary. It seems unpythonic. > > Suggestions are appreciated. > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From zen45800 at zen.co.uk Sat Feb 12 13:29:48 2005 From: zen45800 at zen.co.uk (Lobster) Date: Sat Feb 12 05:29:34 2005 Subject: [Tutor] Idle needles In-Reply-To: <Pine.LNX.4.44.0502111333230.17698-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0502111333230.17698-100000@hkn.eecs.berkeley.edu> Message-ID: <420DF6BC.1040701@zen.co.uk> Danny Yoo wrote: >>More seriously I can not run Idle and Firefox together Not quite sure >>what to do other than download the whole web sites? thanks for the info Danny :-) >What happens if you try running both of them together? Do either of them >fail to start up? > >Firefox and IDLE should not conflict; if you can tell us more details, >we'll try to figure out what's going wrong. > > >Best of wishes to you! They load up. This is the error message I get from IDLE when trying to compile the program ========= Idols subprocess didn't make connection Either Idle can't start or personal firewall is blocking the connection ========= I am allowing the connection from zonealarm. Even tried allowing IDLE to be a server. Would I be better off using the windows only editor (do not want to as I will also be working in Linux)? I tried from a fresh boot and everything seemed OK - then after looking at some email in thunderbird - tried to compile a new program and got the above message. So maybe it is time loop based? Appreciate the help :-) Ed Jason From zen45800 at zen.co.uk Sat Feb 12 13:40:01 2005 From: zen45800 at zen.co.uk (Lobster) Date: Sat Feb 12 05:39:46 2005 Subject: [Tutor] Idle needles In-Reply-To: <Pine.LNX.4.44.0502111333230.17698-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0502111333230.17698-100000@hkn.eecs.berkeley.edu> Message-ID: <420DF921.1010605@zen.co.uk> Danny Yoo wrote: More Info ========= Idols subprocess didn't make connection Either Idle can't start or personal firewall is blocking the connection ========= Now I am getting the added message that the "socket connection is refused" (recently updated to the latest Zone Alarm) Ed Jason From javier at ruere.com.ar Sat Feb 12 05:55:06 2005 From: javier at ruere.com.ar (Javier Ruere) Date: Sat Feb 12 05:51:56 2005 Subject: [Tutor] Re: Larger program organization In-Reply-To: <20050211173944.07AAC1E4008@bag.python.org> References: <20050211173944.07AAC1E4008@bag.python.org> Message-ID: <cuk1s7$ofe$1@sea.gmane.org> Ryan Davis wrote: > I'm starting to make a code-generation suite in python, customized to > the way we ASP.NET at my company, and I'm having some trouble finding a > good way to organize all the code. I keep writing it, but it feels more > and more spaghetti-ish every day. > > I'm going to look at the other stuff in site-packages to see if I can > glean any wisdom, and have googled a bit, coming up mostly blank or with > trivial examples. Are there any helpful links or advice anyone has for > building larger systems? > > My background is mostly C#, so I'm used to the ridiculous rigidity of > strongly-typed languages. I have been using python for helper apps for a > few months now, so am pretty familiar with the syntax now, but I don't > know any of the patterns yet. My nefarious goal is to supplant > C#/ASP.NET with Python, but I need to figure out how to make programs > clients want to pay for before I can make any reasonable argument. I have worked with C# + ASP.NET and liked it very much. It felt more similar to Python than Java; and ASP.NET rules! :) WRT your original question: Organize the code as you would in a C# project unless it feels unnatural. Sorry about that last condition but it's the best I can do[1]. :) Get Bicycle Repair Man[2] or another refactoring browser and hack away! Javier [1] Some usefull links: http://dirtsimple.org/2005/01/courage-to-do-things-simply.html http://dirtsimple.org/2004/12/python-is-not-java.html http://dirtsimple.org/2004/12/java-is-not-python-either.html [2] http://bicyclerepair.sourceforge.net/ From nbbalane at gmail.com Sat Feb 12 06:36:18 2005 From: nbbalane at gmail.com (jrlen balane) Date: Sat Feb 12 06:36:23 2005 Subject: [Tutor] what is wrong with this? Message-ID: <2cad209005021121365aee64a5@mail.gmail.com> this code is for a MDIChildFrame, It has a MDIParentFrame and when I run the MDIPrentFrame, there seems to be no problem, but when I attempt to edit the MDIChildFrame using the designer mode in BOA (i'm using BOA by the way), an error occurs that says: TypeError: wxGrid_CreateGrid() takes at least 3 arguments (2 given) please help. here is the code: from wxPython.wx import * from wxPython.grid import * from wxPython.lib.mixins.grid import wxGridAutoEditMixin def create(parent): return wxMDIChildFrame1(parent) [wxID_WXMDICHILDFRAME1, wxID_WXMDICHILDFRAME1GRID1, ] = map(lambda _init_ctrls: wxNewId(), range(2)) class wxMDIChildFrame1(wxMDIChildFrame): def _init_ctrls(self, prnt): # generated method, don't edit wxMDIChildFrame.__init__(self, id=wxID_WXMDICHILDFRAME1, name='WXMDICHILDFRAME1', parent=prnt, pos=wxPoint(70, 147), size=wxSize(748, 331), style=wxDEFAULT_FRAME_STYLE, title='Table') self.SetClientSize(wxSize(740, 297)) self.grid1 = wxGrid(id=wxID_WXMDICHILDFRAME1GRID1, name='grid1', parent=self, pos=wxPoint(0, 0), size=wxSize(740, 297), style=0) self.grid1.CreateGrid(100,6) self.grid1.SetColLabelValue(0, "Time") self.grid1.SetColLabelValue(1, "Irradiance") self.grid1.SetColLabelValue(2, "Module Temperature") self.grid1.SetColLabelValue(3, "Ambient Temperature") self.grid1.SetColLabelValue(4, "Voltage") self.grid1.SetColLabelValue(5, "Current") self.grid1.SetColSize(2, 125) self.grid1.SetColSize(3, 127) self.grid1.SetColLabelAlignment(wxALIGN_LEFT, wxALIGN_BOTTOM) def __init__(self, parent): self._init_ctrls(parent) From dyoo at hkn.eecs.berkeley.edu Sat Feb 12 08:03:31 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Feb 12 08:03:37 2005 Subject: [Tutor] Idle needles In-Reply-To: <420DF921.1010605@zen.co.uk> Message-ID: <Pine.LNX.4.44.0502112254210.17739-100000@hkn.eecs.berkeley.edu> On Sat, 12 Feb 2005, Lobster wrote: > Idols subprocess didn't make connection Either Idle can't start or > personal firewall is blocking the connection ========= > > Now I am getting the added message that the "socket connection is > refused" (recently updated to the latest Zone Alarm) Hi Ed, That's further evidence that suggests that Zone Alarm is fighting IDLE. Let me see... here's a section of the IDLE documentation README that talks about this issue: """ IDLE displays a new message upon startup: some "personal firewall" kinds of programs (for example, ZoneAlarm) open a dialog of their own when any program opens a socket. IDLE does use sockets, talking on the computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. So, if you get such a dialog when opening IDLE, asking whether to let pythonw.exe talk to address 127.0.0.1, say yes, and rest assured no communication external to your machine is taking place. If you don't allow it, IDLE won't be able to start. """ Just to nail this issue down: try turning ZoneAlarm off, just for a moment, and then start up IDLE. (You can always turn ZoneAlarm back on after this experiment.) If you don't see any problems with IDLE, then it's almost certainly a ZoneAlarm vs. IDLE confrontation, and we can focus on that. Good luck to you! From ejp at zomething.com Sat Feb 12 08:31:45 2005 From: ejp at zomething.com (EJP) Date: Sat Feb 12 08:31:54 2005 Subject: [Tutor] Larger program organization In-Reply-To: <20050211173944.07AAC1E4008@bag.python.org> References: <20050211173944.07AAC1E4008@bag.python.org> Message-ID: <20050211233145.2130185092.ejp@zomething.com> "Ryan Davis" ryan@acceleration.net wrote My background is mostly C#, so I'm used to the ridiculous rigidity of strongly-typed languages. I have been using python for helper apps for a few months now, so am pretty familiar with the syntax now, but I don't know any of the patterns yet. My nefarious goal is to supplant C#/ASP.NET with Python, but I need to figure out how to make programs clients want to pay for before I can make any reasonable argument. without trying to make this one of those classic threads of great, do you feel you could develop fairly complex applications faster in Python than in C#/ASP.NET? It's a rhetorical question (but I'm interested in your answer as a single data point) Speed to market and hours/dollars of programming might resonate with some of your customers. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050211/b534cb94/attachment-0001.html From zen45800 at zen.co.uk Sat Feb 12 16:34:03 2005 From: zen45800 at zen.co.uk (Lobster) Date: Sat Feb 12 08:33:48 2005 Subject: [Tutor] Idle needles In-Reply-To: <Pine.LNX.4.44.0502112254210.17739-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0502112254210.17739-100000@hkn.eecs.berkeley.edu> Message-ID: <420E21EB.4000908@zen.co.uk> Danny Yoo wrote: >On Sat, 12 Feb 2005, Lobster wrote: > > > >>Idols subprocess didn't make connection Either Idle can't start or >>personal firewall is blocking the connection ========= >> >>Now I am getting the added message that the "socket connection is >>refused" (recently updated to the latest Zone Alarm) >> >> > >Hi Ed, > >That's further evidence that suggests that Zone Alarm is fighting IDLE. > > >Let me see... here's a section of the IDLE documentation README that talks >about this issue: > >""" >IDLE displays a new message upon startup: some "personal firewall" > kinds of programs (for example, ZoneAlarm) open a dialog of their > own when any program opens a socket. IDLE does use sockets, talking > on the computer's internal loopback interface. This connection is not > visible on any external interface and no data is sent to or received > from the Internet. So, if you get such a dialog when opening IDLE, > asking whether to let pythonw.exe talk to address 127.0.0.1, say yes, > and rest assured no communication external to your machine is taking > place. If you don't allow it, IDLE won't be able to start. >""" > > > Yes I did read that Danny - many thanks >Just to nail this issue down: try turning ZoneAlarm off, just for a >moment, and then start up IDLE. (You can always turn ZoneAlarm back on >after this experiment.) If you don't see any problems with IDLE, then >it's almost certainly a ZoneAlarm vs. IDLE confrontation, and we can focus >on that. > >Good luck to you! > Turned off Zone Alarm and closed down IDLE on opening IDLE - I got the socket error message and the other error message - so not zone alarm (it seems) - closing down IDLE and pressing ctrl alt and del I notice that 3 copies of pythonw are in memory I closed these down and IDLE is working again What I am going to do next is download the excellent Byte of Python tutorial and work offline with firefox and see what happens - any other ideas welcome (the only other thing I have different in IDLE is I store my Python docs in my docs rather than the default - probably irrelevant but . . .) Thank you very much for helping with this - it is holding me up and I am rearing to "go with the snake. . ." :-) Ed Jason (aka Dragon Shrimp - aka Lobster) PS - had a look at Crimson Editor and PSpad - very good but not quite for me I rather like IDLE - it is specific - focussed From alan.gauld at freenet.co.uk Sat Feb 12 09:41:22 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Feb 12 09:45:32 2005 Subject: [Tutor] default argument frustration References: <420A8938.5040604@po-box.mcgill.ca><07fe01c50f46$60d84240$68b78851@xp><420C670B.4070209@po-box.mcgill.ca><001e01c51067$bd0478f0$31d78751@xp> <ud5v6hlh8.fsf@hamster.pflaesterer.de> Message-ID: <00ef01c510de$a203f680$31d78751@xp> > > interface. The function should return the same result each time > > you call it with the same input. The only way to achieve that > > is to have the default calculated once. > > IBTD. > With full lexical scope you only need to calculate the default argument > in the lexical scope it was defined in. Look at a languale like Common > Lisp. Sorry, you are quite right. I meant its the only sane way to do it given the way Python works. Lisp and others implement closures and defered evaluation quite nicely, but I don't think it would be easy to build that into Python. Although it might be easier now with nested functions etc... Alan G. From alan.gauld at freenet.co.uk Sat Feb 12 09:52:28 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Feb 12 09:52:37 2005 Subject: [Tutor] Larger program organization References: <20050211173944.07AAC1E4008@bag.python.org> <20050211233145.2130185092.ejp@zomething.com> Message-ID: <012401c510e0$2ec72910$31d78751@xp> > without trying to make this one of those classic threads of great, > do you feel you could develop fairly complex applications faster > in Python than in C#/ASP.NET? It's a rhetorical question > (but I'm interested in your answer as a single data point) To be honest it wouldn't make a great deal of difference. For a complex application (by which I assume you mean large as well as being technically difficult) you spend most of your time thinking not physically coding so the language becomes less significant. On a typical "big" project the actual coding time is likely to be less than 10% of the total time so even if Python were twice as fast you only save 5% overall. Python may improve time to fix however since it will be easier to read later and therefore easier to debug and spot errors etc. But on big projects analysis, design and testing will be the big contributers, actually typing in the code is a trivial element. Alan G. From sandip at lug-delhi.org Sat Feb 12 10:27:21 2005 From: sandip at lug-delhi.org (Sandip Bhattacharya) Date: Sat Feb 12 10:43:28 2005 Subject: [Tutor] Re: Data storage, SQL? References: <f2ff2d05021023093bb965ef@mail.gmail.com> Message-ID: <pan.2005.02.12.09.27.14.107059@lug-delhi.org> On Fri, 11 Feb 2005 20:09:10 +1300, Liam Clarke wrote: > Hi, > > I'm looking to create a prog that will store disparate bits of info > all linked together, i.e. address details for a person, transaction > records, specific themes, and the ability to search by certain > criteria, so I'm pretty sure I want a database. > > Can anyone recommend a useful database library for Python that's not > too complex? > Also, I keep hearing about SQL, would this be the best way to go? I > don't know much about databases. You can take a look at sqlite (http://www.sqlite.org/). It doesn't require a client server setup, and offers you the same sql syntax for manipulating data on it. Some amazing facts about this from the website: [...] SQLite is a small C library that implements a self-contained, embeddable, zero-configuration SQL database engine. Features include: * Transactions are atomic, consistent, isolated, and durable (ACID) even after system crashes and power failures. * Zero-configuration - no setup or administration needed. * Implements most of SQL92. * A complete database is stored in a single disk file. * Database files can be freely shared between machines with different byte orders. * Supports databases up to 2 terabytes (2^41 bytes) in size. * Sizes of strings and BLOBs limited only by available memory. * Small code footprint: less than 30K lines of C code, less than 250KB code space (gcc on i486) * Faster than popular client/server database engines for most common operations. * Simple, easy to use API. * Well-commented source code with over 95% test coverage. * Self-contained: no external dependencies. * Sources are in the public domain. Use for any purpose. The SQLite distribution comes with a standalone command-line access program (sqlite) that can be used to administer an SQLite database and which serves as an example of how to use the SQLite library. [...] - Sandip -- Sandip Bhattacharya * Puroga Technologies * sandip@puroga.com Work: http://www.puroga.com * Home/Blog: http://www.sandipb.net/blog PGP/GPG Signature: 51A4 6C57 4BC6 8C82 6A65 AE78 B1A1 2280 A129 0FF3 From bvande at po-box.mcgill.ca Sat Feb 12 10:56:37 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat Feb 12 10:59:07 2005 Subject: [Tutor] help with refactoring needed -- which approach is more Pythonic? In-Reply-To: <420CDE7A.3010408@tds.net> References: <420A8938.5040604@po-box.mcgill.ca> <07fe01c50f46$60d84240$68b78851@xp> <420CDA1D.5040204@po-box.mcgill.ca> <420CDE7A.3010408@tds.net> Message-ID: <420DD2D5.2060708@po-box.mcgill.ca> Kent Johnson said unto the world upon 2005-02-11 11:34: > Brian van den Broek wrote: > >> Alan Gauld said unto the world upon 2005-02-10 02:58: >> >>> Pseudo code: >>> class Body: >>> def __init__(self,content): >>> self.contents = contents >>> self.nodes = [] >>> >>> def parse(self): >>> for line in self.contents: >>> if line == NodeStartTag: >>> node = Node() >>> if line == NodeEndTag: >>> self.nodes.append(node) >>> node.append(line) >>> >>> class Node: >>> def __init__(self,lines=[]): >>> self.lines = lines >>> def append(self,item): >>> self.lines.append(item) >>> def parse(self): >>> # your parsing method here. >> >> >> >> Hi all, >> >> YAQ (Yet Another Question): >> >> Following the general pattern, I end up with a Body object which has >> an attribute .nodes that consists of a list of Node objects. >> >> So, something like: >> >> My Example Body >> Node List >> Node the first >> Node the second >> >> Is there any way to make methods of the Node class access attributes >> of `parents' of instances? I would like a Node instance such as Node >> the first above to be aware just what it is a node of and what its >> siblings are. > > > You have to tell it the parent. ("Explicit is better than implicit.") > For example you could pass a reference to Body to the Node in the > constructor: > > def parse(self): > for line in self.contents: > if line == NodeStartTag: > node = Node(self) # HERE > if line == NodeEndTag: > self.nodes.append(node) > node.append(line) > > In general I think this is a bad design. I try to avoid telling > components about their parents in any kind of containment hierarchy. If > the component knows about its parent, then the component can't be reused > in a different context and it can't be tested without creating the > expected context. > > Is there another way you could accomplish what you want? > > Kent Hi, thanks to everyone for responding. It hadn't occurred to me I could pass self to a class instantiation. So, that solves my issue given my original design intent: thanks. As for Kent's question: I may have a better way now. I'd appreciate help deciding. So, if I may, I'll say a bit more about the problem domain. I've made the description as short as I know how. The file format I am working with is from a `folding notebook' style of application (<www.treepad.com> if anyone is interested). It's a 2-pane editor/outliner. There is a tree of nodes with each with a (not necessarily unique) title, a unique id number, other metadata and an associated article (in plain text, html, or RTF [ugh!]). The file format also defines a header for the entire file. I have a class TP_file, which, when instantiated, creates an Head object and, for each node, a Node object. The program supports hyperlinks in the article text, both to other nodes (by unique id) and to external objects. Before posting this most recent question, I'd planed for the Node class to have a method that would scan the node's article, looking for text strings that match any node title and linkifying them. (I already know how to deal with already linkified instances of the string and cases where one string is the title of multiple nodes.) Since this method needs to know the titles of all Node objects, I thought I needed to make each Node aware of its TP_file object to fetch its nodes. (Hence my most recent question.) And, since it alters the article text of a Node, I thought it needed to be a method of the Node class. But, while reflecting on Kent's question and thinking of how to describe my problem domain, I think I have a better idea now :-) It still seems to me that the actual updating of the article should be a Node method (it is the Node object's article that is being updated, after all). Call it node_linkify. The new thought is to create two new methods for the TP_file class: - One to build a dictionary with Node titles as keys and a list of the corresponding unique ids as values. - Another to pass that list into a the node_linkify Node method, once for each Node object of the TP_file. Does this seem like a reasonable approach given my description of the problem? Thanks for the continued help -- it is most appreciated. I might just become an OOP programmer yet! ;-) Best to all, Brian vdB From bvande at po-box.mcgill.ca Sat Feb 12 10:10:45 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat Feb 12 10:59:20 2005 Subject: [Tutor] Idle needles In-Reply-To: <420E21EB.4000908@zen.co.uk> References: <Pine.LNX.4.44.0502112254210.17739-100000@hkn.eecs.berkeley.edu> <420E21EB.4000908@zen.co.uk> Message-ID: <420DC815.4000900@po-box.mcgill.ca> Lobster said unto the world upon 2005-02-12 10:34: > Danny Yoo wrote: > >> On Sat, 12 Feb 2005, Lobster wrote: <SNIP exchange trying to work out apparent conflict between idle and firefox> > >> Just to nail this issue down: try turning ZoneAlarm off, just for a >> moment, and then start up IDLE. (You can always turn ZoneAlarm back on >> after this experiment.) If you don't see any problems with IDLE, then >> it's almost certainly a ZoneAlarm vs. IDLE confrontation, and we can >> focus >> on that. >> >> Good luck to you! >> > > Turned off Zone Alarm > and closed down IDLE > on opening IDLE - I got the socket error message > and the other error message > - so not zone alarm (it seems) > > - closing down IDLE and pressing ctrl alt and del > I notice that 3 copies of pythonw are in memory > > I closed these down and IDLE is working again Hi, for what it's worth, I've never had issues with Firefox and IDLE when running Zone Alarm. (Currently running ZoneAlarm version:5.5.062.004) But the multiple copies of pythonw seems key, and also the sort of thing that better Python minds than most seem to accept they have to live with too: <http://mail.python.org/pipermail/edu-sig/2005-January/004365.html> > :-) > > Ed Jason (aka Dragon Shrimp - aka Lobster) > > PS - had a look at Crimson Editor and PSpad - very good but not quite > for me > I rather like IDLE - it is specific - focussed I've been pretty happy using IDLE supplemented by SciTe when wanting a better editor than that provided by IDLE. Best, Brian vdB From cyresse at gmail.com Sat Feb 12 11:58:30 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sat Feb 12 11:58:32 2005 Subject: [Tutor] what is wrong with this? In-Reply-To: <2cad209005021121365aee64a5@mail.gmail.com> References: <2cad209005021121365aee64a5@mail.gmail.com> Message-ID: <f2ff2d050212025838941282@mail.gmail.com> Can you post the whole stack trace? On Sat, 12 Feb 2005 13:36:18 +0800, jrlen balane <nbbalane@gmail.com> wrote: > this code is for a MDIChildFrame, It has a MDIParentFrame and when I > run the MDIPrentFrame, there seems to be no problem, but when I > attempt to edit the MDIChildFrame using the designer mode in BOA (i'm > using BOA by the way), an error occurs that says: > > TypeError: wxGrid_CreateGrid() takes at least 3 arguments (2 given) > > please help. here is the code: > > from wxPython.wx import * > from wxPython.grid import * > from wxPython.lib.mixins.grid import wxGridAutoEditMixin > > def create(parent): > return wxMDIChildFrame1(parent) > > [wxID_WXMDICHILDFRAME1, wxID_WXMDICHILDFRAME1GRID1, > ] = map(lambda _init_ctrls: wxNewId(), range(2)) > > class wxMDIChildFrame1(wxMDIChildFrame): > def _init_ctrls(self, prnt): > # generated method, don't edit > wxMDIChildFrame.__init__(self, id=wxID_WXMDICHILDFRAME1, > name='WXMDICHILDFRAME1', parent=prnt, pos=wxPoint(70, 147), > size=wxSize(748, 331), style=wxDEFAULT_FRAME_STYLE, > title='Table') > self.SetClientSize(wxSize(740, 297)) > > self.grid1 = wxGrid(id=wxID_WXMDICHILDFRAME1GRID1, name='grid1', > parent=self, pos=wxPoint(0, 0), size=wxSize(740, 297), style=0) > > self.grid1.CreateGrid(100,6) > self.grid1.SetColLabelValue(0, "Time") > self.grid1.SetColLabelValue(1, "Irradiance") > self.grid1.SetColLabelValue(2, "Module Temperature") > self.grid1.SetColLabelValue(3, "Ambient Temperature") > self.grid1.SetColLabelValue(4, "Voltage") > self.grid1.SetColLabelValue(5, "Current") > > self.grid1.SetColSize(2, 125) > self.grid1.SetColSize(3, 127) > self.grid1.SetColLabelAlignment(wxALIGN_LEFT, wxALIGN_BOTTOM) > > def __init__(self, parent): > self._init_ctrls(parent) > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From zen45800 at zen.co.uk Sat Feb 12 21:18:20 2005 From: zen45800 at zen.co.uk (Lobster) Date: Sat Feb 12 13:18:05 2005 Subject: [Tutor] Idle + Firefox solution - hopefully In-Reply-To: <20050212110109.06ED01E403F@bag.python.org> References: <20050212110109.06ED01E403F@bag.python.org> Message-ID: <420E648C.1000100@zen.co.uk> >> - closing down IDLE and pressing ctrl alt and del >> I notice that 3 copies of pythonw are in memory >> >> I closed these down and IDLE is working again > > >Hi, > >for what it's worth, I've never had issues with Firefox and IDLE when >running Zone Alarm. (Currently running ZoneAlarm version:5.5.062.004) > >But the multiple copies of pythonw seems key, and also the sort of >thing that better Python minds than most seem to accept they have to >live with too: ><http://mail.python.org/pipermail/edu-sig/2005-January/004365.html> > > ======= Thanks Brian and Danny Yep - I found closing down the extra versions was a solution I also ran spybot and found a browser hijacker (just returned from a month in Linux without such hindrances) and it may be somehow related to that - the problem SEEMS to have gone . . . ======= I've been pretty happy using IDLE supplemented by SciTe when wanting a better editor than that provided by IDLE. Best, Brian vdB ====== Will have a look at SciTe thanks for your help - appreciate it . . . Ed Jason ======= From kent37 at tds.net Sat Feb 12 13:50:48 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat Feb 12 13:50:52 2005 Subject: [Tutor] help with refactoring needed -- which approach is more Pythonic? In-Reply-To: <420DD2D5.2060708@po-box.mcgill.ca> References: <420A8938.5040604@po-box.mcgill.ca> <07fe01c50f46$60d84240$68b78851@xp> <420CDA1D.5040204@po-box.mcgill.ca> <420CDE7A.3010408@tds.net> <420DD2D5.2060708@po-box.mcgill.ca> Message-ID: <420DFBA8.6020802@tds.net> Brian van den Broek wrote: > Kent Johnson said unto the world upon 2005-02-11 11:34: >> In general I think this is a bad design. I try to avoid telling >> components about their parents in any kind of containment hierarchy. >> If the component knows about its parent, then the component can't be >> reused in a different context and it can't be tested without creating >> the expected context. >> >> Is there another way you could accomplish what you want? >> >> Kent > > > Hi, > > thanks to everyone for responding. It hadn't occurred to me I could pass > self to a class instantiation. So, that solves my issue given my > original design intent: thanks. > > As for Kent's question: I may have a better way now. I'd appreciate help > deciding. So, if I may, I'll say a bit more about the problem domain. > I've made the description as short as I know how. > > The file format I am working with is from a `folding notebook' style of > application (<www.treepad.com> if anyone is interested). It's a 2-pane > editor/outliner. There is a tree of nodes with each with a (not > necessarily unique) title, a unique id number, other metadata and an > associated article (in plain text, html, or RTF [ugh!]). The file format > also defines a header for the entire file. > > I have a class TP_file, which, when instantiated, creates an Head object > and, for each node, a Node object. > > The program supports hyperlinks in the article text, both to other nodes > (by unique id) and to external objects. Before posting this most recent > question, I'd planed for the Node class to have a method that would scan > the node's article, looking for text strings that match any node title > and linkifying them. (I already know how to deal with already linkified > instances of the string and cases where one string is the title of > multiple nodes.) Since this method needs to know the titles of all Node > objects, I thought I needed to make each Node aware of its TP_file > object to fetch its nodes. (Hence my most recent question.) And, since > it alters the article text of a Node, I thought it needed to be a method > of the Node class. > > But, while reflecting on Kent's question and thinking of how to describe > my problem domain, I think I have a better idea now :-) > > It still seems to me that the actual updating of the article should be a > Node method (it is the Node object's article that is being updated, > after all). Call it node_linkify. The new thought is to create two new > methods for the TP_file class: > > - One to build a dictionary with Node titles as keys and > a list of the corresponding unique ids as values. > > - Another to pass that list into a the node_linkify Node method, > once for each Node object of the TP_file. > > Does this seem like a reasonable approach given my description of the > problem? Yes. This is the kind of solution I look for - instead of having the Node class look 'outside' itself to find what it needs - and therefore have the Node class dependent on a particular context - have something poke the Node from the outside and give it the information it needs to do its job. Do you see how this makes the Node more self-contained? For example you could write a unit test for node_linkify() that would just have to create a Node with some text and a helper dictionary. With the old design you would have to create several nodes and connect them in a Body. It may not seem like a big deal, but in a larger program these cross-dependencies grow and knit the whole thing into an inseparable whole. I worked on a program where the data model was dependent on the GUI implementation classes (*very* bad idea). So to reuse the data model (to be able to access the data in a different program) you had to include the GUI classes! A couple of notes about the general rule, though: - In tree-structured data I often need the node objects to know about their parent. Navigating up the tree is often handy. - In a GUI it can be challenging to figure out how to avoid telling the GUI classes about each other. For example if a button in one panel has to influence another panel. Usually I find a way but it gets a bit convoluted sometimes. > Thanks for the continued help -- it is most appreciated. I might just > become an OOP programmer yet! ;-) You're on your way! Kent > > Best to all, > > Brian vdB > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at freenet.co.uk Sat Feb 12 13:51:42 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Feb 12 13:51:43 2005 Subject: [Tutor] help with refactoring needed -- which approach is morePythonic? References: <420A8938.5040604@po-box.mcgill.ca><07fe01c50f46$60d84240$68b78851@xp><420CDA1D.5040204@po-box.mcgill.ca> <420CDE7A.3010408@tds.net> <420DD2D5.2060708@po-box.mcgill.ca> Message-ID: <013c01c51101$9a276640$31d78751@xp> > It still seems to me that the actual updating of the article should be > a Node method (it is the Node object's article that is being updated, > after all). Yes, the owner of the data should update it. > Call it node_linkify. The new thought is to create two new > methods for the TP_file class: > > - One to build a dictionary with Node titles as keys and > a list of the corresponding unique ids as values. Which saves searching the node list each time, good idea. This dictionary would of course be part of the Head or Body object which manages the Nodes? > - Another to pass that list into a the node_linkify Node method, > once for each Node object of the TP_file. Since the node knows its own ID and shouldn't know about the other nodes I wonder if it would be better for the Body/Head object to pass only what the node needs to create the links. Or do the links go to *all* the other related nodes? In which case the dictionary entry is fine. Alan G. From kent37 at tds.net Sat Feb 12 13:55:31 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat Feb 12 13:55:36 2005 Subject: [Tutor] Idle needles In-Reply-To: <420DC815.4000900@po-box.mcgill.ca> References: <Pine.LNX.4.44.0502112254210.17739-100000@hkn.eecs.berkeley.edu> <420E21EB.4000908@zen.co.uk> <420DC815.4000900@po-box.mcgill.ca> Message-ID: <420DFCC3.4070801@tds.net> Brian van den Broek wrote: > But the multiple copies of pythonw seems key, and also the sort of thing > that better Python minds than most seem to accept they have to live with > too: <http://mail.python.org/pipermail/edu-sig/2005-January/004365.html> Make sure you read the next message in the thread which gives a possible cause of the problem and a patch that might help. http://mail.python.org/pipermail/edu-sig/2005-January/004366.html Kent From exogen at gmail.com Sat Feb 12 14:07:05 2005 From: exogen at gmail.com (Brian Beck) Date: Sat Feb 12 14:22:35 2005 Subject: [Tutor] Re: References in loops In-Reply-To: <cujj2b$jig$1@sea.gmane.org> References: <000a01c51083$f9ef0ac0$8eaaec84@CuriousGeorge> <cujj2b$jig$1@sea.gmane.org> Message-ID: <cukv3j$ul4$1@sea.gmane.org> Andrei wrote: > Numbers are immutable, so the element 1 can't change into a 2 inside the > list. If 1 was not immutable, e.g. a list you could modify it and then > it would be "updated" in the original list too. It doesn't have anything to do with mutability, only the scope of i. Consider a list of lists (lists are mutable): py> l = [[1], [2], [3]] py> for i in l: i = [0] py> print l [[1], [2], [3]] Notice that even though each i (list) is mutable, rebinding the name i in the loop has no effect on the list. > I tend to use list comprehensions for this: > > aList = [elem+1 for elem in aList] This is probably the best solution, provided that the operation you want to perform on each element is simple enough to fit in an expression. Even then, just put the operation into a function. -- Brian Beck Adventurer From mark.kels at gmail.com Sat Feb 12 15:12:56 2005 From: mark.kels at gmail.com (Mark Kels) Date: Sat Feb 12 15:13:00 2005 Subject: [Tutor] Downloading from http Message-ID: <c225925305021206127e464242@mail.gmail.com> Hi list. How can I download a file from an HTTP server ? I checked the documentation but couldn't find what I need. Thanks! -- 1. The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners. 2. Unix is user friendly - it's just picky about it's friends. 3. Documentation is like sex: when it is good, it is very, very good. And when it is bad, it is better than nothing. - Dick Brandon From keridee at jayco.net Sat Feb 12 15:25:10 2005 From: keridee at jayco.net (Jacob S.) Date: Sat Feb 12 15:24:53 2005 Subject: [Tutor] Downloading from http References: <c225925305021206127e464242@mail.gmail.com> Message-ID: <001a01c5110e$ae6583f0$c15428cf@JSLAPTOP> urllib or urllib2 or maybe httplib maybe? urlopen( url[, data]) Open the URL url, which can be either a string or a Request object. data should be a string, which specifies additional data to send to the server. In HTTP requests, which are the only ones that support data, it should be a buffer in the format of application/x-www-form-urlencoded, for example one returned from urllib.urlencode(). This function returns a file-like object with two additional methods: a.. geturl() -- return the URL of the resource retrieved b.. info() -- return the meta-information of the page, as a dictionary-like object Raises URLError on errors. Note that None may be returned if no handler handles the request (though the default installed global OpenerDirector uses UnknownHandler to ensure this never happens). This is taken from the docs on urllib2. I think that's what you want, right? The tutorial or whatever, called "Dive into python", goes into accessing web pages a little more in depth than the docs do, I think. You can google for it, I believe. HTH, Jacob > Hi list. > > How can I download a file from an HTTP server ? > I checked the documentation but couldn't find what I need. > > Thanks! > -- > 1. The day Microsoft makes something that doesn't suck is probably the > day they start making vacuum cleaners. > 2. Unix is user friendly - it's just picky about it's friends. > 3. Documentation is like sex: when it is good, it is very, very good. > And when it is bad, it is better than nothing. - Dick Brandon > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Sat Feb 12 17:28:45 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat Feb 12 17:28:50 2005 Subject: [Tutor] Larger program organization In-Reply-To: <20050211173944.07AAC1E4008@bag.python.org> References: <20050211173944.07AAC1E4008@bag.python.org> Message-ID: <420E2EBD.3000101@tds.net> Ryan Davis wrote: > I'm starting to make a code-generation suite in python, customized to > the way we ASP.NET at my company, and I'm having some trouble finding a > good way to organize all the code. I keep writing it, but it feels more > and more spaghetti-ish every day. Organize your code into packages. Give each package a clear responsibility and clear dependencies on other packages. For example my current (Jython) project has these packages: app - top-level application objects data - database access - all the SQL code and database objects dbload - helpers for initial database load gui - gui classes importer - classes to implement an import function main - misc. main programs, not really part of the main app server - embedded web server tree - support for the Swing TreeModel that is a major part of the app writer - generation of output files I also use some packages that are not specific to the application: db - generic database support swing - generic Swing widgets and support classes util - misc helpful stuff In total there are 121 Python files (including test modules) and 49 Java files. For a smaller project you might just have a few modules in one package, or just a couple of packages. HTH Kent From mark.kels at gmail.com Sat Feb 12 20:47:49 2005 From: mark.kels at gmail.com (Mark Kels) Date: Sat Feb 12 20:47:54 2005 Subject: [Tutor] Downloading from http In-Reply-To: <001a01c5110e$ae6583f0$c15428cf@JSLAPTOP> References: <c225925305021206127e464242@mail.gmail.com> <001a01c5110e$ae6583f0$c15428cf@JSLAPTOP> Message-ID: <c2259253050212114744049f54@mail.gmail.com> On Sat, 12 Feb 2005 09:25:10 -0500, Jacob S. <keridee@jayco.net> wrote: > urllib or urllib2 or maybe httplib maybe? > > urlopen( url[, data]) > > Open the URL url, which can be either a string or a Request object. > data should be a string, which specifies additional data to send to the > server. In HTTP requests, which are the only ones that support data, it > should be a buffer in the format of application/x-www-form-urlencoded, for > example one returned from urllib.urlencode(). > > This function returns a file-like object with two additional methods: > > a.. geturl() -- return the URL of the resource retrieved > b.. info() -- return the meta-information of the page, as a > dictionary-like object > Raises URLError on errors. > > Note that None may be returned if no handler handles the request (though > the default installed global OpenerDirector uses UnknownHandler to ensure > this never happens). > > This is taken from the docs on urllib2. I think that's what you want, right? > The tutorial or whatever, called "Dive into python", goes into accessing web > pages a little more in depth than the docs do, I think. You can google for > it, I believe. > > HTH, > Jacob > I'm sorry, but I didn't understood a thing (maybe its because of my bad english, and mybe its because I'm just dumb :). Anyway, can you give me a code example or a link to a tutorial that talks about this ? Thanks alot. -- 1. The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners. 2. Unix is user friendly - it's just picky about it's friends. 3. Documentation is like sex: when it is good, it is very, very good. And when it is bad, it is better than nothing. - Dick Brandon From zen45800 at zen.co.uk Sun Feb 13 05:25:50 2005 From: zen45800 at zen.co.uk (Lobster) Date: Sat Feb 12 21:25:34 2005 Subject: [Tutor] Idle needles In-Reply-To: <20050212194822.0281D1E4012@bag.python.org> References: <20050212194822.0281D1E4012@bag.python.org> Message-ID: <420ED6CE.5060103@zen.co.uk> tutor-request@python.org wrote: >Brian van den Broek wrote: > > >>But the multiple copies of pythonw seems key, and also the sort of thing >>that better Python minds than most seem to accept they have to live with >>too: <http://mail.python.org/pipermail/edu-sig/2005-January/004365.html> >> >> > >Make sure you read the next message in the thread which gives a possible cause of the problem and a >patch that might help. >http://mail.python.org/pipermail/edu-sig/2005-January/004366.html > >Kent > > > Great advice Kent - have downloaded the IDLE patch :-) the address for the URL is wrong http://mcsp.wartburg.ed/zelle/python it should be http://mcsp.wartburg.edu/zelle/python Ed Jason From bvande at po-box.mcgill.ca Sat Feb 12 22:34:09 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat Feb 12 23:07:13 2005 Subject: [Tutor] help with refactoring needed -- which approach is morePythonic? In-Reply-To: <013c01c51101$9a276640$31d78751@xp> References: <420A8938.5040604@po-box.mcgill.ca> <07fe01c50f46$60d84240$68b78851@xp> <420CDA1D.5040204@po-box.mcgill.ca> <420CDE7A.3010408@tds.net> <420DD2D5.2060708@po-box.mcgill.ca> <013c01c51101$9a276640$31d78751@xp> Message-ID: <420E7651.5090100@po-box.mcgill.ca> Alan Gauld said unto the world upon 2005-02-12 07:51: <SNIP> Thanks Alan and Kent for the replies. I'm responding to a couple of questions Alan asked me about my problem. I don't think I have any further questions of my own (yet), though. :-) >>Call it node_linkify. The new thought is to create two new >>methods for the TP_file class: >> >>- One to build a dictionary with Node titles as keys and >> a list of the corresponding unique ids as values. > > > Which saves searching the node list each time, good idea. > This dictionary would of course be part of the Head or Body > object which manages the Nodes? That's the plan, yes. >>- Another to pass that list into a the node_linkify Node method, >> once for each Node object of the TP_file. > > Since the node knows its own ID and shouldn't know about > the other nodes I wonder if it would be better for the > Body/Head object to pass only what the node needs to > create the links. Or do the links go to *all* the other > related nodes? In which case the dictionary entry is fine. > > Alan G. The Node object being linkified won't know which other Node objects need to be linked to until the to-be-linkified Node's article text is scanned. So, I think the full dict is needed. The best analogy I can come up with for what I am trying to do is this: Consider a wiki which only supports WikiNames rather than arbitrary page names and arbitrary page links. Quite often, in a wiki, people add text which could/should have been in the form of a wiki link, but they didn't format it that way. For example, there might be a page called ExtantWikiName and, on some other page, someone wrote `extant wiki name' rather than `ExtantWikiName'. So, one might want a function which scanned each page of the wiki, looking for strings which match the name of wiki pages, but don't have wiki link formatting and then so format them. It seems to me that this method, if a method of each wiki page, would need to be given knowledge of all page names in the wiki. That's pretty much my task, save that my target app doesn't support wiki linking, so I need to associate node titles (the analogue of wiki page names) with the unique id's of pages with the title to be able to generate the links. Off to code it up! Thanks and best to all, Brian vdB From bvande at po-box.mcgill.ca Sat Feb 12 23:03:42 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat Feb 12 23:07:29 2005 Subject: [Tutor] default argument frustration In-Reply-To: <00ef01c510de$a203f680$31d78751@xp> References: <420A8938.5040604@po-box.mcgill.ca> <07fe01c50f46$60d84240$68b78851@xp> <420C670B.4070209@po-box.mcgill.ca> <001e01c51067$bd0478f0$31d78751@xp> <ud5v6hlh8.fsf@hamster.pflaesterer.de> <00ef01c510de$a203f680$31d78751@xp> Message-ID: <420E7D3E.2030201@po-box.mcgill.ca> I've combined a few email's worth of quoting as no previous post had all the elements I wanted to refer to. Alan Gauld said unto the world upon 2005-02-11 13:30: >><venting> >>FOR THE LOVE OF MIKE can someone tell me even one reason why this >>isn't a misfeature?!?! >></venting> > > Its the only sane way to implement default arguments. The whole > point of function definitions is that they provide a single concise > interface. The function should return the same result each time > you call it with the same input. The only way to achieve that > is to have the default calculated once. Alan Gauld said unto the world upon 2005-02-12 03:41: > Karl Pfl?sterer said unto the world upon 2005-02-11 16:44: >> >>IBTD. >>With full lexical scope you only need to calculate the default >>argument in the lexical scope it was defined in. Look at a >>languale like Common Lisp. > > > Sorry, you are quite right. I meant its the only sane way to do it > given the way Python works. > > Lisp and others implement closures and defered evaluation quite > nicely, but I don't think it would be easy to build that into Python. > Although it might be easier now with nested functions etc... > > Alan G. I get that Karl was saying that other languages (eg Lisp) can do it differently, though the details of the Lisp comparison are lost on me. Alan was saying that there is no other obvious way for Python to do it. What I am still not clear on it is why Alan's claim is true. (Not doubting it is, but would like to get why it is.) Is this the rough idea this?: The def statement is executed only once, and thus the default argument is calculated just the once, too (on building of the function object). So, any way around this feature of Python would either require that defs be executed each time a function is called (giant performance hit across the board even if doable) or require the addition of a new reserved word, say redef, for function defs that should be re-evaluated each time the function is run (again, if doable). If that is in the vicinity of being right, I start to be less inclined to vent. Python's conservatism abut adding new reserved words seems a good thing, and enough to kill such a redef idea, if the performance issue wasn't. That makes the workaround a la the Tutorial seem less irksome. Thanks and best to all, Brian vdB From bvande at po-box.mcgill.ca Sat Feb 12 23:21:54 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat Feb 12 23:39:03 2005 Subject: ****SPAM(11.2)**** [Tutor] Larger program organization In-Reply-To: <6.1.2.0.0.20050211132921.036258d8@mail.mric.net> References: <20050211173944.07AAC1E4008@bag.python.org> <6.1.2.0.0.20050211132921.036258d8@mail.mric.net> Message-ID: <420E8182.9010204@po-box.mcgill.ca> Bob Gailer said unto the world upon 2005-02-11 15:34: > At 10:39 AM 2/11/2005, Ryan Davis wrote: > >> I'm starting to make a code-generation suite in python, customized to >> the way we ASP.NET at my company, and I'm having some trouble finding >> a good way to organize all the code. > > > My take on doing that in Python: > > Organize things into modules. Especially with an eye to potential reuse. > Look at the module index in the docs to see how most of the "standard" > modules focus on doing one thing well. > > Within a module create classes for every conceivable object. Whenever > you find yourself writing an if statement ask whether this would be > better handled by subclasses. Whenever you find yourself about to write > a global statement, consider making the variables properties of a class. <SNIP> Hi all, as readers of another concurrent thread will know, I am, with lots of help, just beginning to start thinking about proper OOP design. I am curious about Bob's "Whenever you find yourself writing an if statement ask whether this would be better handled by subclasses." Could you explain a bit more? Thanks and best, Brian vdB From kent37 at tds.net Sun Feb 13 01:02:58 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun Feb 13 01:03:05 2005 Subject: [Tutor] Downloading from http In-Reply-To: <c2259253050212114744049f54@mail.gmail.com> References: <c225925305021206127e464242@mail.gmail.com> <001a01c5110e$ae6583f0$c15428cf@JSLAPTOP> <c2259253050212114744049f54@mail.gmail.com> Message-ID: <420E9932.50107@tds.net> Mark Kels wrote: > On Sat, 12 Feb 2005 09:25:10 -0500, Jacob S. <keridee@jayco.net> wrote: > >>urllib or urllib2 or maybe httplib maybe? >> >> urlopen( url[, data]) > I'm sorry, but I didn't understood a thing (maybe its because of my > bad english, and mybe its because I'm just dumb :). Anyway, can you > give me a code example or a link to a tutorial that talks about this ? >>> from urllib import urlopen >>> u=urlopen('http://www.google.com') >>> d=u.read() >>> print d[:200] <html><head><meta http-equiv="content-type" content="text/html; charset=ISO-8859-1"><title>Google</title><style><!-- body,td,a,p,.h{font-family:arial,sans-serif;} .h{font-size: 20px;} .q{color:#0000cc From kim.branson at gmail.com Sun Feb 13 04:34:54 2005 From: kim.branson at gmail.com (Kim Branson) Date: Sun Feb 13 04:35:39 2005 Subject: [Tutor] cross platform gui In-Reply-To: <420E648C.1000100@zen.co.uk> References: <20050212110109.06ED01E403F@bag.python.org> <420E648C.1000100@zen.co.uk> Message-ID: <8ccdfa14226d57eed26adf2d72286408@gmail.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi all, i'm interested in building a gui for some code we have. I'm after pointers on gui programming, and a recommendation on a cross platform gui library, wxpython? pythoncard, qt? What do people use. Ideally i'd like something that can work on windows, osx and linux. Its a science program so the look is a of lesser importance :) cheers Kim -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (Darwin) iD8DBQFCDsrfer2hmGbHcokRAlYLAKCXGmve611OUdqprrpLUVAa2rJdDwCdGRKo dqMFRWAYlM60wlMyWpsLG8w= =bqSk -----END PGP SIGNATURE----- From nbbalane at gmail.com Sun Feb 13 05:00:56 2005 From: nbbalane at gmail.com (jrlen balane) Date: Sun Feb 13 05:01:00 2005 Subject: [Tutor] what is wrong with this? In-Reply-To: <f2ff2d050212025838941282@mail.gmail.com> References: <2cad209005021121365aee64a5@mail.gmail.com> <f2ff2d050212025838941282@mail.gmail.com> Message-ID: <2cad20900502122000133a7ef3@mail.gmail.com> how would i find the stack trace? by the way, this is what the log says: 11:53:16: TypeError: wxGrid_CreateGrid() takes at least 3 arguments (2 given)Traceback(most recent call last): 11:53:16: TypeError: wxGrid_CreateGrid() takes at least 3 arguments (2 given) File "C:\PYTHON23\Lib\site-packages\wxPython\tools\boa\Models\wxPythonControllers.py", line 80, in OnDesigner 11:53:16: self.showDesigner() 11:53:16: File "C:\PYTHON23\Lib\site-packages\wxPython\tools\boa\Models\wxPythonControllers.py", line 145, in showDesigner 11:53:16: designer.refreshCtrl() 11:53:16: File "C:\PYTHON23\Lib\site-packages\wxPython\tools\boa\Views\Designer.py",line 379, in refreshCtrl 11:53:16: self.initObjectsAndCompanions(objCol.creators[1:], objCol, deps, depLnks) 11:53:16: File "C:\PYTHON23\Lib\site-packages\wxPython\tools\boa\Views\InspectableViews.py", line 140, in initObjectsAndCompanions 11:53:16: dependents, depLinks) 11:53:16: File "C:\PYTHON23\Lib\site-packages\wxPython\tools\boa\Views\InspectableViews.py", line 216, in initObjProps 11:53:16: getattr(ctrl, prop.prop_setter)(value) 11:53:16: File "C:\PYTHON23\lib\site-packages\wxPython\grid.py", line 973, in CreateGrid 11:53:16: val = gridc.wxGrid_CreateGrid(self, *_args, **_kwargs) 11:53:16: TypeError: wxGrid_CreateGrid() takes at least 3 arguments (2 given) From cyresse at gmail.com Sun Feb 13 07:15:02 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sun Feb 13 07:15:06 2005 Subject: [Tutor] what is wrong with this? In-Reply-To: <2cad20900502122000133a7ef3@mail.gmail.com> References: <2cad209005021121365aee64a5@mail.gmail.com> <f2ff2d050212025838941282@mail.gmail.com> <2cad20900502122000133a7ef3@mail.gmail.com> Message-ID: <f2ff2d05021222151143eb12@mail.gmail.com> Yup, that's what I was after, the full error message. >self.grid1.CreateGrid(100,6) > val = gridc.wxGrid_CreateGrid(self, *_args, **_kwargs) try this self.grid1.CreateGrid(self, 100, 6) I'm pretty sure you have to explicitly pass self. Let me know how ya go. Regards, Liam Clarke On Sun, 13 Feb 2005 12:00:56 +0800, jrlen balane <nbbalane@gmail.com> wrote: > how would i find the stack trace? by the way, this is what the log says: > > 11:53:16: TypeError: wxGrid_CreateGrid() takes at least 3 > arguments (2 given)Traceback(most recent call last): > 11:53:16: TypeError: wxGrid_CreateGrid() takes at least 3 > arguments (2 given) File > "C:\PYTHON23\Lib\site-packages\wxPython\tools\boa\Models\wxPythonControllers.py", > line 80, in OnDesigner > 11:53:16: self.showDesigner() > 11:53:16: File > "C:\PYTHON23\Lib\site-packages\wxPython\tools\boa\Models\wxPythonControllers.py", > line 145, in showDesigner > 11:53:16: designer.refreshCtrl() > 11:53:16: File > "C:\PYTHON23\Lib\site-packages\wxPython\tools\boa\Views\Designer.py",line > 379, in refreshCtrl > 11:53:16: self.initObjectsAndCompanions(objCol.creators[1:], > objCol, deps, depLnks) > 11:53:16: File > "C:\PYTHON23\Lib\site-packages\wxPython\tools\boa\Views\InspectableViews.py", > line 140, in initObjectsAndCompanions > 11:53:16: dependents, depLinks) > 11:53:16: File > "C:\PYTHON23\Lib\site-packages\wxPython\tools\boa\Views\InspectableViews.py", > line 216, in initObjProps > 11:53:16: getattr(ctrl, prop.prop_setter)(value) > 11:53:16: File "C:\PYTHON23\lib\site-packages\wxPython\grid.py", > line 973, in CreateGrid > 11:53:16: val = gridc.wxGrid_CreateGrid(self, *_args, **_kwargs) > 11:53:16: TypeError: wxGrid_CreateGrid() takes at least 3 > arguments (2 given) > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cyresse at gmail.com Sun Feb 13 07:17:29 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sun Feb 13 07:17:32 2005 Subject: [Tutor] cross platform gui In-Reply-To: <8ccdfa14226d57eed26adf2d72286408@gmail.com> References: <20050212110109.06ED01E403F@bag.python.org> <420E648C.1000100@zen.co.uk> <8ccdfa14226d57eed26adf2d72286408@gmail.com> Message-ID: <f2ff2d05021222173598072d@mail.gmail.com> I would recommend wxPython, it seems to be cross platform. Pythoncard is an easy to use wrapper around wxPython, and for some stuff you have to revert back to wxPython code. I can't on QT, and Tkinter is getting a bit old these days (imao.) AFAIK they should all be cross-platform (query QT), so it's all a matter of style. On Sun, 13 Feb 2005 14:34:54 +1100, Kim Branson <kim.branson@gmail.com> wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Hi all, > > i'm interested in building a gui for some code we have. I'm after > pointers on gui programming, and a recommendation on a cross platform > gui library, wxpython? pythoncard, qt? What do people use. Ideally i'd > like something that can work on windows, osx and linux. Its a science > program so the look is a of lesser importance :) > > cheers > > Kim > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.2.4 (Darwin) > > iD8DBQFCDsrfer2hmGbHcokRAlYLAKCXGmve611OUdqprrpLUVAa2rJdDwCdGRKo > dqMFRWAYlM60wlMyWpsLG8w= > =bqSk > -----END PGP SIGNATURE----- > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From zen45800 at zen.co.uk Sun Feb 13 17:03:45 2005 From: zen45800 at zen.co.uk (Lobster) Date: Sun Feb 13 09:03:27 2005 Subject: [Tutor] cross platform gui In-Reply-To: <20050213061736.A8E991E4013@bag.python.org> References: <20050213061736.A8E991E4013@bag.python.org> Message-ID: <420F7A61.7060205@zen.co.uk> =========== From: Kim Branson <kim.branson@gmail.com> Hi all, i'm interested in building a gui for some code we have. I'm after pointers on gui programming, and a recommendation on a cross platform gui library, wxpython? pythoncard, qt? What do people use. Ideally i'd like something that can work on windows, osx and linux. Its a science program so the look is a of lesser importance :) cheers Kim ========= Hi Kim, This is the easiest I could find (even I was able to almost use it) http://www.ferg.org/easygui/ Ed Jason (Lobster) From alan.gauld at freenet.co.uk Sun Feb 13 09:58:51 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Feb 13 09:58:43 2005 Subject: [Tutor] default argument frustration References: <420A8938.5040604@po-box.mcgill.ca><07fe01c50f46$60d84240$68b78851@xp><420C670B.4070209@po-box.mcgill.ca><001e01c51067$bd0478f0$31d78751@xp><ud5v6hlh8.fsf@hamster.pflaesterer.de><00ef01c510de$a203f680$31d78751@xp> <420E7D3E.2030201@po-box.mcgill.ca> Message-ID: <018501c511aa$3d613360$31d78751@xp> > Alan was saying that there is no other obvious way for Python to do it. > > What I am still not clear on it is why Alan's claim is true. (Not > doubting it is, but would like to get why it is.) Doubt away, my knowledge of Python internals is largely intuitive, I've never got round to reading the C code! But as I understand it when Python defs a function it creates a dictionary object at the module level that handles the naming. When the function executes, the local names have their own namespace. In Lisp, again as I understand it, the namespace is effectively passed around with the function (rather than being fixed at module level) so it is easier for the function to modify its own context. Dynamically rebinding the default value in Python would require an external lookup at the module level which would be more complex and expensive. > Is this the rough idea this?: > > The def statement is executed only once, and thus the default argument > is calculated just the once, too (on building of the function object). > So, any way around this feature of Python would either require that > defs be executed each time a function is called (giant performance hit > across the board even if doable) or require the addition of a new > reserved word, say redef, I don't know if the whole def would need to be redone but the binding of function and parameter values would, I think. But as I say most of this is intuitive knowledge - i.e. based on how I think *I* would have built the behaviour I observe! > good thing, and enough to kill such a redef idea, if the performance > issue wasn't. I think its probably possible to change the mechanism but I suspect it would add significantly to the function overgead - which is already quite high in Python. But I'm happy to be enlightened by anyone who *really* knows how and why this stuff works. And in thinking about this I'm stimulated to ask, does anyone know how default arguments work in a threaded context? What happens if two threads try to modify the content of a mutable default argument at the same time? Alan G. From alan.gauld at freenet.co.uk Sun Feb 13 10:06:13 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Feb 13 10:06:01 2005 Subject: ****SPAM(11.2)**** [Tutor] Larger program organization References: <20050211173944.07AAC1E4008@bag.python.org><6.1.2.0.0.20050211132921.036258d8@mail.mric.net> <420E8182.9010204@po-box.mcgill.ca> Message-ID: <018a01c511ab$450ce540$31d78751@xp> > I am curious about Bob's "Whenever you find yourself writing an if > statement ask whether this would be better handled by subclasses." > > Could you explain a bit more? One of the basic purposes of OOP is to eliminate if/switch statements that are conditional on the type of the object being handled. So when writing OO code every time you see an if statement you should ask is this really part of the logic or am I habdling a special type of processing that should be in a separate subclass. For example, if you were writing your Node class parsing method and you started writing code like: if dataType == 'Some literal value' # extract one format of data else # extract another data format Then maybe you should have two classes and rely on polymorphism to do the two different types of extraction. Thus subType = DataType() subType.extractData() By eliminating the if/else you potentially eliminate an ongoing maintenance headache and this is one of the big wins of OOP. HTH, Alan G. From cyresse at gmail.com Sun Feb 13 10:46:36 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sun Feb 13 10:46:39 2005 Subject: [Tutor] Re: Data storage, SQL? In-Reply-To: <pan.2005.02.12.09.27.14.107059@lug-delhi.org> References: <f2ff2d05021023093bb965ef@mail.gmail.com> <pan.2005.02.12.09.27.14.107059@lug-delhi.org> Message-ID: <f2ff2d050213014616877914@mail.gmail.com> ...So, trying to get this straight - if I were going to use SQLite, what would I actually download from http://www.sqlite.org/sqlite.html ? Also, would Gadfly be easier, being native Python? Regards, Liam Clarke On Sat, 12 Feb 2005 14:27:21 +0500, Sandip Bhattacharya <sandip@lug-delhi.org> wrote: > On Fri, 11 Feb 2005 20:09:10 +1300, Liam Clarke wrote: > > > Hi, > > > > I'm looking to create a prog that will store disparate bits of info > > all linked together, i.e. address details for a person, transaction > > records, specific themes, and the ability to search by certain > > criteria, so I'm pretty sure I want a database. > > > > Can anyone recommend a useful database library for Python that's not > > too complex? > > Also, I keep hearing about SQL, would this be the best way to go? I > > don't know much about databases. > > You can take a look at sqlite > (http://www.sqlite.org/). It doesn't require a client > server setup, and offers you the same sql syntax for manipulating data on > it. > > Some amazing facts about this from the website: > > [...] > SQLite is a small C library that implements a self-contained, > embeddable, zero-configuration SQL database engine. Features include: > > * Transactions are atomic, consistent, isolated, and durable (ACID) > even after system crashes and power failures. > * Zero-configuration - no setup or administration needed. > * Implements most of SQL92. > * A complete database is stored in a single disk file. > * Database files can be freely shared between machines with > different byte orders. > * Supports databases up to 2 terabytes (2^41 bytes) in size. > * Sizes of strings and BLOBs limited only by available memory. > * Small code footprint: less than 30K lines of C code, less > than 250KB code space (gcc on i486) > * Faster than popular client/server database engines > for most common operations. > * Simple, easy to use API. > * Well-commented source code with over 95% test coverage. > * Self-contained: no external dependencies. > * Sources are in the public domain. Use for any purpose. > > The SQLite distribution comes with a standalone command-line access > program (sqlite) that can be used to administer an SQLite database and > which serves as an example of how to use the SQLite library. > > [...] > > - Sandip > > -- > Sandip Bhattacharya * Puroga Technologies * sandip@puroga.com > Work: http://www.puroga.com * Home/Blog: http://www.sandipb.net/blog > > PGP/GPG Signature: 51A4 6C57 4BC6 8C82 6A65 AE78 B1A1 2280 A129 0FF3 > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From alan.gauld at freenet.co.uk Sun Feb 13 10:45:49 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Feb 13 10:49:25 2005 Subject: [Tutor] default argument frustration References: <420A8938.5040604@po-box.mcgill.ca><07fe01c50f46$60d84240$68b78851@xp><420C670B.4070209@po-box.mcgill.ca><001e01c51067$bd0478f0$31d78751@xp><ud5v6hlh8.fsf@hamster.pflaesterer.de><00ef01c510de$a203f680$31d78751@xp> <420E7D3E.2030201@po-box.mcgill.ca> Message-ID: <01a601c511b0$cd1ca510$31d78751@xp> > I've combined a few email's worth of quoting as no previous post had > all the elements I wanted to refer to. > > interface. The function should return the same result each time > > you call it with the same input. The only way to achieve that > > is to have the default calculated once. I feel the need to clarify this statement somewhat! :-) Imagine what would happen if you calculated the default each time you ran the program and the def looked like: def f(x,y=g()): # etc... Everytime you called f(42) you would also call g() which could return a completely different value, thus f(42) behaviour would be very inconsistent and almost unpredictable. However if g() is only evaluated once and that value used as the default then f(42) becomes predictable again. If you want the behaviour whereby g() gets called each time then that is easily restored by making the function object g be the default and then within the function definition calling it: def g(): # whatever def f(x,y=g): val = g() # etc... Hmm, I'm not sure this is actually explaining what I'm trying to say... Basically, I think the current behaviour is good because it gives me a wider set of options than the alternative mechanism. Alan G. From krzys_kyku at tlen.pl Sun Feb 13 11:41:27 2005 From: krzys_kyku at tlen.pl (Krzysztof Wrzalik) Date: Sun Feb 13 11:41:09 2005 Subject: [Tutor] Accessing local variables from nested functions. Message-ID: <200502131141.28174.krzys_kyku@tlen.pl> Hello all, what's the Python way of accessing local variables in nesting functions? For example if I have: def p(): ? var1 = 3 ? def q(): ? ? ?print 'var1 in p is', var1 ? q() then there's no problem in running such function, but what if I'd like to modify var1 so that the change were vissible in p()? I can't label var1 as global in q, because it then creates a new var1 in the module scope, leaving the nested one untouched. Thanks in advance From sigurd at 12move.de Sun Feb 13 12:15:03 2005 From: sigurd at 12move.de (Karl =?iso-8859-1?Q?Pfl=E4sterer?=) Date: Sun Feb 13 12:16:24 2005 Subject: [Tutor] Accessing local variables from nested functions. In-Reply-To: <200502131141.28174.krzys_kyku@tlen.pl> (Krzysztof Wrzalik's message of "Sun, 13 Feb 2005 11:41:27 +0100") References: <200502131141.28174.krzys_kyku@tlen.pl> Message-ID: <uis4wbtzy.fsf@hamster.pflaesterer.de> On 13 Feb 2005, krzys_kyku@tlen.pl wrote: > what's the Python way of accessing local variables in nesting functions? For The way you want to work with closures the Python way is not to do it but use a class to hold the state. That's sometimes sad but true. > example if I have: > > def p(): > ? var1 = 3 > ? def q(): > ? ? ?print 'var1 in p is', var1 > ? q() > > then there's no problem in running such function, but what if I'd like to > modify var1 so that the change were vissible in p()? There's a workaround (but see it only as one; it's not pretty). def outer (): var = [1] def inner (): var[0] += 1 return var return inner Now if you call outer it's returns a function which when called changes the value of var. Karl -- Please do *not* send copies of replies to me. I read the list From project5 at redrival.net Sun Feb 13 12:45:42 2005 From: project5 at redrival.net (Andrei) Date: Sun Feb 13 12:45:58 2005 Subject: [Tutor] Re: Accessing local variables from nested functions. References: <200502131141.28174.krzys_kyku@tlen.pl> <uis4wbtzy.fsf@hamster.pflaesterer.de> Message-ID: <ppubdjim6gna.bsqtm6btfcbo.dlg@40tude.net> Karl Pfl?sterer wrote on Sun, 13 Feb 2005 12:15:03 +0100: > what's the Python way of accessing local variables in nesting functions? For > then there's no problem in running such function, but what if I'd like to > modify var1 so that the change were vissible in p()? I'd use return in the form of def p(): v = 3 def q(): return v+1 v = q() If you need to modify a lot of p-vars inside q, I'd say it's probably wiser to go with a class and appropriate methods. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From kohlerj at ukzn.ac.za Sun Feb 13 13:18:27 2005 From: kohlerj at ukzn.ac.za (Johan Kohler) Date: Sun Feb 13 13:18:43 2005 Subject: [Tutor] (no subject) Message-ID: <s20f61be.001@dbnsmtp.nu.ac.za> Hi I still have problems pickling and unpickling. After I couldn't get "complicated" objects to work, i decided to use simple lists. But now there seems to be a difference between assigning a list value, and using the .append method. Please try out the code at http://goose.cs.und.ac.za/python/save1.py There are two "use cases" WorkingCase() and BrokenCase. WorkingCase() saves data in a list using assignment, and by appending, and then reads it back from the file. BrokenCase performs only the reading back step. Now, there are no problems when the two cases are run consecutively. Do this once. Then comment out the WorkingCase() statement, and run only BrokenCase(). This should read back all the list entries, but all the ones created by "appending" are blank! I should mention, that in my application I want to append items one by one to the list. Please can someone help me with this? I am getting extremely frustrated by not being able to get supposedly simple stuff to work. Thanks in advance, Johan From sigurd at 12move.de Sun Feb 13 13:34:14 2005 From: sigurd at 12move.de (Karl =?iso-8859-1?Q?Pfl=E4sterer?=) Date: Sun Feb 13 13:37:31 2005 Subject: [Tutor] Re: Accessing local variables from nested functions. In-Reply-To: <ppubdjim6gna.bsqtm6btfcbo.dlg@40tude.net> (Andrei's message of "Sun, 13 Feb 2005 12:45:42 +0100") References: <200502131141.28174.krzys_kyku@tlen.pl> <uis4wbtzy.fsf@hamster.pflaesterer.de> <ppubdjim6gna.bsqtm6btfcbo.dlg@40tude.net> Message-ID: <uekfkbpxy.fsf@hamster.pflaesterer.de> On 13 Feb 2005, project5@redrival.net wrote: > > Karl Pfl?sterer wrote on Sun, 13 Feb 2005 12:15:03 +0100: > >> what's the Python way of accessing local variables in nesting functions? For I didn't wrote that; please quote correctly. Thanks. Karl -- Please do *not* send copies of replies to me. I read the list From kent37 at tds.net Sun Feb 13 14:00:38 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun Feb 13 14:00:42 2005 Subject: [Tutor] Re: Data storage, SQL? In-Reply-To: <f2ff2d050213014616877914@mail.gmail.com> References: <f2ff2d05021023093bb965ef@mail.gmail.com> <pan.2005.02.12.09.27.14.107059@lug-delhi.org> <f2ff2d050213014616877914@mail.gmail.com> Message-ID: <420F4F76.6050904@tds.net> Liam Clarke wrote: > ...So, trying to get this straight - if I were going to use SQLite, > what would I actually download from http://www.sqlite.org/sqlite.html > ? SQLite itself does not use / interface with Python. So you would download the appropriate version of SQLite for your platform from http://www.sqlite.org/download.html. Then get the matching release of pysqlite from http://sourceforge.net/projects/pysqlite/ - this is the Python interface to SQLite. > Also, would Gadfly be easier, being native Python? Gadfly might be a little easier to install since there is only one piece. Both Gadfly and SQLite have DB-API compliant drivers and use SQL for their command language, so in use they will be similar. Gadfly keeps the database in memory so for large amounts of data it won't work. I think SQLite has been around longer than Gadfly so it may be more mature. If you want a simple database with a Pythonic interface, take a look at KirbyBase. Though from your brief description I think you will want a database that supports joins. There is a great variety of databases usable from Python. Most of them use DB-API and SQL for the interface, so you have to pick one based on features. I guess I see three rough categories. <disclaimer> This is a rough opinion based on reading about these databases. My own experience is with MS SQL Server, PostgreSQL and MS Access. </disclaimer> At the top of the heap are the industrial strength databases. This includes free products like MySQL, PostgreSQL and Firebird as well as commercial products like MS SQL Server, Sybase and Oracle. These databases will take anything you can throw at them with style and aplomb. (MySQL is probably the most limited of this category but it is widely used and clearly quite capable.) They are well supported with tools and they are used in a wide variety of projects. In the middle tier are databases that are not as full featured but still very usable for small to midsize work. I would put SQLite and Gadfly into this category. Some people would argue that MySQL belongs here. These databases will be missing features like transactions, large database support, unicode support... In the bottom tier are programs that are more of a persistence mechanism than a true database. I put KirbyBase here along with the standard Python shelve and dbm modules. OK...I don't know if this has been any help...I suggest you look at the *features* of SQLite and Gadfly and see if either is missing anything you need. Finally, you might want to look at SQLObject. This is a wrapper on top of the database that makes your objects persist themselves. It shields you from DB-API and SQL. http://sqlobject.org HTH, Kent > > Regards, > > Liam Clarke > > > On Sat, 12 Feb 2005 14:27:21 +0500, Sandip Bhattacharya > <sandip@lug-delhi.org> wrote: > >>On Fri, 11 Feb 2005 20:09:10 +1300, Liam Clarke wrote: >> >> >>>Hi, >>> >>>I'm looking to create a prog that will store disparate bits of info >>>all linked together, i.e. address details for a person, transaction >>>records, specific themes, and the ability to search by certain >>>criteria, so I'm pretty sure I want a database. >>> >>>Can anyone recommend a useful database library for Python that's not >>>too complex? >>>Also, I keep hearing about SQL, would this be the best way to go? I >>>don't know much about databases. >> >>You can take a look at sqlite >>(http://www.sqlite.org/). It doesn't require a client >>server setup, and offers you the same sql syntax for manipulating data on >>it. >> >>Some amazing facts about this from the website: >> >>[...] >>SQLite is a small C library that implements a self-contained, >>embeddable, zero-configuration SQL database engine. Features include: >> >>* Transactions are atomic, consistent, isolated, and durable (ACID) >> even after system crashes and power failures. >>* Zero-configuration - no setup or administration needed. >>* Implements most of SQL92. >>* A complete database is stored in a single disk file. >>* Database files can be freely shared between machines with >> different byte orders. >>* Supports databases up to 2 terabytes (2^41 bytes) in size. >>* Sizes of strings and BLOBs limited only by available memory. >>* Small code footprint: less than 30K lines of C code, less >> than 250KB code space (gcc on i486) >>* Faster than popular client/server database engines >> for most common operations. >>* Simple, easy to use API. >>* Well-commented source code with over 95% test coverage. >>* Self-contained: no external dependencies. >>* Sources are in the public domain. Use for any purpose. >> >>The SQLite distribution comes with a standalone command-line access >>program (sqlite) that can be used to administer an SQLite database and >>which serves as an example of how to use the SQLite library. >> >>[...] >> >>- Sandip >> >>-- >>Sandip Bhattacharya * Puroga Technologies * sandip@puroga.com >>Work: http://www.puroga.com * Home/Blog: http://www.sandipb.net/blog >> >>PGP/GPG Signature: 51A4 6C57 4BC6 8C82 6A65 AE78 B1A1 2280 A129 0FF3 >> >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> > > > From kent37 at tds.net Sun Feb 13 14:12:11 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun Feb 13 14:12:15 2005 Subject: [Tutor] what is wrong with this? In-Reply-To: <f2ff2d05021222151143eb12@mail.gmail.com> References: <2cad209005021121365aee64a5@mail.gmail.com> <f2ff2d050212025838941282@mail.gmail.com> <2cad20900502122000133a7ef3@mail.gmail.com> <f2ff2d05021222151143eb12@mail.gmail.com> Message-ID: <420F522B.9020608@tds.net> Liam Clarke wrote: > Yup, that's what I was after, the full error message. > > >self.grid1.CreateGrid(100,6) > >>val = gridc.wxGrid_CreateGrid(self, *_args, **_kwargs) > > try this > > self.grid1.CreateGrid(self, 100, 6) > > I'm pretty sure you have to explicitly pass self. No, that's not it. There is an asymmetry between the way a method is declared and the way it is invoked. In the declaration, you list 'self' as an explicit parameter, e.g. def CreateGrid(self, *_args, **_kwargs) but at the point of call the 'self' argument is implicit, it is the object on which the method is invoked. So the call self.grid1.CreateGrid(100, 6) will call CreateGrid with the three arguments (self.grid1, 100, 6) I don't know what the actual problem is but I'm pretty sure this isn't the solution. jrlen, the error trace you sent looks incomplete, it doesn't show any of your code. Is there more of it? Kent > > Let me know how ya go. > > Regards, > > Liam Clarke > > > On Sun, 13 Feb 2005 12:00:56 +0800, jrlen balane <nbbalane@gmail.com> wrote: > >>how would i find the stack trace? by the way, this is what the log says: >> >>11:53:16: TypeError: wxGrid_CreateGrid() takes at least 3 >>arguments (2 given)Traceback(most recent call last): >>11:53:16: TypeError: wxGrid_CreateGrid() takes at least 3 >>arguments (2 given) File >>"C:\PYTHON23\Lib\site-packages\wxPython\tools\boa\Models\wxPythonControllers.py", >>line 80, in OnDesigner >>11:53:16: self.showDesigner() >>11:53:16: File >>"C:\PYTHON23\Lib\site-packages\wxPython\tools\boa\Models\wxPythonControllers.py", >>line 145, in showDesigner >>11:53:16: designer.refreshCtrl() >>11:53:16: File >>"C:\PYTHON23\Lib\site-packages\wxPython\tools\boa\Views\Designer.py",line >>379, in refreshCtrl >>11:53:16: self.initObjectsAndCompanions(objCol.creators[1:], >>objCol, deps, depLnks) >>11:53:16: File >>"C:\PYTHON23\Lib\site-packages\wxPython\tools\boa\Views\InspectableViews.py", >>line 140, in initObjectsAndCompanions >>11:53:16: dependents, depLinks) >>11:53:16: File >>"C:\PYTHON23\Lib\site-packages\wxPython\tools\boa\Views\InspectableViews.py", >>line 216, in initObjProps >>11:53:16: getattr(ctrl, prop.prop_setter)(value) >>11:53:16: File "C:\PYTHON23\lib\site-packages\wxPython\grid.py", >>line 973, in CreateGrid >>11:53:16: val = gridc.wxGrid_CreateGrid(self, *_args, **_kwargs) >>11:53:16: TypeError: wxGrid_CreateGrid() takes at least 3 >>arguments (2 given) >> > > > From kent37 at tds.net Sun Feb 13 14:17:19 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun Feb 13 14:17:23 2005 Subject: [Tutor] cross platform gui In-Reply-To: <f2ff2d05021222173598072d@mail.gmail.com> References: <20050212110109.06ED01E403F@bag.python.org> <420E648C.1000100@zen.co.uk> <8ccdfa14226d57eed26adf2d72286408@gmail.com> <f2ff2d05021222173598072d@mail.gmail.com> Message-ID: <420F535F.5090209@tds.net> Liam Clarke wrote: > I would recommend wxPython, it seems to be cross platform. Pythoncard > is an easy to use wrapper around wxPython, and for some stuff you have > to revert back to wxPython code. > I can't on QT, and Tkinter is getting a bit old these days (imao.) > > AFAIK they should all be cross-platform (query QT), so it's all a > matter of style. All three (wxPython, Tkinter and QT) will run on Mac, Windows and Linux. QT is not free on Windows though that is changing. Tkinter is included with Python and simple GUIs are easy to create with it. I've heard really good things about QT's ease of development but I haven't tried it myself. wxPython has an extensive widget library. If your GUI requirements are *very* modest, EasyGUI might fit the bill. It lets you build a series of dialog boxes that accept information from the user. http://www.ferg.org/easygui/ Kent > > > On Sun, 13 Feb 2005 14:34:54 +1100, Kim Branson <kim.branson@gmail.com> wrote: > >>-----BEGIN PGP SIGNED MESSAGE----- >>Hash: SHA1 >> >>Hi all, >> >>i'm interested in building a gui for some code we have. I'm after >>pointers on gui programming, and a recommendation on a cross platform >>gui library, wxpython? pythoncard, qt? What do people use. Ideally i'd >>like something that can work on windows, osx and linux. Its a science >>program so the look is a of lesser importance :) >> >>cheers >> >>Kim >>-----BEGIN PGP SIGNATURE----- >>Version: GnuPG v1.2.4 (Darwin) >> >>iD8DBQFCDsrfer2hmGbHcokRAlYLAKCXGmve611OUdqprrpLUVAa2rJdDwCdGRKo >>dqMFRWAYlM60wlMyWpsLG8w= >>=bqSk >>-----END PGP SIGNATURE----- >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> > > > From kent37 at tds.net Sun Feb 13 14:37:53 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun Feb 13 14:38:00 2005 Subject: [Tutor] Pickling In-Reply-To: <s20f61be.001@dbnsmtp.nu.ac.za> References: <s20f61be.001@dbnsmtp.nu.ac.za> Message-ID: <420F5831.3060206@tds.net> Johan, The problem is in your class V. You have > class V: > a=[] > > def add(self, s): > self.a.append(s) The problem is that 'a' is a *class* variable, not an instance variable. The correct way to define V is like this: class V: def __init__(self): self.a=[] # Now 'a' is an instance variable def add(self, s): self.a.append(s) Why does this cause the behaviour you are seeing? Let's take a look at your assign() and add() functions: > def assign(): > p=V() At this point p has no 'a' attribute of its own, just the class attribute inherited from V. > p.a = [1,2,3,4] This assignment *creates* an 'a' attribute in the object p. Now when you pickle p, it gets the list saved with it. > f = open ("blah.dat", 'a') > print 'assign:', p.a > pickle.dump(p,f) > f.close() > OK, how about add()? > def add(): > p=V() > p.add(1);p.add(2);p.add(3);p.add(4); This is changing the *class* attribute 'a'! The object p has no attribute 'a', so when p is pickled, no list is saved with it. > print 'add:', p.a > f = open("blah.dat", 'a') > pickle.dump(p,f) > f.close() The reason you see the expected list when you run both versions is because you have changed the class attribute. A little dabbling in the Python interpreter might clarify a bit more: >>> class V: ... a=[] ... def add(self, s): ... self.a.append(s) ... >>> p=V() >>> p.a [] >>> V.a [] >>> p.add(1) >>> p.add(2) >>> p.a [1, 2] >>> V.a [1, 2] p.a is actually accessing V.a. >>> p=V() >>> p.a = [3,4] >>> p.a [3, 4] >>> V.a [1, 2] Now p has it's own a and V.a is unchanged. Kent Johan Kohler wrote: > Hi > I still have problems pickling and unpickling. After I couldn't get > "complicated" objects to work, i decided to use simple lists. But now > there seems to be a difference between assigning a list value, and using > the .append method. Please try out the code at > http://goose.cs.und.ac.za/python/save1.py There are two "use cases" > WorkingCase() and BrokenCase. > > WorkingCase() saves data in a list using assignment, and by appending, > and then reads it back from the file. BrokenCase performs only the > reading back step. Now, there are no problems when the two cases are > run consecutively. Do this once. Then comment out the WorkingCase() > statement, and run only BrokenCase(). This should read back all the > list entries, but all the ones created by "appending" are blank! I > should mention, that in my application I want to append items one by one > to the list. > > Please can someone help me with this? I am getting extremely frustrated > by not being able to get supposedly simple stuff to work. > > Thanks in advance, > Johan > > > > > > > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From bgailer at alum.rpi.edu Sun Feb 13 16:13:19 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sun Feb 13 16:17:53 2005 Subject: ****SPAM(7.4)**** Re: ****SPAM(11.2)**** [Tutor] Larger program organization In-Reply-To: <420E8182.9010204@po-box.mcgill.ca> References: <20050211173944.07AAC1E4008@bag.python.org> <6.1.2.0.0.20050211132921.036258d8@mail.mric.net> <420E8182.9010204@po-box.mcgill.ca> Message-ID: <6.1.2.0.0.20050213071107.0316f238@mail.mric.net> At 03:21 PM 2/12/2005, Brian van den Broek wrote: [snip] > I am curious about Bob's "Whenever you find yourself writing > an if statement ask whether this would be better handled by subclasses." I start out writing a class like: class A: def __init__(self, type): self.type = type ... def foo(self, ...): if self.type = 1: statements to process object of type 1 else: statements to process object of type 2 The '"if statement" alerts me to consider creating subclasses for types 1 and 2: class A: ... class A1(A); def foo(self, ...): statements to process object of type 1 class A2(A); def foo(self, ...): statements to process object of type 2 That takes less code. Eliminates the type property. I get greater visibility about the existence and distinction of the two (or more) sub-types. I now can much more easily extend each subtype. Bob Gailer mailto:bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From nbbalane at gmail.com Sun Feb 13 16:50:28 2005 From: nbbalane at gmail.com (jrlen balane) Date: Sun Feb 13 16:50:31 2005 Subject: [Tutor] what is wrong with this? In-Reply-To: <420F522B.9020608@tds.net> References: <2cad209005021121365aee64a5@mail.gmail.com> <f2ff2d050212025838941282@mail.gmail.com> <2cad20900502122000133a7ef3@mail.gmail.com> <f2ff2d05021222151143eb12@mail.gmail.com> <420F522B.9020608@tds.net> Message-ID: <2cad209005021307505975cd21@mail.gmail.com> i'm using BOA to construct the GUI. The problem is in this MDIChildFrame. The code was sort of copy and pasted from the wxpython demo "grid.py" then edited so that it fits what i wanted. there seems to be no problem at all when you run the whole program (MDIParentframe). but as i attempt to open this ChildFrame in designer mode, the error occurs. by the way, i tried Sir Liam's suggestion but the error is still there: On Sun, 13 Feb 2005 08:12:11 -0500, Kent Johnson <kent37@tds.net> wrote: > Liam Clarke wrote: > > Yup, that's what I was after, the full error message. > > > > >self.grid1.CreateGrid(100,6) > > > >>val = gridc.wxGrid_CreateGrid(self, *_args, **_kwargs) > > > > try this > > > > self.grid1.CreateGrid(self, 100, 6) > > > > I'm pretty sure you have to explicitly pass self. > > No, that's not it. There is an asymmetry between the way a method is declared and the way it is > invoked. In the declaration, you list 'self' as an explicit parameter, e.g. > def CreateGrid(self, *_args, **_kwargs) > but at the point of call the 'self' argument is implicit, it is the object on which the method is > invoked. So the call > self.grid1.CreateGrid(100, 6) > will call CreateGrid with the three arguments (self.grid1, 100, 6) > > I don't know what the actual problem is but I'm pretty sure this isn't the solution. > > jrlen, the error trace you sent looks incomplete, it doesn't show any of your code. Is there more of it? > > Kent > > > > > Let me know how ya go. > > > > Regards, > > > > Liam Clarke > > > > > > On Sun, 13 Feb 2005 12:00:56 +0800, jrlen balane <nbbalane@gmail.com> wrote: > > > >>how would i find the stack trace? by the way, this is what the log says: > >> > >>11:53:16: TypeError: wxGrid_CreateGrid() takes at least 3 > >>arguments (2 given)Traceback(most recent call last): > >>11:53:16: TypeError: wxGrid_CreateGrid() takes at least 3 > >>arguments (2 given) File > >>"C:\PYTHON23\Lib\site-packages\wxPython\tools\boa\Models\wxPythonControllers.py", > >>line 80, in OnDesigner > >>11:53:16: self.showDesigner() > >>11:53:16: File > >>"C:\PYTHON23\Lib\site-packages\wxPython\tools\boa\Models\wxPythonControllers.py", > >>line 145, in showDesigner > >>11:53:16: designer.refreshCtrl() > >>11:53:16: File > >>"C:\PYTHON23\Lib\site-packages\wxPython\tools\boa\Views\Designer.py",line > >>379, in refreshCtrl > >>11:53:16: self.initObjectsAndCompanions(objCol.creators[1:], > >>objCol, deps, depLnks) > >>11:53:16: File > >>"C:\PYTHON23\Lib\site-packages\wxPython\tools\boa\Views\InspectableViews.py", > >>line 140, in initObjectsAndCompanions > >>11:53:16: dependents, depLinks) > >>11:53:16: File > >>"C:\PYTHON23\Lib\site-packages\wxPython\tools\boa\Views\InspectableViews.py", > >>line 216, in initObjProps > >>11:53:16: getattr(ctrl, prop.prop_setter)(value) > >>11:53:16: File "C:\PYTHON23\lib\site-packages\wxPython\grid.py", > >>line 973, in CreateGrid > >>11:53:16: val = gridc.wxGrid_CreateGrid(self, *_args, **_kwargs) > >>11:53:16: TypeError: wxGrid_CreateGrid() takes at least 3 > >>arguments (2 given) > >> > > > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at freenet.co.uk Sun Feb 13 17:05:19 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Feb 13 17:05:03 2005 Subject: [Tutor] Re: Data storage, SQL? References: <f2ff2d05021023093bb965ef@mail.gmail.com><pan.2005.02.12.09.27.14.107059@lug-delhi.org> <f2ff2d050213014616877914@mail.gmail.com> Message-ID: <01bb01c511e5$d0f3f8c0$31d78751@xp> > ...So, trying to get this straight - if I were going to use SQLite, > what would I actually download from http://www.sqlite.org/sqlite.html > ? Well, I haven't usd it yet but I think you need(for Windoze) 1) The Sqllite executable OR the DLL 2) The pysqlite library to interface between Pyhon DBI and SQLIte and probably 3) SQLIte Explorer for a civilised SQL IDE environment > Also, would Gadfly be easier, being native Python? Gadfly might be easier to accomplish the task but the knowledge would be less transferrable IMHO The effort of learning SQL is fairly minimal (at least to get up to basic speed) but the benefits are immense. I strongly recommend taking the extra time to learn SQL and SQLite looks like a fairly easy way in - it doesn't have power user features like Oracle, Interbase, PostGres etc, but almost all you learn in it will transfer to those heavier weight DBs later if you need it. Thanks for reminding me about SQLite Sandip, I've been meaning to try it for ages and your post was the incentive to download it... It looks promising and I will probably use it for my tutorial, whenever I get round to it! Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Sun Feb 13 17:13:02 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Feb 13 17:12:54 2005 Subject: [Tutor] Accessing local variables from nested functions. References: <200502131141.28174.krzys_kyku@tlen.pl> Message-ID: <01c201c511e6$e565c710$31d78751@xp> > what's the Python way of accessing local variables > in nesting functions? THats usually bad practice, and since it is a nested function why not just return a value? def p(): var1 = 3 def q(): print 'var1 in p is', var1 return 42 var1 = q() After all var1 only exists within p() so you might as well assign it there. If you need to return more than one value recall that Python can return a tuple: def f(): v = 1 u = 2 def g() w = 42 x = 24 return w,x u,v = g() return u Does that help? Alan G. PS In other words I don't know the real answer to your question! Other than maybe messing with locals dictionaries etc that are really horrible and messy :-) From alan.gauld at freenet.co.uk Sun Feb 13 17:42:42 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Feb 13 17:42:36 2005 Subject: [Tutor] Re: Data storage, SQL? References: <f2ff2d05021023093bb965ef@mail.gmail.com> <pan.2005.02.12.09.27.14.107059@lug-delhi.org><f2ff2d050213014616877914@mail.gmail.com> <420F4F76.6050904@tds.net> Message-ID: <01db01c511eb$0a6b5440$31d78751@xp> > Both Gadfly and SQLite have DB-API compliant drivers and use SQL My apologies, I obviously gott confusd somewhere I thought Gadfly was a non SQL DB. In which case you can ignore my previous comments about Gadfly being less suitable than SQLite. > .... I guess I see three rough categories. I'd agree with Kents summary. > At the top of the heap are the industrial strength databases. > This includes free products like MySQL, PostgreSQL and Firebird > as well as commercial products like MS SQL Server, Sybase and Oracle. The commercial ones all tend to scale better at the very big end of things. But you only need to worry if you have more than a thousand users or over a terabyte of data. For 90% plus of applications the freeware ones will do fine. > In the middle tier are databases that are not as full featured > but still very usable for small to midsize work. I would put > SQLite and Gadfly into this category. Some people would argue that MySQL > belongs here. I'd have put MySql here up until release 5 but its now pretty solidly in tier 1 territory - especially since their tie up with SAP and MaxDB for large data sets and with the addition of stored procedures. The other popular one in this tier 2 category is MS Access. > In the bottom tier are programs that are more of a persistence mechanism > than a true database. I put KirbyBase here along with the standard > Python shelve and dbm modules. The other category are the Object Databases like ZODB from Zope. However they are so disparate in capability and architecure that there is little in common. The big win with a SQL solution is that the knowledge transfers easily from one DB to aother as the size grows. Alan G. From nbbalane at gmail.com Sun Feb 13 17:49:36 2005 From: nbbalane at gmail.com (jrlen balane) Date: Sun Feb 13 17:49:40 2005 Subject: [Tutor] how to read from a txt file Message-ID: <2cad209005021308491228ea8b@mail.gmail.com> guys, how would i do this: i want to read from a text file the text file should contain should contain data (say, decimal value from 1-1200). there should be no other type of entry but decimal it should contain 96 data all in all, with each data separated by a comma or each data is numbered from 1-96 (or better yet, any suggestions on this???) now, the program should read each data every 5 minutes for eight hours the data will be sent to the serial port and will be executed by an external hardware. the serial part is ok, and the problem now is how to read from a text file. any help, pls. what i know (chapter 7 of the tutorial): 1) first, to open a txt file, i can use open() say: f = open(*.txt, r) a user can use the notepad to create the text file so i'll just open it for reading. my problem now would be on reading the contents of the file. 2) f.read(size), since my data ranges from 0-1200, size = 2 for each read. 3) should i do this: for data in range (1, 96,1): f.read(2) ... time.sleep(300) # 5 minutes 4) since f.read() returns string, how would i convert this back to decimal value, since i would need the decimal value for the serial part. please help, will try to formulate some questions later to make the problem clearer. thanks in advance... From mark.kels at gmail.com Sun Feb 13 18:27:03 2005 From: mark.kels at gmail.com (Mark Kels) Date: Sun Feb 13 18:27:12 2005 Subject: [Tutor] cross platform gui In-Reply-To: <420F7A61.7060205@zen.co.uk> References: <20050213061736.A8E991E4013@bag.python.org> <420F7A61.7060205@zen.co.uk> Message-ID: <c225925305021309273768a21a@mail.gmail.com> On Sun, 13 Feb 2005 08:03:45 -0800, Lobster <zen45800@zen.co.uk> wrote: > > Hi all, > > i'm interested in building a gui for some code we have. I'm after > pointers on gui programming, and a recommendation on a cross platform > gui library, wxpython? pythoncard, qt? What do people use. Ideally i'd > like something that can work on windows, osx and linux. Its a science > program so the look is a of lesser importance :) > > cheers > Kim I think Tkinter will be the best for your needs... Its totally cross platform (I believe it works anywhere python does) and its the python default GUI toolkit (no additional modules needed). Its downside is that it don't got any fancy widgets, but you don't need them for a science program anyway. Good luck !! -- 1. The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners. 2. Unix is user friendly - it's just picky about it's friends. 3. Documentation is like sex: when it is good, it is very, very good. And when it is bad, it is better than nothing. - Dick Brandon From bvande at po-box.mcgill.ca Sun Feb 13 19:13:50 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sun Feb 13 19:14:06 2005 Subject: [Tutor] how to read from a txt file In-Reply-To: <2cad209005021308491228ea8b@mail.gmail.com> References: <2cad209005021308491228ea8b@mail.gmail.com> Message-ID: <420F98DE.9070208@po-box.mcgill.ca> jrlen balane said unto the world upon 2005-02-13 11:49: > guys, how would i do this: > i want to read from a text file > the text file should contain should contain data (say, decimal value > from 1-1200). there should be no other type of entry but decimal > it should contain 96 data all in all, with each data separated by a > comma or each data is numbered from 1-96 (or better yet, any > suggestions on this???) Hi, So, you have control over the creation of the data file, too? Is it being created by a Python process? If so, pickling your data might make more sense. If the data was generated by a class with each data point stored as a class attribute, for instance, you could just pickle the class. Does this sound possible in your situation? > now, the program should read each data every 5 minutes for eight hours > the data will be sent to the serial port and will be executed by an > external hardware. the serial part is ok, and the problem now is how > to read from a text file. > any help, pls. > > what i know (chapter 7 of the tutorial): > 1) first, to open a txt file, i can use open() say: > f = open(*.txt, r) > a user can use the notepad to create the text file so i'll just open > it for reading. my problem now would be on reading the contents of the > file. > 2) f.read(size), since my data ranges from 0-1200, size = 2 for each read. > 3) should i do this: > for data in range (1, 96,1): > f.read(2) > ... > time.sleep(300) # 5 minutes > 4) since f.read() returns string, how would i convert this back to > decimal value, since i would need the decimal value for the serial > part. Since you files are quite short, I'd do something like: <code> data_file = open(thedata.txt, 'r') # note -- 'r' not r data = data_file.readlines() # returns a list of lines def process(list_of_lines): data_points = [] for line in list_of_lines: data_points.append(int(line)) return data_points process(data) </code> This assumes that each line of the data file has nothing but a string with an int followed by '\n' (for end of line), and that all you need is a list of those integers. Maybe these are bad assumptions -- but they might get you started. HTH, Brian vdB From kent37 at tds.net Sun Feb 13 20:04:04 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun Feb 13 20:04:09 2005 Subject: [Tutor] how to read from a txt file In-Reply-To: <420F98DE.9070208@po-box.mcgill.ca> References: <2cad209005021308491228ea8b@mail.gmail.com> <420F98DE.9070208@po-box.mcgill.ca> Message-ID: <420FA4A4.6000806@tds.net> Brian van den Broek wrote: > Since you files are quite short, I'd do something like: > > <code> > data_file = open(thedata.txt, 'r') # note -- 'r' not r > data = data_file.readlines() # returns a list of lines > > def process(list_of_lines): > data_points = [] > for line in list_of_lines: > data_points.append(int(line)) > return data_points > > process(data) This can be done much more simply with a list comprehension using Python's ability to iterate an open file directly: data_file = open('thedata.txt', 'r') # note -- 'thedata.txt' not thedata.txt :-) data_points = [ int(line) for line in data_file ] then process the data with something like for val in data_points: # do something with val time.sleep(300) Alternately (and my preference) the processing could be done in the read loop like this: data_file = open('thedata.txt', 'r') for line in data_file: val = int(line) # do something with val time.sleep(300) Kent > </code> > > This assumes that each line of the data file has nothing but a string > with an int followed by '\n' (for end of line), and that all you need is > a list of those integers. Maybe these are bad assumptions -- but they > might get you started. > > HTH, > > Brian vdB > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Sun Feb 13 20:06:20 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun Feb 13 20:06:24 2005 Subject: ****SPAM(7.4)**** Re: ****SPAM(11.2)**** [Tutor] Larger program organization In-Reply-To: <6.1.2.0.0.20050213071107.0316f238@mail.mric.net> References: <20050211173944.07AAC1E4008@bag.python.org> <6.1.2.0.0.20050211132921.036258d8@mail.mric.net> <420E8182.9010204@po-box.mcgill.ca> <6.1.2.0.0.20050213071107.0316f238@mail.mric.net> Message-ID: <420FA52C.2030000@tds.net> Bob Gailer wrote: > At 03:21 PM 2/12/2005, Brian van den Broek wrote: > [snip] > > I am curious about Bob's "Whenever you find yourself writing > > an if statement ask whether this would be better handled by subclasses." > > class A: > ... > class A1(A); > def foo(self, ...): > statements to process object of type 1 > class A2(A); > def foo(self, ...): > statements to process object of type 2 > > That takes less code. Eliminates the type property. I get greater > visibility about the existence and distinction of the two (or more) > sub-types. I now can much more easily extend each subtype. Also you can more easily *add* a new subtype. Using if statements, if you add a new type you have to find all the relevant conditionals and add another condition. With subclassing, you create a new subclass and define the necessary methods. The changes are localized to the subclass and much easier to figure out. Kent From kent37 at tds.net Sun Feb 13 20:09:45 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun Feb 13 20:09:49 2005 Subject: [Tutor] what is wrong with this? In-Reply-To: <2cad209005021307505975cd21@mail.gmail.com> References: <2cad209005021121365aee64a5@mail.gmail.com> <f2ff2d050212025838941282@mail.gmail.com> <2cad20900502122000133a7ef3@mail.gmail.com> <f2ff2d05021222151143eb12@mail.gmail.com> <420F522B.9020608@tds.net> <2cad209005021307505975cd21@mail.gmail.com> Message-ID: <420FA5F9.4000307@tds.net> You might try asking for help on the Boa users mailing list. Kent jrlen balane wrote: > i'm using BOA to construct the GUI. The problem is in this > MDIChildFrame. The code was sort of copy and pasted from the wxpython > demo "grid.py" then edited so that it fits what i wanted. there seems > to be no problem at all when you run the whole program > (MDIParentframe). but as i attempt to open this ChildFrame in designer > mode, the error occurs. > by the way, i tried Sir Liam's suggestion but the error is still there: > > > > > On Sun, 13 Feb 2005 08:12:11 -0500, Kent Johnson <kent37@tds.net> wrote: > >>Liam Clarke wrote: >> >>>Yup, that's what I was after, the full error message. >>> >>> >self.grid1.CreateGrid(100,6) >>> >>> >>>>val = gridc.wxGrid_CreateGrid(self, *_args, **_kwargs) >>> >>>try this >>> >>>self.grid1.CreateGrid(self, 100, 6) >>> >>>I'm pretty sure you have to explicitly pass self. >> >>No, that's not it. There is an asymmetry between the way a method is declared and the way it is >>invoked. In the declaration, you list 'self' as an explicit parameter, e.g. >> def CreateGrid(self, *_args, **_kwargs) >>but at the point of call the 'self' argument is implicit, it is the object on which the method is >>invoked. So the call >> self.grid1.CreateGrid(100, 6) >>will call CreateGrid with the three arguments (self.grid1, 100, 6) >> >>I don't know what the actual problem is but I'm pretty sure this isn't the solution. >> >>jrlen, the error trace you sent looks incomplete, it doesn't show any of your code. Is there more of it? >> >>Kent >> >> >>>Let me know how ya go. >>> >>>Regards, >>> >>>Liam Clarke >>> >>> >>>On Sun, 13 Feb 2005 12:00:56 +0800, jrlen balane <nbbalane@gmail.com> wrote: >>> >>> >>>>how would i find the stack trace? by the way, this is what the log says: >>>> >>>>11:53:16: TypeError: wxGrid_CreateGrid() takes at least 3 >>>>arguments (2 given)Traceback(most recent call last): >>>>11:53:16: TypeError: wxGrid_CreateGrid() takes at least 3 >>>>arguments (2 given) File >>>>"C:\PYTHON23\Lib\site-packages\wxPython\tools\boa\Models\wxPythonControllers.py", >>>>line 80, in OnDesigner >>>>11:53:16: self.showDesigner() >>>>11:53:16: File >>>>"C:\PYTHON23\Lib\site-packages\wxPython\tools\boa\Models\wxPythonControllers.py", >>>>line 145, in showDesigner >>>>11:53:16: designer.refreshCtrl() >>>>11:53:16: File >>>>"C:\PYTHON23\Lib\site-packages\wxPython\tools\boa\Views\Designer.py",line >>>>379, in refreshCtrl >>>>11:53:16: self.initObjectsAndCompanions(objCol.creators[1:], >>>>objCol, deps, depLnks) >>>>11:53:16: File >>>>"C:\PYTHON23\Lib\site-packages\wxPython\tools\boa\Views\InspectableViews.py", >>>>line 140, in initObjectsAndCompanions >>>>11:53:16: dependents, depLinks) >>>>11:53:16: File >>>>"C:\PYTHON23\Lib\site-packages\wxPython\tools\boa\Views\InspectableViews.py", >>>>line 216, in initObjProps >>>>11:53:16: getattr(ctrl, prop.prop_setter)(value) >>>>11:53:16: File "C:\PYTHON23\lib\site-packages\wxPython\grid.py", >>>>line 973, in CreateGrid >>>>11:53:16: val = gridc.wxGrid_CreateGrid(self, *_args, **_kwargs) >>>>11:53:16: TypeError: wxGrid_CreateGrid() takes at least 3 >>>>arguments (2 given) >>>> >>> >>> >>> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> > > From bvande at po-box.mcgill.ca Sun Feb 13 19:59:29 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sun Feb 13 20:14:55 2005 Subject: ****SPAM(11.2)**** [Tutor] Larger program organization In-Reply-To: <6.1.2.0.0.20050213071107.0316f238@mail.mric.net> References: <20050211173944.07AAC1E4008@bag.python.org> <6.1.2.0.0.20050211132921.036258d8@mail.mric.net> <420E8182.9010204@po-box.mcgill.ca> <6.1.2.0.0.20050213071107.0316f238@mail.mric.net> Message-ID: <420FA391.3010005@po-box.mcgill.ca> Bob Gailer said unto the world upon 2005-02-13 10:13: > At 03:21 PM 2/12/2005, Brian van den Broek wrote: > [snip] > > I am curious about Bob's "Whenever you find yourself writing > > an if statement ask whether this would be better handled by subclasses." <SNIP Bob's explanation> Thanks Bob and Alan, It's quite clear now :-) Best, Brian vdB From bvande at po-box.mcgill.ca Sun Feb 13 20:32:18 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sun Feb 13 20:32:47 2005 Subject: [Tutor] how to read from a txt file In-Reply-To: <420FA4A4.6000806@tds.net> References: <2cad209005021308491228ea8b@mail.gmail.com> <420F98DE.9070208@po-box.mcgill.ca> <420FA4A4.6000806@tds.net> Message-ID: <420FAB42.7030600@po-box.mcgill.ca> Kent Johnson said unto the world upon 2005-02-13 14:04: > Brian van den Broek wrote: > >> Since you files are quite short, I'd do something like: >> >> <code> >> data_file = open(thedata.txt, 'r') # note -- 'r' not r >> data = data_file.readlines() # returns a list of lines >> >> def process(list_of_lines): >> data_points = [] >> for line in list_of_lines: >> data_points.append(int(line)) >> return data_points >> >> process(data) > > > This can be done much more simply with a list comprehension using > Python's ability to iterate an open file directly: > data_file = open('thedata.txt', 'r') # note -- 'thedata.txt' not > thedata.txt :-) Gah! :-[ Outsmarting myself in public again. (At least I'm good at something :-) ) > data_points = [ int(line) for line in data_file ] > > then process the data with something like > for val in data_points: > # do something with val > time.sleep(300) > > Alternately (and my preference) the processing could be done in the read > loop like this: > data_file = open('thedata.txt', 'r') > for line in data_file: > val = int(line) > # do something with val > time.sleep(300) > > Kent I do get that for the minimal logic I posted, this way is much simpler. But, isn't my way with a separate function more easily extended? (To deal with cases where there is more than just ints on lines, or where the data needs to be similarly processed multiple times, etc.) I do feel a YAGNI coming on, though :-) Anyway, thanks for improving my attempt to help. Best, Brian vdB From kent37 at tds.net Sun Feb 13 21:06:12 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun Feb 13 21:06:16 2005 Subject: [Tutor] how to read from a txt file In-Reply-To: <420FAB42.7030600@po-box.mcgill.ca> References: <2cad209005021308491228ea8b@mail.gmail.com> <420F98DE.9070208@po-box.mcgill.ca> <420FA4A4.6000806@tds.net> <420FAB42.7030600@po-box.mcgill.ca> Message-ID: <420FB334.8090804@tds.net> Brian van den Broek wrote: > Kent Johnson said unto the world upon 2005-02-13 14:04: >> Brian van den Broek wrote: >> >>> Since you files are quite short, I'd do something like: >>> >>> <code> >>> data_file = open(thedata.txt, 'r') # note -- 'r' not r >>> data = data_file.readlines() # returns a list of lines >>> >>> def process(list_of_lines): >>> data_points = [] >>> for line in list_of_lines: >>> data_points.append(int(line)) >>> return data_points >>> >>> process(data) >> >> >> >> This can be done much more simply with a list comprehension using >> Python's ability to iterate an open file directly: >> data_file = open('thedata.txt', 'r') # note -- 'thedata.txt' not >> thedata.txt :-) > > > Gah! :-[ Outsmarting myself in public again. (At least I'm good at > something :-) ) > >> data_points = [ int(line) for line in data_file ] > >> then process the data with something like >> for val in data_points: >> # do something with val >> time.sleep(300) >> >> Alternately (and my preference) the processing could be done in the >> read loop like this: >> data_file = open('thedata.txt', 'r') >> for line in data_file: >> val = int(line) >> # do something with val >> time.sleep(300) >> >> Kent > > > I do get that for the minimal logic I posted, this way is much simpler. > But, isn't my way with a separate function more easily extended? (To > deal with cases where there is more than just ints on lines, or where > the data needs to be similarly processed multiple times, etc.) If the processing is per line, any of the three can be extended by calling a user function instead of int(), e.g. def process_line(line): # do something with a line return val data_points = [ process_line(line) for line in data_file ] If you need to maintain some kind of state then the list comprehension breaks down and you might want to use for line in f: # ... or even a class like this: http://mail.python.org/pipermail/tutor/2005-February/035582.html If you need to process the list of lines multiple times in different ways then using readlines() is appropriate. I tend to prefer solutions that make fewer intermediate lists, using iterators instead. This seems to be the modern Python style with the introduction of list comprehensions, generator functions, itertools, generator expressions... Kent > > I do feel a YAGNI coming on, though :-) Seems appropriate :-) Kent > > Anyway, thanks for improving my attempt to help. > > Best, > > Brian vdB > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From ryan at acceleration.net Sun Feb 13 21:47:24 2005 From: ryan at acceleration.net (Ryan Davis) Date: Sun Feb 13 21:47:29 2005 Subject: [Tutor] Larger program organization In-Reply-To: <012401c510e0$2ec72910$31d78751@xp> Message-ID: <20050213204727.8D8101E4007@bag.python.org> My main reason right now is that I know C#/ASP.NET very well. I don't know how to do things in Python yet. Say I can make a C# web app with a quality of X. Until I know how to make a Python web app with quality X, I can't use it in a production environment. I'm hoping that doing some code-gen work, along with other research will help me along, but the rest of the world can't hold still while I study. So, in sum, I thing I could develop fairly complex applications faster in Python, but I don't know how yet. When I do know, I'm sure I will. Thanks, Ryan -----Original Message----- From: Alan Gauld [mailto:alan.gauld@freenet.co.uk] Sent: Saturday, February 12, 2005 3:52 AM To: EJP; Ryan Davis; tutor@python.org Subject: Re: [Tutor] Larger program organization > without trying to make this one of those classic threads of great, > do you feel you could develop fairly complex applications faster > in Python than in C#/ASP.NET? It's a rhetorical question > (but I'm interested in your answer as a single data point) To be honest it wouldn't make a great deal of difference. For a complex application (by which I assume you mean large as well as being technically difficult) you spend most of your time thinking not physically coding so the language becomes less significant. On a typical "big" project the actual coding time is likely to be less than 10% of the total time so even if Python were twice as fast you only save 5% overall. Python may improve time to fix however since it will be easier to read later and therefore easier to debug and spot errors etc. But on big projects analysis, design and testing will be the big contributers, actually typing in the code is a trivial element. Alan G. From tim at johnsons-web.com Sun Feb 13 22:22:39 2005 From: tim at johnsons-web.com (Tim Johnson) Date: Sun Feb 13 22:22:49 2005 Subject: [Tutor] Problems with test cgi script on windows XP/Apache Message-ID: <6.2.1.2.0.20050213121756.01e59398@postman.johnsons-web.com> I'm attempting to run a test cgi script on windows xp with apache as the http server. I keep getting a not found error from IE, and the error log shows the following error message. No such file or directory: script not found or unable to stat: c:/program files/apache group/apache/cgi-bin/test.py Another cgi script using a different interpreter (rebol) is running properly. I was receiving the same error message with the rebol script until I corrected the first line (she-bang). here is the code for the script: #!d:\Python23\python print "Content-type: text/html\n" print "hello" ## I can confirm the the first line does contain the correct path to ## the python executable. I have tried it with and without the ".exe" From tim at johnsons-web.com Sun Feb 13 23:19:11 2005 From: tim at johnsons-web.com (Tim Johnson) Date: Sun Feb 13 23:19:14 2005 Subject: [Tutor] Problems with test cgi script on windows XP/Apache Message-ID: <6.2.1.2.0.20050213131815.01ee8d30@postman.johnsons-web.com> At 12:22 PM 2/13/2005, you wrote: I'm attempting to run a test cgi script on windows xp with apache as the http server. I keep getting a not found error from IE, and the error log shows the following error message. No such file or directory: script not found or unable to stat: c:/program files/apache group/apache/cgi-bin/test.py Another cgi script using a different interpreter (rebol) is running properly. I was receiving the same error message with the rebol script until I corrected the first line (she-bang). >here is the code for the script: >#!d:\Python23\python >print "Content-type: text/html\n" >print "hello" >## I can confirm the the first line does contain the correct path to >## the python executable. I have tried it with and without the ".exe" My apologies for sending the above too soon. I am working with an unfamiliar email program. To add to the above: the mime-type string ("Content-type: text/html\n") is consistant with what I am used to providing in linux. I am out of ideas for the time being. Does anyone else have any? TIA tim >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > >__________ NOD32 1.998 (20050212) Information __________ > >This message was checked by NOD32 Antivirus System. >http://www.nod32.com __________ NOD32 1.998 (20050212) Information __________ This message was checked by NOD32 Antivirus System. http://www.nod32.com From nbbalane at gmail.com Mon Feb 14 00:45:36 2005 From: nbbalane at gmail.com (jrlen balane) Date: Mon Feb 14 00:45:39 2005 Subject: [Tutor] how to read from a txt file In-Reply-To: <420FB334.8090804@tds.net> References: <2cad209005021308491228ea8b@mail.gmail.com> <420F98DE.9070208@po-box.mcgill.ca> <420FA4A4.6000806@tds.net> <420FAB42.7030600@po-box.mcgill.ca> <420FB334.8090804@tds.net> Message-ID: <2cad2090050213154562fa7ba5@mail.gmail.com> ei guys, chill out! what if i choose to numbered my data from 1-96 for example. how would i be able to exclude the numbered part from the data part? and, mind if I ask, what's a YAGNI by the way? From nbbalane at gmail.com Mon Feb 14 00:51:58 2005 From: nbbalane at gmail.com (jrlen balane) Date: Mon Feb 14 00:52:01 2005 Subject: [Tutor] how to read from a txt file In-Reply-To: <2cad2090050213154562fa7ba5@mail.gmail.com> References: <2cad209005021308491228ea8b@mail.gmail.com> <420F98DE.9070208@po-box.mcgill.ca> <420FA4A4.6000806@tds.net> <420FAB42.7030600@po-box.mcgill.ca> <420FB334.8090804@tds.net> <2cad2090050213154562fa7ba5@mail.gmail.com> Message-ID: <2cad20900502131551416f31ee@mail.gmail.com> and this line: data_points.append(int(line)) this would turn the string back to an integer, am i right? and on this one: data_points = [ int(line) for line in data_file ] this did not use any read(), is this already equal to readline()? so this would already store all the data in the txt file to data_points[], am i right? thank you guys! ei, you two are not competing, are you? anyway, hope its a friendly one. for the benifit of all those newbie like me, hehehe. From alan.gauld at freenet.co.uk Mon Feb 14 01:11:26 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Feb 14 01:11:03 2005 Subject: [Tutor] how to read from a txt file References: <2cad209005021308491228ea8b@mail.gmail.com> Message-ID: <020c01c51229$ba713e70$31d78751@xp> > what i know (chapter 7 of the tutorial): > 1) first, to open a txt file, i can use open() say: > f = open(*.txt, r) > a user can use the notepad to create the text file so i'll just open > it for reading. my problem now would be on reading the contents of the > file. OK So far > 2) f.read(size), since my data ranges from 0-1200, size = 2 for each read. you probably want to read it line by line, either using readline or the simpler: for line in f: > 3) should i do this: > for data in range (1, 96,1): > f.read(2) Nope, read is way too complicated. > 4) since f.read() returns string, how would i convert this back to > decimal value, since i would need the decimal value for the serial > part. You can convert a string to a floating point number using the float() function. HTH Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From bvande at po-box.mcgill.ca Mon Feb 14 01:12:36 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon Feb 14 01:13:04 2005 Subject: [Tutor] how to read from a txt file In-Reply-To: <2cad2090050213154562fa7ba5@mail.gmail.com> References: <2cad209005021308491228ea8b@mail.gmail.com> <420F98DE.9070208@po-box.mcgill.ca> <420FA4A4.6000806@tds.net> <420FAB42.7030600@po-box.mcgill.ca> <420FB334.8090804@tds.net> <2cad2090050213154562fa7ba5@mail.gmail.com> Message-ID: <420FECF4.5060706@po-box.mcgill.ca> jrlen balane said unto the world upon 2005-02-13 18:45: > ei guys, chill out! > what if i choose to numbered my data from 1-96 for example. how would > i be able to exclude the numbered part from the data part? > > and, mind if I ask, what's a YAGNI by the way? > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor Hi, I do hope that my reply to Kent's welcome correction of my suggestions didn't seem defencive. I'm learning too, and I think a few of us learners have found that trying to help is also a good way to learn. I feel confident in trying to do so because Kent and several other likewise much more experienced people are about to catch my slips. I may feel a bit embarrassed by them, but I am always grateful to those how take the time to correct them. So, no defenciveness nor spirit of competition intended on my part (nor, I am am certain, Kent's). YAGNI is a slogan of the Extreme and/or Agile programming community. Stands for You Aren't Going to Need It. The idea is, if you are thinking of doing something other than (another slogan) `the simplest thing that could possibly work' -- don't. The rational for complicating things only when an actual need arises to justify the complexity is that unnecessary complexity adds maintenance issues evey bit as much as needed complexity, but without the payoff of additional functionality. Or, so it seems to a non-XP'er. Best to all, Brian vdB From alan.gauld at freenet.co.uk Mon Feb 14 01:19:09 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Feb 14 01:19:28 2005 Subject: [Tutor] how to read from a txt file References: <2cad209005021308491228ea8b@mail.gmail.com><420F98DE.9070208@po-box.mcgill.ca> <420FA4A4.6000806@tds.net><420FAB42.7030600@po-box.mcgill.ca> <420FB334.8090804@tds.net> <2cad2090050213154562fa7ba5@mail.gmail.com> Message-ID: <023201c5122a$ce42ae10$31d78751@xp> > ei guys, chill out! Its OK, we often get carried away on flights of fancy here :-) > what if i choose to numbered my data from 1-96 for example. how would > i be able to exclude the numbered part from the data part? You can use the string split() method to get a list of the components. Then select the bit you want by indexing the list. > and, mind if I ask, what's a YAGNI by the way? Its from the XP programming camp - You Aren't Going to Need It Basically don't build in fancy features unless you know you need them, coz most often you won't... It works up to a point, but if you know you *will* need them its a lot easier to build the structure up front than to try to bolt it on later! Alan G. From nixonron at yahoo.com Mon Feb 14 02:01:33 2005 From: nixonron at yahoo.com (Ron Nixon) Date: Mon Feb 14 02:01:37 2005 Subject: [Tutor] error message Message-ID: <20050214010133.39173.qmail@web20323.mail.yahoo.com> I'm dping something very simple in RE. Lets say I'm trying to match an American Phone number I write the code this way and try to match it: import re string = 'My phone is 410-995-1155' pattern = r'\d{3}-\d{3}-\d{4}' re.match(pattern,string).group() but I get this error message Traceback (most recent call last): File "C:/Python24/findphone", line 4, in -toplevel- re.match(pattern,string).group() AttributeError: 'NoneType' object has no attribute 'group' __________________________________ Do you Yahoo!? Take Yahoo! Mail with you! Get it on your mobile phone. http://mobile.yahoo.com/maildemo From kent37 at tds.net Mon Feb 14 02:02:06 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Feb 14 02:02:11 2005 Subject: [Tutor] how to read from a txt file In-Reply-To: <2cad20900502131551416f31ee@mail.gmail.com> References: <2cad209005021308491228ea8b@mail.gmail.com> <420F98DE.9070208@po-box.mcgill.ca> <420FA4A4.6000806@tds.net> <420FAB42.7030600@po-box.mcgill.ca> <420FB334.8090804@tds.net> <2cad2090050213154562fa7ba5@mail.gmail.com> <2cad20900502131551416f31ee@mail.gmail.com> Message-ID: <420FF88E.8070909@tds.net> jrlen balane wrote: > and this line: > data_points.append(int(line)) > > this would turn the string back to an integer, am i right? Yes. > > and on this one: > data_points = [ int(line) for line in data_file ] > > this did not use any read(), is this already equal to readline()? so > this would already store all the data in the txt file to > data_points[], am i right? Yes. A handy feature of Python is that a file object is iterable - you can use a for loop or list comprehension to iterate over the lines of the file without an explicit readline(). So this: data_points = [ int(line) for line in data_file ] is roughly equivalent to this (without the list comprehension): data_points = [] for line in data_file: data_points.append(int(line)) or this (with explicit readline()): data_points = [] while True: line = data_file.readline() if not line: break data_points.append(int(line)) only the list comprehension is much more concise and, when you get used to it, much clearer. > > thank you guys! ei, you two are not competing, are you? anyway, hope > its a friendly one. for the benifit of all those newbie like me, > hehehe. Definitely friendly. Kent From cyresse at gmail.com Mon Feb 14 02:09:46 2005 From: cyresse at gmail.com (Liam Clarke) Date: Mon Feb 14 02:09:50 2005 Subject: [Tutor] Tweaking list comprehensions Message-ID: <f2ff2d050213170944758935@mail.gmail.com> Hello, I am fine tuning list comprehensions (at least my understandng thereof), and I'm not near a Python interpreter at the moment, so I was wondering if someone could tell me if I did OK - def approachA(files): isHTML = [] for filename in files: if filename.endswith('.htm') or filename.endswith('.html'): isHTML.append(filename) return isHTML def approachB(files): isHTML = [filename if filename.endswith('.htm') or\ filename.endswith(.html') for filename in files] return isHTML I wanted approachB to be the list comprehension verstion of approachA. Did I get the syntax right? All seems somewhat back to front to me, although when read the comprehension does sorta make sense in a twisted way. Feels almost.. Perlesque in it's perverse compactness. That said, saving myself from the cascading sequential conditionals/loops of approach A is good, I feel. When it's 2am in the morning, and I've run out of coffee, 90% of my bugs have been due to the 'cascades' and one misplaced tab. Regards, Liam Clarke -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From kent37 at tds.net Mon Feb 14 02:11:10 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Feb 14 02:11:13 2005 Subject: [Tutor] how to read from a txt file In-Reply-To: <420FECF4.5060706@po-box.mcgill.ca> References: <2cad209005021308491228ea8b@mail.gmail.com> <420F98DE.9070208@po-box.mcgill.ca> <420FA4A4.6000806@tds.net> <420FAB42.7030600@po-box.mcgill.ca> <420FB334.8090804@tds.net> <2cad2090050213154562fa7ba5@mail.gmail.com> <420FECF4.5060706@po-box.mcgill.ca> Message-ID: <420FFAAE.1070908@tds.net> Brian van den Broek wrote: > YAGNI is a slogan of the Extreme and/or Agile programming community. > Stands for You Aren't Going to Need It. The idea is, if you are > thinking of doing something other than (another slogan) `the simplest > thing that could possibly work' -- don't. The rational for > complicating things only when an actual need arises to justify the > complexity is that unnecessary complexity adds maintenance issues evey > bit as much as needed complexity, but without the payoff of additional > functionality. Or, so it seems to a non-XP'er. There's a little more to it than that. Adding something because you think you are going to need it in the future is a guess that you can predict the future. Often you will guess wrong because requirements will change for many reasons. Plus, time spent developing tomorrow's features is taken away from developing today's features. XP says, do today only what you need to meet today's requirements; tomorrow is soon enough to work on tomorrow's requirements. For more info see the c2 wiki (which is a great resource for good programming practice and Extreme Programming): http://c2.com/cgi/wiki?YouArentGonnaNeedIt Kent From cyresse at gmail.com Mon Feb 14 02:11:15 2005 From: cyresse at gmail.com (Liam Clarke) Date: Mon Feb 14 02:11:18 2005 Subject: [Tutor] error message In-Reply-To: <20050214010133.39173.qmail@web20323.mail.yahoo.com> References: <20050214010133.39173.qmail@web20323.mail.yahoo.com> Message-ID: <f2ff2d05021317111a6c5fb1@mail.gmail.com> Try breaking it down to > import re > string = 'My phone is 410-995-1155' > pattern = r'\d{3}-\d{3}-\d{4}' x = re.match(pattern, string) x.group() See if that offers any improvement. On Sun, 13 Feb 2005 17:01:33 -0800 (PST), Ron Nixon <nixonron@yahoo.com> wrote: > I'm dping something very simple in RE. > > Lets say I'm trying to match an American Phone number > > I write the code this way and try to match it: > import re > string = 'My phone is 410-995-1155' > pattern = r'\d{3}-\d{3}-\d{4}' > re.match(pattern,string).group() > > but I get this error message > Traceback (most recent call last): > File "C:/Python24/findphone", line 4, in -toplevel- > re.match(pattern,string).group() > AttributeError: 'NoneType' object has no attribute 'group' > > > __________________________________ > Do you Yahoo!? > Take Yahoo! Mail with you! Get it on your mobile phone. > http://mobile.yahoo.com/maildemo > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From kent37 at tds.net Mon Feb 14 02:22:13 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Feb 14 02:22:19 2005 Subject: [Tutor] error message In-Reply-To: <20050214010133.39173.qmail@web20323.mail.yahoo.com> References: <20050214010133.39173.qmail@web20323.mail.yahoo.com> Message-ID: <420FFD45.5010701@tds.net> Ron Nixon wrote: > I'm dping something very simple in RE. > > Lets say I'm trying to match an American Phone number > > I write the code this way and try to match it: > import re > string = 'My phone is 410-995-1155' > pattern = r'\d{3}-\d{3}-\d{4}' > re.match(pattern,string).group() Use re.search(). re.match() only matches at the start of the string (as if you had ^ at the start of the re). Kent > > but I get this error message > Traceback (most recent call last): > File "C:/Python24/findphone", line 4, in -toplevel- > re.match(pattern,string).group() > AttributeError: 'NoneType' object has no attribute 'group' > > > > __________________________________ > Do you Yahoo!? > Take Yahoo! Mail with you! Get it on your mobile phone. > http://mobile.yahoo.com/maildemo > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Mon Feb 14 02:24:02 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Feb 14 02:24:08 2005 Subject: [Tutor] Tweaking list comprehensions In-Reply-To: <f2ff2d050213170944758935@mail.gmail.com> References: <f2ff2d050213170944758935@mail.gmail.com> Message-ID: <420FFDB2.2040101@tds.net> Liam Clarke wrote: > Hello, > > I am fine tuning list comprehensions (at least my understandng > thereof), and I'm not near a Python interpreter at the moment, so I > was wondering if someone could tell me if I did OK - > > def approachA(files): > > isHTML = [] > for filename in files: > if filename.endswith('.htm') or filename.endswith('.html'): > isHTML.append(filename) > return isHTML > > def approachB(files): > > isHTML = [filename if filename.endswith('.htm') or\ > filename.endswith(.html') for filename in files] > return isHTML Looks good to me. Kent > > I wanted approachB to be the list comprehension verstion of approachA. > Did I get the syntax right? All seems somewhat back to front to me, > although when read the comprehension does sorta make sense in a > twisted way. > From cyresse at gmail.com Mon Feb 14 02:24:26 2005 From: cyresse at gmail.com (Liam Clarke) Date: Mon Feb 14 02:24:29 2005 Subject: [Tutor] error message In-Reply-To: <20050214011624.5863.qmail@web20322.mail.yahoo.com> References: <f2ff2d05021317111a6c5fb1@mail.gmail.com> <20050214011624.5863.qmail@web20322.mail.yahoo.com> Message-ID: <f2ff2d050213172471d2a94f@mail.gmail.com> OK, so it looks like you're not matching. Remember match only matches at the start of a line, so try re.search instead. On Sun, 13 Feb 2005 17:16:24 -0800 (PST), Ron Nixon <nixonron@yahoo.com> wrote: > > > Got the same error message after trying: > > x =re.match(patt,string) > x.group() > > Traceback (most recent call last): > File "C:/Python24/testphone.py", line 5, in > -toplevel- > x.group() > AttributeError: 'NoneType' object has no attribute > 'group' > > --- Liam Clarke <cyresse@gmail.com> wrote: > > > Try breaking it down to > > > > > import re > > > string = 'My phone is 410-995-1155' > > > pattern = r'\d{3}-\d{3}-\d{4}' > > > > x = re.match(pattern, string) > > x.group() > > > > See if that offers any improvement. > > > > > > On Sun, 13 Feb 2005 17:01:33 -0800 (PST), Ron Nixon > > <nixonron@yahoo.com> wrote: > > > I'm dping something very simple in RE. > > > > > > Lets say I'm trying to match an American Phone > > number > > > > > > I write the code this way and try to match it: > > > import re > > > string = 'My phone is 410-995-1155' > > > pattern = r'\d{3}-\d{3}-\d{4}' > > > re.match(pattern,string).group() > > > > > > but I get this error message > > > Traceback (most recent call last): > > > File "C:/Python24/findphone", line 4, in > > -toplevel- > > > re.match(pattern,string).group() > > > AttributeError: 'NoneType' object has no attribute > > 'group' > > > > > > > > > __________________________________ > > > Do you Yahoo!? > > > Take Yahoo! Mail with you! Get it on your mobile > > phone. > > > http://mobile.yahoo.com/maildemo > > > _______________________________________________ > > > Tutor maillist - Tutor@python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > -- > > 'There is only one basic human right, and that is to > > do as you damn well please. > > And with it comes the only basic human duty, to take > > the consequences. > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > __________________________________ > Do you Yahoo!? > Take Yahoo! Mail with you! Get it on your mobile phone. > http://mobile.yahoo.com/maildemo > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From alan.gauld at freenet.co.uk Mon Feb 14 02:37:56 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Feb 14 02:37:33 2005 Subject: [Tutor] error message References: <20050214010133.39173.qmail@web20323.mail.yahoo.com> Message-ID: <027301c51235$cf8c9230$31d78751@xp> > string = 'My phone is 410-995-1155' > pattern = r'\d{3}-\d{3}-\d{4}' > re.match(pattern,string).group() > AttributeError: 'NoneType' object has no attribute 'group' When match doesn't find anything it returns None, which has no group() method. Why does it not find the regex? Because you used match() which looks for a match starting at the beginning of the line. You need to use search() instead... I discuss this in my tutorial topic on regex... Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From keridee at jayco.net Mon Feb 14 03:04:22 2005 From: keridee at jayco.net (Jacob S.) Date: Mon Feb 14 03:04:02 2005 Subject: [Tutor] error message References: <20050214010133.39173.qmail@web20323.mail.yahoo.com> Message-ID: <004601c51239$87d8dee0$445328cf@JSLAPTOP> Dive into Python, an excellent tutorial has a case study on this very same topic. The biggest problem that nobody has mentioned yet is the fact that group() will not have anything unless you explicitly tell it to group it. I.E. pattern = r'(\d{3})-(\d{3})-(\d{4})' You need the parenthesis to "capture" the groups. BTW, dive into python can be found here: http://www.diveintopython.org/ HTH, Jacob > I'm dping something very simple in RE. > > Lets say I'm trying to match an American Phone number > > I write the code this way and try to match it: > import re > string = 'My phone is 410-995-1155' > pattern = r'\d{3}-\d{3}-\d{4}' > re.match(pattern,string).group() > > but I get this error message > Traceback (most recent call last): > File "C:/Python24/findphone", line 4, in -toplevel- > re.match(pattern,string).group() > AttributeError: 'NoneType' object has no attribute 'group' > > > > __________________________________ > Do you Yahoo!? > Take Yahoo! Mail with you! Get it on your mobile phone. > http://mobile.yahoo.com/maildemo > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From cyresse at gmail.com Mon Feb 14 03:09:24 2005 From: cyresse at gmail.com (Liam Clarke) Date: Mon Feb 14 03:09:27 2005 Subject: [Tutor] error message In-Reply-To: <004601c51239$87d8dee0$445328cf@JSLAPTOP> References: <20050214010133.39173.qmail@web20323.mail.yahoo.com> <004601c51239$87d8dee0$445328cf@JSLAPTOP> Message-ID: <f2ff2d0502131809189decf4@mail.gmail.com> I was wondering about that also, I've only ever used .group() when I've got named groups using (?P<foo>) On Sun, 13 Feb 2005 21:04:22 -0500, Jacob S. <keridee@jayco.net> wrote: > Dive into Python, an excellent tutorial has a case study on this very same > topic. > > The biggest problem that nobody has mentioned yet is the fact that group() > will not have anything unless you explicitly tell it to group it. > I.E. > > pattern = r'(\d{3})-(\d{3})-(\d{4})' > > You need the parenthesis to "capture" the groups. > > BTW, dive into python can be found here: > http://www.diveintopython.org/ > > HTH, > Jacob > > > > I'm dping something very simple in RE. > > > > Lets say I'm trying to match an American Phone number > > > > I write the code this way and try to match it: > > import re > > string = 'My phone is 410-995-1155' > > pattern = r'\d{3}-\d{3}-\d{4}' > > re.match(pattern,string).group() > > > > but I get this error message > > Traceback (most recent call last): > > File "C:/Python24/findphone", line 4, in -toplevel- > > re.match(pattern,string).group() > > AttributeError: 'NoneType' object has no attribute 'group' > > > > > > > > __________________________________ > > Do you Yahoo!? > > Take Yahoo! Mail with you! Get it on your mobile phone. > > http://mobile.yahoo.com/maildemo > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From keridee at jayco.net Mon Feb 14 03:11:48 2005 From: keridee at jayco.net (Jacob S.) Date: Mon Feb 14 03:11:34 2005 Subject: [Tutor] Tweaking list comprehensions References: <f2ff2d050213170944758935@mail.gmail.com> Message-ID: <004d01c5123a$8fa02f10$445328cf@JSLAPTOP> > Hello, > > I am fine tuning list comprehensions (at least my understandng > thereof), and I'm not near a Python interpreter at the moment, so I > was wondering if someone could tell me if I did OK - > > def approachA(files): > > isHTML = [] > for filename in files: > if filename.endswith('.htm') or filename.endswith('.html'): > isHTML.append(filename) > return isHTML > > def approachB(files): > > isHTML = [filename if filename.endswith('.htm') or\ > filename.endswith(.html') for filename in files] > return isHTML No, it should be... isHTML = [filename for filename in files if filename.endswith('.htm') or\ filename.endswith('.html') for filename in files] HTH, Jacob > I wanted approachB to be the list comprehension verstion of approachA. > Did I get the syntax right? All seems somewhat back to front to me, > although when read the comprehension does sorta make sense in a > twisted way. > > Feels almost.. Perlesque in it's perverse compactness. That said, > saving myself from the cascading sequential conditionals/loops of > approach A is good, I feel. When it's 2am in the morning, and I've run > out of coffee, 90% of my bugs have been due to the 'cascades' and one > misplaced tab. > > Regards, > > > Liam Clarke > > > > > > -- > 'There is only one basic human right, and that is to do as you damn well > please. > And with it comes the only basic human duty, to take the consequences. > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Mon Feb 14 03:12:44 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Feb 14 03:12:49 2005 Subject: [Tutor] error message In-Reply-To: <004601c51239$87d8dee0$445328cf@JSLAPTOP> References: <20050214010133.39173.qmail@web20323.mail.yahoo.com> <004601c51239$87d8dee0$445328cf@JSLAPTOP> Message-ID: <4210091C.7080905@tds.net> Jacob S. wrote: > Dive into Python, an excellent tutorial has a case study on this very > same topic. > > The biggest problem that nobody has mentioned yet is the fact that > group() will not have anything unless you explicitly tell it to group it. group() defaults to returning group 0 which is the whole match. >>> import re >>> string = 'My phone is 410-995-1155' >>> pattern = r'\d{3}-\d{3}-\d{4}' >>> re.search(pattern,string).group() '410-995-1155' Kent From keridee at jayco.net Mon Feb 14 03:16:49 2005 From: keridee at jayco.net (Jacob S.) Date: Mon Feb 14 03:16:34 2005 Subject: [Tutor] error message References: <20050214010133.39173.qmail@web20323.mail.yahoo.com><004601c51239$87d8dee0$445328cf@JSLAPTOP> <4210091C.7080905@tds.net> Message-ID: <006501c5123b$48e19180$445328cf@JSLAPTOP> Okay... Cool. Jacob > group() defaults to returning group 0 which is the whole match. > > >>> import re > >>> string = 'My phone is 410-995-1155' > >>> pattern = r'\d{3}-\d{3}-\d{4}' > >>> re.search(pattern,string).group() > '410-995-1155' > > Kent > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From tameyer at ihug.co.nz Mon Feb 14 03:22:38 2005 From: tameyer at ihug.co.nz (Tony Meyer) Date: Mon Feb 14 03:23:27 2005 Subject: [Tutor] Tweaking list comprehensions In-Reply-To: <ECBA357DDED63B4995F5C1F5CBE5B1E802107888@its-xchg4.massey.ac.nz> Message-ID: <ECBA357DDED63B4995F5C1F5CBE5B1E801DAFE62@its-xchg4.massey.ac.nz> >> def approachB(files): >> >> isHTML = [filename if filename.endswith('.htm') or\ >> filename.endswith(.html') for filename in files] >> return isHTML > > No, it should be... > > isHTML = [filename for filename in files if > filename.endswith('.htm') or\ > filename.endswith('.html') for filename in files] Actually: isHTML = [filename for filename in files if filename.endswith('.htm') or \ filename.endswith('.html')] >>> files = "a.html", "b.htm", "c.txt" >>> [filename for filename in files if filename.endswith('.htm') or filename.endswith('.html') for filename in files] ['a.html', 'b.htm', 'c.txt', 'a.html', 'b.htm', 'c.txt'] >>> [filename for filename in files if filename.endswith('.htm') or filename.endswith('.html')] ['a.html', 'b.htm'] FWIW, if you're getting "files" from a directory listing of a local drive, you might be able to use 'glob.glob("*.htm?")' instead. =Tony.Meyer From kent37 at tds.net Mon Feb 14 03:30:40 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Feb 14 03:30:45 2005 Subject: [Tutor] Tweaking list comprehensions In-Reply-To: <420FFDB2.2040101@tds.net> References: <f2ff2d050213170944758935@mail.gmail.com> <420FFDB2.2040101@tds.net> Message-ID: <42100D50.10608@tds.net> Kent Johnson wrote: > Liam Clarke wrote: > >> Hello, >> I am fine tuning list comprehensions (at least my understandng >> thereof), and I'm not near a Python interpreter at the moment, so I >> was wondering if someone could tell me if I did OK - >> >> def approachA(files): >> >> isHTML = [] >> for filename in files: >> if filename.endswith('.htm') or filename.endswith('.html'): >> isHTML.append(filename) >> return isHTML >> >> def approachB(files): >> >> isHTML = [filename if filename.endswith('.htm') or\ >> filename.endswith(.html') for filename in files] return >> isHTML > > > Looks good to me. Oops. Tony is right. isHTML = [filename for filename in files if filename.endswith('.htm') or\ filename.endswith('.html')] Kent From zen45800 at zen.co.uk Mon Feb 14 11:37:22 2005 From: zen45800 at zen.co.uk (Lobster) Date: Mon Feb 14 03:37:03 2005 Subject: [Tutor] calling an external program Message-ID: <42107F62.5010608@zen.co.uk> - I am trying to call up an external program with something like a "Shell" command - can not find a way of doing this (in windows) Any hints? Ed Jason From cyresse at gmail.com Mon Feb 14 03:54:15 2005 From: cyresse at gmail.com (Liam Clarke) Date: Mon Feb 14 03:54:18 2005 Subject: [Tutor] Fwd: Delivery Status Notification (Failure) In-Reply-To: <qbC8wSA1X00000006@mail2world.com> References: <qbC8wSA1X00000006@mail2world.com> Message-ID: <f2ff2d0502131854575133dc@mail.gmail.com> Anyone else getting these? ---------- Forwarded message ---------- From: postmaster@mwde14la.mail2world.com <postmaster@mwde14la.mail2world.com> Date: Sun, 13 Feb 2005 17:59:35 -0800 Subject: Delivery Status Notification (Failure) To: cyresse@gmail.com This is an automatically generated Delivery Status Notification. Delivery to the following recipients failed. bob.gailer@magnoliaroad.net Final-Recipient: rfc822;bob.gailer@magnoliaroad.net Action: failed Status: 5.0.0 Diagnostic-Code: smtp;554 5.0.0 MAIL REFUSED!From Dictionary Attack Spammer. ---------- Forwarded message ---------- From: Liam Clarke <cyresse@gmail.com> To: Tutor Tutor <tutor@python.org> Date: Mon, 14 Feb 2005 15:09:24 +1300 Subject: Re: [Tutor] error message I was wondering about that also, I've only ever used .group() when I've got named groups using (?P<foo>) On Sun, 13 Feb 2005 21:04:22 -0500, Jacob S. <keridee@jayco.net> wrote: > Dive into Python, an excellent tutorial has a case study on this very same > topic. > > The biggest problem that nobody has mentioned yet is the fact that group() > will not have anything unless you explicitly tell it to group it. > I.E. > > pattern = r'(\d{3})-(\d{3})-(\d{4})' > > You need the parenthesis to "capture" the groups. > > BTW, dive into python can be found here: > http://www.diveintopython.org/ > > HTH, > Jacob > > > > I'm dping something very simple in RE. > > > > Lets say I'm trying to match an American Phone number > > > > I write the code this way and try to match it: > > import re > > string = 'My phone is 410-995-1155' > > pattern = r'\d{3}-\d{3}-\d{4}' > > re.match(pattern,string).group() > > > > but I get this error message > > Traceback (most recent call last): > > File "C:/Python24/findphone", line 4, in -toplevel- > > re.match(pattern,string).group() > > AttributeError: 'NoneType' object has no attribute 'group' > > > > > > > > __________________________________ > > Do you Yahoo!? > > Take Yahoo! Mail with you! Get it on your mobile phone. > > http://mobile.yahoo.com/maildemo > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From nixonron at yahoo.com Mon Feb 14 04:32:28 2005 From: nixonron at yahoo.com (Ron Nixon) Date: Mon Feb 14 04:32:32 2005 Subject: [Tutor] writing list to new file Message-ID: <20050214033228.21581.qmail@web20324.mail.yahoo.com> How would I save a list to a new file for example: If line.startswith('XXX'): save list to new file But I get errors saying only stings can be saved this way. __________________________________ Do you Yahoo!? Meet the all-new My Yahoo! - Try it today! http://my.yahoo.com From tameyer at ihug.co.nz Mon Feb 14 04:48:19 2005 From: tameyer at ihug.co.nz (Tony Meyer) Date: Mon Feb 14 04:48:28 2005 Subject: [Tutor] writing list to new file In-Reply-To: <ECBA357DDED63B4995F5C1F5CBE5B1E8021078B5@its-xchg4.massey.ac.nz> Message-ID: <ECBA357DDED63B4995F5C1F5CBE5B1E801DAFE66@its-xchg4.massey.ac.nz> > How would I save a list to a new file > > for example: > > If line.startswith('XXX'): > save list to new file > > But I get errors saying only stings can be saved this > way. What do you want to do with the file afterwards? If you want to load it back in as a list at some later point, then something like pickle is probably what you want: >>> l = ['1','2','3','4','5'] >>> import pickle >>> f = open("temp.txt", "w") >>> pickle.dump(l, f) >>> f.close() The file looks like this: """ (lp0 S'1' p1 aS'2' p2 aS'3' p3 aS'4' p4 aS'5' p5 a. """ If you just want a human to be able to read the file, then you probably just want to turn the list into a string, e.g.: >>> l = ['1','2','3','4','5'] >>> f = open("temp.txt", "w") >>> f.write(','.join(l)) >>> f.close() The file looks like this: """ 1,2,3,4,5 """ =Tony.Meyer From maxnoel_fr at yahoo.fr Mon Feb 14 05:05:50 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Mon Feb 14 05:05:54 2005 Subject: [Tutor] calling an external program In-Reply-To: <42107F62.5010608@zen.co.uk> References: <42107F62.5010608@zen.co.uk> Message-ID: <dfc1616e9a7a5601e1759f36d141291c@yahoo.fr> On Feb 14, 2005, at 10:37, Lobster wrote: > - I am trying to call up an external program > with something like a "Shell" command - can not find a way of doing > this > (in windows) > > Any hints? What about os.system('your_command_here')? -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From tameyer at ihug.co.nz Mon Feb 14 05:45:12 2005 From: tameyer at ihug.co.nz (Tony Meyer) Date: Mon Feb 14 05:45:19 2005 Subject: [Tutor] writing list to new file In-Reply-To: <ECBA357DDED63B4995F5C1F5CBE5B1E8021078CA@its-xchg4.massey.ac.nz> Message-ID: <ECBA357DDED63B4995F5C1F5CBE5B1E801DAFE67@its-xchg4.massey.ac.nz> > I'm just trying to create a new file for all > the lines that startswith my string. So if my original > file looks like this: > > 1 Line 1 > 1 Line 2 > 2 Line 1 > 2 Line 2 > 3 Line 1 > 4 Line 1 > > I want to read in all the ones starting with 1 and > then save them to a new file. I can get the result I > want there by using : > If line.startswith('1'): > > But can't figure out how to save these lines to > another file. Something like this, perhaps? """ def filter_file(in_fn, out_fn, to_match): fin = open(in_fn, "r") fout = open(out_fn, "w") for line in fin: if line.startswith(to_match): fout.write(line) fin.close() fout.close() """ Or, to be concise (but less clear): """ def filter_file(in_fn, out_fn, to_match): open(out_fn, "w").write("".join([line for line in open(in_fn, "r") if line.startswith(to_match)])) """ (That's all one line). =Tony.Meyer From python at bernardlebel.com Mon Feb 14 06:20:40 2005 From: python at bernardlebel.com (Bernard Lebel) Date: Mon Feb 14 06:20:55 2005 Subject: [Tutor] calling an external program In-Reply-To: <42107F62.5010608@zen.co.uk> References: <42107F62.5010608@zen.co.uk> Message-ID: <42103528.6080109@bernardlebel.com> The os module is the answer. Use chdir() to make the target executable's directory the current directory, and then os.system( 'command' ) to run the actual command. Cheers Bernard Lobster wrote: > - I am trying to call up an external program > with something like a "Shell" command - can not find a way of doing this > (in windows) > > Any hints? > > Ed Jason From nixonron at yahoo.com Mon Feb 14 08:11:40 2005 From: nixonron at yahoo.com (Ron Nixon) Date: Mon Feb 14 08:11:44 2005 Subject: [Tutor] Value Error message Message-ID: <20050214071140.49302.qmail@web20322.mail.yahoo.com> Trying to scrape some headlines off a newspaper with this code: import urllib, re pattern = re.compile("""<h2><a href="(.*)">(.*)</p>""", re.DOTALL) page = urllib.urlopen("http://www.startribune.com").read() for (headline, code, description) in pattern.findall(page): print (headline, code, description) I'm getting the error below and can't find anything in the documentation. Suggestions Traceback (most recent call last): File "C:/Python24/Stribwebscrape.py", line 13, in ? for (headline, code, description) in pattern.findall(page): ValueError: need more than 2 values to unpack __________________________________ Do you Yahoo!? Meet the all-new My Yahoo! - Try it today! http://my.yahoo.com From nixonron at yahoo.com Mon Feb 14 08:25:43 2005 From: nixonron at yahoo.com (Ron Nixon) Date: Mon Feb 14 08:25:47 2005 Subject: [Tutor] Value Error solved. Another question Message-ID: <20050214072543.49815.qmail@web20324.mail.yahoo.com> Ignore my first posting. Here's what I'm trying to do. I want to extract headlines from a newspaper's website using this code. It works, but I want to match the second group in <h2><a href="(.*)">(.*)</p> and print that out. Sugguestions import urllib, re pattern = re.compile("""<h2><a href="(.*)">(.*)</p>""", re.DOTALL) page = urllib.urlopen("http://www.startribune.com").read() for headline in pattern.findall(page): print headline __________________________________ Do you Yahoo!? Yahoo! Mail - You care about security. So do we. http://promotions.yahoo.com/new_mail From alan.gauld at freenet.co.uk Mon Feb 14 10:09:46 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Feb 14 10:09:34 2005 Subject: [Tutor] Tweaking list comprehensions References: <f2ff2d050213170944758935@mail.gmail.com> <420FFDB2.2040101@tds.net> Message-ID: <029101c51274$ee44a6b0$31d78751@xp> > > I am fine tuning list comprehensions (at least my understandng > > thereof), and I'm not near a Python interpreter at the moment, so I > > was wondering if someone could tell me if I did OK - > > def approachB(files): > > > > isHTML = [filename if filename.endswith('.htm') or\ > > filename.endswith(.html') for filename in files] > > return isHTML The approach is OK but one thing I'd point out is a style issue. Nor,ally a name like isHTML would indicate a predicate or flag - that is a boolean value. A list might be better having a plural name such as HTMLfiles or even just areHTML (which maintains lowercase first letter convention too!) Just a nit pick... Alan G. From alan.gauld at freenet.co.uk Mon Feb 14 10:11:08 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Feb 14 10:10:43 2005 Subject: [Tutor] error message References: <20050214010133.39173.qmail@web20323.mail.yahoo.com> <004601c51239$87d8dee0$445328cf@JSLAPTOP> Message-ID: <029801c51275$1f2306f0$31d78751@xp> > The biggest problem that nobody has mentioned yet is the fact that group() > will not have anything unless you explicitly tell it to group it. Nope, group will work OK even with a normal string regex. Alan G. From alan.gauld at freenet.co.uk Mon Feb 14 10:13:41 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Feb 14 10:13:16 2005 Subject: [Tutor] Tweaking list comprehensions References: <f2ff2d050213170944758935@mail.gmail.com> <004d01c5123a$8fa02f10$445328cf@JSLAPTOP> Message-ID: <029f01c51275$7abe69a0$31d78751@xp> > > isHTML = [filename if filename.endswith('.htm') or\ > > filename.endswith(.html') for filename in files] > > return isHTML > > No, it should be... Well spotted, but... > > isHTML = [filename for filename in files if filename.endswith('.htm') or\ > filename.endswith('.html') for filename in files] > isHTML = [filename for filename in files if filename.endswith('.htm') or\ > filename.endswith('.html')] you forgot to remove the last loop! Oh, and the line continuation slash shouldn't nbe needed since its inside the [] Alan G. From alan.gauld at freenet.co.uk Mon Feb 14 10:52:13 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Feb 14 10:52:43 2005 Subject: [Tutor] calling an external program References: <42107F62.5010608@zen.co.uk> Message-ID: <02bb01c5127a$dc974b60$31d78751@xp> > - I am trying to call up an external program > with something like a "Shell" command - can not find a way of doing this > (in windows) Look in the os module, there are several options depending on exactly what you need to do. The simplest option is system(). To read the output look at the various popen() and for more sophisticated options try the exec() family. If using system() on DOS you might look at the START DOS command too for the options available there. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Mon Feb 14 10:54:46 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Feb 14 10:54:30 2005 Subject: [Tutor] writing list to new file References: <20050214033228.21581.qmail@web20324.mail.yahoo.com> Message-ID: <02c001c5127b$39720be0$31d78751@xp> > If line.startswith('XXX'): > save list to new file > > But I get errors saying only stings can be saved this > way. You can save the list if the list can be printed, but its usually better to save the list contents. You will need to convert the contents into strings or else use a binary file. See my tutor topic on handling files for more, it includes an examople of saving an address book... Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From s.e.murdock at soton.ac.uk Mon Feb 14 11:26:36 2005 From: s.e.murdock at soton.ac.uk (Stuart Murdock) Date: Mon Feb 14 11:27:53 2005 Subject: [Tutor] Is an executable available? Message-ID: <42107CDC.7060705@soton.ac.uk> Hi I am working from within python and want to know the best way to know if a certain package is installed for use on my machine. I want to know from within python that a specific executable file is on my path where I could actually run the command from a prompt in a system shell. I don't want to restrict exacltly where the file is and I don't want to do a general try catch. Are there any simple one or two liners that anyone is aware of? Thanks Stuart -- Stuart Murdock Ph.D, Research Fellow, Dept. of Chemistry / E-Science, University of Southampton, Highfield, Southampton, SO17 1BJ, United Kingdom http://www.biosimgrid.org From zen45800 at zen.co.uk Mon Feb 14 19:32:26 2005 From: zen45800 at zen.co.uk (Lobster) Date: Mon Feb 14 11:32:06 2005 Subject: [Tutor] Re: Tutor Digest, Vol 12, Issue 71 In-Reply-To: <20050214091048.3493A1E400E@bag.python.org> References: <20050214091048.3493A1E400E@bag.python.org> Message-ID: <4210EEBA.60701@zen.co.uk> >> - I am trying to call up an external program >> with something like a "Shell" command - can not find a way of doing >> this >> (in windows) >> >> Any hints? What about os.system('your_command_here')? ===== That is a good tip and seems to be the place I need to look - not really quite sure what I am looking at in the help docs I also have the complication of having to use is it "C:\\" - two back slashes? I am trying to get a wikipedia directed search that will load firefox and search for an inputted word . . . Anyway this is the code (only my second useful program) eh - not working so far . . . usually dumbing down help appreciated ===== Ed Jason ========= <code> # Wikipedia search engine # Sunday Feb 12 import os word_sought = raw_input("What is your wikipedia search word? ") goto_url_location = "http://en.wikipedia.org/wiki/" + word_sought print goto_url_location os.execv('C:\Program Files\Mozilla Firefox\firefox.exe') + goto_url_location ======== </code> From bvande at po-box.mcgill.ca Mon Feb 14 11:52:24 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon Feb 14 11:52:50 2005 Subject: [Tutor] Re: Tutor Digest, Vol 12, Issue 71 In-Reply-To: <4210EEBA.60701@zen.co.uk> References: <20050214091048.3493A1E400E@bag.python.org> <4210EEBA.60701@zen.co.uk> Message-ID: <421082E7.9070900@po-box.mcgill.ca> Lobster said unto the world upon 2005-02-14 13:32: > >> - I am trying to call up an external program > >> with something like a "Shell" command - can not find a way of doing > >> this > >> (in windows) > >> > >> Any hints? > > What about os.system('your_command_here')? > > > ===== > > That is a good tip and seems to be the place I need to look > - not really quite sure what I am looking at in the help docs > I also have the complication of having to use is it "C:\\" > - two back slashes? Hi, the doubled up backslashes are needed for using backslashes in normal strings as the backslash is the escape character -- the character in a string that says 'hey, this next one's not a normal character' and is how you put tabs '\t' and newlines '\n' in strings. But, a much better option is to use '/'s -- Python's smart enough to get the point if you use them in file paths on windows. > I am trying to get a wikipedia directed search that will load firefox and > search for an inputted word . . . > > > Anyway this is the code (only my second useful program) > eh - not working so far . . . > > usually dumbing down help appreciated > > ===== > > Ed Jason > > ========= <code> > > # Wikipedia search engine > # Sunday Feb 12 > > import os > word_sought = raw_input("What is your wikipedia search word? ") > goto_url_location = "http://en.wikipedia.org/wiki/" + word_sought > print goto_url_location > os.execv('C:\Program Files\Mozilla Firefox\firefox.exe') + > goto_url_location > > ======== </code> It is almost 6am here, so I won't say anything more about your code than that given why you are using os.execv, you should look at the webbrowser module instead. (webbrowser.open() would be perfect if firefox is your default browser, if not, I think the function is webbrowser.get().) Best, and goodnight/morning all, Brian vdB From kent37 at tds.net Mon Feb 14 12:06:38 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Feb 14 12:06:45 2005 Subject: [Tutor] Value Error solved. Another question In-Reply-To: <20050214072543.49815.qmail@web20324.mail.yahoo.com> References: <20050214072543.49815.qmail@web20324.mail.yahoo.com> Message-ID: <4210863E.2060305@tds.net> Ron Nixon wrote: > Ignore my first posting. Here's what I'm trying to do. > I want to extract headlines from a newspaper's website > using this code. It works, but I want to match the > second group in <h2><a href="(.*)">(.*)</p> and print > that out. > Sugguestions > > > import urllib, re > pattern = re.compile("""<h2><a > href="(.*)">(.*)</p>""", re.DOTALL) > page = > urllib.urlopen("http://www.startribune.com").read() > for headline in pattern.findall(page): > print headline I think you want for headline, body in pattern.findall(page): print body pattern.findall() returns a list of tuples of groups. You have two groups in your regex so in your code headline is being assigned to a tuple with two items. In my code the tuple is split and you can print just the second item. PS You might want to look at BeautifulSoup: http://www.crummy.com/software/BeautifulSoup/ Kent > > > > > __________________________________ > Do you Yahoo!? > Yahoo! Mail - You care about security. So do we. > http://promotions.yahoo.com/new_mail > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Mon Feb 14 12:15:17 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Feb 14 12:15:20 2005 Subject: [Tutor] Re: Tutor Digest, Vol 12, Issue 71 In-Reply-To: <4210EEBA.60701@zen.co.uk> References: <20050214091048.3493A1E400E@bag.python.org> <4210EEBA.60701@zen.co.uk> Message-ID: <42108845.1000402@tds.net> Lobster wrote: > That is a good tip and seems to be the place I need to look > - not really quite sure what I am looking at in the help docs > I also have the complication of having to use is it "C:\\" > - two back slashes? > > I am trying to get a wikipedia directed search that will load firefox and > search for an inputted word . . . You might look at the webbrowser module, it makes it easy to load the default browser. If you always want firefox I don't know if it will work though: >>> import webbrowser >>> url = "http://en.wikipedia.org/wiki/" + 'Python' >>> webbrowser.open(url) > Anyway this is the code (only my second useful program) > eh - not working so far . . . > > usually dumbing down help appreciated > > ===== > > Ed Jason > > ========= <code> > > # Wikipedia search engine > # Sunday Feb 12 > > import os > word_sought = raw_input("What is your wikipedia search word? ") > goto_url_location = "http://en.wikipedia.org/wiki/" + word_sought > print goto_url_location > os.execv('C:\Program Files\Mozilla Firefox\firefox.exe') + > goto_url_location Not sure but I think this should be os.execl(r'C:\Program Files\Mozilla Firefox\firefox.exe', goto_url_location) Note the use of raw string so \ means what you want, and goto_url_location is inside the parens. Kent > > ======== </code> > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From RPhillips at engineer.co.summit.oh.us Mon Feb 14 12:48:09 2005 From: RPhillips at engineer.co.summit.oh.us (Ron Phillips) Date: Mon Feb 14 12:48:36 2005 Subject: [Tutor] Negative IF conditions Message-ID: <s21049c0.009@mail.engineer.co.summit.oh.us> And now for something only slightly different: education research shows that people process "positives" far more quickly and accurately than "negatives", so for readability I often code like: if os.path.exists('filename') #no-operation else #operation YMMV, of course. Ron At 08:52 AM 2/11/2005, Mark Brown wrote: Hi, I'm a newbie and was wondering which of these IF conditions is better structure: if not os.path.exists('filename'): if os.path.exists('filename') == False: -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050214/1322abec/attachment.htm From cyresse at gmail.com Mon Feb 14 12:50:51 2005 From: cyresse at gmail.com (Liam Clarke) Date: Mon Feb 14 12:50:55 2005 Subject: [Tutor] Is an executable available? In-Reply-To: <42107CDC.7060705@soton.ac.uk> References: <42107CDC.7060705@soton.ac.uk> Message-ID: <f2ff2d05021403504312de96@mail.gmail.com> Hi Stuart, it's a vague question, so all I can give is vague answers. What OS are you using? But - If your environment variables will contain info about the file, you can use os.environ, however, that pulls all the env variables - i.e., on my WinXP - >>> envVars = os.environ >>> for (key, val) in envVars.items(): ... print key, val ... print .... TMP C:\DOCUME~1\Bob\LOCALS~1\Temp COMPUTERNAME HAL USERDOMAIN HAL VDMSPATH C:\Program Files\VDMSound COMMONPROGRAMFILES C:\Program Files\Common Files PROCESSOR_IDENTIFIER x86 Family 6 Model 2 Stepping 1, AuthenticAMD PROGRAMFILES C:\Program Files PROCESSOR_REVISION 0201 PATH C:\Perl\bin\;C:\WINDOWS\system32;C:\WINDOWS; C:\WINDOWS\System32\Wbem;C:\Program Files\VDMSound; :\python23;c:\j2sdk1.4.0\bin SYSTEMROOT C:\WINDOWS TEMP C:\DOCUME~1\Bob\LOCALS~1\Temp PROCESSOR_ARCHITECTURE x86 ALLUSERSPROFILE C:\Documents and Settings\All Users SESSIONNAME Console HOMEPATH \ USERNAME Bob LOGONSERVER \\HAL COMSPEC C:\WINDOWS\system32\cmd.exe CLASSPATH c:\javastz;c:\javastz\0_hello;c:\javastz\coscClasses;bsh.jar PATHEXT .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH CLIENTNAME Console WINDIR C:\WINDOWS APPDATA C:\Documents and Settings\Bob\Application Data HOMEDRIVE C: SYSTEMDRIVE C: NUMBER_OF_PROCESSORS 1 PROCESSOR_LEVEL 6 OS Windows_NT USERPROFILE C:\Documents and Settings\Bob That long discretion aside, so you can grab stuff straight from os.environ - >>> print os.environ['SYSTEMROOT'] C:\WINDOWS Alternatively, you can walk your directories. If you have a rough idea where it might be, that's better than walking your whole HD, but you could. >>> for (dirpath, dirnames, filenames) in os.walk('c:/python23'): ... if 'cmreportsnocomments.py' in filenames: ... print 'I know this isn\'t OS safe, but I can\'t be bothered importing os.path' ... x = "%s\\cmreportsnocomments.py" % dirpath ... if '/' in x: ... x = x.replace('/','\\') ... print x ... I know this isn't OS safe, but I can't be bothered importing os.path c:\python23\cmreportsnocomments.py I know this isn't OS safe, but I can't be bothered importing os.path c:\python23\tc_project\cmreportsnocomments.py But yeah, I would recommend (if you can control your target app's install) that you chuck a systemenv up with the installed path and go from there. HTH Liam Clarke On Mon, 14 Feb 2005 10:26:36 +0000, Stuart Murdock <s.e.murdock@soton.ac.uk> wrote: > Hi > > I am working from within python and want to know the best way to know if > a certain package is installed for use on my machine. > > I want to know from within python that a specific executable file is on > my path where I could actually run the command from a prompt in a system > shell. > > I don't want to restrict exacltly where the file is and I don't want to > do a general try catch. > > Are there any simple one or two liners that anyone is aware of? > > Thanks > > Stuart > > -- > > Stuart Murdock Ph.D, > Research Fellow, > Dept. of Chemistry / E-Science, > University of Southampton, > Highfield, Southampton, > SO17 1BJ, United Kingdom > > http://www.biosimgrid.org > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cyresse at gmail.com Mon Feb 14 13:07:59 2005 From: cyresse at gmail.com (Liam Clarke) Date: Mon Feb 14 13:08:03 2005 Subject: [Tutor] Negative IF conditions In-Reply-To: <s21049c0.009@mail.engineer.co.summit.oh.us> References: <s21049c0.009@mail.engineer.co.summit.oh.us> Message-ID: <f2ff2d050214040748beedc@mail.gmail.com> It (imao) really depends. If I see if a == 'foo': do nothing else: do what I want I always expect a equalling foo to be the primary result being tested for, as it comes first. When it comes time to bug hunt, it takes a mental readjustment to realise that I don't want a to be 'foo', and it involves reading do nothing. Hence, if not a == "foo" : do what I want else: do nothing is much more obvious to me, I consider 'elses' to be secondary, and I (personally speaking) always look at the first conditional, and expect it to be the primary action, if you get my drift. On Mon, 14 Feb 2005 06:48:09 -0500, Ron Phillips <RPhillips@engineer.co.summit.oh.us> wrote: > > And now for something only slightly different: education research shows that > people process "positives" far more quickly and accurately than "negatives", > so for readability I often code like: > > if os.path.exists('filename') > #no-operation > else > #operation > > YMMV, of course. > > Ron > > At 08:52 AM 2/11/2005, Mark Brown wrote: > > Hi, > I'm a newbie and was wondering which of these IF conditions is better > structure: > if not os.path.exists('filename'): > > if os.path.exists('filename') == False: > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From kent37 at tds.net Mon Feb 14 13:14:47 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Feb 14 13:14:51 2005 Subject: [Tutor] Is an executable available? In-Reply-To: <42107CDC.7060705@soton.ac.uk> References: <42107CDC.7060705@soton.ac.uk> Message-ID: <42109637.2030703@tds.net> Stuart Murdock wrote: > Hi > > I am working from within python and want to know the best way to know if > a certain package is installed for use on my machine. > > I want to know from within python that a specific executable file is on > my path where I could actually run the command from a prompt in a system > shell. Look at the function _iscommand() in the webbrowser module, I think it does exactly what you want - it searches the PATH for the file you give it, e.g. >>> webbrowser._iscommand('python.exe') True Kent From zen45800 at zen.co.uk Mon Feb 14 21:38:29 2005 From: zen45800 at zen.co.uk (Lobster) Date: Mon Feb 14 13:38:09 2005 Subject: [Tutor] I thank you . . . In-Reply-To: <20050214110228.ACE111E401C@bag.python.org> References: <20050214110228.ACE111E401C@bag.python.org> Message-ID: <42110C45.6010507@zen.co.uk> Dear Snake Charmers, Many thanks and much appreciation to everyones kind help on my attempts to open a browser and seek a word in wikipedia here is the code I eventually settled on: ===== <code> # Wikipedia single word search engine # Monday Feb 14 import webbrowser sought_word = raw_input("What is your wikipedia search word? ") goto_url_location = "http://en.wikipedia.org/wiki/" + sought_word webbrowser.open(goto_url_location) ===== </code> Thanks very much - I will be asking more dumb questions . . . Over the weekend I showed Python to a friend (a senior programmer) and he was very impressed too - in fact within half an hour he was already writing and explaining advanced bitwise searching (I just about grasped the concept) within Python - and it was working . . . Good! Lobster http://peace.wikicities.com/wiki/Python From dyoo at hkn.eecs.berkeley.edu Mon Feb 14 18:59:34 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Feb 14 18:59:39 2005 Subject: [Tutor] I thank you . . . In-Reply-To: <42110C45.6010507@zen.co.uk> Message-ID: <Pine.LNX.4.44.0502140944050.16358-100000@hkn.eecs.berkeley.edu> On Mon, 14 Feb 2005, Lobster wrote: > # Wikipedia single word search engine > # Monday Feb 14 > > import webbrowser > > sought_word = raw_input("What is your wikipedia search word? ") > goto_url_location = "http://en.wikipedia.org/wiki/" + sought_word > webbrowser.open(goto_url_location) Hi Lobster, Very cool! *grin* You may want to make the url-building a little more robust. If the sought_word contains wacky characters like spaces, the url might not be "well-formed". For example, we may want to make sure that ampersands '&' aren't being treated as HTTP parameter separators. There's a function called 'urllib.quote_plus()' that should properly protect wacky characters like ampersands: ### >>> import urllib >>> urllib.quote_plus('r&d') 'r%26d' ### So you may want to quote_plus() the sought_word as you're constructing the url_location. Best of wishes to you! From dyoo at hkn.eecs.berkeley.edu Mon Feb 14 19:05:42 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Feb 14 19:05:48 2005 Subject: [Tutor] calling an external program In-Reply-To: <02bb01c5127a$dc974b60$31d78751@xp> Message-ID: <Pine.LNX.4.44.0502141000051.16358-100000@hkn.eecs.berkeley.edu> On Mon, 14 Feb 2005, Alan Gauld wrote: > > - I am trying to call up an external program with something like a > > "Shell" command - can not find a way of doing this (in windows) > > Look in the os module, there are several options depending on exactly > what you need to do. The simplest option is system(). To read the output > look at the various popen() and for more sophisticated options try the > exec() family. > > If using system() on DOS you might look at the START DOS command too for > the options available there. Hi Alan and Lobster, I hope the plethora of choices isn't overwhelming! *grin* As of Python 2.4, there is a nicer external process caller in the new 'subprocess' module: http://www.python.org/doc/lib/module-subprocess.html It tries to consolidate the major functionality of the other methods. I haven't played with it much, but according to the documentation, it looks very capable. Best of wishes to you! From dyoo at hkn.eecs.berkeley.edu Mon Feb 14 19:28:38 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Feb 14 19:28:45 2005 Subject: [Tutor] Is an executable available? In-Reply-To: <42109637.2030703@tds.net> Message-ID: <Pine.LNX.4.44.0502141023000.16358-100000@hkn.eecs.berkeley.edu> On Mon, 14 Feb 2005, Kent Johnson wrote: > > I am working from within python and want to know the best way to know > > if a certain package is installed for use on my machine. > > > > I want to know from within python that a specific executable file is > > on my path where I could actually run the command from a prompt in a > > system shell. > > Look at the function _iscommand() in the webbrowser module, I think it > does exactly what you want - it searches the PATH for the file you give > it, e.g. > > >>> webbrowser._iscommand('python.exe') Hi Kent, Awesome; I didn't know about that functionality there! But since it's marked with an underscore, it's a helper function for webbrowser that isn't meant for public consumption. Stewart may want to do a copy-and-paste of the _iscommand() source code into one of his personal library files, just to make sure the rug isn't yanked out underneath his feet if _iscommand()'s behavior changes in the future. That function seems really useful; I'm double checking with folks on comp.lang.python to explore if webbrowser._iscommand() can be migrated into os.path. From alan.gauld at freenet.co.uk Mon Feb 14 21:27:10 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Feb 14 21:26:39 2005 Subject: [Tutor] Is an executable available? References: <42107CDC.7060705@soton.ac.uk> Message-ID: <02ea01c512d3$902c50f0$31d78751@xp> > I am working from within python and want to know the best way to know if > a certain package is installed for use on my machine. You mean a Python package or a software package in general terms? > I want to know from within python that a specific executable file is on > my path where I could actually run the command from a prompt in a system > shell. OS? > I don't want to restrict exacltly where the file is and I don't want to > do a general try catch. > > Are there any simple one or two liners that anyone is aware of? Its partly OS dependant so we need a wee bit more info. Alan G. From tim at johnsons-web.com Mon Feb 14 21:35:45 2005 From: tim at johnsons-web.com (Tim Johnson) Date: Mon Feb 14 21:36:03 2005 Subject: Fwd: Re: [Tutor] Problems with test cgi script on windows XP/Apache Message-ID: <6.2.1.2.0.20050214113155.01f091a0@postman.johnsons-web.com> >Date: Mon, 14 Feb 2005 10:25:28 -0900 >From: Tim Johnson <tim@johnsons-web.com> >Subject: Re: [Tutor] Problems with test cgi script on windows XP/Apache >To: Tim Johnson <tim@johnsons-web.com> >X-Mailer: QUALCOMM Windows Eudora Version 6.2.1.2 > >At 12:22 PM 2/13/2005, you wrote: >>I'm attempting to run a test cgi script on windows xp with apache >>as the http server. I keep getting a not found error from IE, and the >>error log shows the following error message. >>No such file or directory: script not found or unable to stat: c:/program >>files/apache group/apache/cgi-bin/test.py >>Another cgi script using a different interpreter (rebol) is running >>properly. I was receiving >>the same error message with the rebol script until I corrected the first >>line (she-bang). >>here is the code for the script: >>#!d:\Python23\python >>print "Content-type: text/html\n" >>print "hello" >>## I can confirm the the first line does contain the correct path to >>## the python executable. I have tried it with and without the ".exe" This has been solved. Classic, just classic. I had created a test script, and named it "test.py". Hah! windows renamed it "test.py.py", and it was obfuscated when I edited it. One could say either: 1)Dumb windows newbie or 2)Dumb windows strategy I'll leave that one up to the reader. ---- tim >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> >>__________ NOD32 1.998 (20050212) Information __________ >> >>This message was checked by NOD32 Antivirus System. >>http://www.nod32.com > > >__________ NOD32 1.998 (20050212) Information __________ > >This message was checked by NOD32 Antivirus System. >http://www.nod32.com > From cyresse at gmail.com Mon Feb 14 23:18:28 2005 From: cyresse at gmail.com (Liam Clarke) Date: Mon Feb 14 23:18:31 2005 Subject: [Tutor] Problems with test cgi script on windows XP/Apache In-Reply-To: <6.2.1.2.0.20050214113155.01f091a0@postman.johnsons-web.com> References: <6.2.1.2.0.20050214113155.01f091a0@postman.johnsons-web.com> Message-ID: <f2ff2d050214141837e9551a@mail.gmail.com> Windows, she is a woman, and woman are mysterious in their little quirks. Unfortunately, you cannot divorce her, for she controls your software and you really need DirectX if you want to play Sid Mier's Pirates! On Mon, 14 Feb 2005 11:35:45 -0900, Tim Johnson <tim@johnsons-web.com> wrote: > > >Date: Mon, 14 Feb 2005 10:25:28 -0900 > >From: Tim Johnson <tim@johnsons-web.com> > >Subject: Re: [Tutor] Problems with test cgi script on windows XP/Apache > >To: Tim Johnson <tim@johnsons-web.com> > >X-Mailer: QUALCOMM Windows Eudora Version 6.2.1.2 > > > >At 12:22 PM 2/13/2005, you wrote: > >>I'm attempting to run a test cgi script on windows xp with apache > >>as the http server. I keep getting a not found error from IE, and the > >>error log shows the following error message. > >>No such file or directory: script not found or unable to stat: c:/program > >>files/apache group/apache/cgi-bin/test.py > >>Another cgi script using a different interpreter (rebol) is running > >>properly. I was receiving > >>the same error message with the rebol script until I corrected the first > >>line (she-bang). > >>here is the code for the script: > >>#!d:\Python23\python > >>print "Content-type: text/html\n" > >>print "hello" > >>## I can confirm the the first line does contain the correct path to > >>## the python executable. I have tried it with and without the ".exe" > > This has been solved. Classic, just classic. I had created a test script, > and named it "test.py". Hah! windows renamed it "test.py.py", and it > was obfuscated when I edited it. One could say either: > 1)Dumb windows newbie > or > 2)Dumb windows strategy > I'll leave that one up to the reader. > ---- > tim > > >>_______________________________________________ > >>Tutor maillist - Tutor@python.org > >>http://mail.python.org/mailman/listinfo/tutor > >> > >>__________ NOD32 1.998 (20050212) Information __________ > >> > >>This message was checked by NOD32 Antivirus System. > >>http://www.nod32.com > > > > > >__________ NOD32 1.998 (20050212) Information __________ > > > >This message was checked by NOD32 Antivirus System. > >http://www.nod32.com > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From maxnoel_fr at yahoo.fr Mon Feb 14 23:56:24 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Mon Feb 14 23:56:29 2005 Subject: [Tutor] Problems with test cgi script on windows XP/Apache In-Reply-To: <f2ff2d050214141837e9551a@mail.gmail.com> References: <6.2.1.2.0.20050214113155.01f091a0@postman.johnsons-web.com> <f2ff2d050214141837e9551a@mail.gmail.com> Message-ID: <296d400da0862bc3b03bf3af2a2b7065@yahoo.fr> On Feb 14, 2005, at 22:18, Liam Clarke wrote: > Windows, she is a woman, and woman are mysterious in their little > quirks. Unfortunately, you cannot divorce her, for she controls your > software and you really need DirectX if you want to play Sid Mier's > Pirates! Actually, you can find Atari ST and Amiga emulators for pretty much any system nowadays. :-p -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From cyresse at gmail.com Tue Feb 15 00:01:57 2005 From: cyresse at gmail.com (Liam Clarke) Date: Tue Feb 15 00:02:01 2005 Subject: [Tutor] Problems with test cgi script on windows XP/Apache In-Reply-To: <296d400da0862bc3b03bf3af2a2b7065@yahoo.fr> References: <6.2.1.2.0.20050214113155.01f091a0@postman.johnsons-web.com> <f2ff2d050214141837e9551a@mail.gmail.com> <296d400da0862bc3b03bf3af2a2b7065@yahoo.fr> Message-ID: <f2ff2d05021415016cac3f6f@mail.gmail.com> Hehe, I meant the new one, but yeah... :p On Mon, 14 Feb 2005 22:56:24 +0000, Max Noel <maxnoel_fr@yahoo.fr> wrote: > > On Feb 14, 2005, at 22:18, Liam Clarke wrote: > > > Windows, she is a woman, and woman are mysterious in their little > > quirks. Unfortunately, you cannot divorce her, for she controls your > > software and you really need DirectX if you want to play Sid Mier's > > Pirates! > > Actually, you can find Atari ST and Amiga emulators for pretty much > any system nowadays. :-p > > -- Max > maxnoel_fr at yahoo dot fr -- ICQ #85274019 > "Look at you hacker... A pathetic creature of meat and bone, panting > and sweating as you run through my corridors... How can you challenge a > perfect, immortal machine?" > > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From michael.hall at critterpixstudios.com Tue Feb 15 01:16:37 2005 From: michael.hall at critterpixstudios.com (Mike Hall) Date: Tue Feb 15 01:17:44 2005 Subject: [Tutor] newbie OSX module path question Message-ID: <69f636a7022901cc3c7da02a3f6c39e9@critterpixstudios.com> I'm on OS X, and I cannot get Python to import modules I've saved. I have created the the environment.plist file and appended it with my desired module path. If I print sys.path from the interpreter, my new path does indeed show up as the first listing, yet any attempt at importing modules from this directory fails with ImportError. What am I doing wrong? From dyoo at hkn.eecs.berkeley.edu Tue Feb 15 01:47:34 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Feb 15 01:47:38 2005 Subject: [Tutor] newbie OSX module path question In-Reply-To: <69f636a7022901cc3c7da02a3f6c39e9@critterpixstudios.com> Message-ID: <Pine.LNX.4.44.0502141640180.29664-100000@hkn.eecs.berkeley.edu> On Mon, 14 Feb 2005, Mike Hall wrote: > I'm on OS X, and I cannot get Python to import modules I've saved. I > have created the the environment.plist file and appended it with my > desired module path. If I print sys.path from the interpreter, my new > path does indeed show up as the first listing, Hi Mike, Can you show us what your sys.path looks like? Just do a cut-and-paste so we can quickly validate it for you. > yet any attempt at importing modules from this directory fails with > ImportError. Can you show us the exact thing you're typing, as well as the literal error that Python shows? I don't mean to be suspicious, but we have to check for silly things like case-sensitivity issues. I know that Mac OS X's file system is case insensitive, so this might not be such a big issue, but I'd still like looking at literal error messages. Otherwise, I'm at a loss: the import should work. I think we'll need to see some more before we can diagnose this. Do you have problems doing an import if your modules's directory is the current working directory? Also, can you do a quick 'ls -l' on your module directory? That'll help us just a quick double-check on what the files look like. Best of wishes to you! From dyoo at hkn.eecs.berkeley.edu Tue Feb 15 02:41:21 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Feb 15 02:41:25 2005 Subject: [Tutor] newbie OSX module path question In-Reply-To: <01a041ca1213e3687acda5908af578f2@critterpixstudios.com> Message-ID: <Pine.LNX.4.44.0502141733030.5412-100000@hkn.eecs.berkeley.edu> On Mon, 14 Feb 2005, Mike Hall wrote: > > Can you show us what your sys.path looks like? Just do a > > cut-and-paste so we can quickly validate it for you. > > Thanks for the response. Here's a paste of what sys.path returns. The > first listing is the path inside of environment.plist: > > ['', '/Local_HD/Users/mike/Documents/pythonModules', > '/Users/tempmike/Documents/pythonModules', > '/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ > python23.zip', > '/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ > python2.3', > '/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ > python2.3/plat-darwin', > '/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ > python2.3/plat-mac', > '/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ > python2.3/plat-mac/lib-scriptpackages', > '/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ > python2.3/lib-tk', > '/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ > python2.3/lib-dynload', > '/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ > python2.3/site-packages'] > > > Can you show us the exact thing you're typing, as well as the literal > > error that Python shows? > > I will attempt to import using 'import' followed by file name. Example: > > import module1 > > The error returned will be: > > ImportError: No module named module1 [Meta: Please keep python-tutor in CC, so that all of us on the mailing list can help you.] Hi Mike, Ok, can you do this at the Python prompt? ### >>> import glob >>> print glob.glob('/Local_HD/Users/mike/Documents/pythonModules/*.py') ### Copy and paste the output you see. If things go wrong, then we will have a good focus point to debug the problem. But if things go right --- if you see a bunch of Python module files --- then I will be stuck and will have to think of something else. *grin* > > Do you have problems doing an import if your modules's directory is > > the current working directory? > > Funny you should mention that. After posting to this list, I tried > cd'ing over to the dir I created for modules, and then launched Python. > My modules can indeed be imported using this method. But I'm still > curious as to why I cannot get a successful import (when I'm not within > my work dir) when the path is visibly defined within the sys.path > variable? Thanks very much. Ok, so there appears to be nothing wrong with the modules themselves or with importing them when they're in the current working directory. We should then focus on sys.path itself, since that's the mechanism Python uses to lookup modules that aren't in the current directory. For the moment, I'll assume that there's something funky with the pathname. As mentioned earlier, it could be as subtle as a case-sensitivity issue. The glob statement above will help us check to see if Python can see those files, at least. Best of wishes to you! From michael.hall at critterpixstudios.com Tue Feb 15 03:22:21 2005 From: michael.hall at critterpixstudios.com (Mike Hall) Date: Tue Feb 15 03:23:22 2005 Subject: [Tutor] newbie OSX module path question In-Reply-To: <Pine.LNX.4.44.0502141733030.5412-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0502141733030.5412-100000@hkn.eecs.berkeley.edu> Message-ID: <b2e59cebeae42f536d7493ff17938226@critterpixstudios.com> Hm, so if I import glob, and then execute this line: print glob.glob('/Local_HD/Users/mike/Documents/pythonModules/*.py') I simply get brackets returned: [] ...not sure what this means. Thanks again. On Feb 14, 2005, at 5:41 PM, Danny Yoo wrote: > > > On Mon, 14 Feb 2005, Mike Hall wrote: > >>> Can you show us what your sys.path looks like? Just do a >>> cut-and-paste so we can quickly validate it for you. >> >> Thanks for the response. Here's a paste of what sys.path returns. The >> first listing is the path inside of environment.plist: >> >> ['', '/Local_HD/Users/mike/Documents/pythonModules', >> '/Users/tempmike/Documents/pythonModules', >> '/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ >> python23.zip', >> '/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ >> python2.3', >> '/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ >> python2.3/plat-darwin', >> '/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ >> python2.3/plat-mac', >> '/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ >> python2.3/plat-mac/lib-scriptpackages', >> '/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ >> python2.3/lib-tk', >> '/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ >> python2.3/lib-dynload', >> '/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ >> python2.3/site-packages'] >> >>> Can you show us the exact thing you're typing, as well as the literal >>> error that Python shows? >> >> I will attempt to import using 'import' followed by file name. >> Example: >> >> import module1 >> >> The error returned will be: >> >> ImportError: No module named module1 > > > [Meta: Please keep python-tutor in CC, so that all of us on the mailing > list can help you.] > > > Hi Mike, > > Ok, can you do this at the Python prompt? > > ### >>>> import glob >>>> print glob.glob('/Local_HD/Users/mike/Documents/pythonModules/*.py') > ### > > Copy and paste the output you see. > > If things go wrong, then we will have a good focus point to debug the > problem. But if things go right --- if you see a bunch of Python > module > files --- then I will be stuck and will have to think of something > else. > *grin* > > > >>> Do you have problems doing an import if your modules's directory is >>> the current working directory? >> >> Funny you should mention that. After posting to this list, I tried >> cd'ing over to the dir I created for modules, and then launched >> Python. >> My modules can indeed be imported using this method. But I'm still >> curious as to why I cannot get a successful import (when I'm not >> within >> my work dir) when the path is visibly defined within the sys.path >> variable? Thanks very much. > > Ok, so there appears to be nothing wrong with the modules themselves or > with importing them when they're in the current working directory. We > should then focus on sys.path itself, since that's the mechanism Python > uses to lookup modules that aren't in the current directory. > > For the moment, I'll assume that there's something funky with the > pathname. As mentioned earlier, it could be as subtle as a > case-sensitivity issue. The glob statement above will help us check to > see if Python can see those files, at least. > > > Best of wishes to you! > From david at graniteweb.com Tue Feb 15 03:26:22 2005 From: david at graniteweb.com (David Rock) Date: Tue Feb 15 03:28:03 2005 Subject: [Tutor] newbie OSX module path question In-Reply-To: <b2e59cebeae42f536d7493ff17938226@critterpixstudios.com> References: <Pine.LNX.4.44.0502141733030.5412-100000@hkn.eecs.berkeley.edu> <b2e59cebeae42f536d7493ff17938226@critterpixstudios.com> Message-ID: <20050215022622.GA6438@wdfs.graniteweb.com> * Mike Hall <michael.hall@critterpixstudios.com> [2005-02-14 18:22]: > Hm, so if I import glob, and then execute this line: > > print glob.glob('/Local_HD/Users/mike/Documents/pythonModules/*.py') > > I simply get brackets returned: > > [] > > > ...not sure what this means. Thanks again. It means it didn't find anything that matches that pattern, which suggests that the directory does not contain *.py files. That might be a problem. ;-) -- David Rock david@graniteweb.com -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050214/9cdfbfbe/attachment.pgp From michael.hall at critterpixstudios.com Tue Feb 15 03:38:45 2005 From: michael.hall at critterpixstudios.com (Mike Hall) Date: Tue Feb 15 03:39:52 2005 Subject: [Tutor] newbie OSX module path question In-Reply-To: <20050215022622.GA6438@wdfs.graniteweb.com> References: <Pine.LNX.4.44.0502141733030.5412-100000@hkn.eecs.berkeley.edu> <b2e59cebeae42f536d7493ff17938226@critterpixstudios.com> <20050215022622.GA6438@wdfs.graniteweb.com> Message-ID: <3f91ecce257220ba7970722a43681235@critterpixstudios.com> Ok, I've got it working. The environment.plist file wants a path beginning with /Users, not /Local_HD. So simple! Thanks everyone. On Feb 14, 2005, at 6:26 PM, David Rock wrote: > * Mike Hall <michael.hall@critterpixstudios.com> [2005-02-14 18:22]: >> Hm, so if I import glob, and then execute this line: >> >> print glob.glob('/Local_HD/Users/mike/Documents/pythonModules/*.py') >> >> I simply get brackets returned: >> >> [] >> >> >> ...not sure what this means. Thanks again. > > It means it didn't find anything that matches that pattern, which > suggests that the directory does not contain *.py files. That might be > a > problem. ;-) > > -- > David Rock > david@graniteweb.com > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From keridee at jayco.net Tue Feb 15 04:05:53 2005 From: keridee at jayco.net (Jacob S.) Date: Tue Feb 15 04:05:35 2005 Subject: [Tutor] Negative IF conditions References: <s21049c0.009@mail.engineer.co.summit.oh.us> Message-ID: <002c01c5130b$4a1475b0$d95428cf@JSLAPTOP> > And now for something only slightly different: education research shows > that people process > "positives" far more quickly and accurately than "negatives", so for > readability I often code like: Well, that depends on whether we're optimists or pessimists... ;-) I probably process negatives alot faster because that's what I expect... :-) Jacob ################################################# if os.path.exists('filename') #no-operation else #operation YMMV, of course. Ron At 08:52 AM 2/11/2005, Mark Brown wrote: Hi, I'm a newbie and was wondering which of these IF conditions is better structure: if not os.path.exists('filename'): if os.path.exists('filename') == False: _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From keridee at jayco.net Tue Feb 15 04:06:51 2005 From: keridee at jayco.net (Jacob S.) Date: Tue Feb 15 04:06:38 2005 Subject: [Tutor] Fwd: Delivery Status Notification (Failure) References: <qbC8wSA1X00000006@mail2world.com> <f2ff2d0502131854575133dc@mail.gmail.com> Message-ID: <003001c5130b$6b9a27c0$d95428cf@JSLAPTOP> I got one or two, same recipient... Jacob > Anyone else getting these? > > ---------- Forwarded message ---------- > From: postmaster@mwde14la.mail2world.com > <postmaster@mwde14la.mail2world.com> > Date: Sun, 13 Feb 2005 17:59:35 -0800 > Subject: Delivery Status Notification (Failure) > To: cyresse@gmail.com > > > This is an automatically generated Delivery Status Notification. > > Delivery to the following recipients failed. > > bob.gailer@magnoliaroad.net > > > Final-Recipient: rfc822;bob.gailer@magnoliaroad.net > Action: failed > Status: 5.0.0 > Diagnostic-Code: smtp;554 5.0.0 MAIL REFUSED!From Dictionary Attack > Spammer. > > > > ---------- Forwarded message ---------- > From: Liam Clarke <cyresse@gmail.com> > To: Tutor Tutor <tutor@python.org> > Date: Mon, 14 Feb 2005 15:09:24 +1300 > Subject: Re: [Tutor] error message > I was wondering about that also, I've only ever used .group() when > I've got named groups using (?P<foo>) > > On Sun, 13 Feb 2005 21:04:22 -0500, Jacob S. <keridee@jayco.net> wrote: >> Dive into Python, an excellent tutorial has a case study on this very >> same >> topic. >> >> The biggest problem that nobody has mentioned yet is the fact that >> group() >> will not have anything unless you explicitly tell it to group it. >> I.E. >> >> pattern = r'(\d{3})-(\d{3})-(\d{4})' >> >> You need the parenthesis to "capture" the groups. >> >> BTW, dive into python can be found here: >> http://www.diveintopython.org/ >> >> HTH, >> Jacob >> >> >> > I'm dping something very simple in RE. >> > >> > Lets say I'm trying to match an American Phone number >> > >> > I write the code this way and try to match it: >> > import re >> > string = 'My phone is 410-995-1155' >> > pattern = r'\d{3}-\d{3}-\d{4}' >> > re.match(pattern,string).group() >> > >> > but I get this error message >> > Traceback (most recent call last): >> > File "C:/Python24/findphone", line 4, in -toplevel- >> > re.match(pattern,string).group() >> > AttributeError: 'NoneType' object has no attribute 'group' >> > >> > >> > >> > __________________________________ >> > Do you Yahoo!? >> > Take Yahoo! Mail with you! Get it on your mobile phone. >> > http://mobile.yahoo.com/maildemo >> > _______________________________________________ >> > Tutor maillist - Tutor@python.org >> > http://mail.python.org/mailman/listinfo/tutor >> > >> > >> >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > -- > 'There is only one basic human right, and that is to do as you damn well > please. > And with it comes the only basic human duty, to take the consequences. > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > > > -- > 'There is only one basic human right, and that is to do as you damn well > please. > And with it comes the only basic human duty, to take the consequences. > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From maxnoel_fr at yahoo.fr Tue Feb 15 04:13:14 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Tue Feb 15 04:13:25 2005 Subject: [Tutor] newbie OSX module path question In-Reply-To: <3f91ecce257220ba7970722a43681235@critterpixstudios.com> References: <Pine.LNX.4.44.0502141733030.5412-100000@hkn.eecs.berkeley.edu> <b2e59cebeae42f536d7493ff17938226@critterpixstudios.com> <20050215022622.GA6438@wdfs.graniteweb.com> <3f91ecce257220ba7970722a43681235@critterpixstudios.com> Message-ID: <73fd79bac85bc63a6f6a3eb461b0ce9d@yahoo.fr> On Feb 15, 2005, at 02:38, Mike Hall wrote: > Ok, I've got it working. The environment.plist file wants a path > beginning with /Users, not /Local_HD. So simple! Thanks everyone. Yeah, the system hard drive on Mac OS X (which is seen as "Macintosh HD", or in your case "Local HD" in the Finder) is mounted as the root of the filesystem. IOW, it's referred to as /, not /Macintosh HD. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From billk at fastmail.fm Tue Feb 15 05:02:58 2005 From: billk at fastmail.fm (Bill Kranec) Date: Tue Feb 15 05:02:59 2005 Subject: [Tutor] SQL Datetimes Message-ID: <42117472.2080800@fastmail.fm> Hello, I'm using Kinterbasdb to access a Firebird database through Python, and when I retrieve a row with a datetime value, I get a tuple like: >>> myCursor.execute( 'SELECT * FROM table' ) >>> for row in myCursor.fetchall(): print row (<DateTime object for '2004-08-09 00:00:00.00' at d41720>, 'value2', 'value3', 'value4', 100) I would like to get: ('8/9/2004', 'value2', 'value3', 'value4', 100) The formatting of the date isn't so important, though. Does anyone know how to convert the DateTime object into an actual datetime, and vice versa? I'm pretty sure what I want to do is documented here ( http://kinterbasdb.sourceforge.net/dist_docs/usage.html#adv_param_conv_dynamic_type_translation ), but I don't understand what is going on. Thanks for any help, Bill From jfs.world at gmail.com Tue Feb 15 05:39:15 2005 From: jfs.world at gmail.com (Jeffrey Lim) Date: Tue Feb 15 05:39:18 2005 Subject: [Tutor] Fwd: Delivery Status Notification (Failure) In-Reply-To: <003001c5130b$6b9a27c0$d95428cf@JSLAPTOP> References: <qbC8wSA1X00000006@mail2world.com> <f2ff2d0502131854575133dc@mail.gmail.com> <003001c5130b$6b9a27c0$d95428cf@JSLAPTOP> Message-ID: <4b3125cc05021420392519d48b@mail.gmail.com> perhaps it's the same Bob Gailer in this thread here? - http://mail.python.org/pipermail/tutor/2005-February/035774.html, in which case you should probably not see any such messages anymore. -jf On Mon, 14 Feb 2005 22:06:51 -0500, Jacob S. <keridee@jayco.net> wrote: > I got one or two, same recipient... > Jacob > > > > Anyone else getting these? > > > > ---------- Forwarded message ---------- > > From: postmaster@mwde14la.mail2world.com > > <postmaster@mwde14la.mail2world.com> > > Date: Sun, 13 Feb 2005 17:59:35 -0800 > > Subject: Delivery Status Notification (Failure) > > To: cyresse@gmail.com > > > > > > This is an automatically generated Delivery Status Notification. > > > > Delivery to the following recipients failed. > > > > bob.gailer@magnoliaroad.net > > > > > > Final-Recipient: rfc822;bob.gailer@magnoliaroad.net > > Action: failed > > Status: 5.0.0 > > Diagnostic-Code: smtp;554 5.0.0 MAIL REFUSED!From Dictionary Attack > > Spammer. > > > > From cyresse at gmail.com Tue Feb 15 06:27:22 2005 From: cyresse at gmail.com (Liam Clarke) Date: Tue Feb 15 06:27:25 2005 Subject: [Tutor] Fwd: Delivery Status Notification (Failure) In-Reply-To: <4b3125cc05021420392519d48b@mail.gmail.com> References: <qbC8wSA1X00000006@mail2world.com> <f2ff2d0502131854575133dc@mail.gmail.com> <003001c5130b$6b9a27c0$d95428cf@JSLAPTOP> <4b3125cc05021420392519d48b@mail.gmail.com> Message-ID: <f2ff2d050214212789381ec@mail.gmail.com> I've emailed him about it, I think it's an autodirect somewhere on his end. On Tue, 15 Feb 2005 12:39:15 +0800, Jeffrey Lim <jfs.world@gmail.com> wrote: > perhaps it's the same Bob Gailer in this thread here? - > http://mail.python.org/pipermail/tutor/2005-February/035774.html, in > which case you should probably not see any such messages anymore. > > -jf > > > On Mon, 14 Feb 2005 22:06:51 -0500, Jacob S. <keridee@jayco.net> wrote: > > I got one or two, same recipient... > > Jacob > > > > > > > Anyone else getting these? > > > > > > ---------- Forwarded message ---------- > > > From: postmaster@mwde14la.mail2world.com > > > <postmaster@mwde14la.mail2world.com> > > > Date: Sun, 13 Feb 2005 17:59:35 -0800 > > > Subject: Delivery Status Notification (Failure) > > > To: cyresse@gmail.com > > > > > > > > > This is an automatically generated Delivery Status Notification. > > > > > > Delivery to the following recipients failed. > > > > > > bob.gailer@magnoliaroad.net > > > > > > > > > Final-Recipient: rfc822;bob.gailer@magnoliaroad.net > > > Action: failed > > > Status: 5.0.0 > > > Diagnostic-Code: smtp;554 5.0.0 MAIL REFUSED!From Dictionary Attack > > > Spammer. > > > > > > > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From dyoo at hkn.eecs.berkeley.edu Tue Feb 15 08:05:48 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Feb 15 08:05:53 2005 Subject: [Tutor] SQL Datetimes In-Reply-To: <42117472.2080800@fastmail.fm> Message-ID: <Pine.LNX.4.44.0502142256020.9157-100000@hkn.eecs.berkeley.edu> On Mon, 14 Feb 2005, Bill Kranec wrote: > I'm using Kinterbasdb to access a Firebird database through Python, and > when I retrieve a row with a datetime value, I get a tuple like: > > >>> myCursor.execute( 'SELECT * FROM table' ) > >>> for row in myCursor.fetchall(): > print row > > (<DateTime object for '2004-08-09 00:00:00.00' at d41720>, 'value2', > 'value3', 'value4', 100) > > I would like to get: > > ('8/9/2004', 'value2', 'value3', 'value4', 100) Hi Bill, Just out of curiosity, can you work with the datetime object itself? It sounds like you want it to come out as a string, but that's somewhat "lossy" because we lose things like the 'time' portion of a datetime. According to the documentation here: http://www.python.org/doc/lib/datetime-datetime.html we can call methods on the datetime object to build something like the date string you're looking for. For example: ### >>> import datetime >>> now = datetime.datetime.today() >>> now datetime.datetime(2005, 2, 14, 23, 1, 21, 50304) >>> def getDateString(d): ... return "%s/%s/%s" % (d.year, d.month, d.day) ... >>> getDateString(now) '2005/2/14' ### We can go the other way (from date string to datetime instance), but it'll take a little bit of string manipulation. > Does anyone know how to convert the DateTime object into an actual > datetime, and vice versa? I'm pretty sure what I want to do is > documented here ( > http://kinterbasdb.sourceforge.net/dist_docs/usage.html#adv_param_conv_dynamic_type_translation > ), but I don't understand what is going on. I'd have to read into it more deeply, but I think it might be overkill to override the default type translators between Python and the database. My opinion is that it's probably less work to write functions to go back and forth between the date strings and the datetime objects. If you have more questions, please feel free to ask. Best of wishes to you! From administrata at hotmail.com Tue Feb 15 11:07:56 2005 From: administrata at hotmail.com (=?ks_c_5601-1987?B?wMwgwfi8ug==?=) Date: Tue Feb 15 11:08:04 2005 Subject: [Tutor] NewBie Question... Variables Message-ID: <BAY22-F1374F6516CA8F78B2ABAB6C86B0@phx.gbl> How can I do it with several variables? I = "John" print "%s used to love pizza" % I About 10 or more... HELP plz :) _________________________________________________________________ ?? ??? ?? ?? ??. ??? ??? MSN ???? ?????. http://www.msn.co.kr/news/ From cyresse at gmail.com Tue Feb 15 11:26:06 2005 From: cyresse at gmail.com (Liam Clarke) Date: Tue Feb 15 11:26:10 2005 Subject: [Tutor] DB design Message-ID: <f2ff2d050215022626b948dc@mail.gmail.com> Hi, Working my way through the basics of SQL, and I can see that it's very powerful for searching by different criteria. I'm already hitting my conceptual troubles however, as I'm visualising each table as a 'card'. Always my problems, too much imagination. But yeah, it seems very 1 dimensional. But what I was wondering was is it possible within the bounds of SQL to contain a SQL query reference as a value, so that retrieving a certain value retrieves the results of that query i.e. table foo a b c 1 2 select d from bar table bar d e f 3 4 5 and select c from foo retrieves d from bar? I know I'm leapfrogging way ahead of myself, and probably confusing myself unnecessarily, but I'm just trying to make my cards more 3D in terms of linking data.... Any assistance for my vague question gratefully appreciated. Regards, Liam Clarke -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cyresse at gmail.com Tue Feb 15 11:28:20 2005 From: cyresse at gmail.com (Liam Clarke) Date: Tue Feb 15 11:28:24 2005 Subject: [Tutor] NewBie Question... Variables In-Reply-To: <BAY22-F1374F6516CA8F78B2ABAB6C86B0@phx.gbl> References: <BAY22-F1374F6516CA8F78B2ABAB6C86B0@phx.gbl> Message-ID: <f2ff2d05021502281f8ef34b@mail.gmail.com> a = "foo" b = "bar" c = "duck" print "I will say only this - %s to your %s and no %s" % (a, b, c) I will say only this - foo to your bar and no duck And so forth. On Tue, 15 Feb 2005 19:07:56 +0900, ? ?? <administrata@hotmail.com> wrote: > How can I do it with several variables? > > I = "John" > print "%s used to love pizza" % I > > About 10 or more... > > HELP plz :) > > _________________________________________________________________ > ?? ??? ?? ?? ??. ??? ??? MSN ???? ?????. > http://www.msn.co.kr/news/ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From administrata at hotmail.com Tue Feb 15 11:30:32 2005 From: administrata at hotmail.com (=?ks_c_5601-1987?B?wMwgwfi8ug==?=) Date: Tue Feb 15 11:31:05 2005 Subject: [Tutor] Variables Message-ID: <BAY22-F31DF592234ECC7DBD47C41C86B0@phx.gbl> How can I do it with several variables? I = "John" print "%s used to love pizza" % I About 10 or more... HELP plz :) _________________________________________________________________ ????. ??? ?? ?? ??, ??, ??, ?? ??? http://www.msn.co.kr/fortune/default.asp From administrata at hotmail.com Tue Feb 15 11:47:50 2005 From: administrata at hotmail.com (=?ks_c_5601-1987?B?wMwgwfi8ug==?=) Date: Tue Feb 15 11:48:57 2005 Subject: [Tutor] Variables Message-ID: <BAY22-F14454F18699D09D132CBB8C86B0@phx.gbl> How can I do it with several variables? I = "John" print "%s used to love pizza" % I About 10 or more... HELP plz :) _________________________________________________________________ ?? ?? ?? ??? ??? ?? ? ????. MSN ??/?? http://www.msn.co.kr/stock/ From kent37 at tds.net Tue Feb 15 11:54:13 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Feb 15 11:54:18 2005 Subject: [Tutor] SQL Datetimes In-Reply-To: <Pine.LNX.4.44.0502142256020.9157-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0502142256020.9157-100000@hkn.eecs.berkeley.edu> Message-ID: <4211D4D5.4080503@tds.net> Danny Yoo wrote: > > On Mon, 14 Feb 2005, Bill Kranec wrote: > > >>I'm using Kinterbasdb to access a Firebird database through Python, and >>when I retrieve a row with a datetime value, I get a tuple like: >> >> >>> myCursor.execute( 'SELECT * FROM table' ) >> >>> for row in myCursor.fetchall(): >> print row >> >>(<DateTime object for '2004-08-09 00:00:00.00' at d41720>, 'value2', >>'value3', 'value4', 100) >> >>I would like to get: >> >>('8/9/2004', 'value2', 'value3', 'value4', 100) > > > > Hi Bill, > > Just out of curiosity, can you work with the datetime object itself? It > sounds like you want it to come out as a string, but that's somewhat > "lossy" because we lose things like the 'time' portion of a datetime. I'll second that suggestion...what is it you need to do with the date object? Another alternative would be to change the database field to a string field, if that is really what you want. This may open it up to bad data, though. > > According to the documentation here: > > http://www.python.org/doc/lib/datetime-datetime.html Note that by default Kinterbasdb is using mxDateTime, not Python's (now) standard datetime, to represent the date. Docs for mxDateTime are here: http://www.egenix.com/files/python/mxDateTime.html There is an example on the page originally cited that shows how to use Python's datetime instead of mxDateTime if you prefer. http://kinterbasdb.sourceforge.net/dist_docs/usage.html#adv_param_conv_dynamic_type_translation scroll down until you get to the first example. Kent From cyresse at gmail.com Tue Feb 15 11:57:11 2005 From: cyresse at gmail.com (Liam Clarke) Date: Tue Feb 15 11:57:15 2005 Subject: [Tutor] Re: DB design In-Reply-To: <f2ff2d050215022626b948dc@mail.gmail.com> References: <f2ff2d050215022626b948dc@mail.gmail.com> Message-ID: <f2ff2d05021502571cf9c8d9@mail.gmail.com> Ack, sorry, just found the advanced tutorial and 'joins'. Sorry. *embarrassed* (Also wondering if I spelt embarrassed right.) Regards, Liam Clarke On Tue, 15 Feb 2005 23:26:06 +1300, Liam Clarke <cyresse@gmail.com> wrote: > Hi, > > Working my way through the basics of SQL, and I can see that it's very > powerful for searching by different criteria. > > I'm already hitting my conceptual troubles however, as I'm visualising > each table as a 'card'. > Always my problems, too much imagination. But yeah, it seems very 1 > dimensional. But what I was wondering was is it possible within the > bounds of SQL to contain a SQL query reference as a value, so that > retrieving a certain value retrieves the results of that query i.e. > > table foo > > a b c > > 1 2 select d from bar > > table bar > > d e f > > 3 4 5 > > and select c from foo retrieves d from bar? I know I'm leapfrogging > way ahead of myself, and probably confusing myself unnecessarily, but > I'm just trying to make my cards more 3D in terms of linking data.... > > Any assistance for my vague question gratefully appreciated. > > Regards, > > Liam Clarke > > -- > 'There is only one basic human right, and that is to do as you damn well please. > And with it comes the only basic human duty, to take the consequences. > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From administrata at hotmail.com Tue Feb 15 11:57:20 2005 From: administrata at hotmail.com (Sm0kin'_Bull .) Date: Tue Feb 15 11:59:52 2005 Subject: [Tutor] . Message-ID: <BAY22-F43FA3ECB83E36651E8524C86B0@phx.gbl> . _________________________________________________________________ ?.. ?.. ?.. ?.. ?.. ?.. ?.. ?.. MSN ?? http://www.msn.co.kr/love/ From vishnu at acmet.com Tue Feb 15 11:56:41 2005 From: vishnu at acmet.com (Vishnu) Date: Tue Feb 15 12:00:02 2005 Subject: [Tutor] Variables In-Reply-To: <BAY22-F14454F18699D09D132CBB8C86B0@phx.gbl> Message-ID: <000e01c5134d$08fbb3d0$0800a8c0@vishnu> Hi, Method-I: ========= I1 = "John1" I2 = "John2" I3 = "John3" print "%s, %s and %s used to love pizza" % (I1,I2,I3) Method-II: ========= use dictionaries, name["I1"] = "John1" name["I2"] = "John2" name["I3"] = "John3" print "%{I1}s, %{I2}s and %{I3}s used to love pizza" % name HTH, Vishnu -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of ?? ???? Sent: Tuesday, February 15, 2005 4:18 PM To: tutor@python.org Subject: [Tutor] Variables How can I do it with several variables? I = "John" print "%s used to love pizza" % I About 10 or more... HELP plz :) _________________________________________________________________ ?? ?? ?? ??? ??? ?? ? ????. MSN ??/?? http://www.msn.co.kr/stock/ _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Tue Feb 15 12:02:59 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Feb 15 12:03:04 2005 Subject: [Tutor] DB design In-Reply-To: <f2ff2d050215022626b948dc@mail.gmail.com> References: <f2ff2d050215022626b948dc@mail.gmail.com> Message-ID: <4211D6E3.6000401@tds.net> I don't think you can do exactly that. But SQL does have powerful capabilities to do selects on multiple tables at once. It's called a 'join' and it is very common. For examples suppose you have a customer database with a Customer table: cust_id cust_name 111 Liam Clarke 222 Kent Johnson and a Customer_Order table (way oversimplified): cust_id order_date 111 2004-4-22 111 2004-5-6 222 2004-1-31 111 2005-2-1 To show all customer orders with the customer id and name, you would join these two tables on the cust_id column: select c.cust_id, c.cust_name, co.order_date from Customer c, Customer_Order co where c.cust_id = co.cust_id To get just Liam's orders, add another clause to the above: ... and c.cust_id = '111' Anyway, why don't you tell us more about what you are trying to do and we can give better suggestions. Kent Liam Clarke wrote: > Hi, > > Working my way through the basics of SQL, and I can see that it's very > powerful for searching by different criteria. > > I'm already hitting my conceptual troubles however, as I'm visualising > each table as a 'card'. > Always my problems, too much imagination. But yeah, it seems very 1 > dimensional. But what I was wondering was is it possible within the > bounds of SQL to contain a SQL query reference as a value, so that > retrieving a certain value retrieves the results of that query i.e. > > table foo > > a b c > > 1 2 select d from bar > > table bar > > d e f > > 3 4 5 > > and select c from foo retrieves d from bar? I know I'm leapfrogging > way ahead of myself, and probably confusing myself unnecessarily, but > I'm just trying to make my cards more 3D in terms of linking data.... > > Any assistance for my vague question gratefully appreciated. > > Regards, > > Liam Clarke > From billk at fastmail.fm Tue Feb 15 13:03:59 2005 From: billk at fastmail.fm (Bill Kranec) Date: Tue Feb 15 13:03:59 2005 Subject: [Tutor] DB design In-Reply-To: <f2ff2d050215022626b948dc@mail.gmail.com> References: <f2ff2d050215022626b948dc@mail.gmail.com> Message-ID: <4211E52F.90007@fastmail.fm> Liam, I think what you want is called a view. A view is a memory based table defined by a query as follows: CREATE VIEW myview ( column1, column2, ... ) AS BEGIN SELECT * FROM table1 END; In this example, you can now SELECT * FROM myview, and get table1. You can put joined tables or use SELECT UNION inside the BEGIN, END statements to make the view larger, or use WHERE clauses to make the view a subset of the original table. If the data in the underlying tables changes, the view will change also. So by querying a view, you are querying the results of a query, in a sense, but remember that the database itself will always query the underlying tables, since the view doesn't physically exist. I hope I've been helpful. Just ask if I didn't explain anything clearly. Bill Liam Clarke wrote: >Hi, > >Working my way through the basics of SQL, and I can see that it's very >powerful for searching by different criteria. > >I'm already hitting my conceptual troubles however, as I'm visualising >each table as a 'card'. >Always my problems, too much imagination. But yeah, it seems very 1 >dimensional. But what I was wondering was is it possible within the >bounds of SQL to contain a SQL query reference as a value, so that >retrieving a certain value retrieves the results of that query i.e. > >table foo > >a b c > >1 2 select d from bar > >table bar > >d e f > >3 4 5 > >and select c from foo retrieves d from bar? I know I'm leapfrogging >way ahead of myself, and probably confusing myself unnecessarily, but >I'm just trying to make my cards more 3D in terms of linking data.... > >Any assistance for my vague question gratefully appreciated. > >Regards, > >Liam Clarke > > > From vishnu at acmet.com Tue Feb 15 15:38:28 2005 From: vishnu at acmet.com (Vishnu) Date: Tue Feb 15 15:41:59 2005 Subject: [Tutor] Variables In-Reply-To: <457b5fac05021505577132d38c@mail.gmail.com> Message-ID: <003901c5136c$04846b70$0800a8c0@vishnu> I am forwarding this mail, since tutor@python.org is not added by Matt Hauser. Thank you, Vishnu. -----Original Message----- From: Matt Hauser [mailto:invisible.dog@gmail.com] Sent: Tuesday, February 15, 2005 7:28 PM To: Vishnu Subject: Re: [Tutor] Variables #Create a list of people whoLovesPizza = ["John", "Jack", "Jimmy", "Jane", "Jerry"] #Iterate through the list and print for each name for lover in whoLovesPizza: print "%s used to love pizza" % lover Or you could put the print statement in a function and call it with each variable or name from a list. On Tue, 15 Feb 2005 16:26:41 +0530, Vishnu <vishnu@acmet.com> wrote: > Hi, > > Method-I: > ========= > > I1 = "John1" > I2 = "John2" > I3 = "John3" > > print "%s, %s and %s used to love pizza" % (I1,I2,I3) > > Method-II: > ========= > use dictionaries, > > name["I1"] = "John1" > name["I2"] = "John2" > name["I3"] = "John3" > > print "%{I1}s, %{I2}s and %{I3}s used to love pizza" % name > > HTH, > Vishnu > > -----Original Message----- > From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of ?? ???? > Sent: Tuesday, February 15, 2005 4:18 PM > To: tutor@python.org > Subject: [Tutor] Variables > > How can I do it with several variables? > > I = "John" > print "%s used to love pizza" % I > > About 10 or more... > > HELP plz :) > > _________________________________________________________________ > ?? ?? ?? ??? ??? ?? ? ????. MSN ??/?? > http://www.msn.co.kr/stock/ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Have you seen the dog lately? Email - invisible.dog@gmail.com Blog - invisibledog.blogspot.com From nixonron at yahoo.com Tue Feb 15 17:21:44 2005 From: nixonron at yahoo.com (Ron Nixon) Date: Tue Feb 15 17:21:48 2005 Subject: [Tutor] count words Message-ID: <20050215162145.85071.qmail@web20321.mail.yahoo.com> I know that you can do this to get a count of home many times a word appears in a file f = open('text.txt').read() print f.count('word') Other than using a several print statments to look for seperate words like this, is there a way to do it so that I get a individual count of each word: word1 xxx word2 xxx words xxx etc. __________________________________ Do you Yahoo!? Yahoo! Mail - Find what you need with new enhanced search. http://info.mail.yahoo.com/mail_250 From bill.mill at gmail.com Tue Feb 15 17:50:16 2005 From: bill.mill at gmail.com (Bill Mill) Date: Tue Feb 15 17:50:25 2005 Subject: [Tutor] count words In-Reply-To: <20050215162145.85071.qmail@web20321.mail.yahoo.com> References: <20050215162145.85071.qmail@web20321.mail.yahoo.com> Message-ID: <797fe3d4050215085045b56b2d@mail.gmail.com> Ron, <snip>is there a way to do it so > that I get a individual count of each word: > > word1 xxx > word2 xxx > words xxx > > etc. Ron, I'm gonna throw some untested code at you. Let me know if you understand it or not: word_counts = {} for line in f: for word in line.split(): if word in word_counts: word_counts[word] += 1 else: word_counts[word] = 1 for word in word_counts: print "%s %d" % (word, word_counts[word]) Peace Bill Mill bill.mill at gmail.com From ryan at acceleration.net Tue Feb 15 17:51:57 2005 From: ryan at acceleration.net (Ryan Davis) Date: Tue Feb 15 17:52:00 2005 Subject: [Tutor] count words In-Reply-To: <20050215162145.85071.qmail@web20321.mail.yahoo.com> Message-ID: <20050215165158.899C71E400A@bag.python.org> You could use split() to split the contents of the file into a list of strings. ### >>> x = 'asdf foo bar foo' >>> x.split() ['asdf', 'foo', 'bar', 'foo'] ### Here's one way to iterate over that to get the counts. I'm sure there are dozens. ### >>> x = 'asdf foo bar foo' >>> counts = {} >>> for word in x.split(): ... counts[word] = x.count(word) ... >>> counts {'foo': 2, 'bar': 1, 'asdf': 1} ### The dictionary takes care of duplicates. If you are using a really big file, it might pay to eliminate duplicates from the list before running x.count(word) Thanks, Ryan -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of Ron Nixon Sent: Tuesday, February 15, 2005 11:22 AM To: tutor@python.org Subject: [Tutor] count words I know that you can do this to get a count of home many times a word appears in a file f = open('text.txt').read() print f.count('word') Other than using a several print statments to look for seperate words like this, is there a way to do it so that I get a individual count of each word: word1 xxx word2 xxx words xxx etc. __________________________________ Do you Yahoo!? Yahoo! Mail - Find what you need with new enhanced search. http://info.mail.yahoo.com/mail_250 _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From exogen at gmail.com Tue Feb 15 17:51:34 2005 From: exogen at gmail.com (Brian Beck) Date: Tue Feb 15 17:54:59 2005 Subject: [Tutor] Re: count words In-Reply-To: <20050215162145.85071.qmail@web20321.mail.yahoo.com> References: <20050215162145.85071.qmail@web20321.mail.yahoo.com> Message-ID: <cut9bh$gpc$1@sea.gmane.org> Ron Nixon wrote: > f = open('text.txt').read() > print f.count('word') > > Other than using a several print statments to look for > seperate words like this, is there a way to do it so > that I get a individual count of each word: > > word1 xxx > word2 xxx > words xxx > > etc. Someone else might offer a better way of finding such information in a file, but for now I'll assume that this method is okay and just answer your original question. I'd do it like this (untested): f = open('text.txt').read() words = ['word', 'beef', 'nachos', 'recipe'] # This makes a list of tuples like [('word', 5), ('beef', 0), ...] # You might also consider using a dictionary. count = [(word, f.count(word)) for word in words] # Now print the results. for result in count: print "%s was found %d times." % result # Dictionary method: # Uses the same list comprehension, maybe there's a better way? count = dict([(word, f.count(word)) for word in words]) for key, value in count.iteritems(): print "%s was found %d times." % (key, value) -- Brian Beck Adventurer of the First Order From zanesdad at bellsouth.net Tue Feb 15 17:53:25 2005 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Tue Feb 15 17:55:14 2005 Subject: [Tutor] count words In-Reply-To: <20050215162145.85071.qmail@web20321.mail.yahoo.com> References: <20050215162145.85071.qmail@web20321.mail.yahoo.com> Message-ID: <42122905.8040708@bellsouth.net> Ron Nixon wrote: >I know that you can do this to get a count of home >many times a word appears in a file > > >f = open('text.txt').read() >print f.count('word') > >Other than using a several print statments to look for >seperate words like this, is there a way to do it so >that I get a individual count of each word: > >word1 xxx >word2 xxx >words xxx > >etc. > > > > > Like this? A 14 AND 1 Abantes 3 Abarbarea 1 Abas 1 Abians 1 Ablerus 1 About 2 Abydos 3 Acamas 11 Accept 2 Acessamenus 1 Achaea 1 Achaean 34 Achaeans 540 Achelous 2 Achilles 423 Acrisius 1 Actaea 1 Actor 8 Adamas 5 Admetus 4 Adrastus 2 Adresteia 1 Adrestus 8 Aeacus 20 Aegae 2 Aegaeon 1 Aegeus 1 Aegialeia 1 Aegialus 1 Aegilips 1 Aegina 1 Aegium 1 Aeneas 86 Aenus 1 Aeolus 1 Aepea 2 Aepytus 1 Aesculapius 7 Aesepus 2 Aesopus 4 Aesyetes 2 Aesyme 1 Aesymnus 1 ... wronged 2 wronging 1 wrongs 1 wroth 1 wrought 24 wrung 1 yard 3 yarded 1 yards 2 yawned 1 ye 3 yea 1 year 13 yearling 2 yearned 4 yearning 2 years 15 yellow 5 yesterday 5 yet 160 yield 10 yielded 3 yielding 3 yieldit 1 yoke 24 yoked 11 yokes 1 yokestraps 1 yolking 1 yonder 3 you 1712 young 44 younger 9 youngest 6 your 592 yourelf 1 yours 7 yourself 60 yourselves 17 youselves 1 youth 17 youths 18 zeal 2 I ran the following script on "The Iliad": #!/usr/bin/env python import string text = open('iliad.txt', 'r').read() for punct in string.punctuation: text = text.replace(punct, ' ') words = text.split() word_dict = {} for word in words: word_dict[word] = word_dict.get(word, 0) + 1 word_list = word_dict.keys() word_list.sort() for word in word_list: print "%-25s%d" % (word, word_dict[word]) Jeremy Jones -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050215/23c19381/attachment-0001.html From dyoo at hkn.eecs.berkeley.edu Tue Feb 15 17:59:17 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Feb 15 17:59:21 2005 Subject: [Tutor] count words In-Reply-To: <20050215162145.85071.qmail@web20321.mail.yahoo.com> Message-ID: <Pine.LNX.4.44.0502150851510.31216-100000@hkn.eecs.berkeley.edu> On Tue, 15 Feb 2005, Ron Nixon wrote: > I know that you can do this to get a count of home many times a word > appears in a file > > > f = open('text.txt').read() > print f.count('word') > > Other than using a several print statments to look for seperate words > like this, is there a way to do it so that I get a individual count of > each word: Hi Ron, Let's modify the problem a bit. Let's say that we have a list of words: ### words = """one ring to rule them all one ring to find them one ring to bring them all and in the darkness bind them in the land of mordor where the shadows lie""".split() ### What happens if we sort() this list? ### >>> words.sort() >>> words ['all', 'all', 'and', 'bind', 'bring', 'darkness', 'find', 'in', 'in', 'land', 'lie', 'mordor', 'of', 'one', 'one', 'one', 'ring', 'ring', 'ring', 'rule', 'shadows', 'the', 'the', 'the', 'them', 'them', 'them', 'them', 'to', 'to', 'to', 'where'] ### Would this be easier to process? If you have more questions, please feel free to ask! From nixonron at yahoo.com Tue Feb 15 18:19:38 2005 From: nixonron at yahoo.com (Ron Nixon) Date: Tue Feb 15 18:19:41 2005 Subject: [Tutor] count words In-Reply-To: <20050215165158.899C71E400A@bag.python.org> Message-ID: <20050215171938.24649.qmail@web20322.mail.yahoo.com> Thanks to everyone who replied to my post. All of your suggestions seem to work. My thanks Ron --- Ryan Davis <ryan@acceleration.net> wrote: > You could use split() to split the contents of the > file into a list of strings. > > ### > >>> x = 'asdf foo bar foo' > >>> x.split() > ['asdf', 'foo', 'bar', 'foo'] > ### > > Here's one way to iterate over that to get the > counts. I'm sure there are dozens. > ### > >>> x = 'asdf foo bar foo' > >>> counts = {} > >>> for word in x.split(): > ... counts[word] = x.count(word) > ... > >>> counts > {'foo': 2, 'bar': 1, 'asdf': 1} > ### > The dictionary takes care of duplicates. If you are > using a really big file, it might pay to eliminate > duplicates from the list > before running x.count(word) > > Thanks, > Ryan > > -----Original Message----- > From: tutor-bounces@python.org > [mailto:tutor-bounces@python.org] On Behalf Of Ron > Nixon > Sent: Tuesday, February 15, 2005 11:22 AM > To: tutor@python.org > Subject: [Tutor] count words > > > I know that you can do this to get a count of home > many times a word appears in a file > > > f = open('text.txt').read() > print f.count('word') > > Other than using a several print statments to look > for > seperate words like this, is there a way to do it so > that I get a individual count of each word: > > word1 xxx > word2 xxx > words xxx > > etc. > > > > > > __________________________________ > Do you Yahoo!? > Yahoo! Mail - Find what you need with new enhanced > search. > http://info.mail.yahoo.com/mail_250 > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > __________________________________ Do you Yahoo!? The all-new My Yahoo! - Get yours free! http://my.yahoo.com From maxnoel_fr at yahoo.fr Tue Feb 15 19:03:57 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Tue Feb 15 19:04:05 2005 Subject: [Tutor] count words In-Reply-To: <20050215171938.24649.qmail@web20322.mail.yahoo.com> References: <20050215171938.24649.qmail@web20322.mail.yahoo.com> Message-ID: <c8f67d439661b5e8b97ef53c9bf99695@yahoo.fr> On Feb 15, 2005, at 17:19, Ron Nixon wrote: > Thanks to everyone who replied to my post. All of your > suggestions seem to work. My thanks > > Ron Watch out, though, for all of this to work flawlessly you first have to remove all punctuation (either with regexes or with multiple foo.replace('[symbol]', '')), and to remove the case of each word (foo.upper() or foo.lower() will do). -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From alan.gauld at freenet.co.uk Tue Feb 15 19:03:48 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Feb 15 19:04:42 2005 Subject: [Tutor] NewBie Question... Variables References: <BAY22-F1374F6516CA8F78B2ABAB6C86B0@phx.gbl> Message-ID: <003701c51388$b3b85810$2ca88651@xp> > How can I do it with several variables? > I = "John" > print "%s used to love pizza" % I wrap them in parens: >>> a,b = 3,4 >>> print "%d x %d = %d" % (a,b, a*b) > About 10 or more... Same technique but you might find it easier to use labels to identify the fields. >>> sum = a+b >>> print "%(a)d + %(b)d = %(sum)d" % locals() My tutoroial covers some of this in the Simple Sequences topic. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Tue Feb 15 19:16:10 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Feb 15 19:16:13 2005 Subject: [Tutor] DB design References: <f2ff2d050215022626b948dc@mail.gmail.com> Message-ID: <004801c5138a$6dac9a50$2ca88651@xp> > I'm already hitting my conceptual troubles however, as I'm visualising > each table as a 'card'. Maybe but the cards are made up of rows, each row with fields. Think like a spreadsheet. Each sheet can have references to other sheets - like Tabs in Excel.... > dimensional. But what I was wondering was is it possible within the > bounds of SQL to contain a SQL query reference as a value, so that > retrieving a certain value retrieves the results of that query i.e. Not quite sure what you mean, but lets try an example. create table foo (id number, food varchar); create table b (id, fooID number, val varchar); insert into foo values(1,'Spam'); insert into foo values(2,'Chips'); insert into foo values(3,'Bread'); insert into bar values(1,2,'Sauce'); Now notice that bar has a reference to foo. And the last insert creates a row with a reference to foo id 2 So now we can do a select that finds data based on the reference: SELECT food, value from foo,bar WHERE bar.fooID = foo.id Returns: Chips, Sauce Alternatively we can nest select statements: SELECT value from bar WHERE fooID in (SELECT id from foo); The result (in this case!) should be the same but the efficiency is a lot lower! > I'm just trying to make my cards more 3D in terms of linking data.... Dunno if that clarified anything? Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Tue Feb 15 19:16:52 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Feb 15 19:16:55 2005 Subject: [Tutor] Variables References: <BAY22-F14454F18699D09D132CBB8C86B0@phx.gbl> Message-ID: <004f01c5138a$86a17530$2ca88651@xp> Ahem, we heard you the first time! :-) Alan G. ----- Original Message ----- From: "l 4 l'l1" <administrata@hotmail.com> To: <tutor@python.org> Sent: Tuesday, February 15, 2005 10:47 AM Subject: [Tutor] Variables > How can I do it with several variables? > > > I = "John" > print "%s used to love pizza" % I > > About 10 or more... > > HELP plz :) > > _________________________________________________________________ > l& j6 l k34 j0�l % k9 k%4j3 m8mj2 k34l$ l l l 5kk$. MSN l& j6/m,l > http://www.msn.co.kr/stock/ > > > From alan.gauld at freenet.co.uk Tue Feb 15 19:33:14 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Feb 15 19:33:11 2005 Subject: [Tutor] count words References: <20050215162145.85071.qmail@web20321.mail.yahoo.com> Message-ID: <006e01c5138c$cf9a6b00$2ca88651@xp> > Other than using a several print statments to look for > seperate words like this, is there a way to do it so > that I get a individual count of each word: > > word1 xxx > word2 xxx > words xxx The classic approach is to create a dictionary. Add each word as you come to it and increment the value by one. At the end the dictionaru contains all unique words with the count for each one. Does that work for you? Alan G. From bill.mill at gmail.com Tue Feb 15 19:38:24 2005 From: bill.mill at gmail.com (Bill Mill) Date: Tue Feb 15 19:38:28 2005 Subject: [Tutor] count words In-Reply-To: <c8f67d439661b5e8b97ef53c9bf99695@yahoo.fr> References: <20050215171938.24649.qmail@web20322.mail.yahoo.com> <c8f67d439661b5e8b97ef53c9bf99695@yahoo.fr> Message-ID: <797fe3d405021510381195701f@mail.gmail.com> On Tue, 15 Feb 2005 18:03:57 +0000, Max Noel <maxnoel_fr@yahoo.fr> wrote: > > On Feb 15, 2005, at 17:19, Ron Nixon wrote: > > > Thanks to everyone who replied to my post. All of your > > suggestions seem to work. My thanks > > > > Ron > > Watch out, though, for all of this to work flawlessly you first have > to remove all punctuation (either with regexes or with multiple > foo.replace('[symbol]', '')), and to remove the case of each word > (foo.upper() or foo.lower() will do). To remove all punctuation from the beginning and end of words, at least in 2.4, you can just use: word.strip('.!?\n\t ') plus any other characters that you'd like to strip. In action: >>> word = "?testing..!.\n\t " >>> word.strip('?.!\n\t ') 'testing' Peace Bill Mill bill.mill at gmail.com > > -- Max > maxnoel_fr at yahoo dot fr -- ICQ #85274019 > "Look at you hacker... A pathetic creature of meat and bone, panting > and sweating as you run through my corridors... How can you challenge a > perfect, immortal machine?" > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Tue Feb 15 20:39:30 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Feb 15 20:39:34 2005 Subject: [Tutor] count words In-Reply-To: <20050215165158.899C71E400A@bag.python.org> References: <20050215165158.899C71E400A@bag.python.org> Message-ID: <42124FF2.1050304@tds.net> Ryan Davis wrote: > Here's one way to iterate over that to get the counts. I'm sure there are dozens. > ### > >>>>x = 'asdf foo bar foo' >>>>counts = {} >>>>for word in x.split(): > > ... counts[word] = x.count(word) > ... > >>>>counts > > {'foo': 2, 'bar': 1, 'asdf': 1} > ### > The dictionary takes care of duplicates. If you are using a really big file, it might pay to eliminate duplicates from the list > before running x.count(word) Be wary of using the count() function for this, it can be very slow. The problem is that every time you call count(), Python has to look at every element of the list to see if it matches the word you passed to count(). So if the list has n words in it, you will make n*n comparisons. In contrast, the method that directly accumulates counts in a dictionary just makes one pass over the list. For small lists this doesn't matter much, but for a longer list you will definitely see the difference. For example, I downloaded "The Art of War" from Project Gutenberg (http://www.gutenberg.org/dirs/1/3/132/132a.txt) and tried both methods. Here is a program that times how long it takes to do the counts using two different methods: ######### WordCountTest.py ''' Count words two different ways ''' from string import punctuation from time import time def countWithDict(words): ''' Word count by accumulating counts in a dictionary ''' counts = {} for word in words: counts[word] = counts.get(word, 0) + 1 return counts def countWithCount(words): ''' Word count by calling count() for each word ''' counts = {} for word in words: counts[word] = words.count(word) return counts def timeOne(f, words): ''' Time how long it takes to do f(words) ''' startTime = time() f(words) endTime = time() print '%s: %f' % (f.__name__, endTime-startTime) # Get the word list and strip off punctuation words = open(r'D:\Personal\Tutor\ArtOfWar.txt').read().split() words = [ word.strip(punctuation) for word in words ] # How many words is it, anyway? print len(words), 'words' # Time the word counts c1 = timeOne(countWithDict, words) c2 = timeOne(countWithCount, words) # Check that both get the same result assert c1 == c2 #################### The results (times are in seconds): 14253 words countWithDict: 0.010000 countWithCount: 9.183000 It takes 900 times longer to count() each word individually! Kent From nixonron at yahoo.com Tue Feb 15 20:59:58 2005 From: nixonron at yahoo.com (Ron Nixon) Date: Tue Feb 15 21:00:03 2005 Subject: [Tutor] RE help Message-ID: <20050215195958.54824.qmail@web20327.mail.yahoo.com> Trying to scrape a newspaper site for articles using this code whic ws done with help from the list: import urllib, re pattern = re.compile("""<h[1-2]><a href="/(.*)">(.*).</p>""", re.DOTALL) page =urllib.urlopen("http://www.startribune.com").read() for headline, body in pattern.findall(page): print body It should grab articles from this: <h2><a href="/stories/507/5240764.html">Sid Hartman: Franchise could be moved</a></h2><p>If Reggie Fowler and his business partners from New Jersey are approved to buy the Vikings franchise from Red McCombs, it is my opinion the franchise remains in danger of eventually being relocated.</p> and give me this: Sid Hartman: Franchise could be moved</a></h2><p>If Reggie Fowler and his business partners from New Jersey are approved to buy the Vikings franchise from Red McCombs, it is my opinion the franchise remains in danger of eventually being relocated. Instead it gives me this:<b>Boxerjam</b></a>. from this : href="http://www.startribune.com/stories/1559/4773140.html"><b>Boxerjam</b></a>. </p></div> I know the re works in other programs I've tried. Is there something different about re's in Python? __________________________________ Do you Yahoo!? Yahoo! Mail - Find what you need with new enhanced search. http://info.mail.yahoo.com/mail_250 From bill.mill at gmail.com Tue Feb 15 21:02:30 2005 From: bill.mill at gmail.com (Bill Mill) Date: Tue Feb 15 21:02:34 2005 Subject: [Tutor] count words In-Reply-To: <42124FF2.1050304@tds.net> References: <20050215165158.899C71E400A@bag.python.org> <42124FF2.1050304@tds.net> Message-ID: <797fe3d405021512024bb290f4@mail.gmail.com> Coupla nits: On Tue, 15 Feb 2005 14:39:30 -0500, Kent Johnson <kent37@tds.net> wrote: > from string import punctuation > from time import time > <snip> > > words = open(r'D:\Personal\Tutor\ArtOfWar.txt').read().split() Another advantage of the first method is that it allows a more elegant word counting algorithm if you choose not to read the entire file into memory. It's a better general practice to consume lines from a file via the "for line in f" idiom. > words = [ word.strip(punctuation) for word in words ] And, be careful with this - punctuation does not include whitespace characters. Although that is no problem in this example, because split() strips its component strings automatically, people should be aware that punctuation won't work on strings that haven't had their whitespace stripped. Otherwise though, good stuff. Peace Bill Mill bill.mill at gmail.com From kent37 at tds.net Tue Feb 15 21:26:28 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Feb 15 21:26:35 2005 Subject: [Tutor] RE help In-Reply-To: <20050215195958.54824.qmail@web20327.mail.yahoo.com> References: <20050215195958.54824.qmail@web20327.mail.yahoo.com> Message-ID: <42125AF4.6000907@tds.net> Try it with non-greedy matches. You are matching everything from the first <hX><a to the last </p> in one match. Also I think you want to escape the . before </p> (you want just paragraphs that end in a period?) pattern = re.compile("""<h[1-2]><a href="/(.*?)">(.*?)\.</p>""", re.DOTALL) Kent Ron Nixon wrote: > Trying to scrape a newspaper site for articles using > this code whic ws done with help from the list: > > import urllib, re > pattern = re.compile("""<h[1-2]><a > href="/(.*)">(.*).</p>""", re.DOTALL) > page > =urllib.urlopen("http://www.startribune.com").read() > > for headline, body in pattern.findall(page): > print body > > It should grab articles from this: > > <h2><a href="/stories/507/5240764.html">Sid Hartman: > Franchise could be moved</a></h2><p>If Reggie Fowler > and his business partners from New Jersey are approved > to buy the Vikings franchise from Red McCombs, it is > my opinion the franchise remains in danger of > eventually being relocated.</p> > > and give me this: Sid Hartman: Franchise could be > moved</a></h2><p>If Reggie Fowler and his business > partners from New Jersey are approved to buy the > Vikings franchise from Red McCombs, it is my opinion > the franchise remains in danger of eventually being > relocated. > > Instead it gives me this:<b>Boxerjam</b></a>. from > this : > href="http://www.startribune.com/stories/1559/4773140.html"><b>Boxerjam</b></a>. > </p></div> > > I know the re works in other programs I've tried. Is > there something different about re's in Python? > > > > > > __________________________________ > Do you Yahoo!? > Yahoo! Mail - Find what you need with new enhanced search. > http://info.mail.yahoo.com/mail_250 > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From nixonron at yahoo.com Tue Feb 15 21:37:40 2005 From: nixonron at yahoo.com (Ron Nixon) Date: Tue Feb 15 21:37:43 2005 Subject: [Tutor] RE help In-Reply-To: <42125AF4.6000907@tds.net> Message-ID: <20050215203740.10394.qmail@web20326.mail.yahoo.com> Problem solved. Thanks --- Kent Johnson <kent37@tds.net> wrote: > Try it with non-greedy matches. You are matching > everything from the first <hX><a to the last </p> > in one match. Also I think you want to escape the . > before </p> (you want just paragraphs that end > in a period?) > > pattern = re.compile("""<h[1-2]><a > href="/(.*?)">(.*?)\.</p>""", re.DOTALL) > > Kent > > Ron Nixon wrote: > > Trying to scrape a newspaper site for articles > using > > this code whic ws done with help from the list: > > > > import urllib, re > > pattern = re.compile("""<h[1-2]><a > > href="/(.*)">(.*).</p>""", re.DOTALL) > > page > > > =urllib.urlopen("http://www.startribune.com").read() > > > > > for headline, body in pattern.findall(page): > > print body > > > > It should grab articles from this: > > > > <h2><a href="/stories/507/5240764.html">Sid > Hartman: > > Franchise could be moved</a></h2><p>If Reggie > Fowler > > and his business partners from New Jersey are > approved > > to buy the Vikings franchise from Red McCombs, it > is > > my opinion the franchise remains in danger of > > eventually being relocated.</p> > > > > and give me this: Sid Hartman: Franchise could be > > moved</a></h2><p>If Reggie Fowler and his business > > partners from New Jersey are approved to buy the > > Vikings franchise from Red McCombs, it is my > opinion > > the franchise remains in danger of eventually > being > > relocated. > > > > Instead it gives me this:<b>Boxerjam</b></a>. from > > this : > > > href="http://www.startribune.com/stories/1559/4773140.html"><b>Boxerjam</b></a>. > > </p></div> > > > > I know the re works in other programs I've tried. > Is > > there something different about re's in Python? > > > > > > > > > > > > __________________________________ > > Do you Yahoo!? > > Yahoo! Mail - Find what you need with new enhanced > search. > > http://info.mail.yahoo.com/mail_250 > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > __________________________________ Do you Yahoo!? The all-new My Yahoo! - What will yours do? http://my.yahoo.com From python at bernardlebel.com Tue Feb 15 22:16:44 2005 From: python at bernardlebel.com (python@bernardlebel.com) Date: Tue Feb 15 22:16:44 2005 Subject: [Tutor] Basic terminology Message-ID: <1108502204.421266bc1608b@www.bernardlebel.com> Hi, I'm reading a Python book right now (Learning Python, a great book!), and there are few terms that come are brought up a few times but without any explanation. So what are: - "remainders" (in the context of remainders-of-division modulus for numbers) - "modulus" (in the same context; I have also seen it in different context, like 3D graphics programs to perform certain types of calculations). Thanks Bernard From bill.mill at gmail.com Tue Feb 15 22:30:35 2005 From: bill.mill at gmail.com (Bill Mill) Date: Tue Feb 15 22:30:38 2005 Subject: [Tutor] Basic terminology In-Reply-To: <1108502204.421266bc1608b@www.bernardlebel.com> References: <1108502204.421266bc1608b@www.bernardlebel.com> Message-ID: <797fe3d40502151330c59ef6e@mail.gmail.com> A remainder is what's left over after a division: 10/3 = 3 remainder 1 12/5 = 2 remainder 2 27/3 = 9 remainder 0 and the modulus operator (which is % in python) gives you that remainder: 10%3 = 1 12%5 = 2 27%3 = 0 See http://mathworld.wolfram.com/Remainder.html and http://mathworld.wolfram.com/Modulus.html for more formal explanations. In particular, it explains some deeper meanings of the word "modulus". Once you get into group theory, it can start to mean some related but different things. Peace Bill Mill bill.mill at gmail.com On Tue, 15 Feb 2005 16:16:44 -0500, python@bernardlebel.com <python@bernardlebel.com> wrote: > Hi, > > I'm reading a Python book right now (Learning Python, a great book!), and there > are few terms that come are brought up a few times but without any explanation. > > So what are: > - "remainders" (in the context of remainders-of-division modulus for numbers) > - "modulus" (in the same context; I have also seen it in different context, like > 3D graphics programs to perform certain types of calculations). > > Thanks > Bernard > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From bvande at po-box.mcgill.ca Tue Feb 15 23:19:37 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue Feb 15 23:21:11 2005 Subject: [Tutor] dictionary dispatch for object instance attributes question Message-ID: <42127579.3080001@po-box.mcgill.ca> Hi all, I'm still plugging away at my project of writing code to process treepad files. (This was the task which I posted about in the recent "help with refactoring needed -- which approach is more Pythonic?" thread.) My present problem is how best to reorganize a long (20 elements) elif chain. The file format I am dealing with organizes itself with a file header, and then a series of nodes. Each node has a header filled with up to 20 different metadata elements, followed by the node content proper. These metadata elements can be in arbitrary order, and need not all be present. My Node class defines a _parse method which separates out the node header, and sends those lines to a _parse_metadata method. This is where the elif chain occurs -- each line of the metadata starts with a tag like "dt=" and I need to recognize each tag and set the appropriate Node object attribute, such as .document_type. (I do not want to rely on the unhelpful names for the tags in the file format, preferring more self-documenting attribute names.) I've come up with *a* way to use a dictionary dispatch, but I'll wager a great deal it isn't the *best* way. Here is a minimal illustration of what I have come up with: <code> class A: def __init__(self): self.something = None self.something_else = None self.still_another_thing = None def update(self, data): for key in metadata_dict: if data.startswith(key): exec('''self.%s = """%s"""''' %(metadata_dict[key], data[len(key):])) # triple quotes as there may be quotes in metadata # values break metadata_dict = {'something_tag=': 'something', '2nd_tag=': 'something_else', 'last=': 'still_another_thing'} a = A() print a.still_another_thing a.update('last=the metadata value for the "last=" metadata tag') print a.still_another_thing </code> <output> >>> None the metadata value for the "last=" metadata tag </output> So, it works. Yay :-) But, should I be doing it another way? Also, I know the general security concerns about things like exec. They make me nervous in using it, even though I am (as yet) the sole user. Am I right in thinking that the constrained way I am using it here protects me? My code uses most of the attributes as a simple storage container for later rewriting of the file, but in a few cases they enter into (safe seeming) conditionals like: if 'text' == self.document_type: self.do_text_stuff() if 'RTF' == self.document_type: self.do_RTF_stuff() Thanks and best to all, Brian vdB From dyoo at hkn.eecs.berkeley.edu Tue Feb 15 23:26:52 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Feb 15 23:26:59 2005 Subject: [Tutor] Basic terminology In-Reply-To: <797fe3d40502151330c59ef6e@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0502151405110.31589-100000@hkn.eecs.berkeley.edu> > A remainder is what's left over after a division: > > 10/3 = 3 remainder 1 > 12/5 = 2 remainder 2 > 27/3 = 9 remainder 0 > > and the modulus operator (which is % in python) gives you that remainder: > > 10%3 = 1 > 12%5 = 2 > 27%3 = 0 Hi Bernard, Another familiar example of modulo is checking to see if a number is even or odd: ### def isEven(n): """Check to see if n is divisible by 2.""" return n % 2 == 0 ### The remainder of 'n' divided by 2, that is, "n modulo 2", is zero if 'n' is even. Another cute thing about modulo is that we can use it to evenly distribute things. Let's make this more concrete, or at least a little sweeter. Imagine that it's Halloween, and we want to evenly distribute some candy out to some trick-or-treaters: ### people = ['fred', 'wilma', 'barney', 'betty'] candy = ['almond joy', 'take 5', 'cadbury', 'twizzlers', 'reeses', 'york', 'jolly rancher', 'nestle crunch'] ### There are two ways we can pass candy to the folks: we can give each people two candies each: ### >>> for (i, c) in enumerate(candy): ... print people[i / (len(candy) / len(people))], "gets", c ... fred gets almond joy fred gets take 5 wilma gets cadbury wilma gets twizzlers barney gets reeses barney gets york betty gets jolly rancher betty gets nestle crunch ### That is, since there are eight pieces of candy, and only four people, we can give each person two pieces of candy each. We use simple division: (i / (len(candy) / len(people)) ==> i / 2 to figure out, given the index number of the candy, which person can seize the sugary treat. So the first two pieces belong to fred, the second two pieces belong to wilma, and so on. Or we can do something that looks more round-robin: ### >>> for (i, c) in enumerate(candy): ... print people[i % len(people)], "gets", c ... fred gets almond joy wilma gets take 5 barney gets cadbury betty gets twizzlers fred gets reeses wilma gets york barney gets jolly rancher betty gets nestle crunch ### And here, we use the modulo operator to figure out which person each candy belongs to. In this case, we see the calculation involves: i % len(people) So there's this intimate relationship between division and modulo that corresponds to two main ways we pass things out to people. Does this make sense? From cyresse at gmail.com Wed Feb 16 00:08:41 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed Feb 16 00:08:45 2005 Subject: [Tutor] dictionary dispatch for object instance attributes question In-Reply-To: <42127579.3080001@po-box.mcgill.ca> References: <42127579.3080001@po-box.mcgill.ca> Message-ID: <f2ff2d05021515085aaf6647@mail.gmail.com> Hi Brian, why not take it the next step and > for key in metadata_dict: > if data.startswith(key): > exec('''self.%s = """%s"""''' %(metadata_dict[key], > data[len(key):])) > # triple quotes as there may be quotes in metadata > # values > break self.foo = {} for key in metadata_dict.keys(): #? I got confused, so I guessed. if data.startswith(key): self.foo[metadata_dict[key]]=data[len(key):] And then instead of self.x (if metadata_dict[key] = x] You just call self.foo['x'] A bit more obfuscated, but it would seem to remove the exec, although I'm not sure how else it impacts your class. I came across something similar when using Pythoncard, because Pythoncard stores widgets as a dictionary. To crate a widget via a method in your card, you'd use - self.components.myButton = {'properties'} But to generate widgets based on data input, I'd use a dictionary generated by the data - a = raw_input('name? ') widgDict = {a: {dict of properties}} for (key, val) in widgDict.items(): self.components[key]=val (Which incidentally is why Pythoncard rocks) So yeah, hope that helps a wee bit. Regards, Liam Clarke On Tue, 15 Feb 2005 17:19:37 -0500, Brian van den Broek <bvande@po-box.mcgill.ca> wrote: > Hi all, > > I'm still plugging away at my project of writing code to process > treepad files. (This was the task which I posted about in the recent > "help with refactoring needed -- which approach is more Pythonic?" > thread.) > > My present problem is how best to reorganize a long (20 elements) elif > chain. The file format I am dealing with organizes itself with a file > header, and then a series of nodes. Each node has a header filled with > up to 20 different metadata elements, followed by the node content > proper. These metadata elements can be in arbitrary order, and need > not all be present. > > My Node class defines a _parse method which separates out the node > header, and sends those lines to a _parse_metadata method. This is > where the elif chain occurs -- each line of the metadata starts with a > tag like "dt=" and I need to recognize each tag and set the > appropriate Node object attribute, such as .document_type. (I do not > want to rely on the unhelpful names for the tags in the file format, > preferring more self-documenting attribute names.) > > I've come up with *a* way to use a dictionary dispatch, but I'll wager > a great deal it isn't the *best* way. > > Here is a minimal illustration of what I have come up with: > > <code> > class A: > > def __init__(self): > > self.something = None > self.something_else = None > self.still_another_thing = None > > def update(self, data): > > > metadata_dict = {'something_tag=': 'something', > '2nd_tag=': 'something_else', > 'last=': 'still_another_thing'} > > a = A() > print a.still_another_thing > a.update('last=the metadata value for the "last=" metadata tag') > print a.still_another_thing > </code> > > <output> > >>> > None > the metadata value for the "last=" metadata tag > </output> > > So, it works. Yay :-) > > But, should I be doing it another way? > > Also, I know the general security concerns about things like exec. > They make me nervous in using it, even though I am (as yet) the sole > user. Am I right in thinking that the constrained way I am using it > here protects me? My code uses most of the attributes as a simple > storage container for later rewriting of the file, but in a few cases > they enter into (safe seeming) conditionals like: > > if 'text' == self.document_type: > self.do_text_stuff() > if 'RTF' == self.document_type: > self.do_RTF_stuff() > > Thanks and best to all, > > Brian vdB > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From bill.mill at gmail.com Wed Feb 16 00:09:36 2005 From: bill.mill at gmail.com (Bill Mill) Date: Wed Feb 16 00:09:39 2005 Subject: [Tutor] Basic terminology In-Reply-To: <Pine.LNX.4.44.0502151405110.31589-100000@hkn.eecs.berkeley.edu> References: <797fe3d40502151330c59ef6e@mail.gmail.com> <Pine.LNX.4.44.0502151405110.31589-100000@hkn.eecs.berkeley.edu> Message-ID: <797fe3d405021515095a42364a@mail.gmail.com> On Tue, 15 Feb 2005 14:26:52 -0800 (PST), Da > > Hi Bernard, > > Another familiar example of modulo is checking to see if a number is even > or odd: > <snip lots of good stuff from danny> Since Danny got it started with the examples, I'll give another canonical example of the use of the modulus operator. Imagine that we're trying to figure out what number the hour hand of a clock will be pointing at x hours from now. If it's one o'clock right now, in 5 hours, the hour hand will be pointing at the six, and in 10 hours, it will be pointing at the 11. However, where will it be pointing in 16 hours? Well, in 12 hours it will be at the one, then four more hours later it will be pointing at the five. This can be represented as: 1 + (16 % 12) = 1 + 4 = 5 In general, the hour at some point in the future will be: (start time) + (hours in the future % 12) Peace Bill Mill bill.mill at gmail.com From rmkrauter at yahoo.com Wed Feb 16 00:09:56 2005 From: rmkrauter at yahoo.com (Rich Krauter) Date: Wed Feb 16 00:10:11 2005 Subject: [Tutor] dictionary dispatch for object instance attributes question In-Reply-To: <42127579.3080001@po-box.mcgill.ca> References: <42127579.3080001@po-box.mcgill.ca> Message-ID: <42128144.3030802@yahoo.com> Brian van den Broek wrote: [snip text] > <code> > class A: > > def __init__(self): > > self.something = None > self.something_else = None > self.still_another_thing = None > > def update(self, data): > > for key in metadata_dict: > if data.startswith(key): > exec('''self.%s = """%s"""''' %(metadata_dict[key], > data[len(key):])) > # triple quotes as there may be quotes in metadata > # values > break > [snip usage example and additional text] Brian, You could use setattr(self,metadata_dict[key],data[len(key):]). Rich From luke.jordan at gmail.com Wed Feb 16 00:16:37 2005 From: luke.jordan at gmail.com (Luke Jordan) Date: Wed Feb 16 00:17:35 2005 Subject: [Tutor] Case acceptance using raw_input Message-ID: <ea0feb80050215151613bb9a05@mail.gmail.com> Hi all, thanks to all for running such a great list. Is there a better way for raw_input to accept both caps and lower case letters than: def aFunction(): action = raw_input("Perform an action?(y,n): ") if action == 'y' or action == 'Y': anotherFunction() elif action == 'n' or action == 'N': yetAnotherFunction() else: aFunction() Thanks! -- No success or discovery is an accident. It is the result of time invested in the process. -- No success or discovery is an accident. It is the result of time invested in the process. From cyresse at gmail.com Wed Feb 16 00:24:06 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed Feb 16 00:24:11 2005 Subject: [Tutor] Case acceptance using raw_input In-Reply-To: <ea0feb80050215151613bb9a05@mail.gmail.com> References: <ea0feb80050215151613bb9a05@mail.gmail.com> Message-ID: <f2ff2d050215152466a4518f@mail.gmail.com> if action in 'yY': dostuff() elif action in 'nN': doothersutff() Although, that does mean that if a user enters 'nN' they'll get no, but that shouldn't be a huge problem, and it it does, you can just do a if len(action) != 1... HTH Liam Clarke On Tue, 15 Feb 2005 15:16:37 -0800, Luke Jordan <luke.jordan@gmail.com> wrote: > Hi all, thanks to all for running such a great list. > > Is there a better way for raw_input to accept both caps and lower case > letters than: > > def aFunction(): > action = raw_input("Perform an action?(y,n): ") > if action == 'y' or action == 'Y': > anotherFunction() > elif action == 'n' or action == 'N': > yetAnotherFunction() > else: > aFunction() > > Thanks! > > -- > No success or discovery is an accident. It is the result of time > invested in the process. > > -- > No success or discovery is an accident. It is the result of time > invested in the process. > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From tameyer at ihug.co.nz Wed Feb 16 00:33:28 2005 From: tameyer at ihug.co.nz (Tony Meyer) Date: Wed Feb 16 00:33:34 2005 Subject: [Tutor] Case acceptance using raw_input In-Reply-To: <ECBA357DDED63B4995F5C1F5CBE5B1E802107E12@its-xchg4.massey.ac.nz> Message-ID: <ECBA357DDED63B4995F5C1F5CBE5B1E801DAFE95@its-xchg4.massey.ac.nz> >> Is there a better way for raw_input to accept both caps and >> lower case letters than: [...] >> if action == 'y' or action == 'Y': > > if action in 'yY': > dostuff() [...] > Although, that does mean that if a user enters 'nN' they'll > get no, but that shouldn't be a huge problem, and it it does, > you can just do a if len(action) != 1... Alternatively, you could do: if action.lower() == 'y': This is the most readable, IMO, but is probably slower (function calls are expensive) than 'if len(action) == 1 and action in "yY"' or 'if action == "y" or action == "Y"'. (Of course, the difference in speed here is almost certainly irrelevant). =Tony.Meyer From maxnoel_fr at yahoo.fr Wed Feb 16 00:34:40 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Wed Feb 16 00:34:46 2005 Subject: [Tutor] Basic terminology In-Reply-To: <797fe3d405021515095a42364a@mail.gmail.com> References: <797fe3d40502151330c59ef6e@mail.gmail.com> <Pine.LNX.4.44.0502151405110.31589-100000@hkn.eecs.berkeley.edu> <797fe3d405021515095a42364a@mail.gmail.com> Message-ID: <e66a8c77c7d4fe1df3dd64a412bc8275@yahoo.fr> In a slightly more generic fashion (everybody started dropping examples), the goal of an integer (euclidian) division (say, a / b) is to express an integer as such: a = b * quotient + remainder Where all the numbers used are integers, and 0 <= remainder < b. When you perform integer division in Python, a / b (a // b in 2.4+) gives you the quotient, and a % b gives you the remainder. See the other posts for examples of use :p -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From bvande at po-box.mcgill.ca Wed Feb 16 01:11:03 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed Feb 16 01:12:03 2005 Subject: [Tutor] dictionary dispatch for object instance attributes question In-Reply-To: <f2ff2d05021515085aaf6647@mail.gmail.com> References: <42127579.3080001@po-box.mcgill.ca> <f2ff2d05021515085aaf6647@mail.gmail.com> Message-ID: <42128F97.1040909@po-box.mcgill.ca> Liam Clarke said unto the world upon 2005-02-15 18:08: > Hi Brian, why not take it the next step and > >> for key in metadata_dict: >> if data.startswith(key): >> exec('''self.%s = """%s"""''' %(metadata_dict[key], >> data[len(key):])) >> # triple quotes as there may be quotes in metadata >> # values >> break > > > self.foo = {} > > for key in metadata_dict.keys(): #? I got confused, so I guessed. > if data.startswith(key): > self.foo[metadata_dict[key]]=data[len(key):] > > And then instead of self.x (if metadata_dict[key] = x] You just call > self.foo['x'] > > A bit more obfuscated, but it would seem to remove the exec, although > I'm not sure how else it impacts your class. <SNIP related Pythoncard example> > So yeah, hope that helps a wee bit. > > Regards, > > Liam Clarke and Rich Krauter said unto the world upon 2005-02-15 18:09: > Brian, > > You could use setattr(self,metadata_dict[key],data[len(key):]). > > Rich Hi Liam, Rich, and all, thanks for the replies. (And for heroically working through the long question -- if there is a tutee verbosity award, I think its mine ;-) Rich: thanks. setattr, yeah, that's the ticket! Liam: The reason I didn't want to take it this way is: "Flat is better than nested" :-) The code I am working on is an improved (I hope ;-) ) and expanded class-based version of some more primitive code I had done purely procedurally. There, I had a dictionary approach for storing the metadata (akin to the self.foo dictionary you suggested above). One of the benefits of going OOP, in my opinion, is that instead of using dictionary access syntax, you can just say things like self.document_type. It might be little more than sugar[*], but I've a sweet tooth, and I'd want to avoid going back to the dictionary syntax if I could. Though, absent the setattr way that Rich pointed to, I must admit the exec in my originally posted version would have me dithering whether to opt for sugar or safety. Thankfully, it's all moot. [*] In that, if I've understood correctly, class namespaces are just fancily packaged dictionaries. Thanks to all, Brian vdB From dyoo at hkn.eecs.berkeley.edu Wed Feb 16 01:26:14 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Feb 16 01:26:22 2005 Subject: [Tutor] Case acceptance using raw_input In-Reply-To: <ECBA357DDED63B4995F5C1F5CBE5B1E801DAFE95@its-xchg4.massey.ac.nz> Message-ID: <Pine.LNX.4.44.0502151605470.24398-100000@hkn.eecs.berkeley.edu> On Wed, 16 Feb 2005, Tony Meyer wrote: > >> Is there a better way for raw_input to accept both caps and > >> lower case letters than: > [...] > >> if action == 'y' or action == 'Y': > > > > if action in 'yY': > > dostuff() > [...] > > Although, that does mean that if a user enters 'nN' they'll > > get no, but that shouldn't be a huge problem, and it it does, > > you can just do a if len(action) != 1... Hello! There's one other major problem that's not obvious: watch what happens if the user just presses Enter: ### >>> if raw_input("y/n?") in "yY": ... print "Yes!" ... y/n? Yes! ### The empty string "" is a substring of everything. *grin* So the length check against the input is something we definitely need to do if we take this approach. Given that, it's probably safer to go with Tony's: > if action.lower() == 'y': and if we end up doing a lot of yes/no questions to the user, it'll probably be a good idea to write a helper function or two to do the grunt work of parsing the user's input: ### def isYes(choice): return choice.lower() == 'y' def isNo(choice): return choice.lower() == 'n' ### just so that we don't have to worry about the problem anymore. I see that the original code is written using a tail-call recursion style, such as one supported by Scheme. Here's the code, with isYes()/isNo() modifications: ### def aFunction(): action = raw_input("Perform an action?(y,n): ") if isYes(action): anotherFunction() elif isNo(action): yetAnotherFunction() else: aFunction() ### Unfortunately, Python doesn't support tail call optimization. *sigh* This means that the recursion here takes stack space in Python. To get around Python's lack of tail-call optimization, you may want to use an explicit loop here instead: ### def aFunction(): while True: action = raw_input("Perform an action?(y,n): ") if isYes(action): anotherFunction() break elif isNo(action): yetAnotherFunction() break ### If you have more questions, please feel free to ask! From python at bernardlebel.com Wed Feb 16 02:39:57 2005 From: python at bernardlebel.com (Bernard Lebel) Date: Wed Feb 16 02:40:04 2005 Subject: [Tutor] Basic terminology In-Reply-To: <e66a8c77c7d4fe1df3dd64a412bc8275@yahoo.fr> References: <797fe3d40502151330c59ef6e@mail.gmail.com> <Pine.LNX.4.44.0502151405110.31589-100000@hkn.eecs.berkeley.edu> <797fe3d405021515095a42364a@mail.gmail.com> <e66a8c77c7d4fe1df3dd64a412bc8275@yahoo.fr> Message-ID: <4212A46D.3020107@bernardlebel.com> Well, thanks everyone who answered, much clearer now. Bernard Max Noel wrote: > In a slightly more generic fashion (everybody started dropping > examples), the goal of an integer (euclidian) division (say, a / b) is > to express an integer as such: > > a = b * quotient + remainder > > Where all the numbers used are integers, and 0 <= remainder < b. > > When you perform integer division in Python, a / b (a // b in 2.4+) > gives you the quotient, and a % b gives you the remainder. > > See the other posts for examples of use :p > > -- Max > maxnoel_fr at yahoo dot fr -- ICQ #85274019 > "Look at you hacker... A pathetic creature of meat and bone, panting and > sweating as you run through my corridors... How can you challenge a > perfect, immortal machine?" > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > From python at bernardlebel.com Wed Feb 16 02:58:15 2005 From: python at bernardlebel.com (Bernard Lebel) Date: Wed Feb 16 02:58:23 2005 Subject: [Tutor] Queued threads Message-ID: <4212A8B7.8060005@bernardlebel.com> Hello, I have already messed a little with simple thread programming, wich took this form: from threading import Thread def mainFunction(): pass Thread( target=mainFunction ).start() Now, I have a list of "jobs", each job being a windows bat file that launches an executable and performs a rendering task. So I have this queue of jobs, and would like to launch one only when the previous one has finished, and in a separate window. So far I have not been having much success with simple stuff: from threading import Thread def mainFunction(): print 'function print' return 1 for i in range( 0, 3 ): oThread = Thread( target=mainFunction ).start() if oThread == 1: print 'sleeping 3 seconds' time.sleep( 3 ) In this example, 'sleeping 3 seconds' not returned, and each thread is started without any waiting. I'm looking at the various threading module details in the library but I have to admit that, well, I'm a bit at loss here. Thanks in advance Bernard From jeffshannon at gmail.com Wed Feb 16 03:20:09 2005 From: jeffshannon at gmail.com (Jeff Shannon) Date: Wed Feb 16 03:20:44 2005 Subject: [Tutor] dictionary dispatch for object instance attributes question In-Reply-To: <42127579.3080001@po-box.mcgill.ca> References: <42127579.3080001@po-box.mcgill.ca> Message-ID: <5d0204a105021518204d86acc9@mail.gmail.com> On Tue, 15 Feb 2005 17:19:37 -0500, Brian van den Broek <bvande@po-box.mcgill.ca> wrote: > My Node class defines a _parse method which separates out the node > header, and sends those lines to a _parse_metadata method. This is > where the elif chain occurs -- each line of the metadata starts with a > tag like "dt=" and I need to recognize each tag and set the > appropriate Node object attribute, such as .document_type. (I do not > want to rely on the unhelpful names for the tags in the file format, > preferring more self-documenting attribute names.) In addition to using setattr(), I'd take a slightly different approach to this. (This may just be a matter of personal style, and is not as clearly advantageous as using setattr() instead of exec, but...) .class Node(object): . metadata = {'dt': 'document_type', 'something': 'some_other_field', ...} . def __init__(self): # .... . def update(self, **kwargs): . for key, value in kwargs.items(): . try: . attr_name = self.metadata[key] . except KeyError: . raise ValueError("Invalid field type '%s'" % key) . setattr(self, attr_name, value) For starters, I've made metadata a class attribute rather than an unconnected dictionary. This seems conceptually nicer to me. In addition, update() can now modify several attributes at once, at the cost of a bit of extra parsing up front. Supposing that your node header looks like this: .header = "dt=text/plain;something=some_value;last=some_other_thing_here" Now, we can break that into fields, and then split the fields into a name and a value -- .tags = {} .for field in header.split(';'): . name, value = field.split('=') . tags[name] = value . .n = Node() .n.update(**tags) You can even simplify this a bit more, by rewriting the __init__(): . def __init__(self, **kwargs): . if kwargs: . self.update(**kwargs) Now you can create and update in a single step: .n = Node(**tags) You could also put all of the splitting into fields in a method, and when __init__ gets a single string as its argument simply pass it to that method and update with the results... --Jeff Shannon From maxnoel_fr at yahoo.fr Wed Feb 16 03:30:38 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Wed Feb 16 03:31:01 2005 Subject: [Tutor] Queued threads In-Reply-To: <4212A8B7.8060005@bernardlebel.com> References: <4212A8B7.8060005@bernardlebel.com> Message-ID: <ff57114e5baff9fdb2eeb95c8c52a0c1@yahoo.fr> On Feb 16, 2005, at 01:58, Bernard Lebel wrote: > Now, I have a list of "jobs", each job being a windows bat file that > launches an executable and performs a rendering task. So I have this > queue of jobs, and would like to launch one only when the previous one > has finished, and in a separate window. So far I have not been having > much success with simple stuff: > > > from threading import Thread > > def mainFunction(): > print 'function print' > return 1 > > for i in range( 0, 3 ): > oThread = Thread( target=mainFunction ).start() > > if oThread == 1: > print 'sleeping 3 seconds' > time.sleep( 3 ) > > > In this example, 'sleeping 3 seconds' not returned, and each thread is > started without any waiting. > > > I'm looking at the various threading module details in the library but > I have to admit that, well, I'm a bit at loss here. Okay, so basically, what you want to do is: - Start the first bat file. - Wait for it to finish. - Start the second bat file. - Wait for it to finish. - Start the third bat file. - Wait for it to finish. This just begs the following question: why are you even using threads to do that? This is perfectly sequential, with no element of simultaneity whatsoever... -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From cyresse at gmail.com Wed Feb 16 03:36:40 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed Feb 16 03:36:43 2005 Subject: [Tutor] Queued threads In-Reply-To: <4212A8B7.8060005@bernardlebel.com> References: <4212A8B7.8060005@bernardlebel.com> Message-ID: <f2ff2d050215183662ba997b@mail.gmail.com> I'm sorry, but when does oThread get the value 1? If you're testing for it's existence via a True/False thing, try if oThread: But otherwise, I'm not sure what you're expecting to get. On Tue, 15 Feb 2005 20:58:15 -0500, Bernard Lebel <python@bernardlebel.com> wrote: > Hello, > > I have already messed a little with simple thread programming, wich took > this form: > > from threading import Thread > > def mainFunction(): > pass > > Thread( target=mainFunction ).start() > > Now, I have a list of "jobs", each job being a windows bat file that > launches an executable and performs a rendering task. So I have this > queue of jobs, and would like to launch one only when the previous one > has finished, and in a separate window. So far I have not been having > much success with simple stuff: > > from threading import Thread > > def mainFunction(): > print 'function print' > return 1 > > for i in range( 0, 3 ): > oThread = Thread( target=mainFunction ).start() > > if oThread == 1: > print 'sleeping 3 seconds' > time.sleep( 3 ) > > In this example, 'sleeping 3 seconds' not returned, and each thread is > started without any waiting. > > I'm looking at the various threading module details in the library but I > have to admit that, well, I'm a bit at loss here. > > Thanks in advance > Bernard > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From maxnoel_fr at yahoo.fr Wed Feb 16 03:53:24 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Wed Feb 16 03:53:29 2005 Subject: [Tutor] Queued threads In-Reply-To: <f2ff2d050215183662ba997b@mail.gmail.com> References: <4212A8B7.8060005@bernardlebel.com> <f2ff2d050215183662ba997b@mail.gmail.com> Message-ID: <3d70e2f6108f42117519f598ac4f7c4a@yahoo.fr> On Feb 16, 2005, at 02:36, Liam Clarke wrote: > I'm sorry, but when does oThread get the value 1? > > If you're testing for it's existence via a True/False thing, try > > if oThread: > > But otherwise, I'm not sure what you're expecting to get. Once again, you hit the spot, Liam. It seems that a Thread object evaluates to False once it's terminated. That's probably what you're looking for, Bernard, my "threads won't be of any use here" argument notwithstanding. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From python at bernardlebel.com Wed Feb 16 03:54:04 2005 From: python at bernardlebel.com (Bernard Lebel) Date: Wed Feb 16 03:54:10 2005 Subject: [Tutor] Queued threads In-Reply-To: <f2ff2d050215183662ba997b@mail.gmail.com> References: <4212A8B7.8060005@bernardlebel.com> <f2ff2d050215183662ba997b@mail.gmail.com> Message-ID: <4212B5CC.5030102@bernardlebel.com> That is an attempt to catch the death of the thread. I guess I'm not taking the right steps ;-) Bernard Liam Clarke wrote: > I'm sorry, but when does oThread get the value 1? > > If you're testing for it's existence via a True/False thing, try > > if oThread: > > But otherwise, I'm not sure what you're expecting to get. > > > On Tue, 15 Feb 2005 20:58:15 -0500, Bernard Lebel > <python@bernardlebel.com> wrote: > >>Hello, >> >>I have already messed a little with simple thread programming, wich took >>this form: >> >>from threading import Thread >> >>def mainFunction(): >> pass >> >>Thread( target=mainFunction ).start() >> >>Now, I have a list of "jobs", each job being a windows bat file that >>launches an executable and performs a rendering task. So I have this >>queue of jobs, and would like to launch one only when the previous one >>has finished, and in a separate window. So far I have not been having >>much success with simple stuff: >> >>from threading import Thread >> >>def mainFunction(): >> print 'function print' >> return 1 >> >>for i in range( 0, 3 ): >> oThread = Thread( target=mainFunction ).start() >> >> if oThread == 1: >> print 'sleeping 3 seconds' >> time.sleep( 3 ) >> >>In this example, 'sleeping 3 seconds' not returned, and each thread is >>started without any waiting. >> >>I'm looking at the various threading module details in the library but I >>have to admit that, well, I'm a bit at loss here. >> >>Thanks in advance >>Bernard From cyresse at gmail.com Wed Feb 16 04:50:07 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed Feb 16 04:50:17 2005 Subject: [Tutor] Queued threads In-Reply-To: <4212B5CC.5030102@bernardlebel.com> References: <4212A8B7.8060005@bernardlebel.com> <f2ff2d050215183662ba997b@mail.gmail.com> <4212B5CC.5030102@bernardlebel.com> Message-ID: <f2ff2d050215195016f9e5d5@mail.gmail.com> Oops, you probably want to do this then- for i in range( 0, 3 ): oThread = Thread( target=mainFunction ).start() while oThread: print 'sleeping 3 seconds' time.sleep( 3 ) A if <condition> generally has an implicit else: pass clause as I think of it, so it will just keep reiterating if the condition isn't met. To see what I mean try - for i in range(5): #The 0 is default starting for range function if i==15: print 'fifteen' print i You'll, of course, get 0 1 2 3 4 It won't wait until i equals 15. on the other hand - for i in range(5): while i != 15: print "nope" print i You'll get a runaway while, and 'nope' will cascade down your stream, and you'll have great trouble closing Python. But i will never get printed, as it will still be waiting for i to equal fifteen. On Tue, 15 Feb 2005 21:54:04 -0500, Bernard Lebel <python@bernardlebel.com> wrote: > That is an attempt to catch the death of the thread. I guess I'm not > taking the right steps ;-) > > > Bernard > > > Liam Clarke wrote: > > I'm sorry, but when does oThread get the value 1? > > > > If you're testing for it's existence via a True/False thing, try > > > > if oThread: > > > > But otherwise, I'm not sure what you're expecting to get. > > > > > > On Tue, 15 Feb 2005 20:58:15 -0500, Bernard Lebel > > <python@bernardlebel.com> wrote: > > > >>Hello, > >> > >>I have already messed a little with simple thread programming, wich took > >>this form: > >> > >>from threading import Thread > >> > >>def mainFunction(): > >> pass > >> > >>Thread( target=mainFunction ).start() > >> > >>Now, I have a list of "jobs", each job being a windows bat file that > >>launches an executable and performs a rendering task. So I have this > >>queue of jobs, and would like to launch one only when the previous one > >>has finished, and in a separate window. So far I have not been having > >>much success with simple stuff: > >> > >>from threading import Thread > >> > >>def mainFunction(): > >> print 'function print' > >> return 1 > >> > >>for i in range( 0, 3 ): > >> oThread = Thread( target=mainFunction ).start() > >> > >> if oThread == 1: > >> print 'sleeping 3 seconds' > >> time.sleep( 3 ) > >> > >>In this example, 'sleeping 3 seconds' not returned, and each thread is > >>started without any waiting. > >> > >>I'm looking at the various threading module details in the library but I > >>have to admit that, well, I'm a bit at loss here. > >> > >>Thanks in advance > >>Bernard > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From bvande at po-box.mcgill.ca Wed Feb 16 05:48:31 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed Feb 16 05:51:01 2005 Subject: [Tutor] dictionary dispatch for object instance attributes question In-Reply-To: <5d0204a105021518204d86acc9@mail.gmail.com> References: <42127579.3080001@po-box.mcgill.ca> <5d0204a105021518204d86acc9@mail.gmail.com> Message-ID: <4212D09F.5010601@po-box.mcgill.ca> Jeff Shannon said unto the world upon 2005-02-15 21:20: > On Tue, 15 Feb 2005 17:19:37 -0500, Brian van den Broek > <bvande@po-box.mcgill.ca> wrote: > > >>My Node class defines a _parse method which separates out the node >>header, and sends those lines to a _parse_metadata method. This is >>where the elif chain occurs -- each line of the metadata starts with a >>tag like "dt=" and I need to recognize each tag and set the >>appropriate Node object attribute, such as .document_type. (I do not >>want to rely on the unhelpful names for the tags in the file format, >>preferring more self-documenting attribute names.) > > > In addition to using setattr(), I'd take a slightly different approach > to this. (This may just be a matter of personal style, and is not as > clearly advantageous as using setattr() instead of exec, but...) Hi Jeff and all, I am *pretty* sure I followed what you meant, Jeff. Thank you for the suggestions! I don't think they will fit with my situation, but that I think so might say more about my present level of understanding of OOP and design issues than about either the suggestions or the situation. :-) > .class Node(object): > . metadata = {'dt': 'document_type', 'something': 'some_other_field', ...} > . def __init__(self): # .... > . def update(self, **kwargs): > . for key, value in kwargs.items(): > . try: > . attr_name = self.metadata[key] > . except KeyError: > . raise ValueError("Invalid field type '%s'" % key) > . setattr(self, attr_name, value) > > For starters, I've made metadata a class attribute rather than an > unconnected dictionary. This seems conceptually nicer to me. The problem is that my Node instance live in a TP_file class instance, and the way my code is now, the TP_file instance also needs to see the metadata dict. There are a few tags, which if present in any Node of the file make me want to treat the entire file a bit differently. (Of course, here is the place where my novice-designer status is most likely to be bitting me.) So, that's why I have it as a module level object, rather than within a class. (I do, however, see your point about it being neater.) > In addition, update() can now modify several attributes at once, at > the cost of a bit of extra parsing up front. > > Supposing that your node header looks like this: > > .header = "dt=text/plain;something=some_value;last=some_other_thing_here" > > Now, we can break that into fields, and then split the fields into a > name and a value -- > > .tags = {} > .for field in header.split(';'): > . name, value = field.split('=') > . tags[name] = value > . > .n = Node() > .n.update(**tags) > > You can even simplify this a bit more, by rewriting the __init__(): > > . def __init__(self, **kwargs): > . if kwargs: > . self.update(**kwargs) > > Now you can create and update in a single step: > > .n = Node(**tags) The metadata all occurs one element to a line in my original file. I've got the TP_file class breaking the nodes up and sending the contents to new Node instances (as Alan suggested in my previous thread). The Node instance has a parse method that reads the node contents line by line and sends the appropriate lines to the parse_metadata method. (All lines before a designated `header-ending' line.) Maybe I'm still missing a better way, but as I am processing line by line, each line with one element, I don't see how to use this cool looking multiple elements at once approach. (The other complication that I didn't mention is that the parse_metadata method has to do more than just store the metadata -- some elements must be converted to ints, others left as strings, and still others can have multiple instances in a single Node, so rather than be set they must be appended to an attribute list, etc. The setattr way has taken me from 20 elifs to just 4, though :-) ) At any rate, my whole code is (perhaps wrongly) organized around logical-line based processing. > You could also put all of the splitting into fields in a method, and > when __init__ gets a single string as its argument simply pass it to > that method and update with the results... > > --Jeff Shannon Anyway, such are the reasons I'm not sure the suggestions will work in my situation. I'm glad to have seen them, though, and am going to save them for the point where I actually have the whole program working and can think about large-scale refactoring. I may well then find that my current uncertainty is unwarranted. But I'd like to make the beast live before I make it thrive :-) Thanks again, and best, Brian vdB From peateyk at gmail.com Wed Feb 16 06:45:54 2005 From: peateyk at gmail.com (Peter Kim) Date: Wed Feb 16 06:45:57 2005 Subject: [Tutor] best way to scrape html Message-ID: <5ef6678005021521456ee5c006@mail.gmail.com> Which method is best and most pythonic to scrape text data with minimal formatting? I'm trying to read a large html file and strip out most of the markup, but leaving the simple formatting like <p>, <b>, and <i>. For example: <p class="BodyText" style="MARGIN: 0in 0in 12pt"><font face="Times New Roman"><b style="font-weight: normal"><span lang="EN-GB" style="FONT-SIZE: 12pt">Trigger:</span></b><span lang="EN-GB" style="FONT-SIZE: 12pt"><span style="spacerun: yes"> </span> Debate on budget in Feb-Mar. New moves to cut medical costs by better technology.</span></font></p> I want to change the above to: <p><b>Trigger:</b> Debate on budget in Feb-Mar. New moves to cutmedical costs by better technology.</p> Since I wanted some practice in regex, I started with something like this: pattern = "(?:<)(.+?)(?: ?.*?>)(.*?)(</\1>)" result = re.compile(pattern, re.IGNORECASE | re.VERBOSE | re.DOTALL).findall(html) But it's getting messy real fast and somehow the non-greedy parts don't seem to work as intended. Also I realized that the html file is going to be 10,000+ lines, so I wonder if regex can be used for large strings. So I'm thinking of using sgmllib.py (as in the Dive into Python example). Is this where I should be using libxml2.py? As you can tell this is my first foray into both parsing and regex so advice in terms of best practice would be very helpful. Thanks, Peter Kim From alan.gauld at freenet.co.uk Wed Feb 16 07:40:58 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Feb 16 07:42:45 2005 Subject: [Tutor] Case acceptance using raw_input References: <ea0feb80050215151613bb9a05@mail.gmail.com> Message-ID: <00ea01c513f2$79e150f0$2ca88651@xp> > Is there a better way for raw_input to accept both caps and lower case > letters than: > > def aFunction(): > action = raw_input("Perform an action?(y,n): ") > if action == 'y' or action == 'Y': if action in 'yY': > anotherFunction() > elif action == 'n' or action == 'N': elif action in 'nN': > yetAnotherFunction() > else: > aFunction() HTH, Alan G From alan.gauld at freenet.co.uk Wed Feb 16 07:48:18 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Feb 16 07:51:39 2005 Subject: [Tutor] best way to scrape html References: <5ef6678005021521456ee5c006@mail.gmail.com> Message-ID: <010d01c513f3$7fb4e770$2ca88651@xp> > Which method is best and most pythonic to scrape text data with > minimal formatting? Use the HTMLParser module. > I want to change the above to: > > <p><b>Trigger:</b> Debate on budget in Feb-Mar. New moves to > cutmedical costs by better technology.</p> > > Since I wanted some practice in regex, I started with something like this: Using regex is usually the wrong way to parse html for anything beyond the trivial. The parser module helps deal with the complexities. > So I'm thinking of using sgmllib.py (as in the Dive into Python > example). Is this where I should be using libxml2.py? As you can > tell this is my first foray into both parsing and regex so advice in > terms of best practice would be very helpful. There is an html parser which is built on the sgml one. Its rather more specific to your task. Alan G. From administrata at hotmail.com Wed Feb 16 11:26:46 2005 From: administrata at hotmail.com (. Sm0kin'_Bull) Date: Wed Feb 16 11:27:32 2005 Subject: [Tutor] Trivia program. Message-ID: <BAY22-F34F89048BF494C3282FF9CC86C0@phx.gbl> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050216/ccc363e4/attachment.htm From rschroev_nospam_ml at fastmail.fm Wed Feb 16 11:34:55 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Wed Feb 16 11:35:19 2005 Subject: [Tutor] Re: Basic terminology In-Reply-To: <797fe3d405021515095a42364a@mail.gmail.com> References: <797fe3d40502151330c59ef6e@mail.gmail.com> <Pine.LNX.4.44.0502151405110.31589-100000@hkn.eecs.berkeley.edu> <797fe3d405021515095a42364a@mail.gmail.com> Message-ID: <cuv7fh$dm5$1@sea.gmane.org> Bill Mill wrote: > However, where will it be pointing in 16 hours? Well, in 12 hours it > will be at the one, then four more hours later it will be pointing at > the five. This can be represented as: > > 1 + (16 % 12) = 1 + 4 = 5 Correcter is (1 + 16) % 12 = 17 % 12 = 5 > In general, the hour at some point in the future will be: > > (start time) + (hours in the future % 12) (start time + hours in the future) % 12 The difference can be seen in a small example: suppose it is 10 o'clock, and you want to know what it will be in 6 hours. Your formula gives 10 + (6 % 12) = 10 + 6 = 16 which is not correct (unless dealing with 24-hour systems of course, but that's not the case here) Correct is: (10 + 6) % 12 = 16 % 12 = 4 (In 24-hour systems, just replace 12 with 24) -- "Codito ergo sum" Roel Schroeven From kraus at hagen-partner.de Wed Feb 16 11:40:08 2005 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Wed Feb 16 11:40:23 2005 Subject: [Tutor] Re: Trivia program. In-Reply-To: <BAY22-F34F89048BF494C3282FF9CC86C0@phx.gbl> References: <BAY22-F34F89048BF494C3282FF9CC86C0@phx.gbl> Message-ID: <cuv7or$d78$1@sea.gmane.org> . Sm0kin'_Bull wrote: > Hi, I got a problem with this program. > > > name = raw_input("Hi. What's your name? ") > called = name * 5 called = ' '.join([name]*5) > print "\nIf a small child were trying to get your attention, " \ > "your name would become:" > print called > When i input the name like "John Goodman" > > it prints like... > > John GoodmanJohn GoodmanJohn GoodmanJohn GoodmanJohn Goodman > > But i want to print it like... > > John Goodman John Goodman John Goodman John Goodman John Goodman > > How can I do it? > [name]*5 gives you a list with five items, every item is name. join uses a space (' ') to join all items in the list into a new string. HTH, Wolfram From maxnoel_fr at yahoo.fr Wed Feb 16 11:39:48 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Wed Feb 16 11:43:48 2005 Subject: [Tutor] Trivia program. In-Reply-To: <BAY22-F34F89048BF494C3282FF9CC86C0@phx.gbl> References: <BAY22-F34F89048BF494C3282FF9CC86C0@phx.gbl> Message-ID: <be770203f67a05b5aed54d5f0fd0fe7c@yahoo.fr> On Feb 16, 2005, at 10:26, . Sm0kin'_Bull wrote: > it prints like... > ? > John GoodmanJohn GoodmanJohn GoodmanJohn GoodmanJohn Goodman > ? > But i want to print it like... > ? > John Goodman? John Goodman? John Goodman? John Goodman? John Goodman > ? > How can I do it? Try replacing the called = name * 5 line with: if not name.endswith(' '): called = ((name + ' ') * 5).strip() else: called = (name * 5).strip() -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From pierre.barbier at cirad.fr Wed Feb 16 11:46:09 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Wed Feb 16 11:44:27 2005 Subject: [Tutor] Trivia program. In-Reply-To: <BAY22-F34F89048BF494C3282FF9CC86C0@phx.gbl> References: <BAY22-F34F89048BF494C3282FF9CC86C0@phx.gbl> Message-ID: <42132471.9010505@cirad.fr> Mmmhh ... one very simple way would be to replace your first line by : name = raw_input("Hi. What's your name? ") + " " But if you want to keep the name as it is, I bet the best way is to replace your second line by : called = " ".join([ name for i in xrange(5) ]) The advantage of this second method is the " " is added only *between* the names, and not after ... Pierre . Sm0kin'_Bull a ?crit : > Hi, I got a problem with this program. > > > name = raw_input("Hi. What's your name? ") > called = name * 5 > print "\nIf a small child were trying to get your attention, " \ > "your name would become:" > print called > When i input the name like "John Goodman" > > it prints like... > > John GoodmanJohn GoodmanJohn GoodmanJohn GoodmanJohn Goodman > > But i want to print it like... > > John Goodman John Goodman John Goodman John Goodman John Goodman > > How can I do it? > > -------------------------------------------------------------------------------- > Express yourself instantly with MSN Messenger! MSN Messenger > <http://g.msn.com/8HMBEN/2728??PS=47575> Download today it's FREE! > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 From cyresse at gmail.com Wed Feb 16 11:55:40 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed Feb 16 11:55:43 2005 Subject: [Tutor] Trivia program. In-Reply-To: <42132471.9010505@cirad.fr> References: <BAY22-F34F89048BF494C3282FF9CC86C0@phx.gbl> <42132471.9010505@cirad.fr> Message-ID: <f2ff2d0502160255719c6f48@mail.gmail.com> Or name = raw_input("Hi. What's your name? ") called = "%s " % name On Wed, 16 Feb 2005 11:46:09 +0100, Pierre Barbier de Reuille <pierre.barbier@cirad.fr> wrote: > Mmmhh ... one very simple way would be to replace your first line by : > > name = raw_input("Hi. What's your name? ") + " " > > But if you want to keep the name as it is, I bet the best way is to > replace your second line by : > > called = " ".join([ name for i in xrange(5) ]) > > The advantage of this second method is the " " is added only *between* > the names, and not after ... > > Pierre > > . Sm0kin'_Bull a ?crit : > > Hi, I got a problem with this program. > > > > > > name = raw_input("Hi. What's your name? ") > > called = name * 5 > > print "\nIf a small child were trying to get your attention, " \ > > "your name would become:" > > print called > > When i input the name like "John Goodman" > > > > it prints like... > > > > John GoodmanJohn GoodmanJohn GoodmanJohn GoodmanJohn Goodman > > > > But i want to print it like... > > > > John Goodman John Goodman John Goodman John Goodman John Goodman > > > > How can I do it? > > > > -------------------------------------------------------------------------------- > > Express yourself instantly with MSN Messenger! MSN Messenger > > <http://g.msn.com/8HMBEN/2728??PS=47575> Download today it's FREE! > > > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > -- > Pierre Barbier de Reuille > > INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP > Botanique et Bio-informatique de l'Architecture des Plantes > TA40/PSII, Boulevard de la Lironde > 34398 MONTPELLIER CEDEX 5, France > > tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From kent37 at tds.net Wed Feb 16 11:58:07 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Feb 16 11:58:12 2005 Subject: [Tutor] dictionary dispatch for object instance attributes question In-Reply-To: <42127579.3080001@po-box.mcgill.ca> References: <42127579.3080001@po-box.mcgill.ca> Message-ID: <4213273F.4020905@tds.net> Brian van den Broek wrote: > My Node class defines a _parse method which separates out the node > header, and sends those lines to a _parse_metadata method. This is where > the elif chain occurs -- each line of the metadata starts with a tag > like "dt=" and I need to recognize each tag and set the appropriate Node > object attribute, such as .document_type. (I do not want to rely on the > unhelpful names for the tags in the file format, preferring more > self-documenting attribute names.) > > I've come up with *a* way to use a dictionary dispatch, but I'll wager a > great deal it isn't the *best* way. > > Here is a minimal illustration of what I have come up with: > > <code> > class A: > > def __init__(self): > > self.something = None > self.something_else = None > self.still_another_thing = None > > def update(self, data): > > for key in metadata_dict: > if data.startswith(key): > exec('''self.%s = """%s"""''' %(metadata_dict[key], > data[len(key):])) > # triple quotes as there may be quotes in metadata > # values > break > > metadata_dict = {'something_tag=': 'something', > '2nd_tag=': 'something_else', > 'last=': 'still_another_thing'} > > a = A() > print a.still_another_thing > a.update('last=the metadata value for the "last=" metadata tag') > print a.still_another_thing > </code> > > <output> > >>> > None > the metadata value for the "last=" metadata tag > </output> > > So, it works. Yay :-) > > But, should I be doing it another way? Another way to do this is to use dispatch methods. If you have extra processing to do for each tag, this might be a good way to go. I'm going to assume that your data lines have the form 'tag=data'. Then your Node class might have methods that look like this: class Node: ... def parse_metadata(self, line): tag, data = line.split('=', 1) try: handler = getattr(self, 'handle_' + tag) except AttributeError: print 'Unexpected tag:', tag, data else: handler(data) def handle_something_tag(self, data): self.something = int(data) # for example def handle_last(self, data): try: self.another_thing.append(data) # attribute is a list except AttributeError: self.another_thing = [data] and so on. This organization avoids any if / else chain and puts all the processing for each tag in a single place. BTW the try / except / else idiom is used here to avoid catching unexpected exceptions. The naive way to write it would be try: handler = getattr(self, 'handle_' + tag) handler(data) except AttributeError: print 'Unexpected tag:', tag, data The problem with this is that if handler() raise AttributeError you will get an unhelpful error message and no stack trace. Putting the call to handler() in an else clause puts it out of the scope of the try / except but it will still be executed only if the getattr succeeds. > Also, I know the general security concerns about things like exec. They > make me nervous in using it, even though I am (as yet) the sole user. Am > I right in thinking that the constrained way I am using it here protects > me? My code uses most of the attributes as a simple storage container > for later rewriting of the file, but in a few cases they enter into > (safe seeming) conditionals like: > > if 'text' == self.document_type: > self.do_text_stuff() > if 'RTF' == self.document_type: > self.do_RTF_stuff() Conditionals on a 'type' flag are a code smell that suggests using subclasses. Maybe you should have a TextNode class and an RtfNode class. Then the above becomes just self.do_stuff() and TextNode and RtfNode each have the appropriate implementations of do_stuff(). I'm not saying this is the right choice for you, just something you might consider. Kent > > Thanks and best to all, > > Brian vdB > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Wed Feb 16 12:20:22 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Feb 16 12:20:27 2005 Subject: [Tutor] best way to scrape html In-Reply-To: <5ef6678005021521456ee5c006@mail.gmail.com> References: <5ef6678005021521456ee5c006@mail.gmail.com> Message-ID: <42132C76.5000302@tds.net> You might find these threads on comp.lang.python interesting: http://tinyurl.com/5zmpn http://tinyurl.com/6mxmb Peter Kim wrote: > Which method is best and most pythonic to scrape text data with > minimal formatting? > > I'm trying to read a large html file and strip out most of the markup, > but leaving the simple formatting like <p>, <b>, and <i>. For example: > > <p class="BodyText" style="MARGIN: 0in 0in 12pt"><font face="Times New > Roman"><b style="font-weight: normal"><span lang="EN-GB" > style="FONT-SIZE: 12pt">Trigger:</span></b><span lang="EN-GB" > style="FONT-SIZE: 12pt"><span style="spacerun: yes"> </span> > Debate on budget in Feb-Mar. New moves to cut medical costs by better > technology.</span></font></p> > > I want to change the above to: > > <p><b>Trigger:</b> Debate on budget in Feb-Mar. New moves to > cutmedical costs by better technology.</p> > > Since I wanted some practice in regex, I started with something like this: > > pattern = "(?:<)(.+?)(?: ?.*?>)(.*?)(</\1>)" > result = re.compile(pattern, re.IGNORECASE | re.VERBOSE | > re.DOTALL).findall(html) > > But it's getting messy real fast and somehow the non-greedy parts > don't seem to work as intended. Also I realized that the html file is > going to be 10,000+ lines, so I wonder if regex can be used for large > strings. > > So I'm thinking of using sgmllib.py (as in the Dive into Python > example). Is this where I should be using libxml2.py? As you can > tell this is my first foray into both parsing and regex so advice in > terms of best practice would be very helpful. > > Thanks, > Peter Kim > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Wed Feb 16 13:41:58 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Feb 16 13:42:02 2005 Subject: [Tutor] dictionary dispatch for object instance attributes question In-Reply-To: <4213273F.4020905@tds.net> References: <42127579.3080001@po-box.mcgill.ca> <4213273F.4020905@tds.net> Message-ID: <42133F96.5000402@tds.net> Kent Johnson wrote: > Another way to do this is to use dispatch methods. If you have extra > processing to do for each tag, this might be a good way to go. > > I'm going to assume that your data lines have the form 'tag=data'. Then > your Node class might have methods that look like this: > > class Node: > ... > def parse_metadata(self, line): > tag, data = line.split('=', 1) > try: > handler = getattr(self, 'handle_' + tag) > except AttributeError: > print 'Unexpected tag:', tag, data > else: > handler(data) > > def handle_something_tag(self, data): > self.something = int(data) # for example > > def handle_last(self, data): > try: > self.another_thing.append(data) # attribute is a list > except AttributeError: > self.another_thing = [data] > > and so on. This organization avoids any if / else chain and puts all the > processing for each tag in a single place. One more idea. If you have 20 different tags but only four different ways of processing them, maybe you want to use a dict that maps from the tag name to a tuple of (attribute name, processing method). With this approach you need only four handler methods instead of 20. It would look like this: metadata_dict = { 'something_tag' : ( 'something', self.handle_int ), 'last' : ( 'another_thing', self.handle_list ), } def parse_metadata(self, line): tag, data = line.split('=', 1) try: attr_name, handler = metadata_dict[tag] except AttributeError: print 'Unexpected tag:', tag, data else: handler(attr_name, data) def handle_int(self, attr_name, data): setattr(self, attr_name, int(data)) def handle_list(self, attr_name, data): l = getattr(self, attr_name, []) l.append(data) setattr(self, attr_name, l) I-have-to-stop-replying-to-my-own-posts-ly yours, Kent From zanesdad at bellsouth.net Wed Feb 16 13:50:24 2005 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Wed Feb 16 13:52:12 2005 Subject: [Tutor] Queued threads In-Reply-To: <f2ff2d050215195016f9e5d5@mail.gmail.com> References: <4212A8B7.8060005@bernardlebel.com> <f2ff2d050215183662ba997b@mail.gmail.com> <4212B5CC.5030102@bernardlebel.com> <f2ff2d050215195016f9e5d5@mail.gmail.com> Message-ID: <42134190.50802@bellsouth.net> Not to beat a dead horse, but.... Liam Clarke wrote: >Oops, you probably want to do this then- > >for i in range( 0, 3 ): > oThread = Thread( target=mainFunction ).start() > > Thread.start() looks like it returns None. ############################# In [23]: from threading import Thread In [24]: import time In [25]: def foo(): ....: print "doing..." ....: time.sleep(15) ....: print "done...." ....: In [26]: t = Thread(target=foo).start() doing... In [27]: print t None In [28]: done.... In [28]: print t None In [29]: t = Thread(target=foo) In [30]: t.start() doing... In [31]: t.isAlive() Out[31]: True In [32]: done.... In [32]: t.isAlive() Out[32]: False ############################# So, checking the return of Thread.start() doesn't seem like it would do what you think it would do. You probably want to get the thread object and check that directly with isAlive(). Oh, and if you spawn a bunch of threads at once and you want to wait until the all complete before doing something else, do something like this: ############################# #create a list to contain the threads thread_list = [] for i in range(10): t = Thread(target=foo) print "creating thread", t #put each thread in the list thread_list.append(t) #iterate over thread list and start each thread for t in thread_list: print "starting thread", t t.start() #iterate over thread list and wait for each thread for t in thread_list: print "waiting for thread", t while 1: if not t.isAlive(): break time.sleep(.2) ############################# It'll give you output something like this: ############################# creating thread <Thread(Thread-35, initial)> creating thread <Thread(Thread-36, initial)> creating thread <Thread(Thread-37, initial)> creating thread <Thread(Thread-38, initial)> creating thread <Thread(Thread-39, initial)> creating thread <Thread(Thread-40, initial)> creating thread <Thread(Thread-41, initial)> creating thread <Thread(Thread-42, initial)> creating thread <Thread(Thread-43, initial)> creating thread <Thread(Thread-44, initial)> starting thread <Thread(Thread-35, initial)> starting thread <Thread(Thread-36, initial)> starting thread <Thread(Thread-37, initial)> starting thread <Thread(Thread-38, initial)> doing... starting thread <Thread(Thread-39, initial)> doing... doing... starting thread <Thread(Thread-40, initial)> doing... starting thread doing... <Thread(Thread-41, initial)> doing... starting thread <Thread(Thread-42, initial)> starting thread <Thread(Thread-43, initial)> starting thread <Thread(Thread-44, initial)> doing... doing... doing... waiting for thread <Thread(Thread-35, started)> doing... done.... done.... done.... done.... done.... done.... waiting for thread <Thread(Thread-36, stopped)> waiting for thread <Thread(Thread-37, stopped)> waiting for thread done.... done.... done.... done.... <Thread(Thread-38, stopped)> waiting for thread <Thread(Thread-39, stopped)> waiting for thread <Thread(Thread-40, stopped)> waiting for thread <Thread(Thread-41, stopped)> waiting for thread <Thread(Thread-42, stopped)> waiting for thread <Thread(Thread-43, stopped)> waiting for thread <Thread(Thread-44, stopped)> ################################# But in this situation, I totally agree with Max. You don't need threads for this. Just use os.system. You could use one of the popens (or the new subprocess module - never used that one myself), but os.system blocks until the called program exits. > while oThread: > print 'sleeping 3 seconds' > time.sleep( 3 ) > >A if <condition> generally has an implicit else: pass clause as I >think of it, so it will just keep reiterating if the condition isn't >met. > > Jeremy Joens From administrata at hotmail.com Wed Feb 16 15:15:24 2005 From: administrata at hotmail.com (. Sm0kin'_Bull) Date: Wed Feb 16 15:17:25 2005 Subject: [Tutor] Problem with variables Message-ID: <BAY22-F17A8C1AD32C527F66CE831C86C0@phx.gbl> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050216/1b882650/attachment.html From administrata at hotmail.com Wed Feb 16 15:16:54 2005 From: administrata at hotmail.com (. Sm0kin'_Bull) Date: Wed Feb 16 15:17:32 2005 Subject: [Tutor] Problems in making calulating program. Message-ID: <BAY22-F296566BC841DF94519EE6DC86C0@phx.gbl> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050216/d0ed06e1/attachment.htm From zanesdad at bellsouth.net Wed Feb 16 15:45:27 2005 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Wed Feb 16 15:47:14 2005 Subject: [Tutor] Problem with variables In-Reply-To: <BAY22-F17A8C1AD32C527F66CE831C86C0@phx.gbl> References: <BAY22-F17A8C1AD32C527F66CE831C86C0@phx.gbl> Message-ID: <42135C87.8060609@bellsouth.net> . Sm0kin'_Bull wrote: > > wrote this, It's a bit lame though > > I = "Allen" > me = "Allen" > my = "Allen's" > > print \ > """ > %s woke up early in the morning. But, it was unusal by %s. %s pillow > was with %s. %s didn't want to wake up But, %s tried my best and woke up. > it was so amazing!""" % (I,me,my,me,I,I) > > raw_input("\n\\t\t\t- The End -") > > But it looks like this... > > Allen woke up early in the morning. But, it was unusal by Allen. > Allen's pillow > was with Allen. Allen didn't want to wake up But, Allen tried my best > and woke up. > it was so amazing > > - The End - > >the problem is about lining > > >I want it to print like this... > > >Allen woke up early in the morning. But, it was unusal by Allen. >Allen's pillow was with Allen. Allen didn't want to wake up But, Allen >tried my best and woke up. it was so amazing > > > This is what I got: ######################## In [45]: I = "Allen" In [46]: me = "Allen" In [47]: my = "Allen's" In [48]: In [48]: print \ ....: """ ....: %s woke up early in the morning. But, it was unusal by %s. %s pillow ....: was with %s. %s didn't want to wake up But, %s tried my best and woke up. ....: it was so amazing!""" % (I,me,my,me,I,I) Allen woke up early in the morning. But, it was unusal by Allen. Allen's pillow was with Allen. Allen didn't want to wake up But, Allen tried my best and woke up. it was so amazing! ######################## It looks like it should. If you want it to show up exactly like posted at the end, you need something more like this: ######################## In [50]: print \ ....: """ ....: %s woke up early in the morning. But, it was unusal by %s. ....: %s pillow was with %s. %s didn't want to wake up But, %s ....: tried my best and woke up. it was so amazing!""" % (I,me,my,me,I,I) Allen woke up early in the morning. But, it was unusal by Allen. Allen's pillow was with Allen. Allen didn't want to wake up But, Allen tried my best and woke up. it was so amazing! ########################### Jeremy Jones > ** > > ------------------------------------------------------------------------ > FREE pop-up blocking with the new MSN Toolbar MSN Toolbar > <http://g.msn.com/8HMAEN/2755??PS=47575> Get it now! > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050216/bff6d70b/attachment.html From bill.mill at gmail.com Wed Feb 16 16:00:30 2005 From: bill.mill at gmail.com (Bill Mill) Date: Wed Feb 16 16:01:01 2005 Subject: [Tutor] Re: Basic terminology In-Reply-To: <cuv7fh$dm5$1@sea.gmane.org> References: <797fe3d40502151330c59ef6e@mail.gmail.com> <Pine.LNX.4.44.0502151405110.31589-100000@hkn.eecs.berkeley.edu> <797fe3d405021515095a42364a@mail.gmail.com> <cuv7fh$dm5$1@sea.gmane.org> Message-ID: <797fe3d405021607002a6f8b44@mail.gmail.com> On Wed, 16 Feb 2005 11:34:55 +0100, Roel Schroeven <rschroev_nospam_ml@fastmail.fm> wrote: > Bill Mill wrote: > > However, where will it be pointing in 16 hours? Well, in 12 hours it > > will be at the one, then four more hours later it will be pointing at > > the five. This can be represented as: > > > > 1 + (16 % 12) = 1 + 4 = 5 > > Correcter is > > (1 + 16) % 12 = 17 % 12 = 5 d'oh! thanks for the correction. > > > In general, the hour at some point in the future will be: > > > > (start time) + (hours in the future % 12) > > (start time + hours in the future) % 12 > Peace Bill Mill bill.mill at gmail.com From bgailer at alum.rpi.edu Wed Feb 16 17:07:57 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed Feb 16 17:07:54 2005 Subject: [Tutor] Case acceptance using raw_input In-Reply-To: <00ea01c513f2$79e150f0$2ca88651@xp> References: <ea0feb80050215151613bb9a05@mail.gmail.com> <00ea01c513f2$79e150f0$2ca88651@xp> Message-ID: <6.1.2.0.0.20050216090525.034358a8@mail.mric.net> At 11:40 PM 2/15/2005, Alan Gauld wrote: > Is there a better way for raw_input to accept both caps and lower >case letters than: > > def aFunction(): > action = raw_input("Perform an action?(y,n): ") action = raw_input("Perform an action?(y,n): ").upper() > if action == 'y' or action == 'Y': if action == 'Y': > anotherFunction() etc. Bob Gailer mailto:bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From bvande at po-box.mcgill.ca Wed Feb 16 20:04:45 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed Feb 16 20:25:42 2005 Subject: [Tutor] dictionary dispatch for object instance attributes question In-Reply-To: <4213273F.4020905@tds.net> References: <42127579.3080001@po-box.mcgill.ca> <4213273F.4020905@tds.net> Message-ID: <4213994D.9000205@po-box.mcgill.ca> Kent Johnson said unto the world upon 2005-02-16 05:58: > Brian van den Broek wrote: <SNIP Kent's useful explanation of how to use handlers> >> Also, I know the general security concerns about things like exec. >> They make me nervous in using it, even though I am (as yet) the sole >> user. Am I right in thinking that the constrained way I am using it >> here protects me? My code uses most of the attributes as a simple >> storage container for later rewriting of the file, but in a few cases >> they enter into (safe seeming) conditionals like: >> >> if 'text' == self.document_type: >> self.do_text_stuff() >> if 'RTF' == self.document_type: >> self.do_RTF_stuff() > > > Conditionals on a 'type' flag are a code smell that suggests using > subclasses. Maybe you should have a TextNode class and an RtfNode class. > Then the above becomes just > self.do_stuff() > > and TextNode and RtfNode each have the appropriate implementations of > do_stuff(). > > I'm not saying this is the right choice for you, just something you > might consider. > > Kent Hi Kent, thanks for the snipped discussion on handlers -- very useful. As for the code smell thing, I have a follow-up question. I now get the point of the type-based conditional being a smell for classes. (I get it due to a previous thread that an over-enthusiastic inbox purge prevents me from citing with certainty, but I think it was Bill and Alan who clarified it for me.) My problem is that I've got a lot of code which was written before I got that point and my code doesn't yet actually do much. (I do have working code for parsing my original source files and storing all of their metadata, etc., but I haven't yet got working code for doing the manipulating the data in the ways I want.) I had been thinking better to get everything working and then refactor. Is that an unsound approach? My worry about refactoring now is that I feel like I am rearranging deck-chairs when I should be worried about getting the ship to float :-) Thanks and best to all, Brian vdB From bvande at po-box.mcgill.ca Wed Feb 16 20:49:16 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed Feb 16 20:49:32 2005 Subject: [Tutor] dictionary dispatch for object instance attributes question In-Reply-To: <4213994D.9000205@po-box.mcgill.ca> References: <42127579.3080001@po-box.mcgill.ca> <4213273F.4020905@tds.net> <4213994D.9000205@po-box.mcgill.ca> Message-ID: <4213A3BC.9090202@po-box.mcgill.ca> Brian van den Broek said unto the world upon 2005-02-16 14:04: > Kent Johnson said unto the world upon 2005-02-16 05:58: >>> >>> if 'text' == self.document_type: >>> self.do_text_stuff() >>> if 'RTF' == self.document_type: >>> self.do_RTF_stuff() >> >> Conditionals on a 'type' flag are a code smell that suggests using >> subclasses. Maybe you should have a TextNode class and an RtfNode >> class. Then the above becomes just >> self.do_stuff() >> >> and TextNode and RtfNode each have the appropriate implementations of >> do_stuff(). >> >> I'm not saying this is the right choice for you, just something you >> might consider. >> >> Kent > > > Hi Kent, > > thanks for the snipped discussion on handlers -- very useful. <SNIP> > I had been thinking better to get everything working and then refactor. > Is that an unsound approach? My worry about refactoring now is that I > feel like I am rearranging deck-chairs when I should be worried about > getting the ship to float :-) > > Thanks and best to all, > > Brian vdB Hi all, as applied to my particular case -- strike the above. I just spent some time looking at my code and playing in the interpreter and have come to the conclusion that, in this case at least, the refactor Kent suggested isn't playing with deck chairs. It's more like installing bulkheads. Thanks and best, Brian vdB From kent37 at tds.net Wed Feb 16 21:02:03 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Feb 16 21:02:07 2005 Subject: [Tutor] dictionary dispatch for object instance attributes question In-Reply-To: <4213994D.9000205@po-box.mcgill.ca> References: <42127579.3080001@po-box.mcgill.ca> <4213273F.4020905@tds.net> <4213994D.9000205@po-box.mcgill.ca> Message-ID: <4213A6BB.1080708@tds.net> Brian van den Broek wrote: > As for the code smell thing, I have a follow-up question. I now get the > point of the type-based conditional being a smell for classes. (I get it > due to a previous thread that an over-enthusiastic inbox purge prevents > me from citing with certainty, but I think it was Bill and Alan who > clarified it for me.) > > My problem is that I've got a lot of code which was written before I got > that point and my code doesn't yet actually do much. (I do have working > code for parsing my original source files and storing all of their > metadata, etc., but I haven't yet got working code for doing the > manipulating the data in the ways I want.) > > I had been thinking better to get everything working and then refactor. > Is that an unsound approach? My worry about refactoring now is that I > feel like I am rearranging deck-chairs when I should be worried about > getting the ship to float :-) It's a hard question because it really comes down to programming style and judgement. I like to work in a very incremental style - design a little, code a little, test a little, repeat as needed. I believe in 'Refactor Mercilessly' - another XP slogan. I have many years experience and a well-developed opinion of what is good design and bad design. One consequence of this style is, I usually have working code and tests to go with it. It may not do very much, but it works. So for me, if I smell something, and think that refactoring into subclasses - or some other change - is the best design for the problem as I understand it, I will probably do the refactoring. It's not going to be easier tomorrow :-) If it just smells a little, or the refactoring is major, I might think about how to get rid of the smell but put it off until I'm pretty sure it is a good idea. I don't think of this as rearranging the deck chairs - it's more like building the right foundation. Clean, expressive, well-designed code is a pleasure to work with. For you, it's probably not so cut-and-dried. If you don't have the experience to judge how bad a smell is, or to think through the possibilities so clearly, it's harder to know how to proceed. If you are in part dabbling with OOP design to learn about it, maybe you want to put off some changes until the code is working; then you could make the change and do a comparison and see which one feels cleaner to you. I hope this helps at least a little :-) Kent From jeffshannon at gmail.com Wed Feb 16 21:49:38 2005 From: jeffshannon at gmail.com (Jeff Shannon) Date: Wed Feb 16 21:49:41 2005 Subject: [Tutor] Queued threads In-Reply-To: <f2ff2d050215195016f9e5d5@mail.gmail.com> References: <4212A8B7.8060005@bernardlebel.com> <f2ff2d050215183662ba997b@mail.gmail.com> <4212B5CC.5030102@bernardlebel.com> <f2ff2d050215195016f9e5d5@mail.gmail.com> Message-ID: <5d0204a105021612492a1665bd@mail.gmail.com> On Wed, 16 Feb 2005 16:50:07 +1300, Liam Clarke <cyresse@gmail.com> wrote: > Oops, you probably want to do this then- > > for i in range( 0, 3 ): > oThread = Thread( target=mainFunction ).start() > > while oThread: > print 'sleeping 3 seconds' > time.sleep( 3 ) Probably not. Note that, since oThread's value is not changed in the body of this while loop, you will either never execute the body (if oThread is false) or execute it infintely many times (if oThread is true). I doubt that's the desired behavior. ;) In this case, since Thread.start() apparently always returns None, the while loop is effectively a no-op. However, if it *did* get triggered, it would do so immediately after the first thread [which returned a true value from start()] was started -- preventing later threads from being started because the main program is stuck in this endless loop. You could perhaps rewrite the whole thing like this: .for i in range(3): . mythread = Thread(target=mainFunction) . mythread.start() . while mythread.isAlive(): . print "sleeping 3 seconds [main thread]" . time.sleep(3) Though as others have said, if you're not starting the second thread until the first is finished, then you might as well just make it explicitly sequental and not bother with threads: .for i in range(3): . mainFunction() If you actually want the threads to process concurrently, and simply wait until all of them are done, you could do this: .threadlist = [] .for i in range (3): . mythread = Thread(target=mainFunction) . mythread.start() . threadlist.append(mythread) .for thread in threadlist: . thread.join() The join() method will wait until that thread is finished, and then return. If the thread is already finished when it's called, it returns immediately. Jeff Shannon From jeffshannon at gmail.com Wed Feb 16 22:09:28 2005 From: jeffshannon at gmail.com (Jeff Shannon) Date: Wed Feb 16 22:09:31 2005 Subject: [Tutor] dictionary dispatch for object instance attributes question In-Reply-To: <4212D09F.5010601@po-box.mcgill.ca> References: <42127579.3080001@po-box.mcgill.ca> <5d0204a105021518204d86acc9@mail.gmail.com> <4212D09F.5010601@po-box.mcgill.ca> Message-ID: <5d0204a10502161309775723c5@mail.gmail.com> On Tue, 15 Feb 2005 23:48:31 -0500, Brian van den Broek <bvande@po-box.mcgill.ca> wrote: > Jeff Shannon said unto the world upon 2005-02-15 21:20: > > On Tue, 15 Feb 2005 17:19:37 -0500, Brian van den Broek > > <bvande@po-box.mcgill.ca> wrote: > > > > For starters, I've made metadata a class attribute rather than an > > unconnected dictionary. This seems conceptually nicer to me. > > The problem is that my Node instance live in a TP_file class instance, > and the way my code is now, the TP_file instance also needs to see the > metadata dict. There are a few tags, which if present in any Node of > the file make me want to treat the entire file a bit differently. (Of > course, here is the place where my novice-designer status is most > likely to be bitting me.) So, that's why I have it as a module level > object, rather than within a class. (I do, however, see your point > about it being neater.) Okay, that makes sense. You have two different classes (the TP_file class and the Node class) that need access to the same information, so yes, having it at the module level lets them share it more effectively. (Alternately, since it sounds like the TP_file class is where all of the Node instances are created, you *could* decide that the metadata belongs as part of the TP_file, which would then actively share it with Node... but what you've got sounds like a very reasonable plan, so at this point I wouldn't worry about it.) > > In addition, update() can now modify several attributes at once, at > > the cost of a bit of extra parsing up front. > > The metadata all occurs one element to a line in my original file. > [...] Maybe I'm still missing a better way, but as I am processing > line by line, each line with one element, I don't see how to use this > cool looking multiple elements at once approach. Yes, if you know that you will only have one header per line, then it's reasonable to process them one line at a time. You could alternatively have the TP_file gather all the header lines for a given node into a list, and then process that list to create the Node instance, but given the specifics of your case you probably wouldn't gain anything over your current approach by doing so. This is what makes programming so interesting -- there's so many different choices possible, and which one is best depends on a large number of factors. When writing a program for some task, the best design for a particular set of circumstances may be completely different than the best design for a somewhat different particular set of circumstances -- and the best design for general usage is probably an altogether different thing still. Good luck! Jeff Shannon From carroll at tjc.com Wed Feb 16 22:18:41 2005 From: carroll at tjc.com (Terry Carroll) Date: Wed Feb 16 22:18:44 2005 Subject: ****SPAM(11.2)**** [Tutor] Larger program organization In-Reply-To: <6.1.2.0.0.20050211132921.036258d8@mail.mric.net> Message-ID: <Pine.LNX.4.44.0502161315220.23025-100000@violet.rahul.net> On Fri, 11 Feb 2005, Bob Gailer wrote: > Whenever you find yourself writing an if statement ask whether this > would be better handled by subclasses. Whenever you find yourself about > to write a global statement, consider making the variables properties of > a class. Bob -- Brian already asked for an explanation of your first statement, and I found the ensuing discussion very instructive. Can you explain the second? As an aesthetic point, I hate globals, and I'd love a discussion with some examples of using class variables as a way of avoiding this. Terry From lgxjcb at nottingham.ac.uk Wed Feb 16 22:37:10 2005 From: lgxjcb at nottingham.ac.uk (Chris Bromley) Date: Wed Feb 16 22:42:17 2005 Subject: [Tutor] Help needed with script to batch-create shapefiles Message-ID: <s213be34.015@ccw0m1.nottingham.ac.uk> Dear all, I have several thousand files in dBaseIV format that I need to convert to shapefiles for use in ArcGIS. I've written a script (see below) to automate this process but thus far have been unable to get it to work. I suspect that there's a simple reason for this, but I'm a complete novice with Python and have been unable to find it. Any help would be greatly appreciated! Regards, Chris Bromley ##Script Name: dBase Table to Shapefile ##Description: Converts dBase files to shapefiles ##Created By: Chris Bromley. ##Date: 16/02/2005 # Import system modules import sys, string, os, win32com.client # Create the Geoprocessor object gp = win32com.client.Dispatch("esriGeoprocessing.GpDispatch.1") try: # Load required toolboxes... gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Conversion Tools.tbx") gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx") #Define & create variables to contain the source files and output file location paths gp.workspace = "C:\PhD\ElwhaRiverProject\Physical_modelling\Model_Data_Corrected\Tester3\One" out_workspace = "C:\PhD\ElwhaRiverProject\Physical_modelling\Model_Data_Corrected\Tester3" # Get a list of the dBase tables in the workspace fcs = gp.ListTables("*","dBase") # Loop through the list of feature classes fcs.reset() fc = fcs.next() while fc: # Set the output filename for each output to be the same as the input filename output = out_workspace + fc # Process: Make XY Event Layer... gp.MakeXYEventLayer_management(fc, "x", "y", output, "") # Process: Feature Class To Shapefile (multiple)... gp.FeatureClassToShapefile_conversion(output, out_workspace, ) fc = fcs.next() except: gp.AddMessage(gp.GetMessages(2)) print gp.GetMessages(2) This message has been checked for viruses but the contents of an attachment may still contain software viruses, which could damage your computer system: you are advised to perform your own checks. Email communications with the University of Nottingham may be monitored as permitted by UK legislation. From bvande at po-box.mcgill.ca Wed Feb 16 22:42:46 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed Feb 16 22:43:08 2005 Subject: [Tutor] dictionary dispatch for object instance attributes question In-Reply-To: <4213A6BB.1080708@tds.net> References: <42127579.3080001@po-box.mcgill.ca> <4213273F.4020905@tds.net> <4213994D.9000205@po-box.mcgill.ca> <4213A6BB.1080708@tds.net> Message-ID: <4213BE56.4000109@po-box.mcgill.ca> Kent Johnson said unto the world upon 2005-02-16 15:02: > Brian van den Broek wrote: <SNIP> >> I had been thinking better to get everything working and then >> refactor. Is that an unsound approach? My worry about refactoring now >> is that I feel like I am rearranging deck-chairs when I should be >> worried about getting the ship to float :-) > > It's a hard question because it really comes down to programming style > and judgement. > > I like to work in a very incremental style - design a little, code a > little, test a little, repeat as needed. I believe in 'Refactor > Mercilessly' - another XP slogan. I have many years experience and a > well-developed opinion of what is good design and bad design. > > One consequence of this style is, I usually have working code and tests > to go with it. It may not do very much, but it works. > > So for me, if I smell something, and think that refactoring into > subclasses - or some other change - is the best design for the problem > as I understand it, I will probably do the refactoring. It's not going > to be easier tomorrow :-) If it just smells a little, or the refactoring > is major, I might think about how to get rid of the smell but put it off > until I'm pretty sure it is a good idea. > > I don't think of this as rearranging the deck chairs - it's more like > building the right foundation. Clean, expressive, well-designed code is > a pleasure to work with. > > For you, it's probably not so cut-and-dried. If you don't have the > experience to judge how bad a smell is, or to think through the > possibilities so clearly, it's harder to know how to proceed. If you are > in part dabbling with OOP design to learn about it, maybe you want to > put off some changes until the code is working; then you could make the > change and do a comparison and see which one feels cleaner to you. > > I hope this helps at least a little :-) > > Kent Hi Kent, I see my `strike that' msg. didn't get through in time, to save you from the reply. But, from the selfish perspective, I'm glad enough about that; the above does indeed help more than a little. I get, in the abstract at least, how Test Driven Development would make these refactorings much easier to do with confidence. (Somewhere near half the point, isn't it?) The goal of my current project, beyond the given of having useful code, is to write a medium sized project in OOP. At the outset, I felt I had to choose between getting a handle on OOP or TDD. I felt I could only tackle one new paradigm at a time. I went with OOP as I didn't want to spend the effort of getting procedural code down using TDD and then have to redo it in OOP. But, not having test does make the refactoring more scary than I imagine it would be tests in hand. And I would have had the need to redo it, I think. The file format I am working with is from an application I've been using as a PIM/Knowledge manager for several years. So, I've got tons of data and tons of plans. I'm not certain if the term is the right one, but I'm thinking of the code I am working on as a base toolset or `framework' for all the other things I want to do with the files of that format. Thus, subclassing and other OOP techniques are sure to be important for those plans. But, I think you hit it right on the head -- my inexperience with OOP doesn't provide me with any metric for judgement about these things. Browsing through things like Fowler, Beck, Brant, & Opdyke's _Refactoring_, while fun, doesn't help much without my having struggled with my own OOP code first. Hey, yesterday I proved that having read about setattr numerous times is no guarantee I'll remember it the first time a use case comes up :-) Thanks for the continued efforts to help me `get' it. Best to all, Brian vdB From bill.mill at gmail.com Wed Feb 16 22:47:26 2005 From: bill.mill at gmail.com (Bill Mill) Date: Wed Feb 16 22:47:30 2005 Subject: [Tutor] Help needed with script to batch-create shapefiles In-Reply-To: <s213be34.015@ccw0m1.nottingham.ac.uk> References: <s213be34.015@ccw0m1.nottingham.ac.uk> Message-ID: <797fe3d405021613474b854060@mail.gmail.com> Chris, On Wed, 16 Feb 2005 21:37:10 +0000, Chris Bromley <lgxjcb@nottingham.ac.uk> wrote: > Dear all, > > I have several thousand files in dBaseIV format that I need to convert to shapefiles for use in ArcGIS. I've written a script (see below) to automate this process but thus far have been unable to get it to work. I suspect that there's a simple reason for this, but I'm a complete novice with Python and have been unable to find it. > > Any help would be greatly appreciated! > > Regards, > > Chris Bromley <snip script> What you've written translates, in newsgroup-speak, to "Will somebody write this script for me that I need?" Boil your question down into something smaller, and then ask it with the appropriate information. I suggest reading http://www.catb.org/~esr/faqs/smart-questions.html . Peace Bill Mill bill.mill at gmail.com From bvande at po-box.mcgill.ca Wed Feb 16 22:49:21 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed Feb 16 22:50:42 2005 Subject: [Tutor] dictionary dispatch for object instance attributes question In-Reply-To: <5d0204a10502161309775723c5@mail.gmail.com> References: <42127579.3080001@po-box.mcgill.ca> <5d0204a105021518204d86acc9@mail.gmail.com> <4212D09F.5010601@po-box.mcgill.ca> <5d0204a10502161309775723c5@mail.gmail.com> Message-ID: <4213BFE1.1070005@po-box.mcgill.ca> Jeff Shannon said unto the world upon 2005-02-16 16:09: > On Tue, 15 Feb 2005 23:48:31 -0500, Brian van den Broek > <bvande@po-box.mcgill.ca> wrote: <SNIP some of Jeff's responses to my evaluation of his earlier suggestions> > Yes, if you know that you will only have one header per line, then > it's reasonable to process them one line at a time. You could > alternatively have the TP_file gather all the header lines for a given > node into a list, and then process that list to create the Node > instance, but given the specifics of your case you probably wouldn't > gain anything over your current approach by doing so. > > This is what makes programming so interesting -- there's so many > different choices possible, and which one is best depends on a large > number of factors. When writing a program for some task, the best > design for a particular set of circumstances may be completely > different than the best design for a somewhat different particular set > of circumstances -- and the best design for general usage is probably > an altogether different thing still. > > Good luck! > > Jeff Shannon Thanks Jeff, the confirmation that my assessment made sense is very helpful. Due to the my lack of experience (as discussed in my response to Kent) I'm always uncomfortable rejecting a proposed solution -- is my assessment that the solution isn't the best a product of that inexperience, or am I on to something? So, thanks for taking the time to `bless' my assessment. Best to all, Brian vdB From bvande at po-box.mcgill.ca Wed Feb 16 23:04:25 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed Feb 16 23:06:04 2005 Subject: ****SPAM(11.2)**** [Tutor] Larger program organization In-Reply-To: <Pine.LNX.4.44.0502161315220.23025-100000@violet.rahul.net> References: <Pine.LNX.4.44.0502161315220.23025-100000@violet.rahul.net> Message-ID: <4213C369.4010602@po-box.mcgill.ca> Terry Carroll said unto the world upon 2005-02-16 16:18: > On Fri, 11 Feb 2005, Bob Gailer wrote: > > >>Whenever you find yourself writing an if statement ask whether this >>would be better handled by subclasses. Whenever you find yourself about >>to write a global statement, consider making the variables properties of >>a class. > > > Bob -- > > Brian already asked for an explanation of your first statement, and I > found the ensuing discussion very instructive. > > Can you explain the second? As an aesthetic point, I hate globals, and > I'd love a discussion with some examples of using class variables as a way > of avoiding this. > > Terry Hi Terry and all, I'm probably not the best person to explain this, but I've got a use case that might help illustrate. The thing that finally got me to write my first Class statement was a procedural program where I had a hard to find bug. I wrote a debug_report function which would print out an informative report about the state of all the objects I suspected were implicated in the bug. Then, I put debug_report calls at the suspicious places. But, my procedural code had function call chains 4 or 5 links deep, and at no level did any of the functions have access to all of the objects of interest. To make it work in purely procedural, I had to either make many objects global or litter my functions with passing objects up and down as parameters that weren't needed for the function's tasks, but simply so debug_report could see them. I made a class, put my functions in it, and suddenly, they all could `see' the objects of interest without the passing and returning of objects just for the sake of visibility. Some `self's sprinkled around did the work instead. So, even if you don't make use of further OOP features (as I am learning to do on other threads), classes give you a namespace option between globals and locals -- `continentals' if you like ;-) HTH, and looking forward to more expert explanations, Brian vdB From cyresse at gmail.com Thu Feb 17 00:24:25 2005 From: cyresse at gmail.com (Liam Clarke) Date: Thu Feb 17 00:24:29 2005 Subject: [Tutor] Help needed with script to batch-create shapefiles In-Reply-To: <797fe3d405021613474b854060@mail.gmail.com> References: <s213be34.015@ccw0m1.nottingham.ac.uk> <797fe3d405021613474b854060@mail.gmail.com> Message-ID: <f2ff2d0502161524524d163d@mail.gmail.com> What are you getting? What are you expecting? Are you getting an error? If so, what's it telling you? Can you email this stuff up? I suspect you want to find the pywin documentation and go through that. Cheers, Liam Clarke On Wed, 16 Feb 2005 16:47:26 -0500, Bill Mill <bill.mill@gmail.com> wrote: > Chris, > > On Wed, 16 Feb 2005 21:37:10 +0000, Chris Bromley > <lgxjcb@nottingham.ac.uk> wrote: > > Dear all, > > > > I have several thousand files in dBaseIV format that I need to convert to shapefiles for use in ArcGIS. I've written a script (see below) to automate this process but thus far have been unable to get it to work. I suspect that there's a simple reason for this, but I'm a complete novice with Python and have been unable to find it. > > > > Any help would be greatly appreciated! > > > > Regards, > > > > Chris Bromley > <snip script> > > What you've written translates, in newsgroup-speak, to "Will somebody > write this script for me that I need?" > > Boil your question down into something smaller, and then ask it with > the appropriate information. I suggest reading > http://www.catb.org/~esr/faqs/smart-questions.html . > > Peace > Bill Mill > bill.mill at gmail.com > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From dyoo at hkn.eecs.berkeley.edu Thu Feb 17 00:23:45 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Feb 17 00:24:53 2005 Subject: [Tutor] Help needed with script to batch-create shapefiles In-Reply-To: <797fe3d405021613474b854060@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0502161513230.21501-100000@hkn.eecs.berkeley.edu> On Wed, 16 Feb 2005, Bill Mill wrote: > > I have several thousand files in dBaseIV format that I need to convert > > to shapefiles for use in ArcGIS. I've written a script (see below) to > > automate this process but thus far have been unable to get it to work. > > I suspect that there's a simple reason for this, but I'm a complete > > novice with Python and have been unable to find it. > > Boil your question down into something smaller, and then ask it with > the appropriate information. I suggest reading > http://www.catb.org/~esr/faqs/smart-questions.html . Hi Chris, Yes, at the moment, without even a clue what kind of problem there is, there's little we can do. We don't have dBase on our system, so the kind of diagnostics we have access to is limited to what you tell us. *grin* We just don't have enough information, and telling us that something is going wrong isn't enough for us to do a good analysis. Let's try pinpointing what you mean by "not working". I notice that your code has the following structure: ### try: ## .. do a bunch of stuff except: gp.AddMessage(gp.GetMessages(2)) print gp.GetMessages(2) ### This is a blanket try/except block that catches everything. This kind of exception handler tends to disguise problems in the code that have nothing to do with dBaseIV. I'm also not sure at all if it's the right thing for the program to ignore the error and try to continue working with the 'gp' object. Try to make exceptional conditions yell out when an exception occurs. That may make it much easier to see the problems at hand. Can you add the following import to your program? ### import traceback ### Also modify the except block to this: ### try: ## .. do a bunch of stuff except: traceback.print_exc() ### These changes use the excellent 'traceback' error-tracing module: http://www.python.org/doc/lib/module-traceback.html and traceback.print_exc() will print out the details of errors that occur in the try block. We have to do what we can to get some useful information what's going wrong, before continuing to work on this problem. Good luck to you! From jeffshannon at gmail.com Thu Feb 17 01:52:19 2005 From: jeffshannon at gmail.com (Jeff Shannon) Date: Thu Feb 17 01:52:23 2005 Subject: [Tutor] Help needed with script to batch-create shapefiles In-Reply-To: <s213be34.015@ccw0m1.nottingham.ac.uk> References: <s213be34.015@ccw0m1.nottingham.ac.uk> Message-ID: <5d0204a10502161652702e6ffc@mail.gmail.com> On Wed, 16 Feb 2005 21:37:10 +0000, Chris Bromley <lgxjcb@nottingham.ac.uk> wrote: > Any help would be greatly appreciated! Others have already pointed out that we will have a hard time helping without a bit more information. But I've noticed something odd in your code -- it probably doesn't have anything to do with your problem, but it seems like an awkward idiom to me. > fc = fcs.next() > > while fc: > # [...] > fc = fcs.next() This, it seems to me, is equivalent to (but less readable than) the following: . for fc in fcs: . # [...] If you're going to do something with every member of a list, then it's much more straightforward to use a for loop (which automatically tracks the iteration) than to use a while loop and manually adjusting the loop-controlling expression. Actually, it occurs to me that this *might* cause a confusing result in your code. Presuming that fcs is a standard iterator (as your usage of next() suggests), then calling next() on an exhausted iterator will raise a StopIteration exception. The for loop will automatically handle that, but with your while loop it would be caught by the following bare except statement. That means that you'll run (what I presume to be) your error-handling code even when you successfully convert every member of fcs... Jeff Shannon From kent37 at tds.net Thu Feb 17 03:40:20 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Feb 17 03:40:24 2005 Subject: [Tutor] Larger program organization In-Reply-To: <Pine.LNX.4.44.0502161315220.23025-100000@violet.rahul.net> References: <Pine.LNX.4.44.0502161315220.23025-100000@violet.rahul.net> Message-ID: <42140414.10407@tds.net> Terry Carroll wrote: > On Fri, 11 Feb 2005, Bob Gailer wrote: > > >>Whenever you find yourself writing an if statement ask whether this >>would be better handled by subclasses. Whenever you find yourself about >>to write a global statement, consider making the variables properties of >>a class. > > > Bob -- > > Brian already asked for an explanation of your first statement, and I > found the ensuing discussion very instructive. > > Can you explain the second? As an aesthetic point, I hate globals, and > I'd love a discussion with some examples of using class variables as a way > of avoiding this. Global variables are one way to make state persist across function calls. Here's a toy example that might give you the idea. Suppose you want to write a function that keeps a running total. You could do something like this (not recommended!): total = 0 def addToTotal(inc): global total total += inc Every time you call addToTotal, total is incremented. This is already a poor design. - There is no encapsulation - to increment the total, you call a function, to view the total you look at the global variable. - There is no API - to reset the total you would have to set the global variable. You could try to fix this by adding more functions: def printTotal(): print 'Total is', total def resetTotal(): global total total = 0 That's a little better, maybe. But there are other problems: - You can only have one total. What if you want two different totals? - Your global namespace has extra names - total, addToTotal, etc. For short scripts this structure can work, but for larger projects it gets unwieldy. OOP to the rescue! How about a Total class? class Total: def __init__(self): self.reset() def add(self, inc): self.total += inc def print(self): print 'Total is', self.total def reset(self): self.total = 0 You can use this like this: t = Total() t.inc(5) t.print() t.reset() Now everything is wrapped up in a nice neat package. There is a clear, consistent API, no namespace pollution, and you have a reusable object. You might also be interested in this essay: http://www.pycs.net/users/0000323/stories/15.html Kent From rcx at mchsi.com Thu Feb 17 04:49:14 2005 From: rcx at mchsi.com (Robert Campbell) Date: Thu Feb 17 04:49:17 2005 Subject: [Tutor] Active Python Message-ID: <20050217034915.1979C1E4002@bag.python.org> Hi, I am not a programmer, but have decided to learn Python. I am wondering if anyone has used the Activestate ActivePython and what are the advantages/disadvantages of using it rather than the standard Python tools. Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050216/7d4f9f70/attachment.htm From tony at tcapp.com Thu Feb 17 08:21:06 2005 From: tony at tcapp.com (Tony Cappellini) Date: Thu Feb 17 08:21:19 2005 Subject: [Tutor] Reading/writing Wave files Message-ID: <6.1.2.0.0.20050216231704.020500e8@mail.yamato.com> After looking at the Python docs for the wave module, I'm a bit puzzled as to how to use it. Does anyone have an example I can browse? If I write to a wave file, is the data I write actually audible, if I use Winamp or some other wave player, or is it more complicated than that? Is the data I write actually part of the content of the wave file, or do I have to manually handle the file structure of the wave file too (the part that is unique to wave files, that is)? thanks From bvande at po-box.mcgill.ca Thu Feb 17 09:51:07 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Thu Feb 17 09:52:45 2005 Subject: [Tutor] how to read from a txt file In-Reply-To: <2cad209005021623413001e0bb@mail.gmail.com> References: <2cad209005021308491228ea8b@mail.gmail.com> <420F98DE.9070208@po-box.mcgill.ca> <2cad209005021623413001e0bb@mail.gmail.com> Message-ID: <42145AFB.4050208@po-box.mcgill.ca> jrlen balane said unto the world upon 2005-02-17 02:41: > sir, what seemed to be the problem with this: > > def process(list_of_lines): > data_points = [] > for line in list_of_lines: > data_points.append(int(line)) > return data_points > > data_file = open('C:/Documents and Settings/nyer/Desktop/nyer.txt', 'r') > data = data_file.readline() > > print process(data) > > > here is what is written in the nyer.txt: > 1000 > 890 > 900 > 500 > 650 > 850 > 1200 > 1100 > > what i want is to print data_points: > and this is the error: > > Traceback (most recent call last): > File "C:\Python23\practices\opentxt", line 12, in -toplevel- > process(data) > File "C:\Python23\practices\opentxt", line 6, in process > data_points.append(int(line)) > ValueError: invalid literal for int(): Hi, I think the traceback is my fault from an oversight in the code I sent you when you posted before. Sorry about that :-[ There are two problems with your code. The immediate one, due to my advice, is that each line of your file ends with a newline character ('\n'). So, you cannot call int on '1000\n'. Try data_points.append(int(line[:-1])) instead. That will call int on line minus the last character (the newline). The other problem is that you use data = data_file.readline(). That will give you a single line each time you call it. If you stick with this approach, I think you want data = data_file.readlines() (note the 's' at the end.) But, you might do well to consider some of the other suggestions you got. They came from more capable programmers than me! Best, Brian vdB From project5 at redrival.net Thu Feb 17 09:51:49 2005 From: project5 at redrival.net (Andrei) Date: Thu Feb 17 09:55:43 2005 Subject: [Tutor] Re: Active Python References: <20050217034915.1979C1E4002@bag.python.org> Message-ID: <loom.20050217T094216-992@post.gmane.org> Robert Campbell <rcx <at> mchsi.com> writes: > I am not a programmer, but have decided to learn Python. I am > wondering if anyone has used the Activestate ActivePython and what are the > advantages/disadvantages of using it rather than the standard Python > tools. I use it, but I haven't used an official Python distro in quite some time, so perhaps my info is outdated. Anyway, what I like about it is that it comes with the Win32 stuff (including the PythonWin IDE) and that it has a better help system. I think the official distro by now also has HTMLHelp, but I don't know if it also includes Dive into Python, FAQ's and HowTo's like the ActiveState one does. It's nothing that you can't download on your own for free, but it's just more comfortable to get it all in a single package. Andrei From bvande at po-box.mcgill.ca Thu Feb 17 10:01:53 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Thu Feb 17 10:02:47 2005 Subject: [Tutor] how to read from a txt file In-Reply-To: <42145AFB.4050208@po-box.mcgill.ca> References: <2cad209005021308491228ea8b@mail.gmail.com> <420F98DE.9070208@po-box.mcgill.ca> <2cad209005021623413001e0bb@mail.gmail.com> <42145AFB.4050208@po-box.mcgill.ca> Message-ID: <42145D81.7010709@po-box.mcgill.ca> Brian van den Broek said unto the world upon 2005-02-17 03:51: > jrlen balane said unto the world upon 2005-02-17 02:41: > >> sir, what seemed to be the problem with this: <SNIP> > Hi, > > I think the traceback is my fault from an oversight in the code I sent > you when you posted before. Sorry about that :-[ <SNIP> In case that confused anyone, it was only after I sent my reply to the list that I noticed the email that I was replying to had been sent to me directly. (By reflex I filled in the tutor address thinking I'd hit reply rather than reply all.) I've sent the usual 'better to write to the list' explanation to the OP. best to all, Brian vdB From kraus at hagen-partner.de Thu Feb 17 10:04:47 2005 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Thu Feb 17 10:03:56 2005 Subject: [Tutor] Re: how to read from a txt file In-Reply-To: <42145AFB.4050208@po-box.mcgill.ca> References: <2cad209005021308491228ea8b@mail.gmail.com> <420F98DE.9070208@po-box.mcgill.ca> <2cad209005021623413001e0bb@mail.gmail.com> <42145AFB.4050208@po-box.mcgill.ca> Message-ID: <cv1mfn$nqp$1@sea.gmane.org> Brian van den Broek wrote: > jrlen balane said unto the world upon 2005-02-17 02:41: [...] >> data_file = open('C:/Documents and Settings/nyer/Desktop/nyer.txt', 'r') [...] > The immediate one, due to my advice, is that each line of your file ends > with a newline character ('\n'). So, you cannot call int on '1000\n'. > > Try > data_points.append(int(line[:-1])) > instead. That will call int on line minus the last character (the newline). The OS is from MS, so the lines will probably end with '\r\n'. It is better to call strip() on each line: data_points.append(int(line.strip())) HTH, Wolfram From bvande at po-box.mcgill.ca Thu Feb 17 10:18:23 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Thu Feb 17 10:20:41 2005 Subject: [Tutor] how to read from a txt file In-Reply-To: <42145AFB.4050208@po-box.mcgill.ca> References: <2cad209005021308491228ea8b@mail.gmail.com> <420F98DE.9070208@po-box.mcgill.ca> <2cad209005021623413001e0bb@mail.gmail.com> <42145AFB.4050208@po-box.mcgill.ca> Message-ID: <4214615F.8020008@po-box.mcgill.ca> Brian van den Broek said unto the world upon 2005-02-17 03:51: > jrlen balane said unto the world upon 2005-02-17 02:41: >> sir, what seemed to be the problem with this: >> >> def process(list_of_lines): >> data_points = [] >> for line in list_of_lines: >> data_points.append(int(line)) >> return data_points >> >> data_file = open('C:/Documents and Settings/nyer/Desktop/nyer.txt', 'r') >> data = data_file.readline() >> >> print process(data) <SNIP> >> Traceback (most recent call last): >> File "C:\Python23\practices\opentxt", line 12, in -toplevel- >> process(data) >> File "C:\Python23\practices\opentxt", line 6, in process >> data_points.append(int(line)) >> ValueError: invalid literal for int(): > The immediate one, due to my advice, is that each line of your file ends > with a newline character ('\n'). So, you cannot call int on '1000\n'. Bollocks! Nobody read any thing I write where I am claiming to answer anyone! IDLE 1.1 >>> int('1000\n') 1000 >>> So, sorry, I don't know what's wrong with the code you sent me, and I fear that if I tried to work it out, I'd do more damage. I yield the floor as I am off to write "Don't post untested code 1000 times. (I will say I suspect it is the readline vs. readlines, but then hopefully no one is reading this ;-) Sheepishly, bran vdB From dyoo at hkn.eecs.berkeley.edu Thu Feb 17 10:44:19 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Feb 17 10:44:23 2005 Subject: [Tutor] how to read from a txt file In-Reply-To: <4214615F.8020008@po-box.mcgill.ca> Message-ID: <Pine.LNX.4.44.0502170139230.22520-100000@hkn.eecs.berkeley.edu> > >> Traceback (most recent call last): > >> File "C:\Python23\practices\opentxt", line 12, in -toplevel- > >> process(data) > >> File "C:\Python23\practices\opentxt", line 6, in process > >> data_points.append(int(line)) > >> ValueError: invalid literal for int(): Hi Brian, Ah, think about empty lines. Let's look at the error message again: ValueError: invalid literal for int(): ^^^^^^^ There's nothing visible there after the colon, and that's our hint. Notice what happens when we pass int() some wacky strings: ### >>> int("foobar") Traceback (most recent call last): File "<stdin>", line 1, in ? ValueError: invalid literal for int(): foobar ### So whatever is being passed to int() should show up in the error message. This is exactly why getting literal error messages is so wonderful. *grin* Since we don't see anything here: > >> File "C:\Python23\practices\opentxt", line 12, in -toplevel- > >> process(data) > >> File "C:\Python23\practices\opentxt", line 6, in process > >> data_points.append(int(line)) > >> ValueError: invalid literal for int(): my best guess is that there's an empty line in the file, since we get the same kind of error if we do this: ### >>> int("") Traceback (most recent call last): File "<stdin>", line 1, in ? ValueError: invalid literal for int(): ### Best of wishes to you! From glingl at aon.at Thu Feb 17 10:49:38 2005 From: glingl at aon.at (Gregor Lingl) Date: Thu Feb 17 10:47:48 2005 Subject: [Tutor] how to read from a txt file In-Reply-To: <4214615F.8020008@po-box.mcgill.ca> References: <2cad209005021308491228ea8b@mail.gmail.com> <420F98DE.9070208@po-box.mcgill.ca> <2cad209005021623413001e0bb@mail.gmail.com> <42145AFB.4050208@po-box.mcgill.ca> <4214615F.8020008@po-box.mcgill.ca> Message-ID: <421468B2.9080403@aon.at> Brian van den Broek schrieb: > Brian van den Broek said unto the world upon 2005-02-17 03:51: > > > jrlen balane said unto the world upon 2005-02-17 02:41: > >>> sir, what seemed to be the problem with this: >>> >>> def process(list_of_lines): >>> data_points = [] >>> for line in list_of_lines: >>> data_points.append(int(line)) >>> return data_points >>> >>> data_file = open('C:/Documents and Settings/nyer/Desktop/nyer.txt', 'r') >>> data = data_file.readline() >>> >>> print process(data) > > > <SNIP> > >>> Traceback (most recent call last): >>> File "C:\Python23\practices\opentxt", line 12, in -toplevel- >>> process(data) >>> File "C:\Python23\practices\opentxt", line 6, in process >>> data_points.append(int(line)) >>> ValueError: invalid literal for int(): > > > >> The immediate one, due to my advice, is that each line of your file >> ends with a newline character ('\n'). So, you cannot call int on >> '1000\n'. > > > Bollocks! Nobody read any thing I write where I am claiming to answer > anyone! Unfortunately I read it. So I'll try a modest advice, too. If I read "invalid literal for int" in the error-message, I try out, what this literal is, by inserting one or two simple print-statements ;-) : def process(list_of_lines): data_points = [] print list_of_lines for line in list_of_lines: print (line,) data_points.append(int(line)) return data_points Running the program n oe yields: >>> 1000 ('1',) ('0',) ('0',) ('0',) ('\n',) Traceback (most recent call last): File "C:/_/Tutorstuff/intprog.py", line 12, in -toplevel- print process(data) File "C:/_/Tutorstuff/intprog.py", line 6, in process data_points.append(int(line)) ValueError: invalid literal for int(): >>> which indicates, that your suspicion (readline - readlines) was right Regards Gregor > > IDLE 1.1 > >>> int('1000\n') > 1000 > >>> > > So, sorry, I don't know what's wrong with the code you sent me, and I > fear that if I tried to work it out, I'd do more damage. I yield the > floor as I am off to write "Don't post untested code 1000 times. > > (I will say I suspect it is the readline vs. readlines, but then > hopefully no one is reading this ;-) > > Sheepishly, > > bran vdB > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Gregor Lingl Reisnerstrasse 3/19 A-1030 Wien Telefon: +43 1 713 33 98 Mobil: +43 664 140 35 27 Autor von "Python f?r Kids" Website: python4kids.net From kent37 at tds.net Thu Feb 17 11:42:48 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Feb 17 11:42:54 2005 Subject: [Tutor] how to read from a txt file In-Reply-To: <4214615F.8020008@po-box.mcgill.ca> References: <2cad209005021308491228ea8b@mail.gmail.com> <420F98DE.9070208@po-box.mcgill.ca> <2cad209005021623413001e0bb@mail.gmail.com> <42145AFB.4050208@po-box.mcgill.ca> <4214615F.8020008@po-box.mcgill.ca> Message-ID: <42147528.4090505@tds.net> Brian van den Broek wrote: > So, sorry, I don't know what's wrong with the code you sent me, and I > fear that if I tried to work it out, I'd do more damage. I yield the > floor as I am off to write "Don't post untested code 1000 times. for i in range(1000): print "Don't post untested code" (tested, seems to work OK) :-) Kent From gopinathv at hcltech.com Thu Feb 17 11:49:02 2005 From: gopinathv at hcltech.com (Gopinath V, ASDC Chennai) Date: Thu Feb 17 11:49:14 2005 Subject: [Tutor] RE: Message-ID: <A125AF3F419E97458A237BE2484C3C8B197118BF@pluto.msdc.hcltech.com> robert wrote........ Message: 1 Date: Wed, 16 Feb 2005 21:49:14 -0600 From: "Robert Campbell" <rcx@mchsi.com> Subject: [Tutor] Active Python To: <tutor@python.org> Message-ID: <20050217034915.1979C1E4002@bag.python.org> Content-Type: text/plain; charset="iso-8859-1" Hi, I am not a programmer, but have decided to learn Python. I am wondering if anyone has used the Activestate ActivePython and what are the advantages/disadvantages of using it rather than the standard Python tools. Robert > Hi robert , active state python is user friendly..infact i have downloaded it from the net to learn it as a begginer. It is easy to use regards gopi -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050217/c0e39985/attachment.htm From cyresse at gmail.com Thu Feb 17 12:27:11 2005 From: cyresse at gmail.com (Liam Clarke) Date: Thu Feb 17 12:27:15 2005 Subject: [Tutor] DB design In-Reply-To: <4211D6E3.6000401@tds.net> References: <f2ff2d050215022626b948dc@mail.gmail.com> <4211D6E3.6000401@tds.net> Message-ID: <f2ff2d05021703277633c607@mail.gmail.com> Hi, > > Anyway, why don't you tell us more about what you are trying to do and we can give better suggestions. > > Kent I told you it was vague. ; ) Ok, so if you'll tolerate some bad ASCII, I've been narrowing down what I want to do, and I think it's like this. __________________________________ | Gui | |_________________________________| | A | | | | _______v___________ __ |______ | | | Parser | | PySQLite wrapper | ? |________| |__________________| | | | | | | | ______V_____________ / | | / | DB |___/ |___________________| So, GUI generates requests for info/enters info, wrapper translates them into SQL, and DB responds, either directly to GUI or through parser. Not sure if I'll need to parse anything. Database organised - Client details ---- Jobs ---- Finances | | | Costs Resolutions It will go by client#/ and job# to reference various bits. To be totally honest, I haven't the faintest idea how to go about this. I think I want go OOP for this, especially when submitting requests to the wrapper. First I gotta figure out how to use PySQLite... what's a cursor? Regards, Liam Clarke 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From Kevin.Hine at renova.se Thu Feb 17 14:08:52 2005 From: Kevin.Hine at renova.se (Kevin Hine) Date: Thu Feb 17 14:09:00 2005 Subject: [Tutor] (no subject) Message-ID: <OF9DDF0EAA.24EA5485-ONC1256FAB.00471B06-C1256FAB.0048391B@goteborg.se> Hello I'm very new to python but need to write a script to update a single geodatabase table in arcview9 from several dbf files. If I can do this I can then use windows scheduled tasks to up date the tables automatically. The field names in the dbs files are or can be slightly different from those in the geodatabase table and the information already contained within the geodatabase table must be kept.in the ge -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050217/93e17207/attachment.html From lgxjcb at nottingham.ac.uk Thu Feb 17 17:05:58 2005 From: lgxjcb at nottingham.ac.uk (Chris Bromley) Date: Thu Feb 17 17:11:38 2005 Subject: [Tutor] Help needed with script to batch-create shapefiles Message-ID: <s214c21d.030@ccw0m1.nottingham.ac.uk> Hello again, First off, please accept my apologies for my last message, which was sorely= lacking in the detail department. I'm such a beginner with programming tha= t I assumed the error would be glaringly obvious to an experienced programm= er and would jump of the page/screen right away. This wasn't the case, thou= gh.=20 Second, thanks to everyone who did reply, despite the absence of detail, an= d the info. I got from these enable me to modify the script a little and al= so get more information about what might be going wrong. So, to start again, and with much more detail...=20=20 I have several thousand files of x,y,z coordinates in dBaseIV format (.dbf = file extension) that I am trying to convert into shapefiles in order to be = able to perform cut/fill analyses in ArcGIS 9.0. I am thus trying to automa= te this conversion using a Python script (in Python 2.1). I=92ve taken as m= y starting point the batch clip tool that can be found at:=20 http://support.esri.com/index.cfm?fa=3Dknowledgebase.techarticles.articleSh= ow&d=3D26892=20 and have tried to modify it to suit my purpose. I have replaced the clip to= ol with the Make XY Event Layer tool (from the the Data Management Tools to= olbox), in order to create an xy Layer from the .dbf files, and with the Fe= ature class to Shapefile (multiple) tool (from the Conversion Tools toolbox= ) in order to turn this xy layer into a shapefile. The full script as I hav= e modified it is below. Prior to running the script I use the =91check=92 button in the PythonWin a= nd the script=92s syntax is fine. When I run the script though, the message= =20 =91Script =91C:\ dBase_File_To_Shapefile.py=92 returned exit code 0=92=20= =20=20 appears in the status bar at the bottom of the PythonWin window. The follow= ing text also appears in the Interactive window=85 Traceback (most recent call last): File "C:\dBase_File_To_Shapefile2.py", line 37, in ? GP.FeatureClassToShapefile_conversion(outxyLayer, outputShapefiles) File "", line 2, in FeatureClassToShapefile_conversion com_error: (-2147467259, 'Unspecified error', None, None) Executing: FeatureClassToShapefile C:/xyLayerFiles/R302190.dbf C:\Shapefile= s C:\Shapefiles Start Time: Thu Feb 17 14:23:09 2005 Running script FeatureClassToShapefile... Error in script FeatureClassToShapefile. Error in executing: cmd.exe /C C:\PROGRA~1\ArcGIS\ARCTOO~1\Scripts\FEATUR~1= .PY "C:/xyLayerFiles/R302190.dbf" "C:\Shapefiles" "C:\Shapefiles" Failed to execute (FeatureClassToShapefile). End Time: Thu Feb 17 14:23:10 2005 (Elapsed Time: 1.00 secs) What I think my code should be doing is using the .dbf files from the "C:/O= ne" folder, storing the xy layer files in the "C:/xyLayerFiles" folder and,= finally, storing the shapefiles in the "C:/Shapefiles" folder. After I've = run the code, however, there is nothing in either of the latter two folders= .=20 One possibilty is that there is a problem with the way that I am passing th= e input and output variables from the first toolbox command to the second, = and perhaps also with the way that these variable are, or are not, being sa= ved in the folders in which I think they should be saved. Another possibility is that all the slashes in the workspace paths in the c= ode are forward slashes, whereas all paths appear with back slashes in the = address bar in my computer. However, if I try changing the forward slashes = to back slashes in the code I get a warning about syntax when I use the 'ch= eck' button.=20=20 I=92ve been trying to automate this conversion process since Monday of this= week and it is beginning to drive me insane! Regards,=20 Chris Bromley. Here is the script as I have modified it: #Import standard library modules import win32com.client, sys, os #Create the Geoprocessor object GP =3D win32com.client.Dispatch("esriGeoprocessing.GpDispatch.1") import traceback #Set the input workspace GP.workspace =3D "C:/One" #Set the xyLayer output workspace xyLayerFiles =3D "C:/xyLayerFiles" #Set the shapefile output workspace outputShapefiles =3D "C:/Shapefiles" try: # Load required toolboxes...=20=20=20=20 GP.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data M= anagement Tools.tbx") GP.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Conversion = Tools.tbx") =20=20=20=20 #Get a list of dBase files in the input folder fcs =3D GP.ListTables("*","dBASE") #Loop through the list of dBase files fcs.Reset() fc =3D fcs.Next() while fc: # Set the outputname for each output to be the same as the input. outxyLayer =3D xyLayerFiles + "/" + fc #Convert each dBase table in the list into an xyLayer. GP.MakeXYEventLayer_management(fc, "X", "Y", outxyLayer, "") #Convert each xyLayer into a shapefile GP.FeatureClassToShapefile_conversion(outxyLayer, outputShapefil= es) #Move to the next fc in the list. fc =3D fcs.Next() except: traceback.print_exc() # If an error occurred print the message to the screen print GP.GetMessages() This message has been checked for viruses but the contents of an attachment may still contain software viruses, which could damage your computer system: you are advised to perform your own checks. Email communications with the University of Nottingham may be monitored as permitted by UK legislation. From kent37 at tds.net Thu Feb 17 17:38:16 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Feb 17 17:39:03 2005 Subject: [Tutor] (no subject) In-Reply-To: <OF9DDF0EAA.24EA5485-ONC1256FAB.00471B06-C1256FAB.0048391B@goteborg.se> References: <OF9DDF0EAA.24EA5485-ONC1256FAB.00471B06-C1256FAB.0048391B@goteborg.se> Message-ID: <4214C878.9000704@tds.net> Kevin Hine wrote: > Hello I'm very new to python but need to write a script to update a > single geodatabase table in arcview9 from several dbf files. If I can do > this I can then use windows scheduled tasks to up date the tables > automatically. The field names in the dbs files are or can be slightly > different from those in the geodatabase table and the information > already contained within the geodatabase table must be kept.in the ge What have you tried so far? What can you tell us about the data? Do you know how to read dbf files from Python? Don't expect the readers of this list to know what 'geodatabase table' and 'arcview9' are; if you are lucky someone will but I sure don't. Coincidentally there seems to be someone else with a similar problem this week; see this thread: http://mail.python.org/pipermail/tutor/2005-February/036077.html Kent From bvande at po-box.mcgill.ca Thu Feb 17 18:14:38 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Thu Feb 17 18:22:26 2005 Subject: [Tutor] Help needed with script to batch-create shapefiles In-Reply-To: <s214c21d.030@ccw0m1.nottingham.ac.uk> References: <s214c21d.030@ccw0m1.nottingham.ac.uk> Message-ID: <4214D0FE.8000105@po-box.mcgill.ca> Chris Bromley said unto the world upon 2005-02-17 11:05: <SNIP> > Prior to running the script I use the ‘check’ button in the > PythonWin and the script’s syntax is fine. When I run the script > though, the message > > ‘Script ‘C:\ dBase_File_To_Shapefile.py’ returned exit code 0’ > > appears in the status bar at the bottom of the PythonWin window. > The following text also appears in the Interactive window… > > Traceback (most recent call last): File > "C:\dBase_File_To_Shapefile2.py", line 37, in ? > GP.FeatureClassToShapefile_conversion(outxyLayer, outputShapefiles) > File "", line 2, in FeatureClassToShapefile_conversion com_error: > (-2147467259, 'Unspecified error', None, None) Executing: > FeatureClassToShapefile C:/xyLayerFiles/R302190.dbf C:\Shapefiles > C:\Shapefiles Start Time: Thu Feb 17 14:23:09 2005 Running script > FeatureClassToShapefile... Error in script FeatureClassToShapefile. > Error in executing: cmd.exe /C > C:\PROGRA~1\ArcGIS\ARCTOO~1\Scripts\FEATUR~1.PY > "C:/xyLayerFiles/R302190.dbf" "C:\Shapefiles" "C:\Shapefiles" > > Failed to execute (FeatureClassToShapefile). End Time: Thu Feb 17 > 14:23:10 2005 (Elapsed Time: 1.00 secs) <SNIP> > Another possibility is that all the slashes in the workspace paths > in the code are forward slashes, whereas all paths appear with back > slashes in the address bar in my computer. However, if I try > changing the forward slashes to back slashes in the code I get a > warning about syntax when I use the 'check' button. > > <SNIP> As to what the difficulty is, I've no idea. But the forward slash, backward slash thing isn't the problem. Windows broke the previous standard of using '\' as an escape character. In a string a '\' means "this next character is to be treated as a special code.". Try: print "An\texample" So, to use backslashes in file paths, you either have to use raw strings or double them up. '\\' gets interpreted as "the next character is to be treated as special code -- no, wait, its a regular character backslash". Fortunately, Python is smart enough to let you use '/' for path specifications, and it works out what's appropriate for your environment: IDLE 1.1 >>> # Look, ma, I tested *this* code >>> a = open('C:/sample_file.txt', 'w') >>> a.writelines(["I wrote to this file using /'s.\n", "I read from it using \\'s.\n"]) >>> a.close() >>> b = open('C:\\sample_file.txt', 'r') >>> for line in b: print line I wrote to this file using /'s. I read from it using \'s. >>> HTH, Brian vdB From bgailer at alum.rpi.edu Thu Feb 17 20:57:59 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu Feb 17 20:58:38 2005 Subject: ****SPAM(11.2)**** [Tutor] Larger program organization In-Reply-To: <4213C369.4010602@po-box.mcgill.ca> References: <Pine.LNX.4.44.0502161315220.23025-100000@violet.rahul.net> <4213C369.4010602@po-box.mcgill.ca> Message-ID: <6.1.2.0.0.20050217125624.032a29f0@mail.mric.net> At 03:04 PM 2/16/2005, Brian van den Broek wrote: >Terry Carroll said unto the world upon 2005-02-16 16:18: >>On Fri, 11 Feb 2005, Bob Gailer wrote: >> >>>Whenever you find yourself writing an if statement ask whether this >>>would be better handled by subclasses. Whenever you find yourself about >>>to write a global statement, consider making the variables properties of >>>a class. >> >>Bob -- >>Brian already asked for an explanation of your first statement, and I >>found the ensuing discussion very instructive. >>Can you explain the second? As an aesthetic point, I hate globals, and >>I'd love a discussion with some examples of using class variables as a >>way of avoiding this. >>Terry Brian's response is similar to what I'd say. >Hi Terry and all, > >I'm probably not the best person to explain this, but I've got a use case >that might help illustrate. > >The thing that finally got me to write my first Class statement was a >procedural program where I had a hard to find bug. > >I wrote a debug_report function which would print out an informative >report about the state of all the objects I suspected were implicated in >the bug. Then, I put debug_report calls at the suspicious places. But, my >procedural code had function call chains 4 or 5 links deep, and at no >level did any of the functions have access to all of the objects of interest. > >To make it work in purely procedural, I had to either make many objects >global or litter my functions with passing objects up and down as >parameters that weren't needed for the function's tasks, but simply so >debug_report could see them. > >I made a class, put my functions in it, and suddenly, they all could `see' >the objects of interest without the passing and returning of objects just >for the sake of visibility. Some `self's sprinkled around did the work instead. > >So, even if you don't make use of further OOP features (as I am learning >to do on other threads), classes give you a namespace option between >globals and locals -- `continentals' if you like ;-) > >HTH, and looking forward to more expert explanations, > >Brian vdB > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor Bob Gailer mailto:bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From tegmine at gmail.com Fri Feb 18 00:00:59 2005 From: tegmine at gmail.com (Luis N) Date: Fri Feb 18 00:01:02 2005 Subject: [Tutor] Class in a class Message-ID: <77bfa81a050217150044e0ca4f@mail.gmail.com> Does it make sense to do this: In [2]: class AB: ...: pass ...: In [3]: a = AB() In [4]: a Out[4]: <__main__.AB instance at 0x8428bec> In [5]: class BC: ...: def __init__(self, foo): ...: self.foo = foo In [6]: b = BC(a) In [7]: b.foo Out[7]: <__main__.AB instance at 0x8428bec> From tegmine at gmail.com Fri Feb 18 00:02:09 2005 From: tegmine at gmail.com (Luis N) Date: Fri Feb 18 00:02:14 2005 Subject: [Tutor] elementtree, lists, and dictionaries In-Reply-To: <420D77F7.6090609@tds.net> References: <77bfa81a050211135376b1843f@mail.gmail.com> <420D77F7.6090609@tds.net> Message-ID: <77bfa81a05021715022df37bbe@mail.gmail.com> Thanks that's much nicer. On Fri, 11 Feb 2005 22:28:55 -0500, Kent Johnson <kent37@tds.net> wrote: > If you iterate over the author nodes you can check the user name and password of each in turn. > > Not tested code! > > def authenticateAuthor(author, password): > authorxml = 'author.xml' > path = os.path.join(xml, authorxml) > if not os.path.exists(path): > return False, False > else: > tree = E.ElementTree(file=path) > for authorNode in tree.getiterator('author'): > user = authorNode.find('user').text > pass = authorNode.find('password').text > > if author == user: > if password == pass: > return True, True > else: > return False, True > > return False, True From administrata at hotmail.com Fri Feb 18 00:11:57 2005 From: administrata at hotmail.com (. Sm0kin'_Bull) Date: Fri Feb 18 00:12:05 2005 Subject: [Tutor] Problem in making calulator Message-ID: <BAY22-F292660EF70256AA0D65B3AC86D0@phx.gbl> No-one answered question So, I e-mail it again Help me please I wrote this to add 2 numbers... print "Please input data" number1 = int(raw_input(" ")) number2 = int(raw_input("+ ")) total = number1 + number2 print total raw_input("") I want to make output like this... 1 + 1 = 2 But, actually... it looks like this... 1 + 1 2 Cheers! :) _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From kent37 at tds.net Fri Feb 18 00:14:01 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Feb 18 00:14:08 2005 Subject: [Tutor] Class in a class In-Reply-To: <77bfa81a050217150044e0ca4f@mail.gmail.com> References: <77bfa81a050217150044e0ca4f@mail.gmail.com> Message-ID: <42152539.9080405@tds.net> Luis N wrote: > Does it make sense to do this: > > In [2]: class AB: > ...: pass > ...: > In [3]: a = AB() > > In [4]: a > Out[4]: <__main__.AB instance at 0x8428bec> > > In [5]: class BC: > ...: def __init__(self, foo): > ...: self.foo = foo > > In [6]: b = BC(a) > > In [7]: b.foo > Out[7]: <__main__.AB instance at 0x8428bec> Absolutely. This is called composition - one object is made up of others. It's a very powerful way to create higher-level abstractions from component parts. For example, I have a project that uses a database. The lowest level of access to the database is through a JDBC connection object. I have a generic DbAccess class that builds on the connection to provide easier ways to do queries and updates. I have a CbDao class that builds on a DbAccess to provide application-specific primitives such as saveCourse() and findCourse(). Higher-level classes use a CbDao to do some real work. GUI classes present the results to the user and allow the data to be manipulated. So the layering is GUI - user interaction Application functionality CbDao - application-specific database access DbAccess - generic database access, easy to use JDBC connection - raw database access, not so easy to use Kent From alan.gauld at freenet.co.uk Fri Feb 18 00:27:11 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 18 00:26:34 2005 Subject: [Tutor] Class in a class References: <77bfa81a050217150044e0ca4f@mail.gmail.com> Message-ID: <009401c51548$350c14e0$2ca88651@xp> > Does it make sense to do this: That depends on what you are trying to do! If its to make scrambled eggs thewn nope, no sense whatsoever, but if writing a programme storing an instance inside another instance is very common indeed! :-) > In [2]: class AB: > ...: pass > ...: > In [3]: a = AB() > > In [5]: class BC: > ...: def __init__(self, foo): > ...: self.foo = foo > > In [6]: b = BC(a) Indeed you can even store a class inside an object: class C: def shout(self): print 'HELLO! from C' class D: def shout(self): print 'HELLO! from D' class A: def __init__(self,cls): self.c = cls def speak(self): print 'I'm an A but I have an object that says:' self.c().shout() a = A(C) b = A(D) a.speak() b.speak() More commonly a method of A could also be created that returned an instance of C with certain A specific values. The point of the example being simply that you can quite reasonably pass any PYthon object to a class/instance and it can be stored and later used or returned. You can see a practical example of storing a class reference within an object in my Games Framework, described in the book of my tutorial (and the code is on Useless Python). HTH Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From maxnoel_fr at yahoo.fr Fri Feb 18 00:29:17 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri Feb 18 00:29:22 2005 Subject: [Tutor] Problem in making calulator In-Reply-To: <BAY22-F292660EF70256AA0D65B3AC86D0@phx.gbl> References: <BAY22-F292660EF70256AA0D65B3AC86D0@phx.gbl> Message-ID: <9fc5f890b4f0b9e3bc4c5c079be5887a@yahoo.fr> On Feb 17, 2005, at 23:11, . Sm0kin'_Bull wrote: > I wrote this to add 2 numbers... > > print "Please input data" > number1 = int(raw_input(" ")) > number2 = int(raw_input("+ ")) > > > total = number1 + number2 > print total > > raw_input("") > > I want to make output like this... > > 1 + 1 = 2 > > But, actually... it looks like this... > > 1 > + 1 > 2 Do you really need to do it as the user enters the numbers? Aside from being a little bit confusing for him, it'd require playing around with bizarre special terminal control characters to go back one line -- every time the user hits Enter to validate his input, the newline character is echoed to the terminal and the cursor goes down one line. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From kent37 at tds.net Fri Feb 18 00:32:55 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Feb 18 00:33:01 2005 Subject: [Tutor] Problem in making calulator In-Reply-To: <BAY22-F292660EF70256AA0D65B3AC86D0@phx.gbl> References: <BAY22-F292660EF70256AA0D65B3AC86D0@phx.gbl> Message-ID: <421529A7.7050201@tds.net> . Sm0kin'_Bull wrote: > No-one answered question > So, I e-mail it again > Help me please > > I wrote this to add 2 numbers... > > print "Please input data" > number1 = int(raw_input(" ")) > number2 = int(raw_input("+ ")) > > > total = number1 + number2 > print total > > raw_input("") > > I want to make output like this... > > 1 + 1 = 2 > > But, actually... it looks like this... > This is your input to the first raw_input: > 1 This is the prompt and input to the second raw_input: > + 1 This is your printed result: > 2 It's not so easy to get the input and output all on one line. What you can do easily is format the output the way you like. Instead of print total try print number1, '+', number2, '=', total That will give you output the way you want it. You can also do this with the string format operator: print '%d + %d = %d' % (number1, number2, total) Kent > > > Cheers! :) > > _________________________________________________________________ > Express yourself instantly with MSN Messenger! Download today it's FREE! > http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From carroll at tjc.com Fri Feb 18 00:54:43 2005 From: carroll at tjc.com (Terry Carroll) Date: Fri Feb 18 00:54:47 2005 Subject: [Tutor] Active Python In-Reply-To: <20050217034915.1979C1E4002@bag.python.org> Message-ID: <Pine.LNX.4.44.0502171551450.31786-100000@green.rahul.net> On Wed, 16 Feb 2005, Robert Campbell wrote: > I am not a programmer, but have decided to learn Python. I am wondering > if anyone has used the Activestate ActivePython and what are the > advantages/disadvantages of using it rather than the standard Python > tools. If you're on Windows, I recommend it. It is the full Python, plus some Windows extensions. The only downside I've encountered is that, as of 2.4, it no longer includes the Help files in their original HTML format. Instead, there's just one big help file in Windows Help format. I prefer the HTML, because I can then run searches against it from outside the help system. I've gotten around this by also installing the help files from www.python.org; that gives me everything but the Win32-specific stuff. From cyresse at gmail.com Fri Feb 18 07:03:15 2005 From: cyresse at gmail.com (Liam Clarke) Date: Fri Feb 18 07:03:18 2005 Subject: [Tutor] Class in a class In-Reply-To: <009401c51548$350c14e0$2ca88651@xp> References: <77bfa81a050217150044e0ca4f@mail.gmail.com> <009401c51548$350c14e0$2ca88651@xp> Message-ID: <f2ff2d05021722039383993@mail.gmail.com> Hi Kent, >So the layering is >GUI - user interaction >Application functionality >CbDao - application-specific database access >DbAccess - generic database access, easy to use >JDBC connection - raw database access, not so easy to use This sounds a lot like what I'm aiming for in a project, the layers & objects passed up and down, are you able to provide an example of your CbDao class for my learning edification? (btw, is it Dao as in Lao Tzu?) Regards, Liam Clarke On Thu, 17 Feb 2005 23:27:11 -0000, Alan Gauld <alan.gauld@freenet.co.uk> wrote: > > > Does it make sense to do this: > > That depends on what you are trying to do! > If its to make scrambled eggs thewn nope, no sense > whatsoever, but if writing a programme storing an > instance inside another instance is very common > indeed! :-) > > > In [2]: class AB: > > ...: pass > > ...: > > In [3]: a = AB() > > > > In [5]: class BC: > > ...: def __init__(self, foo): > > ...: self.foo = foo > > > > In [6]: b = BC(a) > > Indeed you can even store a class inside an object: > > class C: > def shout(self): print 'HELLO! from C' > > class D: > def shout(self): print 'HELLO! from D' > > class A: > def __init__(self,cls): > self.c = cls > > def speak(self): > print 'I'm an A but I have an object that says:' > self.c().shout() > > a = A(C) > b = A(D) > > a.speak() > b.speak() > > More commonly a method of A could also be created that > returned an instance of C with certain A specific values. > > The point of the example being simply that you can quite reasonably > pass any PYthon object to a class/instance and it can be stored > and later used or returned. > > You can see a practical example of storing a class reference > within an object in my Games Framework, described in the book > of my tutorial (and the code is on Useless Python). > > HTH > > 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 > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From peateyk at gmail.com Fri Feb 18 07:22:47 2005 From: peateyk at gmail.com (Peter Kim) Date: Fri Feb 18 07:22:50 2005 Subject: [Tutor] help with HTMLParseError Message-ID: <5ef6678005021722226c3da33e@mail.gmail.com> I'm using HTMLParser.py to parse XHTML and invalid tag is throwing an exception. How do I handle this? 1. Below is the faulty markup. Notice the missing >. Both Firefox and IE6 correct automatically but HTMLParser is less forgiving. My code has to be able to treat this gracefully because I don't have control over the XHTML source. ###/ <A NAME='anchor'</a> /### 2. Below is the current code that raises a self.error("malformed start tag") at line 301 in HTMLParser.py due to the invalid markup. ###/ from HTMLParser import HTMLParser def parseHTML(htmlsource): class MyHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): print "<%s>" % tag, def handle_endtag(self, tag): print "</%s>" % tag, MyParser = MyHTMLParser() MyParser.feed(htmlsource) MyParser.close() return MyParser.output() if __name__ == "__main": htmlsource = r"<P><A NAME='anchor'</a></P>" result = parseHTML(htmlsource) /### 3. I think the ideal solution is to be able to do something like below, but I don't know how. ###/ class MyHTMLParseError(HTMLParseError): if self.message == "malformed start tag": text.append(">") else: raise /### Thanks in advance for the help! From jeffshannon at gmail.com Fri Feb 18 08:34:22 2005 From: jeffshannon at gmail.com (Jeff Shannon) Date: Fri Feb 18 08:34:26 2005 Subject: [Tutor] Active Python In-Reply-To: <Pine.LNX.4.44.0502171551450.31786-100000@green.rahul.net> References: <20050217034915.1979C1E4002@bag.python.org> <Pine.LNX.4.44.0502171551450.31786-100000@green.rahul.net> Message-ID: <5d0204a10502172334930d6f9@mail.gmail.com> On Thu, 17 Feb 2005 15:54:43 -0800 (PST), Terry Carroll <carroll@tjc.com> wrote: > On Wed, 16 Feb 2005, Robert Campbell wrote: > > > I am not a programmer, but have decided to learn Python. I am wondering > > if anyone has used the Activestate ActivePython and what are the > > advantages/disadvantages of using it rather than the standard Python > > tools. > > If you're on Windows, I recommend it. > > It is the full Python, plus some Windows extensions. I fully agree. ActivePython contains everything that you'd get from the standard distribution, plus extra tools that are especially useful under Windows. (I like PythonWin a lot more than IDLE...) > The only downside I've encountered is that, as of 2.4, it no longer > includes the Help files in their original HTML format. Instead, there's > just one big help file in Windows Help format. > > I prefer the HTML, because I can then run searches against it from > outside the help system. Interesting -- I prefer the CHM (Windows helpfile), because it's internally indexed. I feel that the internal search is more convenient than external searches would be. But I suppose that there's room for reasonable people to disagree, here. :) Jeff Shannon From project5 at redrival.net Fri Feb 18 09:37:37 2005 From: project5 at redrival.net (Andrei) Date: Fri Feb 18 09:41:00 2005 Subject: [Tutor] Re: Class in a class References: <77bfa81a050217150044e0ca4f@mail.gmail.com> Message-ID: <loom.20050218T082139-350@post.gmane.org> Luis N <tegmine <at> gmail.com> writes: > Does it make sense to do this: > > In [2]: class AB: > ...: pass > In [3]: a = AB() > In [4]: a > In [5]: class BC: > ...: def __init__(self, foo): > ...: self.foo = foo > In [6]: b = BC(a) > In [7]: b.foo This case is not that different from what you probably already do in classes, given the fact that all attributes are objects anyway. Compare the following two classes which have pretty much identical structure: class Point(object): def __init__(self, x, y): self.x = x self.y = y # x and y would be simple floats, but nothing # stops you from using more fancy attributes, # like in the Line class below class Line(object): def __init__(self, point1, point2): self.points = [point1, point2] # note how self.points is a complex # data structure (list object)! Certainly if we can use standard objects like floats, lists or dictionaries as attributes, we can also use objects of our own design: class Triangle(object): def __init__(self, line1, line2, line3): self.lines = [line1, line2, line3] self.points = [] for line in self.lines: for point in line.points: if point not in self.points: self.points.append(point) And you could go even higher, to a tetraeder made out of triangles, if you extended Point to also allow z coordinates. Andrei From shaleh at speakeasy.net Fri Feb 18 11:03:32 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Fri Feb 18 11:04:27 2005 Subject: [Tutor] help with HTMLParseError In-Reply-To: <5ef6678005021722226c3da33e@mail.gmail.com> References: <5ef6678005021722226c3da33e@mail.gmail.com> Message-ID: <4215BD74.7040801@speakeasy.net> Peter Kim wrote: > I'm using HTMLParser.py to parse XHTML and invalid tag is throwing an > exception. How do I handle this? > > 1. Below is the faulty markup. Notice the missing >. Both Firefox > and IE6 correct automatically but HTMLParser is less forgiving. My > code has to be able to treat this gracefully because I don't have > control over the XHTML source. > > ###/ > <A NAME='anchor'</a> > /### > what you want is to encapsulate check_for_whole_start_tag() in your own parser class. Call the parent's version, if it returns -1, do some fuzzy logic (well, maybe if I add a '>', now does it work?), and continue. From kent37 at tds.net Fri Feb 18 12:05:39 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Feb 18 12:02:15 2005 Subject: [Tutor] Class in a class In-Reply-To: <f2ff2d05021722039383993@mail.gmail.com> References: <77bfa81a050217150044e0ca4f@mail.gmail.com> <009401c51548$350c14e0$2ca88651@xp> <f2ff2d05021722039383993@mail.gmail.com> Message-ID: <4215CC03.1010204@tds.net> Liam Clarke wrote: > Hi Kent, > > >>So the layering is > > >>GUI - user interaction >>Application functionality >>CbDao - application-specific database access >>DbAccess - generic database access, easy to use >>JDBC connection - raw database access, not so easy to use > > > This sounds a lot like what I'm aiming for in a project, the layers & > objects passed up and down, are you able to provide an example of your > CbDao class for my learning edification? > > (btw, is it Dao as in Lao Tzu?) The Way that can be known is not the true way. Which makes it hard to provide examples. :-) Actually DAO stands for Data Access Object which a common pattern for database access, and Lao Tzu's version is usually spelled Tao. Though I do appreciate the pun. http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html My CbDao is work code so I can't just post it. It's actually pretty long and ugly too. But the idea of it is simple - it includes all of the SQL code of the main application and exposes it as application-specific methods. For example my app has a Category object that gets linked into a tree and is saved to the database. CbDao has methods like def saveCategory(self, category): def saveCategoryAsChild(self, category, parent): def moveCategory(self, catToMove, newParent, pos): def deleteCategory(self, cat): def findOneCategory(self, uniqueGroupId, treeId): The higher levels of the application don't have to worry about the implementation of these methods in terms of database operations. Kent From kent37 at tds.net Fri Feb 18 13:33:09 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Feb 18 13:33:13 2005 Subject: [Tutor] help with HTMLParseError In-Reply-To: <5ef6678005021722226c3da33e@mail.gmail.com> References: <5ef6678005021722226c3da33e@mail.gmail.com> Message-ID: <4215E085.9070101@tds.net> Peter Kim wrote: > I'm using HTMLParser.py to parse XHTML and invalid tag is throwing an > exception. How do I handle this? My understanding is that HTMLParser is not very forgiving of badly formed HTML. You might want to look at alternatives. Here are a few: http://www.crummy.com/software/BeautifulSoup/ and see the links at the bottom of the page http://effbot.org/zone/element-tidylib.htm Kent From mark.kels at gmail.com Fri Feb 18 17:29:59 2005 From: mark.kels at gmail.com (Mark Kels) Date: Fri Feb 18 17:30:05 2005 Subject: [Tutor] Help with error handling in a while loop Message-ID: <c2259253050218082932837c7a@mail.gmail.com> Hi all. I'm trying to build a simple port scanner (just to learn sockets). here is the code (doesn't work) : import socket sk=socket.socket(socket.AF_INET, socket.SOCK_STREAM) host=raw_input("Enter name of host to scan: ") start_port=input("Enter the start port: ") end_port=input("Enter the end port: ") while start_port<end_port: try: sk.connect((host,start_port)) print "port",start_port,"is open on",host start_port=start_port+1 except: print "Port",start_port,"is closed on",host sk.close() As you can see, when there is an exception the socket closes (I run the program from idle, so I don't need to exit it). An exception will be every time the connection fails (because the port is closed ). I want it to print the text and go back and continue the loop whenever there is an exception, how do I do that ? Thanks in advance. -- 1. The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners. 2. Unix is user friendly - it's just picky about it's friends. 3. Documentation is like sex: when it is good, it is very, very good. And when it is bad, it is better than nothing. - Dick Brandon From apple_py at biz-experts.net Fri Feb 18 18:27:24 2005 From: apple_py at biz-experts.net (Victor) Date: Fri Feb 18 18:29:05 2005 Subject: [Tutor] DB design In-Reply-To: <f2ff2d05021703277633c607@mail.gmail.com> References: <f2ff2d050215022626b948dc@mail.gmail.com> <4211D6E3.6000401@tds.net> <f2ff2d05021703277633c607@mail.gmail.com> Message-ID: <4216257C.3030601@biz-experts.net> Liam Clarke wrote: > > >>Anyway, why don't you tell us more about what you are trying to do and we can give better suggestions. >> >>Kent >> >> > > >Database organised - > >Client details ---- Jobs ---- Finances > | | > | Costs > Resolutions > >It will go by client#/ and job# to reference various bits. > > > Hi Liam, I am not a proficient Python nor OO programmer but I know my way around databases and SQL. I believe that before you can fully jump into coding or even writing SQL queries for your project, you need to get to know relational databases lingo and what your subject refers to: DB Design. Basically you need to organize your data into different tables or "entities" and then build relationships around them. You need ot identify how each entity relates to each other. Database designers usually refer to this as an entity-relationship diagram. For example, your entity (table) Clients describes certain attributes (fields) each one has. The kind of relationship the entity Client can have to the entity Jobs is that "one Client can hold one or more Jobs" (or in this case "none to many jobs"). So you define the relationship between entity Clients and Jobs to be a "none or one-to-many" relationship. Additionally, there can be "one-to-one" relationships or "many-to-many" (e.g. People to Jobs). I do not know the functionality you want to get from your application, but that will take you to define the kind of relationships you can build from there. Schematically this has its own representation, but I prefer to direct you to some of the links I just found through googling a little bit. For example, look into: http://miner.chem.purdue.edu/Lectures/Lecture23.pdf which is very high level. It does not describe the details in the lecture, but helps as a first hand intro http://r937.com/relational.html More desccriptive, particularly an explanation of what normalization is, and how to approach the database design process. Anybody have any other references or suggestions relating to the subject? About Python, I assume (experts please jump in) you will build a class for each entity, and any record of the entity or table becomes a class instance. I hope this helps. Victor Bouffier Finance Manager www.grupoandersons.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050218/5f2d6c1d/attachment.html From ternary at gmail.com Fri Feb 18 18:56:34 2005 From: ternary at gmail.com (Mike Bell) Date: Fri Feb 18 18:56:38 2005 Subject: [Tutor] Help with error handling in a while loop In-Reply-To: <c2259253050218082932837c7a@mail.gmail.com> References: <c2259253050218082932837c7a@mail.gmail.com> Message-ID: <82975b0c05021809567f8986cb@mail.gmail.com> I haven't tried the code, but it looks like you need to increment on connection failures, too. I think it's more pythonic to iterate over a range, as in the following for test_port in range(start_port, end_port) but it would suffice to just move the start_port+=1 outside of the try From carroll at tjc.com Sat Feb 19 02:20:03 2005 From: carroll at tjc.com (Terry Carroll) Date: Sat Feb 19 02:20:16 2005 Subject: [Tutor] Active Python In-Reply-To: <5d0204a10502172334930d6f9@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0502181700540.18584-100000@violet.rahul.net> On Thu, 17 Feb 2005, Jeff Shannon wrote: > On Thu, 17 Feb 2005 15:54:43 -0800 (PST), Terry Carroll <carroll@tjc.com> wrote: > > > > I prefer the HTML, because I can then run searches against it from > > outside the help system. > > Interesting -- I prefer the CHM (Windows helpfile), because it's > internally indexed. I feel that the internal search is more > convenient than external searches would be. But I suppose that > there's room for reasonable people to disagree, here. :) Sure, and I'd expect I'm in the minority. I use Agent Ransack for searching files on my system. I do a search for, for example, a filename of html$ containing the word "socket" and can get a pretty good look at what I'm looking for. I'll bet that the CHM file can do that at least as well, but since I use Agent Ransack for all my document searches (Python-related or otherwise), it's most convenient for me use one consistent mechanism. I'll tell you, if Google desktop had a way of limiting searches to specific directories, I'd be in heaven. From bill.mill at gmail.com Sat Feb 19 02:29:16 2005 From: bill.mill at gmail.com (Bill Mill) Date: Sat Feb 19 02:29:20 2005 Subject: [Tutor] Active Python In-Reply-To: <Pine.LNX.4.44.0502181700540.18584-100000@violet.rahul.net> References: <5d0204a10502172334930d6f9@mail.gmail.com> <Pine.LNX.4.44.0502181700540.18584-100000@violet.rahul.net> Message-ID: <797fe3d4050218172959c6e4b8@mail.gmail.com> On Fri, 18 Feb 2005 17:20:03 -0800 (PST), Terry Carroll <carroll@tjc.com> wrote: > On Thu, 17 Feb 2005, Jeff Shannon wrote: > > > On Thu, 17 Feb 2005 15:54:43 -0800 (PST), Terry Carroll <carroll@tjc.com> wrote: > > > > Interesting -- I prefer the CHM (Windows helpfile), because it's > > internally indexed. I feel that the internal search is more > > convenient than external searches would be. But I suppose that > > there's room for reasonable people to disagree, here. :) > > Sure, and I'd expect I'm in the minority. > > I use Agent Ransack for searching files on my system. I do a search for, > for example, a filename of html$ containing the word "socket" and can get > a pretty good look at what I'm looking for. > > I'll bet that the CHM file can do that at least as well, but since > I use Agent Ransack for all my document searches (Python-related or > otherwise), it's most convenient for me use one consistent mechanism. > > I'll tell you, if Google desktop had a way of limiting searches to > specific directories, I'd be in heaven. > How do you live without cygwin? Just 'cd' to the directory and 'grep -r' to search through it. It's the first thing I install on a windows box, even before python. Peace Bill Mill bill.mill at gmail.com From carroll at tjc.com Sat Feb 19 03:49:28 2005 From: carroll at tjc.com (Terry Carroll) Date: Sat Feb 19 07:11:28 2005 Subject: [Tutor] Active Python In-Reply-To: <797fe3d4050218172959c6e4b8@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0502181847280.18584-100000@violet.rahul.net> On Fri, 18 Feb 2005, Bill Mill wrote: > How do you live without cygwin? I don't. I have it installed, too. But Agent Ransack is more convenient. If it wasn't free, I'd pay for it. It's primarily to search by filename, but the grep-like capability is a nice plus. From bvande at po-box.mcgill.ca Sat Feb 19 09:24:43 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat Feb 19 09:25:11 2005 Subject: [Tutor] Active Python In-Reply-To: <797fe3d4050218172959c6e4b8@mail.gmail.com> References: <5d0204a10502172334930d6f9@mail.gmail.com> <Pine.LNX.4.44.0502181700540.18584-100000@violet.rahul.net> <797fe3d4050218172959c6e4b8@mail.gmail.com> Message-ID: <4216F7CB.6030905@po-box.mcgill.ca> Bill Mill said unto the world upon 2005-02-18 20:29: > On Fri, 18 Feb 2005 17:20:03 -0800 (PST), Terry Carroll <carroll@tjc.com> wrote: > >>On Thu, 17 Feb 2005, Jeff Shannon wrote: >> >> >>>On Thu, 17 Feb 2005 15:54:43 -0800 (PST), Terry Carroll <carroll@tjc.com> wrote: >>> >>>Interesting -- I prefer the CHM (Windows helpfile), because it's >>>internally indexed. I feel that the internal search is more >>>convenient than external searches would be. But I suppose that >>>there's room for reasonable people to disagree, here. :) >> >>Sure, and I'd expect I'm in the minority. >> >>I use Agent Ransack for searching files on my system. I do a search for, >>for example, a filename of html$ containing the word "socket" and can get >>a pretty good look at what I'm looking for. >> >>I'll bet that the CHM file can do that at least as well, but since >>I use Agent Ransack for all my document searches (Python-related or >>otherwise), it's most convenient for me use one consistent mechanism. >> >>I'll tell you, if Google desktop had a way of limiting searches to >>specific directories, I'd be in heaven. >> > > > How do you live without cygwin? Just 'cd' to the directory and 'grep > -r' to search through it. It's the first thing I install on a windows > box, even before python. > > Peace > Bill Mill > bill.mill at gmail.com Hi all, I like the html docs and Agent Ransack, too. (Not yet command line oriented.) I've lately been making use of pydoc's html documentation server. I started when wanting to use it on my own modules; I've been finding it is really useful to use for quick reference on built ins, too. Best, Brian vdB From kabads at gmail.com Sat Feb 19 09:36:44 2005 From: kabads at gmail.com (Adam Cripps) Date: Sat Feb 19 09:36:48 2005 Subject: [Tutor] Trying out Tkinter with problems Message-ID: <c7ff385505021900366e921b36@mail.gmail.com> I'm trying out Tkinter as one of my first forays into GUI programming. However, I'm having a couple of problems. My intitial efforts can be seen at: http://www.monkeez.org/code/python/tkinter/min.txt or here [1]. Firstly, I'm trying to grab the contents of Entry widget entry1 with a StringVar and take that value to another function to print the value to the command line. However, my function 'printentry' always runs when the application is run, without the button being pressed. Then, when I do press the button, the function isn't called. However, this button is just the same as all the other buttons. Why is this? Secondly, when I try to exit the app, the quit button doesn't kill the root, window, but just the widgets. How do I reference the root window and all, instead of just exiting the widgets? TIA - Adam -- http://www.monkeez.org PGP key: 0x7111B833 [1] #!/usr/bin/python from Tkinter import * import tkFont import tkMessageBox class Application(Frame): def __init__(self, master=None, geometry="500x200-10x10"): Frame.__init__(self, master) self.grid() self.createWidgets() def createWidgets(self): largeFont = tkFont.Font(family = "Verdana",size= "18", weight="bold") arialFont = tkFont.Font(family="Arial", size="12", slant="italic") self.quitButton = Button(self, text="Quit", command = self.exiting, font = largeFont ) self.saveButton = Button(self, text = "save", command = self.save, fg = "blue", activebackground="red") self.save1Button = Button(self, text = "save1", command = self.save, relief="groove") self.save3Button = Button(self, text = "save3", command = self.save, state = DISABLED) #label = Label(self, text="This is the label text", font = arialFont) entry = Entry(self, text="Start here") entry.grid(column="0",row="4") # This is the entry that I'm trying to capture self.content = StringVar() entry1 = Entry(self, textvariable=self.content) entry1.grid(column="1", row="5") #And this is the button which will capture it. self.save2Button = Button(self, text = "Submit", command= self.printentry(self.content.get())) #label.grid(column=0,row=2) self.quitButton.grid(column=0, row=0) self.saveButton.grid(column=1, row = 0) self.save1Button.grid(column=2, row = 1) self.save2Button.grid(column=2, row = 5) self.save3Button.grid(column=4, row = 1) self.sexVar = StringVar() self.sex = Checkbutton (self, text = "Sex:", variable=self.sexVar, onvalue="male", offvalue="female") self.sex.grid(column=0, row=6) def printentry(self, event): print "ok - the submit has been pressed - I need to get it's value" #print "\n", event def save(event): print "This is a save" print "\n event is ", event def exiting(self): if tkMessageBox.askokcancel("Quit", "Do you really wish to quit?"): self.destroy() self.exit() app = Application() app.master.title("Sample Application") app.mainloop() From glingl at aon.at Sat Feb 19 10:43:07 2005 From: glingl at aon.at (Gregor Lingl) Date: Sat Feb 19 10:41:13 2005 Subject: [Tutor] Trying out Tkinter with problems In-Reply-To: <c7ff385505021900366e921b36@mail.gmail.com> References: <c7ff385505021900366e921b36@mail.gmail.com> Message-ID: <42170A2B.3050805@aon.at> Hi Adam! I'm not a Tkinter expert, so I probably cannot provide the best solution for your problem. Nevertheless I tried two corrections, which adress your problem seeminly successfully Adam Cripps schrieb: > I'm trying out Tkinter as one of my first forays into GUI programming. > However, I'm having a couple of problems. > > My intitial efforts can be seen at: > http://www.monkeez.org/code/python/tkinter/min.txt or here [1]. > > Firstly, I'm trying to grab the contents of Entry widget entry1 with a > StringVar and take that value to another function to print the value > to the command line. However, my function 'printentry' always runs > when the application is run, without the button being pressed. Then, > when I do press the button, the function isn't called. However, this > button is just the same as all the other buttons. Why is this? This is because of command=self.printentry(self.content.get()) in createWidgets. Here you don't assign the method pintentry to command, but the result of executing this method. (So it is ececuted, when createWidget is called, but not when the command is executed. Remedy: self.save2Button = Button(self, text = "Submit", command=self.printentry) *and* def printentry(self): print "ok - the submit has been pressed - \ I need to get it's value" print self.content.get() > > Secondly, when I try to exit the app, the quit button doesn't kill the > root, window, but just the widgets. How do I reference the root window > and all, instead of just exiting the widgets? self.destroy destroys the frame, not the root window. Remedy: def exiting(self): if tkMessageBox.askokcancel("Quit", "Do you really wish to quit?"): self.master.destroy() I'm not sure if this is the canonical way of exiting a Tkinter-App :-( (Perhaps somebody knows more.) Hope this helps, Gregor > > TIA - Adam > -- Gregor Lingl Reisnerstrasse 3/19 A-1030 Wien Telefon: +43 1 713 33 98 Mobil: +43 664 140 35 27 Autor von "Python f?r Kids" Website: python4kids.net From kabads at gmail.com Sat Feb 19 11:00:04 2005 From: kabads at gmail.com (Adam Cripps) Date: Sat Feb 19 11:00:08 2005 Subject: [Tutor] Trying out Tkinter with problems In-Reply-To: <42170A2B.3050805@aon.at> References: <c7ff385505021900366e921b36@mail.gmail.com> <42170A2B.3050805@aon.at> Message-ID: <c7ff385505021902004b87a574@mail.gmail.com> On Sat, 19 Feb 2005 10:43:07 +0100, Gregor Lingl <glingl@aon.at> wrote: > Hi Adam! > > I'm not a Tkinter expert, so I probably cannot provide > the best solution for your problem. > Nevertheless I tried two corrections, which adress your > problem seeminly successfully > > Adam Cripps schrieb: > > I'm trying out Tkinter as one of my first forays into GUI programming. > > However, I'm having a couple of problems. > > > > My intitial efforts can be seen at: > > http://www.monkeez.org/code/python/tkinter/min.txt or here [1]. > > > > Firstly, I'm trying to grab the contents of Entry widget entry1 with a > > StringVar and take that value to another function to print the value > > to the command line. However, my function 'printentry' always runs > > when the application is run, without the button being pressed. Then, > > when I do press the button, the function isn't called. However, this > > button is just the same as all the other buttons. Why is this? > > This is because of > > command=self.printentry(self.content.get()) > > in createWidgets. Here you don't assign the method pintentry > to command, but the result of executing this method. (So it is > ececuted, when createWidget is called, but not when the command > is executed. > > Remedy: > > self.save2Button = Button(self, text = "Submit", > command=self.printentry) > > *and* > > def printentry(self): > print "ok - the submit has been pressed - \ > I need to get it's value" > print self.content.get() > > > > > Secondly, when I try to exit the app, the quit button doesn't kill the > > root, window, but just the widgets. How do I reference the root window > > and all, instead of just exiting the widgets? > > self.destroy destroys the frame, not the root window. > > Remedy: > > def exiting(self): > if tkMessageBox.askokcancel("Quit", > "Do you really wish to quit?"): > self.master.destroy() > > I'm not sure if this is the canonical way of exiting a > Tkinter-App :-( (Perhaps somebody knows more.) > > Hope this helps, > Gregor > > > > > TIA - Adam > > > > -- > Gregor Lingl Gregor - many thanks! All suggestions worked, so perhaps you underestimate your skills? Level of skills are just relative aren't they? Thanks again. Adam -- http://www.monkeez.org PGP key: 0x7111B833 From kent37 at tds.net Sat Feb 19 14:29:35 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat Feb 19 14:29:39 2005 Subject: [Tutor] Trying out Tkinter with problems In-Reply-To: <c7ff385505021900366e921b36@mail.gmail.com> References: <c7ff385505021900366e921b36@mail.gmail.com> Message-ID: <42173F3F.3030700@tds.net> Adam Cripps wrote: > Secondly, when I try to exit the app, the quit button doesn't kill the > root, window, but just the widgets. How do I reference the root window > and all, instead of just exiting the widgets? Try self.quit() instead of > self.destroy() > self.exit() Kent From invisible.dog at gmail.com Sat Feb 19 19:33:17 2005 From: invisible.dog at gmail.com (Matt Hauser) Date: Sat Feb 19 19:33:21 2005 Subject: [Tutor] OT: Google Gmail Accounts Message-ID: <457b5fac05021910337908aac5@mail.gmail.com> If anyone is interested in an invitation to Google GMail, let me know and I will send you a free invitation to join. It works great for organizing mailing lists and with 1000 MB of storage, you don't have to manage your inbox. -- Have you seen the dog lately? Email - invisible.dog@gmail.com Blog - invisibledog.blogspot.com From ismaelgf at adinet.com.uy Sat Feb 19 21:51:57 2005 From: ismaelgf at adinet.com.uy (Ismael Garrido) Date: Sat Feb 19 21:51:36 2005 Subject: [Tutor] Instance into another instance Message-ID: <4217A6ED.4080703@adinet.com.uy> Hello. This is my code: class Node: def __init__(self, tag, value=None, **kwargs): self.tag = tag self.value = value self.kwargs = kwargs self.childs = [] def addChild(self, tag, value=None, **kwargs): node = Node(tag, value, kwargs) self.childs.append(node) def __repr__(self): return "Tag %s ; value %s ; kwargs %s ; childs %s" % (self.tag, self.value, self.kwargs, self.childs) And this is what I do to test it: >>> ppal = Node("Test", value="Test") >>> ppal.addChild("test", value=2) Traceback (most recent call last): File "<pyshell#75>", line 1, in -toplevel- ppal.addChild("test", value=2) File "...node.py", line 10, in addChild node = Node(tag, value, kwargs) TypeError: __init__() takes at most 3 arguments (4 given) I don't understand. Why 4 arguments are given? What can I do to solve that? The idea of the class is to be able to create a "tree". Where each node can have subnodes, which in turn can have their subnodes... Thanks Ismael From administrata at hotmail.com Sat Feb 19 22:15:22 2005 From: administrata at hotmail.com (. Sm0kin'_Bull) Date: Sat Feb 19 22:16:05 2005 Subject: [Tutor] Advanced Calculator Program... Message-ID: <BAY22-F30E6A6F3E90F9322D58936C86F0@phx.gbl> I want to make caculator program which enables me to enter 2numbers and mathsmatics sign and calculates it. I think this is too difficult for newbie like me... Please input data Number1: Mathsmetics Sign: Number2: (Number1) (Sign) (Number2) = (Result) I wrote this but, Error occurs print "Please input data" number1 = int(raw_input("\nNumber1: ")) sign = (raw_input("\nMathsmetics Sign: ")) number2 = int(raw_input("\nNumber2: ")) total = number1 sign number2 print number1, sign, number2, '=', total please help me Cheers! :) _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From glingl at aon.at Sat Feb 19 23:36:00 2005 From: glingl at aon.at (Gregor Lingl) Date: Sat Feb 19 23:34:04 2005 Subject: [Tutor] Instance into another instance In-Reply-To: <4217A6ED.4080703@adinet.com.uy> References: <4217A6ED.4080703@adinet.com.uy> Message-ID: <4217BF50.7060303@aon.at> Ismael Garrido schrieb: > Hello. > > This is my code: > class Node: > def __init__(self, tag, value=None, **kwargs): > self.tag = tag > self.value = value > self.kwargs = kwargs > self.childs = [] > > def addChild(self, tag, value=None, **kwargs): > node = Node(tag, value, kwargs) > self.childs.append(node) > > def __repr__(self): > return "Tag %s ; value %s ; kwargs %s ; childs %s" % (self.tag, > self.value, self.kwargs, self.childs) > And this is what I do to test it: > >>> ppal = Node("Test", value="Test") > >>> ppal.addChild("test", value=2) > > Traceback (most recent call last): > File "<pyshell#75>", line 1, in -toplevel- > ppal.addChild("test", value=2) > File "...node.py", line 10, in addChild > node = Node(tag, value, kwargs) > TypeError: __init__() takes at most 3 arguments (4 given) This means, afaik, __init__() takes at most 3 non-keyword arguments (plus an arbitrary number of keyword-arguments). You passed 4 non-keyword - arguments, the first beeing (implicitely) self (i. e. node), and then three more: tag, value, kwargs. (In your case kwargs is the empty dictionary.) I suppose you wanted to pass addChild's **kwargs to Node's **kwargs, which goes like this: def addChild(self, tag, value=None, **kwargs): node = Node(tag, value, **kwargs) self.childs.append(node) HTH, Gregor > > I don't understand. Why 4 arguments are given? What can I do to solve that? > > The idea of the class is to be able to create a "tree". Where each node > can have subnodes, which in turn can have their subnodes... > > Thanks > Ismael > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Gregor Lingl Reisnerstrasse 3/19 A-1030 Wien Telefon: +43 1 713 33 98 Mobil: +43 664 140 35 27 Autor von "Python f?r Kids" Website: python4kids.net From bvande at po-box.mcgill.ca Sun Feb 20 00:09:19 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sun Feb 20 00:09:36 2005 Subject: [Tutor] Advanced Calculator Program... In-Reply-To: <BAY22-F30E6A6F3E90F9322D58936C86F0@phx.gbl> References: <BAY22-F30E6A6F3E90F9322D58936C86F0@phx.gbl> Message-ID: <4217C71F.7060508@po-box.mcgill.ca> . Sm0kin'_Bull said unto the world upon 2005-02-19 16:15: > I want to make caculator program which enables me to > enter 2numbers and mathsmatics sign and calculates it. > I think this is too difficult for newbie like me... > > Please input data > > Number1: > Mathsmetics Sign: > Number2: > > (Number1) (Sign) (Number2) = (Result) > > > I wrote this but, Error occurs > > print "Please input data" > number1 = int(raw_input("\nNumber1: ")) > sign = (raw_input("\nMathsmetics Sign: ")) > number2 = int(raw_input("\nNumber2: ")) > > total = number1 sign number2 > print number1, sign, number2, '=', total > > please help me > > > > Cheers! :) Hi, what are you expecting this line: total = number1 sign number2 to do? >>> total = number1 sign number2 SyntaxError: invalid syntax The Python interpreter reads the line and says 'Ah, total should equal number1 -- hey, wait, what I am supposed to do with this other stuff like sign?' So, you've got to figure a way to tell the interpreter just how you want these things combined. Following the sort of approach you have started with, you've got some integers and a mathematical operation sign, and you want to *eval*uate their combination somehow. That suggests >>> eval('5 + 6') 11 So, this code will work (tested!): <code> print "Please input data" number1 = raw_input("\nNumber1: ") sign = raw_input("\nMathsmetics Sign: ") number2 = raw_input("\nNumber2: ") print eval(number1 + sign + number2) </code> <output> IDLE 1.1 >>> ================================ RESTART ================================ >>> Please input data Number1: 42 Mathsmetics Sign: * Number2: 100 4200 >>> </output> But, this isn't a very good approach, in my opinion. For one thing, eval is dangerous. I have an alternate suggestion. It uses several things which may be new to you. And, as you know, I am no expert, so I make no claim this is the *best* way. I do think it is better but think it likely that someone else will post a better idea, still. Anyway, take a look at this code and see if you can work it out. If not, post again. <tested code> import operator ops_dict = {'+': operator.add, '*' : operator.mul} def perform_arithmetic(): print "Please input data" number1 = int(raw_input("\nNumber1: ")) sign = raw_input("\nMathsmetics Sign: ") number2 = int(raw_input("\nNumber2: ")) try: result = ops_dict[sign](number1, number2) except KeyError: raise NotImplementedError, "I don't know the sign '%s'" %sign # add output formatting logic as desired return result print perform_arithmetic() <tested code> Hope that helps, Brian vdB From glingl at aon.at Sun Feb 20 00:12:13 2005 From: glingl at aon.at (Gregor Lingl) Date: Sun Feb 20 00:10:17 2005 Subject: [Tutor] Advanced Calculator Program... In-Reply-To: <BAY22-F30E6A6F3E90F9322D58936C86F0@phx.gbl> References: <BAY22-F30E6A6F3E90F9322D58936C86F0@phx.gbl> Message-ID: <4217C7CD.8010807@aon.at> . Sm0kin'_Bull schrieb: > I want to make caculator program which enables me to > enter 2numbers and mathsmatics sign and calculates it. > I think this is too difficult for newbie like me... > > Please input data > > Number1: > Mathsmetics Sign: > Number2: > > (Number1) (Sign) (Number2) = (Result) > > > I wrote this but, Error occurs > > print "Please input data" > number1 = int(raw_input("\nNumber1: ")) > sign = (raw_input("\nMathsmetics Sign: ")) > number2 = int(raw_input("\nNumber2: ")) > > total = number1 sign number2 > print number1, sign, number2, '=', total > hey, bull! that's a bit tricky. You had a nice idea, but it doesn't work in Python. The point is, that you must not use names for operators in arithmetic expressions. Those operators have to be used literally. *One* way to solve your problem is, e. g., to use a branching statement for checking, which operator is used. So replace the line total = number1 sign number2 by something similar to if sign == "+": total = number1 + number2 elif sign == "-": total = numer1 - number2 ... (for other operators ..) HTH, Gregor > please help me > > > > Cheers! :) > > _________________________________________________________________ > Express yourself instantly with MSN Messenger! Download today it's FREE! > http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Gregor Lingl Reisnerstrasse 3/19 A-1030 Wien Telefon: +43 1 713 33 98 Mobil: +43 664 140 35 27 Autor von "Python f?r Kids" Website: python4kids.net From wilson at visi.com Sun Feb 20 02:37:02 2005 From: wilson at visi.com (Tim Wilson) Date: Sun Feb 20 02:37:04 2005 Subject: [Tutor] Attaching an uploaded file to an email Message-ID: <BE3D45DE.A11%wilson@visi.com> Hi everyone, I'm working on a little Python CGI project, but I think I'm stuck on some of the MIME magic. I've got a Web form that collects various bit of text and, optionally, a file can be uploaded too. The file could be almost any kind of document from jpeg to PDF. The form data get passed to a Python CGI script that does some light text manipulation and generates an email with some custom headers to a certain address. If the user uploaded a file with the Web form, I want to have that file included as an email attachment. I've got it all working except for attaching the file to the email. I don't understand how all of the MIME options work in the Python email module. Here are two relevant sections of my code: import cgi, smtplib, time from email.MIMEText import MIMEText from email.MIMEBase import MIMEBase from email.MIMEImage import MIMEImage from email.MIMEMultipart import MIMEMultipart import cgitb; cgitb.enable() # Collect form information form = cgi.FieldStorage() requestername = form["requestername"].value fromaddr = form["email"].value itemname = form["itemname"].value description = form["description"].value buildings = form.getlist("building") room = form["room"].value dateneeded = form["dateneeded"].value po = form["po"].value budgetcode = form["budgetcode"].value attachment = form["attachment"].value buildinglist = ", ".join(buildings) **[ misc code snipped ]** # Set some email headers #msg = MIMEText(msgtext) msg = MIMEMultipart() msg['Subject'] = itemname msg['From'] = "%s <%s>" % (requestername, fromaddr) msg['To'] = toaddr if len(buildings) != 0: for building in buildings: msg['X-HRT-Building'] = building if po != "": msg['X-HRT-PO'] = po if dateneeded != "": try: duedate = time.asctime(time.strptime(dateneeded, "%m/%d/%Y")) msg['X-HRT-Due-Date'] = duedate except ValueError: pass msg.preamble = "Tech order request" msg.epilogue = "" # Attach the uploaded file msg.attach(attachment) # Send the message server = smtplib.SMTP('localhost') server.sendmail(fromaddr, toaddr, msg.as_string(0)) server.quit() In this program 'attachment' is the uploaded file. I know there are some significant problems here, but I'm not making any headway. Unless I'm reading them wrong, the docs for the email module don't seem to cover a case like this. Any ideas anyone? -Tim -- Tim Wilson Twin Cities, Minnesota, USA Educational technology guy, Linux and OS X fan, Grad. student, Daddy mailto: wilson@visi.com aim: tis270 blog: http://technosavvy.org/ From dyoo at hkn.eecs.berkeley.edu Sun Feb 20 05:01:09 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Feb 20 05:01:13 2005 Subject: [Tutor] Advanced Calculator Program... In-Reply-To: <4217C7CD.8010807@aon.at> Message-ID: <Pine.LNX.4.44.0502191953470.30691-100000@hkn.eecs.berkeley.edu> > > I want to make caculator program which enables me to enter 2numbers > > and mathsmatics sign and calculates it. I think this is too difficult > > for newbie like me... > > > > Please input data > > > > Number1: > > Mathsmetics Sign: > > Number2: > > > > (Number1) (Sign) (Number2) = (Result) > > > *One* way to solve your problem is, e. g., to use a branching statement > for checking, which operator is used. > > So replace the line > > total = number1 sign number2 > > by something similar to > > if sign == "+": > total = number1 + number2 > elif sign == "-": > total = numer1 - number2 > ... (for other operators ..) One variation of this is to turn the 'sign' from a string into a function: ### import operator def getOperator(sign): if sign == '+': return operator.add elif sign == '-': return operator.sub elif sign == '*': return operator.mul elif sign == '/': return operator.div else: raise ValueError, ("I don't know about %s" % sign) ### We're pulling out functions from the 'operator' module: http://www.python.org/doc/lib/module-operator.html If we have this, then we can do: ### >>> myop = getOperator("+") >>> myop(3, 17) 20 >>> >>> >>> myop = getOperator("*") >>> myop(42, 17) 714 ### Best of wishes to you! From peateyk at gmail.com Sun Feb 20 07:20:41 2005 From: peateyk at gmail.com (Peter Kim) Date: Sun Feb 20 07:20:45 2005 Subject: [Tutor] best way to scrape html In-Reply-To: <010d01c513f3$7fb4e770$2ca88651@xp> References: <5ef6678005021521456ee5c006@mail.gmail.com> <010d01c513f3$7fb4e770$2ca88651@xp> Message-ID: <5ef66780050219222019e18792@mail.gmail.com> Thank you, I subclassed SGMLParser.py, borrowing ideas from DiveIntoPython's BaseHTMLProcessor.py. It appears to work: ### class Scrape(SGMLParser): TAGS_TO_SCRAPE = ['p', 'br', 'b', 'i'] def reset(self): self.pieces = [] self.isScraping = 0 SGMLParser.reset(self) def unknown_starttag(self, tag, attrs): """Called for each start tag, attrs is alist of (attr, value) tuples, e.g. for <pre class='top'>, tag='pre', attrs=[('class', 'top')]""" for i,v in attrs: if ('name' == i) and ('anchor' in v): # name='anchor*' self.isScraping += 1 #begin scraping break elif ('class' == i) and ('txtend' == v): # class='txtend' self.isScraping -= 1 #stop scraping break if self.isScraping and tag in self.TAGS_TO_SCRAPE: self.pieces.append("<%(tag)s>" % locals()) def unknown_endtag(self, tag): """Called for each end tag, e.g. for </pre>, tag='pre'""" if self.isScraping and tag in self.TAGS_TO_SCRAPE: self.pieces.append("</%(tag)s>" % locals()) def handle_charref(self, ref): """Called for each character reference, e.g. for ' ', ref='160'""" if self.isScraping: self.pieces.append("&#%(ref)s;" % locals()) def handle_entitydef(self, ref): """Called for each entity reference, e.g. for '©', ref='copy'""" if self.isScraping: self.pieces.append("&#%(ref)s" % locals()) if htmlentitydefs.entitydefs.has_key(ref): self.pieces.append(";") # standard HTML entities end with ';' def handle_data(self, text): """Called for each block of plain text, i.e. outside of any tag""" if self.isScraping: self.pieces.append(text) def output(self): return "".join(self.pieces) # return processed HTML as a single string ### On Wed, 16 Feb 2005 06:48:18 -0000, Alan Gauld <alan.gauld@freenet.co.uk> wrote: > > > Which method is best and most pythonic to scrape text data with > > minimal formatting? > > Use the HTMLParser module. > > > I want to change the above to: > > > > <p><b>Trigger:</b> Debate on budget in Feb-Mar. New moves to > > cutmedical costs by better technology.</p> > > > > Since I wanted some practice in regex, I started with something like > this: > > Using regex is usually the wrong way to parse html for anything > beyond the trivial. The parser module helps deal with the > complexities. > > > So I'm thinking of using sgmllib.py (as in the Dive into Python > > example). Is this where I should be using libxml2.py? As you can > > tell this is my first foray into both parsing and regex so advice in > > terms of best practice would be very helpful. > > There is an html parser which is built on the sgml one. > Its rather more specific to your task. > > Alan G. > > From cyresse at gmail.com Sun Feb 20 10:59:17 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sun Feb 20 10:59:20 2005 Subject: [Tutor] dictionary dispatch for object instance attributes question In-Reply-To: <4213BFE1.1070005@po-box.mcgill.ca> References: <42127579.3080001@po-box.mcgill.ca> <5d0204a105021518204d86acc9@mail.gmail.com> <4212D09F.5010601@po-box.mcgill.ca> <5d0204a10502161309775723c5@mail.gmail.com> <4213BFE1.1070005@po-box.mcgill.ca> Message-ID: <f2ff2d05022001591da993a7@mail.gmail.com> Hi, just an expansion on Brian's query, is there a variant of getattr for instance methods? i.e. class DBRequest: def __init__(self, fields, action): self.get(fields) def get(self, fields): print fields Instead of self.get in _init__, the value of action to call a function? Or, is it going to have to be dictionary dispatch? Regards, Liam Clarke On Wed, 16 Feb 2005 16:49:21 -0500, Brian van den Broek <bvande@po-box.mcgill.ca> wrote: > Jeff Shannon said unto the world upon 2005-02-16 16:09: > > On Tue, 15 Feb 2005 23:48:31 -0500, Brian van den Broek > > <bvande@po-box.mcgill.ca> wrote: > > <SNIP some of Jeff's responses to my evaluation of his earlier > suggestions> > > > > Yes, if you know that you will only have one header per line, then > > it's reasonable to process them one line at a time. You could > > alternatively have the TP_file gather all the header lines for a given > > node into a list, and then process that list to create the Node > > instance, but given the specifics of your case you probably wouldn't > > gain anything over your current approach by doing so. > > > > This is what makes programming so interesting -- there's so many > > different choices possible, and which one is best depends on a large > > number of factors. When writing a program for some task, the best > > design for a particular set of circumstances may be completely > > different than the best design for a somewhat different particular set > > of circumstances -- and the best design for general usage is probably > > an altogether different thing still. > > > > Good luck! > > > > Jeff Shannon > > Thanks Jeff, > > the confirmation that my assessment made sense is very helpful. Due to > the my lack of experience (as discussed in my response to Kent) I'm > always uncomfortable rejecting a proposed solution -- is my assessment > that the solution isn't the best a product of that inexperience, or am > I on to something? So, thanks for taking the time to `bless' my > assessment. > > Best to all, > > Brian vdB > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From ralfasy2k at hotmail.com Sun Feb 20 11:15:10 2005 From: ralfasy2k at hotmail.com (Ralfas Jegorovas) Date: Sun Feb 20 11:16:07 2005 Subject: [Tutor] Create list of IPs Message-ID: <BAY101-F12ECA490FC5E061D553BD2E4600@phx.gbl> I am wondering how I would go about making a list of IPs between two set IPs. This is my initial code: <my code> def list2str(list): ip='' for part in list: if len(ip)!=0: ip=ip+'.'+part else: ip=ip+part return ip iplist = [] minip = ['1','0','0','1'] # starting IP maxip = ['1','0','15','16'] # ending IP currentip = minip # set currentip to value of minip while currentip != maxip: # carry out while currentip is not the same as the maxip iplist.append(list2str(currentip)) if currentip[2]<maxip[2] and currentip[3]<256: currentip[3] = currentip[3]+1 <end my code> I'd appreciate any help. Thanks, Ralf From cyresse at gmail.com Sun Feb 20 11:43:07 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sun Feb 20 11:43:10 2005 Subject: Fwd: [Tutor] Create list of IPs In-Reply-To: <f2ff2d05022002425bb8052f@mail.gmail.com> References: <BAY101-F12ECA490FC5E061D553BD2E4600@phx.gbl> <f2ff2d05022002425bb8052f@mail.gmail.com> Message-ID: <f2ff2d0502200243297ffeab@mail.gmail.com> Erp. ---------- Forwarded message ---------- From: Liam Clarke <cyresse@gmail.com> Date: Sun, 20 Feb 2005 23:42:43 +1300 Subject: Re: [Tutor] Create list of IPs To: Ralfas Jegorovas <ralfasy2k@hotmail.com> Hi, you could save yourself some hassle and do >>> minipstr = '1.0.0.1' >>> maxipstr = '1.0.15.16' >>> >>> minip = map(int, minipstr.split('.')) >>> maxip = map(int, maxipstr.split('.')) >>> >>> iplist = [] >>> >>> for a in range(minip[2], maxip[2]+1): ... if a < maxip[2]: ... for b in range(minip[3], 255): ... iplist.append('.'.join(map(str, [minip[0],minip[1], a, b]))) ... else: ... for b in range(minip[3], minip[3]+1): ... iplist.append('.'.join(map(str, [minip[0],minip[1], a, b]))) Eek, that's a bit Perlish, might want to break the iplist.append line into ipintlist = [minip[0],minip[1], a, b] ipstrlist = map(str, ipintlist) iplist.append('.'.join(ipstrlist)) HTH Liam Clarke <Disclaimer> It's ugly, but it works, someone better will shortly post a prettier, more elegant and efficient version. </disclaimer> -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cyresse at gmail.com Sun Feb 20 11:44:01 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sun Feb 20 11:44:05 2005 Subject: [Tutor] Create list of IPs In-Reply-To: <f2ff2d0502200243297ffeab@mail.gmail.com> References: <BAY101-F12ECA490FC5E061D553BD2E4600@phx.gbl> <f2ff2d05022002425bb8052f@mail.gmail.com> <f2ff2d0502200243297ffeab@mail.gmail.com> Message-ID: <f2ff2d05022002442150062e@mail.gmail.com> Oops, also change this line for b in range(minip[3], 255): to for b in change(minip[3], 256): On Sun, 20 Feb 2005 23:43:07 +1300, Liam Clarke <cyresse@gmail.com> wrote: > Erp. > > > ---------- Forwarded message ---------- > From: Liam Clarke <cyresse@gmail.com> > Date: Sun, 20 Feb 2005 23:42:43 +1300 > Subject: Re: [Tutor] Create list of IPs > To: Ralfas Jegorovas <ralfasy2k@hotmail.com> > > Hi, you could save yourself some hassle and do > > >>> minipstr = '1.0.0.1' > >>> maxipstr = '1.0.15.16' > >>> > >>> minip = map(int, minipstr.split('.')) > >>> maxip = map(int, maxipstr.split('.')) > >>> > >>> iplist = [] > >>> > >>> for a in range(minip[2], maxip[2]+1): > ... if a < maxip[2]: > ... for b in range(minip[3], 255): > ... iplist.append('.'.join(map(str, > [minip[0],minip[1], a, b]))) > ... else: > ... for b in range(minip[3], minip[3]+1): > ... iplist.append('.'.join(map(str, > [minip[0],minip[1], a, b]))) > > Eek, that's a bit Perlish, might want to break the iplist.append line into > > ipintlist = [minip[0],minip[1], a, b] > ipstrlist = map(str, ipintlist) > iplist.append('.'.join(ipstrlist)) > > HTH > > Liam Clarke > > <Disclaimer> > > It's ugly, but it works, someone better will shortly post a prettier, > more elegant and efficient version. > </disclaimer> > -- > 'There is only one basic human right, and that is to do as you damn well please. > And with it comes the only basic human duty, to take the consequences. > > -- > 'There is only one basic human right, and that is to do as you damn well please. > And with it comes the only basic human duty, to take the consequences. > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From kent37 at tds.net Sun Feb 20 13:07:52 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun Feb 20 13:08:05 2005 Subject: [Tutor] Instance into another instance In-Reply-To: <4217A6ED.4080703@adinet.com.uy> References: <4217A6ED.4080703@adinet.com.uy> Message-ID: <42187D98.7090004@tds.net> Ismael Garrido wrote: > The idea of the class is to be able to create a "tree". Where each node > can have subnodes, which in turn can have their subnodes... Are you creating a tree to represent XML data? There are many packages available that do this. You might want to look at ElementTree which is one of the easiest to use. In fact, even if you aren't trying to represent XML you might find ElementTree useful. http://effbot.org/zone/element.htm Kent From kent37 at tds.net Sun Feb 20 13:26:54 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun Feb 20 13:26:58 2005 Subject: [Tutor] dictionary dispatch for object instance attributes question In-Reply-To: <f2ff2d05022001591da993a7@mail.gmail.com> References: <42127579.3080001@po-box.mcgill.ca> <5d0204a105021518204d86acc9@mail.gmail.com> <4212D09F.5010601@po-box.mcgill.ca> <5d0204a10502161309775723c5@mail.gmail.com> <4213BFE1.1070005@po-box.mcgill.ca> <f2ff2d05022001591da993a7@mail.gmail.com> Message-ID: <4218820E.3050908@tds.net> Liam Clarke wrote: > Hi, > > just an expansion on Brian's query, is there a variant of getattr for > instance methods? > > i.e. class DBRequest: > def __init__(self, fields, action): > self.get(fields) > > def get(self, fields): > print fields > > > Instead of self.get in _init__, the value of action to call a > function? Or, is it going to have to be dictionary dispatch? I don't understand your example, but instance methods are attributes too, so getattr() works with them as well as simple values. An instance method is an attribute of the class whose value is a function. When you access the attribute on an instance you get something called a 'bound method' which holds a reference to the actual function and a reference to the instance (to pass to the function as the 'self' parameter). You can call a bound method just like any other function. So: >>> class foo: ... def __init__(self): ... self.bar = 3 ... def baz(self): ... print self.bar ... >>> f=foo() getattr() of a simple attribute: >>> getattr(f, 'bar') 3 getattr() of an instance method returns a 'bound method': >>> getattr(f, 'baz') <bound method foo.baz of <__main__.foo instance at 0x008D5FD0>> Calling the bound method (note the added ()) is the same as calling the instance method directly: >>> getattr(f, 'baz')() 3 Of course you can do the same thing with dot notation for attributes: >>> b=f.baz >>> b <bound method foo.baz of <__main__.foo instance at 0x008D5FD0>> >>> b() 3 Kent From kent37 at tds.net Sun Feb 20 13:53:47 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun Feb 20 13:53:52 2005 Subject: Fwd: [Tutor] Create list of IPs In-Reply-To: <f2ff2d0502200243297ffeab@mail.gmail.com> References: <BAY101-F12ECA490FC5E061D553BD2E4600@phx.gbl> <f2ff2d05022002425bb8052f@mail.gmail.com> <f2ff2d0502200243297ffeab@mail.gmail.com> Message-ID: <4218885B.8050609@tds.net> Liam Clarke wrote: > Hi, you could save yourself some hassle and do > > >>>>minipstr = '1.0.0.1' >>>>maxipstr = '1.0.15.16' >>>> >>>>minip = map(int, minipstr.split('.')) >>>>maxip = map(int, maxipstr.split('.')) >>>> >>>>iplist = [] >>>> >>>>for a in range(minip[2], maxip[2]+1): > > ... if a < maxip[2]: > ... for b in range(minip[3], 255): > ... iplist.append('.'.join(map(str, > [minip[0],minip[1], a, b]))) > ... else: > ... for b in range(minip[3], minip[3]+1): > ... iplist.append('.'.join(map(str, > [minip[0],minip[1], a, b]))) > > Eek, that's a bit Perlish, might want to break the iplist.append line into > > ipintlist = [minip[0],minip[1], a, b] > ipstrlist = map(str, ipintlist) > iplist.append('.'.join(ipstrlist)) I don't think this will work correctly with for example minipstr = '1.0.0.1' maxipstr = '1.2.0.0' I would break this problem up conceptually. It has maybe four different parts: - convert a string representation of an IP address to a useful representation. Liam shows how to do this above, a list of ints is easy to work with. - convert the useful representation back to a string. Again, Liam shows how to do this. - compare two IPs. If the IPs are represented as lists of ints, you can compare them directly: >>> a=[1,2,1,5] >>> b=[1,2,3,4] >>> a>b False >>> a<b True >>> a==[1,2,1,5] True - increment an IP. This is the hardest part. You have to implement a counter that works with the list representation. Here is one way to do it - this function does the right thing with the last 'digit', then if there was a carry it calls itself recursively to increment the next digit. It rolls over from [255, 255, 255, 255] to [0, 0, 0, 0]: def incr(n, limit, ix=None): ''' Increment a number base (limit+1) represented as a list of ints ''' if ix is None: # initial call starts at the end ix = len(n) - 1 if ix < 0: # Off the end, give up return if n[ix] < limit: # Normal increment n[ix] += 1 else: # Increment with carry n[ix] = 0 incr(n, limit, ix-1) a=[1,2,1,5] incr(a, 255) print a a=[1,2,1,255] incr(a, 255) print a a=[1,2,255,255] incr(a, 255) print a a=[1,255,255,255] incr(a, 255) print a a=[255,255, 255,255] incr(a, 255) print a ## prints [1, 2, 1, 6] [1, 2, 2, 0] [1, 3, 0, 0] [2, 0, 0, 0] [0, 0, 0, 0] Kent From mark.kels at gmail.com Sun Feb 20 16:12:54 2005 From: mark.kels at gmail.com (Mark Kels) Date: Sun Feb 20 16:12:58 2005 Subject: [Tutor] help with .get in Tkinter Message-ID: <c225925305022007123c05955d@mail.gmail.com> Hi all. First, here is the code I have a problem with (I got same problem in my project) : from Tkinter import * def go(): e.get() print e main=Tk() e=Entry(main) e.pack() b=Button(main,text='OK',command=go()).pack() main.mainloop() For some reason the function is called before I click the button, and I get .10037088 before I have done a thing. How do I do it right ??? -- 1. The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners. 2. Unix is user friendly - it's just picky about it's friends. 3. Documentation is like sex: when it is good, it is very, very good. And when it is bad, it is better than nothing. - Dick Brandon From lumbricus at gmx.net Sun Feb 20 16:18:34 2005 From: lumbricus at gmx.net (lumbricus@gmx.net) Date: Sun Feb 20 16:18:38 2005 Subject: Fwd: [Tutor] Create list of IPs References: <4218885B.8050609@tds.net> Message-ID: <19138.1108912714@www4.gmx.net> > Liam Clarke wrote: [ snip ] > - increment an IP. This is the hardest part. Why? An ip (V4) is just an 32bit integer :-) The problem arises from the representation. Use something like "http://pynms.sourceforge.net/ipv4.html" to switch between the various representations. > Kent HTH and Greetings, J"o! -- Wir sind jetzt ein Imperium und wir schaffen uns unsere eigene Realit?t. Wir sind die Akteure der Geschichte, und Ihnen, Ihnen allen bleibt nichts, als die Realit?t zu studieren, die wir geschaffen haben. -- Karl Rove zu Ron Suskind (NYT) DSL Komplett von GMX +++ Superg?nstig und stressfrei einsteigen! AKTION "Kein Einrichtungspreis" nutzen: http://www.gmx.net/de/go/dsl From rschroev_nospam_ml at fastmail.fm Sun Feb 20 16:21:00 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sun Feb 20 16:21:22 2005 Subject: [Tutor] Re: Create list of IPs In-Reply-To: <BAY101-F12ECA490FC5E061D553BD2E4600@phx.gbl> References: <BAY101-F12ECA490FC5E061D553BD2E4600@phx.gbl> Message-ID: <cva9mo$c7$1@sea.gmane.org> Ralfas Jegorovas wrote: > I am wondering how I would go about making a list of IPs between two set > IPs. # First, list2str can be written shorter .def list2str(lst): . return '.'.join(map(str, lst)) # The inverse of that is also needed .def str2list(s): . return map(int, s.split('.')) # Note that an IP address can also be represented as an integer .def lst2int(lst): . return (lst[0] << 24) | (lst[1] << 16) | (lst[2] << 8) | lst[3] # Reverse: .def lst2int(ip_int): . return map(int, [ip_int >> 24, . (ip_int >> 16) & 0xff, . (ip_int >> 8) & 0xff, . ip_int & 0xff]) # Once the IP addresses are converted to integers, we can simply # loop from the first to the second .def generate_iplist(minip, maxip): . iplist = [] . minip_int = lst2int(str2list(minip)) . maxip_int = lst2int(str2list(maxip)) . for ip in range(minip_int, maxip_int+1): . iplist.append(list2str(int2lst(ip))) . return iplist # Example: .>>> if __name__ == '__main__': . for ip in generate_iplist('1.0.0.250', '1.0.1.5'): . print ip 1.0.0.250 1.0.0.251 1.0.0.252 1.0.0.253 1.0.0.254 1.0.0.255 1.0.1.0 1.0.1.1 1.0.1.2 1.0.1.3 1.0.1.4 1.0.1.5 -- "Codito ergo sum" Roel Schroeven From s.varun at gmail.com Sun Feb 20 16:25:40 2005 From: s.varun at gmail.com (Varun Soundararajan) Date: Sun Feb 20 16:25:43 2005 Subject: [Tutor] Time Controlled Execution Message-ID: <32b5ee7605022007255851f221@mail.gmail.com> Hi, I want to know how to do this: I have an executable file, which reads input from stdin provided output at stdout or stderr. I have to run it for a specific period of time (say 5 secs), get the output and display it. If i use popen(), this way: from subprocess import * p = Popen(["test","<test.in"," >test.out"], shell=True) p.wait() print p.stdin,p.stdout I dont get output in p.stdout.Apart from this, can u say how to stop this subprocess after 5 secs (or whatever time frame specified)? signal SIGALRM may not work (as i want it to work in windows & unix). -Varun From klappnase at freenet.de Sun Feb 20 17:11:05 2005 From: klappnase at freenet.de (Michael Lange) Date: Sun Feb 20 17:08:21 2005 Subject: [Tutor] help with .get in Tkinter In-Reply-To: <c225925305022007123c05955d@mail.gmail.com> References: <c225925305022007123c05955d@mail.gmail.com> Message-ID: <20050220171105.519ac9fd.klappnase@freenet.de> On Sun, 20 Feb 2005 17:12:54 +0200 Mark Kels <mark.kels@gmail.com> wrote: > Hi all. > First, here is the code I have a problem with (I got same problem in > my project) : > from Tkinter import * > def go(): > e.get() > print e > > main=Tk() > e=Entry(main) > e.pack() > b=Button(main,text='OK',command=go()).pack() > main.mainloop() > > For some reason the function is called before I click the button, and > I get .10037088 before I have done a thing. > How do I do it right ??? > -- Hi Mark, First problem: you need to assign the command for the button without parenthesis: b = Button(main, text='OK', command=go) b.pack() I split the line you used into two lines, because pack() returns None , so you don't have a reference to the button once you created it. Of course you can do it the way you did if you don't need to reference the button anymore, however there's not much use in assigning a new variable to it, just write: Button(main,text='OK',command=go()).pack() Second problem: your go() function does just what you told it to: it prints the "window name" (or however this is called) of the entry widget. You surely meant something like this: def go(): contents = e.get() print contents or simply: def go(): print e.get() I hope this helps Michael From amonroe at columbus.rr.com Sun Feb 20 17:24:36 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sun Feb 20 17:25:36 2005 Subject: Fwd: [Tutor] Create list of IPs In-Reply-To: <19138.1108912714@www4.gmx.net> References: <4218885B.8050609@tds.net> <19138.1108912714@www4.gmx.net> Message-ID: <401796869421.20050220112436@columbus.rr.com> >> Liam Clarke wrote: > [ snip ] >> - increment an IP. This is the hardest part. > Why? An ip (V4) is just an 32bit integer :-) Indeed. Some early versions of MacTCP for MacOS made you input the address as a single large decimal number :^) Alan From kent37 at tds.net Sun Feb 20 18:16:05 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun Feb 20 18:16:11 2005 Subject: Fwd: [Tutor] Create list of IPs In-Reply-To: <19138.1108912714@www4.gmx.net> References: <4218885B.8050609@tds.net> <19138.1108912714@www4.gmx.net> Message-ID: <4218C5D5.1020108@tds.net> lumbricus@gmx.net wrote: >>Liam Clarke wrote: > > > [ snip ] > > >>- increment an IP. This is the hardest part. > > > Why? An ip (V4) is just an 32bit integer :-) > The problem arises from the representation. > Use something like > "http://pynms.sourceforge.net/ipv4.html" > to switch between the various representations. :-) Amazing what a difference it makes to look at a problem a different way. Kent From kent37 at tds.net Sun Feb 20 18:22:49 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun Feb 20 18:22:55 2005 Subject: [Tutor] Instance into another instance In-Reply-To: <4218B608.7010008@adinet.com.uy> References: <4217A6ED.4080703@adinet.com.uy> <42187D98.7090004@tds.net> <4218B608.7010008@adinet.com.uy> Message-ID: <4218C769.20508@tds.net> Ismael Garrido wrote: > Kent Johnson wrote: > >> Are you creating a tree to represent XML data? There are many packages >> available that do this. You might want to look at ElementTree which is >> one of the easiest to use. In fact, even if you aren't trying to >> represent XML you might find ElementTree useful. >> http://effbot.org/zone/element.htm >> >> Kent > > > Yes, that was my intention. ElementTree looks very interesting. Thanks > for the suggestion. You can find other ideas here: http://www.xml.com/pub/a/2004/10/13/py-xml.html Kent From alan.gauld at freenet.co.uk Sun Feb 20 19:09:06 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Feb 20 19:08:42 2005 Subject: [Tutor] help with .get in Tkinter References: <c225925305022007123c05955d@mail.gmail.com> Message-ID: <015301c51777$45211430$2ca88651@xp> Mark, There are two problems here: > from Tkinter import * > def go():... > e=Entry(main) > e.pack() This is OK but... > b=Button(main,text='OK',command=go()).pack() Problem 1: This will store None in b because pack() always returns None. Problem 2: > For some reason the function is called before I click the button, and > I get .10037088 before I have done a thing. Thats because you are calling go() inside the widget specification, you need to pass a reference to the function instead - ie miss out the parens: b=Button(main,text='OK',command=go) b.pack() That should fix it. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From rschroev_nospam_ml at fastmail.fm Sun Feb 20 20:59:39 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sun Feb 20 21:00:03 2005 Subject: [Tutor] Re: Fwd: Create list of IPs In-Reply-To: <401796869421.20050220112436@columbus.rr.com> References: <4218885B.8050609@tds.net> <19138.1108912714@www4.gmx.net> <401796869421.20050220112436@columbus.rr.com> Message-ID: <cvaq16$bvj$1@sea.gmane.org> R. Alan Monroe wrote: >>>Liam Clarke wrote: > > >>[ snip ] > > >>>- increment an IP. This is the hardest part. > > >>Why? An ip (V4) is just an 32bit integer :-) > > > Indeed. Some early versions of MacTCP for MacOS made you input the > address as a single large decimal number :^) And you can use it in URLs too (at least in Mozilla): python.org's IP address is 194.109.137.226, which is 3261958626 when represented as an integer. Typing http://3261958626/ in the browsers address bar takes you to the homepage :) -- "Codito ergo sum" Roel Schroeven From mwalsh at groktech.org Sun Feb 20 21:32:13 2005 From: mwalsh at groktech.org (Martin Walsh) Date: Sun Feb 20 21:32:20 2005 Subject: [Tutor] Attaching an uploaded file to an email In-Reply-To: <BE3D45DE.A11%wilson@visi.com> References: <BE3D45DE.A11%wilson@visi.com> Message-ID: <4218F3CD.1090402@groktech.org> Tim Wilson wrote: >Hi everyone, > > Hi Tim, I'm a newb, first time posting, so please take any of the following advice at face value.... ># Collect form information >form = cgi.FieldStorage() >requestername = form["requestername"].value >fromaddr = form["email"].value >itemname = form["itemname"].value >description = form["description"].value >buildings = form.getlist("building") >room = form["room"].value >dateneeded = form["dateneeded"].value >po = form["po"].value >budgetcode = form["budgetcode"].value >attachment = form["attachment"].value > > based on this cookbook recipe http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/273844, it looks like cgi.FieldStorage() returns a file-like object for file input fields, having .filename and .file attributes. the file attribute has a read() method which may be useful. having never used cgi I'm not sure what .value returns for file input fields, don't know if this is of any consequence. >buildinglist = ", ".join(buildings) > >**[ misc code snipped ]** > ># Set some email headers >#msg = MIMEText(msgtext) >msg = MIMEMultipart() >msg['Subject'] = itemname >msg['From'] = "%s <%s>" % (requestername, fromaddr) >msg['To'] = toaddr >if len(buildings) != 0: > for building in buildings: > msg['X-HRT-Building'] = building >if po != "": msg['X-HRT-PO'] = po >if dateneeded != "": > try: > duedate = time.asctime(time.strptime(dateneeded, "%m/%d/%Y")) > msg['X-HRT-Due-Date'] = duedate > except ValueError: > pass >msg.preamble = "Tech order request" >msg.epilogue = "" > > if you know that the attachment will always be a text file and your assignment of 'attachment' looks like this: attachment = form["attachment"] then you might try the following (untested): part = MIMEText(attachment.file.read()) # if I understand correctly, the 'Content-Disposition' header is necessary to make the file # appear in the message as an attachment, otherwise it may occupy the msg body. part.add_header('Content-Disposition', 'attachment', filename=attachment.filename) msg.attach(part) ># Send the message >server = smtplib.SMTP('localhost') >server.sendmail(fromaddr, toaddr, msg.as_string(0)) >server.quit() > > there's a great example in the email module docs if you're dealing with more than just text files : http://docs.python.org/lib/node578.html (3rd example, using the mimetypes module) I have collected code snippets from various sources (python docs, ASPNs python cookbook) into a basic MIMEMailer class, that I use fairly regularly in hobby projects. If anyone is interested, I'd be happy to share, or post it here. HTH, Marty From ralfasy2k at hotmail.com Sun Feb 20 21:41:59 2005 From: ralfasy2k at hotmail.com (Ralfas Jegorovas) Date: Sun Feb 20 21:42:11 2005 Subject: [Tutor] Re: Create list of IPs Message-ID: <BAY101-F39C161EC7096C0640EF8FCE4600@phx.gbl> Thanks alot to everyone for your help! I'm not completely sure I understand how Roel's code works so I'll be doing a bit of research :-) (but it works :-D). Thanks again. All the best, Ralf From cyresse at gmail.com Sun Feb 20 22:54:05 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sun Feb 20 22:54:09 2005 Subject: [Tutor] dictionary dispatch for object instance attributes question In-Reply-To: <4218820E.3050908@tds.net> References: <42127579.3080001@po-box.mcgill.ca> <5d0204a105021518204d86acc9@mail.gmail.com> <4212D09F.5010601@po-box.mcgill.ca> <5d0204a10502161309775723c5@mail.gmail.com> <4213BFE1.1070005@po-box.mcgill.ca> <f2ff2d05022001591da993a7@mail.gmail.com> <4218820E.3050908@tds.net> Message-ID: <f2ff2d050220135445628385@mail.gmail.com> Ah, see, I should convince my bosses that I need a Python interpreter. Of course, then they'd ask what Python was, and why I was thinking about it at work.... Duh, I was just reading the docs, and I kept thinking that an attribute was just a class variable. Thanks, Kent, now I have all sorts of interesting experiments to undertake... On Sun, 20 Feb 2005 07:26:54 -0500, Kent Johnson <kent37@tds.net> wrote: > Liam Clarke wrote: > > Hi, > > > > just an expansion on Brian's query, is there a variant of getattr for > > instance methods? > > > > i.e. class DBRequest: > > def __init__(self, fields, action): > > self.get(fields) > > > > def get(self, fields): > > print fields > > > > > > Instead of self.get in _init__, the value of action to call a > > function? Or, is it going to have to be dictionary dispatch? > > I don't understand your example, but instance methods are attributes too, so getattr() works with > them as well as simple values. > > An instance method is an attribute of the class whose value is a function. When you access the > attribute on an instance you get something called a 'bound method' which holds a reference to the > actual function and a reference to the instance (to pass to the function as the 'self' parameter). > You can call a bound method just like any other function. So: > > >>> class foo: > ... def __init__(self): > ... self.bar = 3 > ... def baz(self): > ... print self.bar > ... > >>> f=foo() > > getattr() of a simple attribute: > >>> getattr(f, 'bar') > 3 > > getattr() of an instance method returns a 'bound method': > >>> getattr(f, 'baz') > <bound method foo.baz of <__main__.foo instance at 0x008D5FD0>> > > Calling the bound method (note the added ()) is the same as calling the instance method directly: > >>> getattr(f, 'baz')() > 3 > > Of course you can do the same thing with dot notation for attributes: > >>> b=f.baz > >>> b > <bound method foo.baz of <__main__.foo instance at 0x008D5FD0>> > >>> b() > 3 > > Kent > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cyresse at gmail.com Sun Feb 20 22:57:48 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sun Feb 20 22:57:53 2005 Subject: [Tutor] Attaching an uploaded file to an email In-Reply-To: <4218F3CD.1090402@groktech.org> References: <BE3D45DE.A11%wilson@visi.com> <4218F3CD.1090402@groktech.org> Message-ID: <f2ff2d050220135761438f20@mail.gmail.com> Yeah, you really have to see a few examples to get the hang of creating MIME emails, this is one area where I think the Python docs, quite frankly, stink. I had enough trouble getting attachments from a MIME email, let alone adding one. (But, if I recall correctly, a MIME email has a distinct structure, to the point that the email module has a walk() function to traverse it.) Regards, Liam Clarke On Sun, 20 Feb 2005 15:32:13 -0500, Martin Walsh <mwalsh@groktech.org> wrote: > Tim Wilson wrote: > > >Hi everyone, > > > > > Hi Tim, > > I'm a newb, first time posting, so please take any of the following > advice at face value.... > > ># Collect form information > >form = cgi.FieldStorage() > >requestername = form["requestername"].value > >fromaddr = form["email"].value > >itemname = form["itemname"].value > >description = form["description"].value > >buildings = form.getlist("building") > >room = form["room"].value > >dateneeded = form["dateneeded"].value > >po = form["po"].value > >budgetcode = form["budgetcode"].value > >attachment = form["attachment"].value > > > > > based on this cookbook recipe > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/273844, it looks > like cgi.FieldStorage() returns a file-like object for file input > fields, having .filename and .file attributes. the file attribute has a > read() method which may be useful. having never used cgi I'm not sure > what .value returns for file input fields, don't know if this is of any > consequence. > > >buildinglist = ", ".join(buildings) > > > >**[ misc code snipped ]** > > > ># Set some email headers > >#msg = MIMEText(msgtext) > >msg = MIMEMultipart() > >msg['Subject'] = itemname > >msg['From'] = "%s <%s>" % (requestername, fromaddr) > >msg['To'] = toaddr > >if len(buildings) != 0: > > for building in buildings: > > msg['X-HRT-Building'] = building > >if po != "": msg['X-HRT-PO'] = po > >if dateneeded != "": > > try: > > duedate = time.asctime(time.strptime(dateneeded, "%m/%d/%Y")) > > msg['X-HRT-Due-Date'] = duedate > > except ValueError: > > pass > >msg.preamble = "Tech order request" > >msg.epilogue = "" > > > > > if you know that the attachment will always be a text file and your > assignment of 'attachment' looks like this: > > attachment = form["attachment"] > > then you might try the following (untested): > > part = MIMEText(attachment.file.read()) > # if I understand correctly, the 'Content-Disposition' header is > necessary to make the file > # appear in the message as an attachment, otherwise it may occupy > the msg body. > part.add_header('Content-Disposition', 'attachment', > filename=attachment.filename) > msg.attach(part) > > ># Send the message > >server = smtplib.SMTP('localhost') > >server.sendmail(fromaddr, toaddr, msg.as_string(0)) > >server.quit() > > > > > there's a great example in the email module docs if you're dealing with > more than just text files : > http://docs.python.org/lib/node578.html (3rd example, using the > mimetypes module) > > I have collected code snippets from various sources (python docs, ASPNs > python cookbook) into a basic MIMEMailer class, that I use fairly > regularly in hobby projects. If anyone is interested, I'd be happy to > share, or post it here. > > HTH, > Marty > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From gltewalt at yahoo.com Mon Feb 21 01:02:05 2005 From: gltewalt at yahoo.com (Greg T) Date: Mon Feb 21 01:02:09 2005 Subject: [Tutor] Re: Create list of IPs In-Reply-To: <20050220110107.6F2621E401F@bag.python.org> Message-ID: <20050221000205.70996.qmail@web52904.mail.yahoo.com> > I am wondering how I would go about making a list of > IPs between two set > IPs. > This is my initial code: > > <my code> > > def list2str(list): > ip='' > for part in list: > if len(ip)!=0: > ip=ip+'.'+part > else: > ip=ip+part > return ip > > iplist = [] > > minip = ['1','0','0','1'] # starting IP > maxip = ['1','0','15','16'] # ending IP > > currentip = minip # set currentip to value of minip > **snip** > I'd appreciate any help. > > Thanks, > Ralf > It looks like you need not concern yourself with the ['1','0',...] part of your array(s). Only to increment from '0','1' to '15','16' Keeping with arrays, you could get last position of the array and increment number until 16. If last position > 15, stop incrementation and move to next to last position in the array until it reaches 15 (also breaks to to adding 15 to each octet in the last two array positions, one by one) > > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From cmeesters at ucdavis.edu Mon Feb 21 11:01:26 2005 From: cmeesters at ucdavis.edu (Christian Meesters) Date: Mon Feb 21 11:01:33 2005 Subject: [Tutor] Initializing with a call like: someClass.open("someFile")? Message-ID: <200502211001.j1LA1Q9d029551@diometes.ucdavis.edu> Hi My cryptic subject is perhaps not sufficient - I'll try to make it a little better: Assume you'd like to write something like: import someClass x = someClass.open("someFile") Here '.open' should read in the data and initialize the instance - with or without calling __init__. How is this to implement? Up to now I rather wrote something like x = someClass(somePrepFunction("someFile")) where the return value of somePrepFunction was used to initialize x or called the conventional 'open' within __init__. But is there no direct approach like in my pseudo-code? My problem is that if I simply define open as a method of someClass (with def open(self,file_name): #somecode pass ) all I get is: TypeError: unbound method open() must be called with someClass instance as first argument (got str instance instead) Which is perfectly understandable. But what is a possible workaround? (Instead of 'open' I could, of course, better use some other keyword which is no Python keyword.) Any hints? Thanks a lot in advance. Christian From cvmallari at gmail.com Mon Feb 21 11:42:22 2005 From: cvmallari at gmail.com (Chris Mallari) Date: Mon Feb 21 11:42:25 2005 Subject: [Tutor] database programming Message-ID: <bea19ca2050221024253145e03@mail.gmail.com> hi there! can u pls send me sample code in accessing a simple database using python. Chris Mallari thanks From lgxjcb at nottingham.ac.uk Mon Feb 21 11:57:26 2005 From: lgxjcb at nottingham.ac.uk (Chris Bromley) Date: Mon Feb 21 12:03:04 2005 Subject: [Tutor] Help needed with script to batch-create shapefiles Message-ID: <s219bfc7.011@ccw0m1.nottingham.ac.uk> Dear All, Just a quick follow up for those of you who are interested. The batching script is now working and is attached below. The intermediate step of saving the xy layer to a folder was unecessary and has been removed. The 'MakeXYEventLayer' command only creates "in memory" layers and not .lyr files on disk. Also, the 'FeatureClassToShapefile' command has been replaced by the 'CopyFeatures' command, since all that FeatureClassToShapefile does is call CopyFeatures multiple times. CopyFeatures is faster. Thanks again to evryone who replied to my second posting. Regards, Chris. #Import standard library modules import win32com.client, sys, os #Create the Geoprocessor object GP = win32com.client.Dispatch("esriGeoprocessing.GpDispatch.1") import traceback #Set the input workspace GP.workspace = "C:/One" #Set the shapefile output workspace outputShapefiles = "C:/Shapefiles" try: # Load required toolboxes... GP.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx") GP.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Conversion Tools.tbx") #Get a list of dBase files in the input folder fcs = GP.ListTables("*","dBASE") #Loop through the list of dBase files fcs.Reset() fc = fcs.Next() while fc: # Set the outputname for each output to be the same as the input. outxyLayer = fc.split(".")[0] #Convert each dBase table in the list into an xyLayer. GP.MakeXYEventLayer_management(fc, "X", "Y", outxyLayer, "") print "Made XYEvent layer %s with %i features" % (outxyLayer, gp.GetCount(outxyLayer)) #Convert each xyLayer into a shapefile GP.CopyFeatures(outxyLayer, outputShapefiles + "/" + outxyLayer) #Move to the next fc in the list. print "FINISHED converting %s TO %s" % (fc, outputShapefiles + "/" + outxyLayer) fc = fcs.Next() except: traceback.print_exc() # If an error occurred print the message to the screen print GP.GetMessages() This message has been checked for viruses but the contents of an attachment may still contain software viruses, which could damage your computer system: you are advised to perform your own checks. Email communications with the University of Nottingham may be monitored as permitted by UK legislation. From kent37 at tds.net Mon Feb 21 12:29:26 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Feb 21 12:29:31 2005 Subject: [Tutor] Initializing with a call like: someClass.open("someFile")? In-Reply-To: <200502211001.j1LA1Q9d029551@diometes.ucdavis.edu> References: <200502211001.j1LA1Q9d029551@diometes.ucdavis.edu> Message-ID: <4219C616.60109@tds.net> Christian Meesters wrote: > Hi > > My cryptic subject is perhaps not sufficient - I'll try to make it a little better: > Assume you'd like to write something like: > > import someClass > x = someClass.open("someFile") > > Here '.open' should read in the data and initialize the instance - with or without calling __init__. > How is this to implement? Up to now I rather wrote something like x = > someClass(somePrepFunction("someFile")) where the return value of somePrepFunction was used > to initialize x or called the conventional 'open' within __init__. But is there no direct approach like > in my pseudo-code? You can make your code work as written by making open() a module-level function in someClass.py. Call the function fromFile() to avoid redefining open. Assuming the class has a constructor that takes a string argument: ## someClass.py def fromFile(f): data = open(f).read() return someClass(data) class someClass: def __init__(self, data ): # init from data Another way to do it, if this is the only way you create someClass instances, is to put the file read right in __init__(): class someClass: def __init__(self, f): data = open(f).read() # init from data Finally, you can implement fromFile() as a classmethod of someClass: class someClass: def __init__(self, data ): # init from data @classmethod@ # requires Python 2.4 def fromFile(cls, f): data = open(f).read() return cls(data) Clients would do this: from someClass import someClass x = someClass.fromFile("someFile") See this thread on comp.lang.python for more discussion of a similar requirement: http://tinyurl.com/497vg Kent > My problem is that if I simply define open as a method of someClass (with > def open(self,file_name): > #somecode > pass > ) all I get is: > TypeError: unbound method open() must be called with someClass instance as first argument > (got str instance instead) > Which is perfectly understandable. But what is a possible workaround? (Instead of 'open' I could, > of course, better use some other keyword which is no Python keyword.) Several possibilities: - you can make a function to do what you want: > > Any hints? > > Thanks a lot in advance. > Christian > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From bgibson at us.ibm.com Mon Feb 21 13:59:43 2005 From: bgibson at us.ibm.com (Bob Gibson) Date: Mon Feb 21 13:59:48 2005 Subject: [Tutor] Re: database programming In-Reply-To: <20050221104231.123791E400D@bag.python.org> Message-ID: <OF0B992281.A66D997E-ON85256FAF.00473086-85256FAF.004762AC@us.ibm.com> > hi there! can u pls send me sample code in accessing a simple database > using python. > > Chris Mallari > thanks Chris: How about "Jython"? Here's an article that I just wrote: http://www-128.ibm.com/developerworks/db2/library/techarticle/dm-0502gibson/index.html Bob -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050221/7d561766/attachment.html From misha.dunn at gmail.com Mon Feb 21 15:22:54 2005 From: misha.dunn at gmail.com (Michael Dunn) Date: Mon Feb 21 15:23:00 2005 Subject: [Tutor] database programming In-Reply-To: <bea19ca2050221024253145e03@mail.gmail.com> References: <bea19ca2050221024253145e03@mail.gmail.com> Message-ID: <e95c92e005022106225b5b61b0@mail.gmail.com> Hi Chris, If you just want to learn about databases, then sqlite is a good way to go. It's small, it's typeless (which means you don't have to define ahead of time what sort of thing is going to go in which bit of the database; python is typeless too), and it is not split into client and server (making it much simpler to install and manage, although you can't use it for fancy stuff over a network). You can install sqlite from http://www.sqlite.org/ if you want to play around with the interpreter. This is a good idea if you're not used to databases or you don't know sql, because then you'll learn better what python is trying to do (or what you're trying to make python do). There are plenty of one-off jobs that are easier to do directly in the sqlite interpreter too. To use sqlite from python you need pysqlite from http://sourceforge.net/projects/pysqlite. If you install the binary you don't need to install sqlite separately. There are simple examples of usage in the manual (at http://pysqlite.org/manual.html, or with the installation files). A short example is: import sqlite connection = sqlite.connect("my_database") # make a connection cursor = connection.cursor() # make a database cursor cursor.execute("select * from table1") # send a sql command to the database results = cursor.fetchall() # get a list with the results Cheers, Michael On Mon, 21 Feb 2005 18:42:22 +0800, Chris Mallari <cvmallari@gmail.com> wrote: > hi there! can u pls send me sample code in accessing a simple database > using python. > > Chris Mallari > thanks > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From pierre.barbier at cirad.fr Mon Feb 21 16:06:51 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Mon Feb 21 16:04:57 2005 Subject: [Tutor] Time Controlled Execution In-Reply-To: <32b5ee7605022007255851f221@mail.gmail.com> References: <32b5ee7605022007255851f221@mail.gmail.com> Message-ID: <4219F90B.5030205@cirad.fr> I really don't think you can have a common way to do this on both systems. First, the way to kill a process is quite different on both systems (the os.kill function works only on UNIX systems, and I don't know is there is such a function available in Python for MS Windows). Then, I really doubt the use of pipes will work on Windows ... In our labs, there was some tries to port UNIX program using pipes under Windows and bidirectionnal pipes did not work at all and were thus abandonned. But try googling for some package doing something similar. If you get any answer, don't forget to warn the list :) Pierre Varun Soundararajan a ?crit : > Hi, > I want to know how to do this: > I have an executable file, which reads input from stdin provided > output at stdout or stderr. > I have to run it for a specific period of time (say 5 secs), get the > output and display it. > If i use popen(), this way: > from subprocess import * > p = Popen(["test","<test.in"," >test.out"], shell=True) > p.wait() > print p.stdin,p.stdout > I dont get output in p.stdout.Apart from this, can u say how to stop > this subprocess after 5 secs (or whatever time frame specified)? > signal SIGALRM may not work (as i want it to work in windows & unix). > -Varun > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 From ryan at acceleration.net Mon Feb 21 16:34:31 2005 From: ryan at acceleration.net (Ryan Davis) Date: Mon Feb 21 16:34:35 2005 Subject: [Tutor] Initializing with a call like: someClass.open("someFile")? In-Reply-To: <200502211001.j1LA1Q9d029551@diometes.ucdavis.edu> Message-ID: <20050221153433.4661A1E4003@bag.python.org> You could make the __init__ take the filename: def __init__(self, filename=None): #do whatever And then instantiate the object like: >>>x = someClass(filename="someFile") Alternatively, you could make the Open function a module level function, defined in someClass.py, but not in the actual class definition. There's also a way to do it with @staticmethod, but I haven't ever touched that. Thanks, Ryan -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of Christian Meesters Sent: Monday, February 21, 2005 5:01 AM To: tutor@python.org Subject: [Tutor] Initializing with a call like: someClass.open("someFile")? Hi My cryptic subject is perhaps not sufficient - I'll try to make it a little better: Assume you'd like to write something like: import someClass x = someClass.open("someFile") Here '.open' should read in the data and initialize the instance - with or without calling __init__. How is this to implement? Up to now I rather wrote something like x = someClass(somePrepFunction("someFile")) where the return value of somePrepFunction was used to initialize x or called the conventional 'open' within __init__. But is there no direct approach like in my pseudo-code? My problem is that if I simply define open as a method of someClass (with def open(self,file_name): #somecode pass ) all I get is: TypeError: unbound method open() must be called with someClass instance as first argument (got str instance instead) Which is perfectly understandable. But what is a possible workaround? (Instead of 'open' I could, of course, better use some other keyword which is no Python keyword.) Any hints? Thanks a lot in advance. Christian _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From mark.kels at gmail.com Mon Feb 21 18:36:32 2005 From: mark.kels at gmail.com (Mark Kels) Date: Mon Feb 21 18:36:37 2005 Subject: [Tutor] Help debuging a small program Message-ID: <c225925305022109366ee359b0@mail.gmail.com> Hi list ! Here is a small port scanner I made to practice sockets and GUI programming ( WARNING: the program crash when scan button is clicked): #----------Imports---------- from Tkinter import * import socket #----------The result GUI window function--------- def result(): global result_t #I made result_t global so I will be able to insert data into it from the scan function r_root=Toplevel(root) result_t=Text(r_root) result_t.pack() #----------Command Functions---------- # + ---Function to get the info from the gui and start the scan--- def get_info(): result() host=host_e.get() start_port=int(start_port_e.get()) end_port=int(end_port_e.get()) scan(host,start_port,end_port) # + ---The Scan--- def scan(host,start_port,end_port): sk=socket.socket(socket.AF_INET, socket.SOCK_STREAM) while start_port<=end_port: try: sk.connect((host,start_port)) except: result_t.insert(END,"Port",start_port,"is CLOSED on",host,"\n") else: result_t.insert(END,"Port",start_port,"is OPENED on",host,"\n") start_port=start_port+1 #----------The main GUI window---------- root=Tk() Label(root,text="Host: ").grid(row=1,column=1) host_e=Entry(root) host_e.grid(row=1,column=2) Label(root,text="Start port: ").grid(row=2,column=1) start_port_e=Entry(root) start_port_e.grid(row=2,column=2) Label(root,text="End port: ").grid(row=3,column=1) end_port_e=Entry(root) end_port_e.grid(row=3,column=2) Button(root,text="Scan",command=get_info).grid(row=5,column=1) root.mainloop() Why does the program crash (without any errors :-/ ) when I click the Scan button ?? -- 1. The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners. 2. Unix is user friendly - it's just picky about it's friends. 3. Documentation is like sex: when it is good, it is very, very good. And when it is bad, it is better than nothing. - Dick Brandon From kent37 at tds.net Mon Feb 21 19:21:35 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Feb 21 19:21:42 2005 Subject: [Tutor] Help debuging a small program In-Reply-To: <c225925305022109366ee359b0@mail.gmail.com> References: <c225925305022109366ee359b0@mail.gmail.com> Message-ID: <421A26AF.5020906@tds.net> Mark Kels wrote: > Hi list ! > Here is a small port scanner I made to practice sockets and GUI > programming ( WARNING: the program crash when scan button is clicked): How far does it get? How do you know? I would put some debug print statements in. Also you should call sk.close() in the else clause of scan(). Finally, I don't think you will see any output in the result window until get_info() returns; you have to give some time to mainloop() for it to be able to trigger the updates. > > #----------Imports---------- > from Tkinter import * > import socket > #----------The result GUI window function--------- > def result(): > global result_t #I made result_t global so I will be able to > insert data into it from the scan function > r_root=Toplevel(root) > result_t=Text(r_root) > result_t.pack() > > #----------Command Functions---------- > # + ---Function to get the info from the gui and start the scan--- > def get_info(): > result() > host=host_e.get() > start_port=int(start_port_e.get()) > end_port=int(end_port_e.get()) > scan(host,start_port,end_port) > > # + ---The Scan--- > def scan(host,start_port,end_port): > sk=socket.socket(socket.AF_INET, socket.SOCK_STREAM) > while start_port<=end_port: > try: > sk.connect((host,start_port)) > except: > result_t.insert(END,"Port",start_port,"is CLOSED on",host,"\n") > else: > result_t.insert(END,"Port",start_port,"is OPENED on",host,"\n") > start_port=start_port+1 > > #----------The main GUI window---------- > root=Tk() > Label(root,text="Host: ").grid(row=1,column=1) > host_e=Entry(root) > host_e.grid(row=1,column=2) > Label(root,text="Start port: ").grid(row=2,column=1) > start_port_e=Entry(root) > start_port_e.grid(row=2,column=2) > Label(root,text="End port: ").grid(row=3,column=1) > end_port_e=Entry(root) > end_port_e.grid(row=3,column=2) > Button(root,text="Scan",command=get_info).grid(row=5,column=1) > > root.mainloop() > > Why does the program crash (without any errors :-/ ) when I click the > Scan button ?? > From dyoo at hkn.eecs.berkeley.edu Mon Feb 21 19:38:31 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Feb 21 19:38:38 2005 Subject: [Tutor] database programming In-Reply-To: <bea19ca2050221024253145e03@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0502211037140.26448-100000@hkn.eecs.berkeley.edu> On Mon, 21 Feb 2005, Chris Mallari wrote: > hi there! can u pls send me sample code in accessing a simple database > using python. Hi Chris, You may want to look at the Database topic guide: http://www.python.org/topics/database/ It has links to examples, tutorials, and other documentation. From bvande at po-box.mcgill.ca Mon Feb 21 21:02:18 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon Feb 21 21:08:09 2005 Subject: [Tutor] design?--having subclassed methods add logic in the middel of class methods Message-ID: <421A3E4A.7000106@po-box.mcgill.ca> Hi all, I am still building my toolset for working with treepad files. (This is the one all my recent posts concerning Node classes have been about.) I am exploring ways of having the methods of a sub-class insert additional logic into their version of a class's methods, while still running the original class's method logic. All code below is pseudo-code. My Node class has a parse method which in part looks something like: def _parse(self, list_of_lines): # some parsing based on whole list_of_lines for line in list_of_lines: # Do line parsing stuff here In a subclass of Node class, I am wanting Subclassed_Node._parse() to behave somewhat differently than does Node._parse(). I need the subclass method to insert new logic into the for line in list_of_lines part of _parse method. Is this an acceptable design for doing this? # in Node class def _parse(self, list_of_lines): # some parsing based on whole list_of_lines for line in list_of_lines: _subclass_preparse(line) # Do line parsing stuff here def _subclass_preparse(self, line): '''Dummy method to override''' pass # in Subclassed_Node class def _subclass_preparse(self, line): '''Subclassed_Node class specific parsing, overrides Node method.''' # Do special parsing of the line here here Does this scream `Danger -- spaghetti code will result down the road'? The method name containing `preparse' indicates I might also feel a need for a `postparse' structure, too. The only viable alternative I see (copy and paste is clearly worse ;-) is to break my Node._parse up into a part that works on the whole list_of_lines and a part that works on each line as in def _parse(self, list_of_lines): self._parse_list_of_lines(self, list_of_lines) for line in list_of_lines: self._parse_line(line) def _parse_line(self, line): # line parsing logic here Then the subclass of Node would define _parse_line like so: def _parse_line(self, line): # line parsing logic before the Node class line parsing logic # akin to _subclass_preparse above Node._parse_line(self, line) # line parsing logic after the Node class line parsing logic # akin to the possibly needed _subclass_postparse mentioned above Are there general reasons to prefer one approach over the other? Alternative ways I've overlooked? Best and thanks to all, Brian vdB From administrata at hotmail.com Mon Feb 21 21:55:26 2005 From: administrata at hotmail.com (. Sm0kin'_Bull) Date: Mon Feb 21 21:56:06 2005 Subject: [Tutor] More Advanced Calculator. Message-ID: <BAY22-F4056E66650D4D1F22FA8CFC8610@phx.gbl> With your helps i managed to program Advanced Calculator. But, I want to change(or add) some to it. 1. How can i /n/n result bit? I tired.. but, I can't 2. How can i enable it to calculate float-pointing numbers? (Which will make it complicated) It should looks like this... Please input data Number1: Mathsmetical Sign: Number2: Result: And the source i got import operator ops_dict = {'+': operator.add, '*' : operator.mul, '-' : operator.sub, '/' : operator.div} def perform_arithmetic(): print "Please input data" number1 = int(raw_input("\nNumber1: ")) sign = raw_input("Mathsmetics Sign: ") number2 = int(raw_input("Number2: ")) try: result = ops_dict[sign](number1, number2) except KeyError: raise NotImplementedError, "I don't know the sign '%s'" %sign # add output formatting logic as desired return result print perform_arithmetic() raw_input("") Cheers! :) _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From cyresse at gmail.com Mon Feb 21 21:58:00 2005 From: cyresse at gmail.com (Liam Clarke) Date: Mon Feb 21 21:58:05 2005 Subject: [Tutor] database programming In-Reply-To: <Pine.LNX.4.44.0502211037140.26448-100000@hkn.eecs.berkeley.edu> References: <bea19ca2050221024253145e03@mail.gmail.com> <Pine.LNX.4.44.0502211037140.26448-100000@hkn.eecs.berkeley.edu> Message-ID: <f2ff2d05022112583c661d98@mail.gmail.com> >>>import sqlite >>>x = sqlite.connect('mysqlitedb') >>>cx = x.cursor() >>>cx.execute( 'create table foo (columnA varchar(15), columnB number(3))' ) >>>cx.execute ('insert into foo (columnA, columnB) values ("Parrot", 90)') >>>x.commit() >>>cx.execute('select * from foo') >>>cx.fetchall() [('Parrot', 90)] >>>cx.execute('insert into foo (columnA, columnB) values ("Sketch", 120)' ) >>>cx.execute('select * from foo') >>>cx.fetchall() [('Parrot', 90), ('Sketch', 120)] >>>cx.execute('select * from foo where columnB < 100') >>>cx.fetchall() [('Parrot', 90)] The key part to all of that is the SQL in the execute statements. I recommend http://www.sqlcourse.com/ which was recommended to me by Alan. Oh, and don't forget the c.commit() part! That had me running around in circles all night last night. Regards, Liam Clarke PS Anyone know if there's a way to get a list of tables in a DB? I've got the pragma to get a list of columns in a table, but just in the off chance... On Mon, 21 Feb 2005 10:38:31 -0800 (PST), Danny Yoo <dyoo@hkn.eecs.berkeley.edu> wrote: > > > On Mon, 21 Feb 2005, Chris Mallari wrote: > > > hi there! can u pls send me sample code in accessing a simple database > > using python. > > Hi Chris, > > You may want to look at the Database topic guide: > > http://www.python.org/topics/database/ > > It has links to examples, tutorials, and other documentation. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From kent37 at tds.net Mon Feb 21 22:21:23 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Feb 21 22:21:35 2005 Subject: [Tutor] database programming In-Reply-To: <f2ff2d05022112583c661d98@mail.gmail.com> References: <bea19ca2050221024253145e03@mail.gmail.com> <Pine.LNX.4.44.0502211037140.26448-100000@hkn.eecs.berkeley.edu> <f2ff2d05022112583c661d98@mail.gmail.com> Message-ID: <421A50D3.2020406@tds.net> Liam Clarke wrote: > PS Anyone know if there's a way to get a list of tables in a DB? I've > got the pragma to get a list of columns in a table, but just in the > off chance... AFAIK there is no standard way to do this - it is different for each database. For SQLite, see this FAQ: http://www.sqlite.org/faq.html#q9 Kent From kent37 at tds.net Mon Feb 21 22:40:30 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Feb 21 22:40:36 2005 Subject: [Tutor] design?--having subclassed methods add logic in the middel of class methods In-Reply-To: <421A3E4A.7000106@po-box.mcgill.ca> References: <421A3E4A.7000106@po-box.mcgill.ca> Message-ID: <421A554E.5000909@tds.net> Brian van den Broek wrote: > Hi all, > > I am still building my toolset for working with treepad files. (This is > the one all my recent posts concerning Node classes have been about.) > > I am exploring ways of having the methods of a sub-class insert > additional logic into their version of a class's methods, while still > running the original class's method logic. > > All code below is pseudo-code. > > My Node class has a parse method which in part looks something like: > > def _parse(self, list_of_lines): > > # some parsing based on whole list_of_lines > > for line in list_of_lines: > # Do line parsing stuff here > > In a subclass of Node class, I am wanting Subclassed_Node._parse() to > behave somewhat differently than does Node._parse(). I need the subclass > method to insert new logic into the for line in list_of_lines part of > _parse method. > > Is this an acceptable design for doing this? Yes. This is an example of the Template Method pattern. It is a very useful technique for allowing subclasses to specialize an operation. http://home.earthlink.net/~huston2/dp/templateMethod.html > > # in Node class > > def _parse(self, list_of_lines): > > # some parsing based on whole list_of_lines > > for line in list_of_lines: > _subclass_preparse(line) > # Do line parsing stuff here > > def _subclass_preparse(self, line): > '''Dummy method to override''' > pass > > > # in Subclassed_Node class > > def _subclass_preparse(self, line): > '''Subclassed_Node class specific parsing, overrides Node method.''' > # Do special parsing of the line here here > > Does this scream `Danger -- spaghetti code will result down the road'? > The method name containing `preparse' indicates I might also feel a need > for a `postparse' structure, too. No, IMO it's a reasonable design. > > The only viable alternative I see (copy and paste is clearly worse ;-) > is to break my Node._parse up into a part that works on the whole > list_of_lines and a part that works on each line as in > > def _parse(self, list_of_lines): > > self._parse_list_of_lines(self, list_of_lines) > > for line in list_of_lines: > self._parse_line(line) > > def _parse_line(self, line): > # line parsing logic here > > Then the subclass of Node would define _parse_line like so: > > def _parse_line(self, line): > > # line parsing logic before the Node class line parsing logic > # akin to _subclass_preparse above > > Node._parse_line(self, line) > > # line parsing logic after the Node class line parsing logic > # akin to the possibly needed _subclass_postparse mentioned above > > Are there general reasons to prefer one approach over the other? > Alternative ways I've overlooked? They are both template methods. I would choose between them based on whether there is common processing between the subclasses or not. In other words, in the version with _subclass_preparse() is there actually some work for the base class to do after _subclass_preparse() is called? If so, _subclass_preparse() might be a better design; if not, you might as well just use _parse_line(). BTW I would just call it _preparse() myself. Kent > > Best and thanks to all, > > Brian vdB > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Mon Feb 21 22:46:04 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Feb 21 22:46:10 2005 Subject: [Tutor] More Advanced Calculator. In-Reply-To: <BAY22-F4056E66650D4D1F22FA8CFC8610@phx.gbl> References: <BAY22-F4056E66650D4D1F22FA8CFC8610@phx.gbl> Message-ID: <421A569C.2040107@tds.net> . Sm0kin'_Bull wrote: > With your helps i managed to program Advanced Calculator. > But, I want to change(or add) some to it. > > 1. How can i /n/n result bit? I tired.. but, I can't You can use the print command to print your results. You can give print a list of values and it will print them separated with spaces. Try print 'Result:', number1, sign, number2, '=', result > > 2. How can i enable it to calculate float-pointing numbers? (Which will > make it complicated) Actually, I think you can just replace number1 = int(raw_input("\nNumber1: ")) with number1 = float(raw_input("\nNumber1: ")) (etc) to make it work with floating point! Kent > > > It should looks like this... > > Please input data > > Number1: > Mathsmetical Sign: > Number2: > > > Result: > > > And the source i got > > import operator > > ops_dict = {'+': operator.add, '*' : operator.mul, '-' : operator.sub, > '/' : operator.div} > > def perform_arithmetic(): > print "Please input data" > number1 = int(raw_input("\nNumber1: ")) > sign = raw_input("Mathsmetics Sign: ") > number2 = int(raw_input("Number2: ")) > > try: > result = ops_dict[sign](number1, number2) > except KeyError: > raise NotImplementedError, "I don't know the sign '%s'" %sign > > # add output formatting logic as desired > > return result > > print perform_arithmetic() > > raw_input("") > > > Cheers! :) > > _________________________________________________________________ > Express yourself instantly with MSN Messenger! Download today it's FREE! > http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From ternary at gmail.com Mon Feb 21 23:58:57 2005 From: ternary at gmail.com (Mike Bell) Date: Mon Feb 21 23:59:00 2005 Subject: [Tutor] Time Controlled Execution In-Reply-To: <32b5ee7605022007255851f221@mail.gmail.com> References: <32b5ee7605022007255851f221@mail.gmail.com> Message-ID: <82975b0c050221145871dfb17@mail.gmail.com> On Windows it looks like msvcrt will give you a non-blocking terminal read -- on mac / *nix systems it looks a little trickier: http://mail.python.org/pipermail/pythonmac-sig/2004-February/010140.html The os module in windows doesn't even have O_NONBLOCK. That seems like trouble. m On Sun, 20 Feb 2005 20:55:40 +0530, Varun Soundararajan <s.varun@gmail.com> wrote: > Hi, > I want to know how to do this: > I have an executable file, which reads input from stdin provided > output at stdout or stderr. > I have to run it for a specific period of time (say 5 secs), get the > output and display it. > If i use popen(), this way: > from subprocess import * > p = Popen(["test","<test.in"," >test.out"], shell=True) > p.wait() > print p.stdin,p.stdout > I dont get output in p.stdout.Apart from this, can u say how to stop > this subprocess after 5 secs (or whatever time frame specified)? > signal SIGALRM may not work (as i want it to work in windows & unix). > -Varun > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From bvande at po-box.mcgill.ca Tue Feb 22 00:37:52 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue Feb 22 00:44:53 2005 Subject: [Tutor] design?--having subclassed methods add logic in the middel of class methods In-Reply-To: <421A554E.5000909@tds.net> References: <421A3E4A.7000106@po-box.mcgill.ca> <421A554E.5000909@tds.net> Message-ID: <421A70D0.9090105@po-box.mcgill.ca> Kent Johnson said unto the world upon 2005-02-21 16:40: > Brian van den Broek wrote: <SNIP> >> >> I am exploring ways of having the methods of a sub-class insert >> additional logic into their version of a class's methods, while still >> running the original class's method logic. >> >> All code below is pseudo-code. >> >> My Node class has a parse method which in part looks something like: >> >> def _parse(self, list_of_lines): >> >> # some parsing based on whole list_of_lines >> >> for line in list_of_lines: >> # Do line parsing stuff here >> >> In a subclass of Node class, I am wanting Subclassed_Node._parse() to >> behave somewhat differently than does Node._parse(). I need the >> subclass method to insert new logic into the for line in list_of_lines >> part of _parse method. >> >> Is this an acceptable design for doing this? > > > Yes. This is an example of the Template Method pattern. It is a very > useful technique for allowing subclasses to specialize an operation. > http://home.earthlink.net/~huston2/dp/templateMethod.html Hi all, thanks for the link, Kent. I came up with something that has a non-pejorative name? I must be getting warmer! ;-) <SNIP my code sketch of how to do this `Template Method Pattern'> >> Does this scream `Danger -- spaghetti code will result down the road'? >> The method name containing `preparse' indicates I might also feel a >> need for a `postparse' structure, too. > > > No, IMO it's a reasonable design. > >> >> The only viable alternative I see (copy and paste is clearly worse ;-) >> is to break my Node._parse up into a part that works on the whole >> list_of_lines and a part that works on each line as in >> <SNIP example code sketch> >> >> Are there general reasons to prefer one approach over the other? >> Alternative ways I've overlooked? > > > They are both template methods. I would choose between them based on > whether there is common processing between the subclasses or not. In > other words, in the version with _subclass_preparse() is there actually > some work for the base class to do after _subclass_preparse() is called? > If so, _subclass_preparse() might be a better design; if not, you might > as well just use _parse_line(). Thanks for the advice; useful as ever. :-) Best to all, Brian vdB From cyresse at gmail.com Tue Feb 22 01:15:31 2005 From: cyresse at gmail.com (Liam Clarke) Date: Tue Feb 22 01:15:36 2005 Subject: [Tutor] database programming In-Reply-To: <421A50D3.2020406@tds.net> References: <bea19ca2050221024253145e03@mail.gmail.com> <Pine.LNX.4.44.0502211037140.26448-100000@hkn.eecs.berkeley.edu> <f2ff2d05022112583c661d98@mail.gmail.com> <421A50D3.2020406@tds.net> Message-ID: <f2ff2d0502211615359990af@mail.gmail.com> /me smacks head. Thanks Kent. Exactly what I need. Regards, Liam Clarke On Mon, 21 Feb 2005 16:21:23 -0500, Kent Johnson <kent37@tds.net> wrote: > Liam Clarke wrote: > > > PS Anyone know if there's a way to get a list of tables in a DB? I've > > got the pragma to get a list of columns in a table, but just in the > > off chance... > > AFAIK there is no standard way to do this - it is different for each database. For SQLite, see this FAQ: > http://www.sqlite.org/faq.html#q9 > > Kent > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From bgibson at us.ibm.com Tue Feb 22 03:24:14 2005 From: bgibson at us.ibm.com (Bob Gibson) Date: Tue Feb 22 04:25:37 2005 Subject: [Tutor] Re: database programming (list of tables) In-Reply-To: <20050221234458.01E4B1E4008@bag.python.org> Message-ID: <OF4A197C5A.A3DD382F-ON85256FB0.000CE6D8-85256FB0.000D347C@us.ibm.com> Liam: I agree with Kent. It depends. Not only on the database, but also on the interface (API) used to connect to the database. For example, if you use ODBC to connect to all of your databases, you should be able to use the SQLTables() routine. For more details, see the following: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/odbc/htm/odbcsqltables.asp Bob -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050221/a79a86bb/attachment.htm From alan.gauld at freenet.co.uk Tue Feb 22 05:46:13 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Feb 22 05:45:25 2005 Subject: [Tutor] design?--having subclassed methods add logic in the middelof class methods References: <421A3E4A.7000106@po-box.mcgill.ca> Message-ID: <01ae01c51899$7031c520$2ca88651@xp> > All code below is pseudo-code. > > Is this an acceptable design for doing this? > > # in Node class > > def _parse(self, list_of_lines): > > # some parsing based on whole list_of_lines > > for line in list_of_lines: > _subclass_preparse(line) > # Do line parsing stuff here > > def _subclass_preparse(self, line): > '''Dummy method to override''' > pass > > > # in Subclassed_Node class > > def _subclass_preparse(self, line): > '''Subclassed_Node class specific parsing, overrides Node method.''' > # Do special parsing of the line here here > > Does this scream `Danger -- spaghetti code will result down the road'? This is a perfectly normal approach. It is even formalised in some Lisp OO dialects which have BEFORE, AROUND and AFTER methods. They work like this: class Parent: def myMethod(...) class Child_A(Parent) def myMethod(BEFORE,...) # always execute before Parent method class Child_B(Parent): def myMethod(AFTER,....) # always execute afyter parent method class Child_C(Parent): def myMethod(AROUND,...) # only execute parent if I explicitly call it Languages without such support use a system of *hooks*, which is what you have done class Parent: def pre_Method(...): pass # only for overridding def method(...): self.preMethod() # code here self.postMethod() def postMetrhod(...): pass # only for over ridding > The method name containing `preparse' indicates I might also feel a > need for a `postparse' structure, too. Absolutely. Alan G. From alan.gauld at freenet.co.uk Tue Feb 22 05:49:50 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Feb 22 05:49:10 2005 Subject: [Tutor] database programming References: <bea19ca2050221024253145e03@mail.gmail.com><Pine.LNX.4.44.0502211037140.26448-100000@hkn.eecs.berkeley.edu> <f2ff2d05022112583c661d98@mail.gmail.com> Message-ID: <01b501c51899$f1c241f0$2ca88651@xp> > Oh, and don't forget the c.commit() part! That had me running around > in circles all night last night. Yep, I got got with lack of commit syndrome when I started with SQL too :-) > PS Anyone know if there's a way to get a list of tables in a DB? I've > got the pragma to get a list of columns in a table, but just in the > off chance... Irs very DB dependant. Standard SQL doesn't have such thing but most DB systems provide commands to do so, but they are different for each DB. Often there is a "meta table" somewhere that stores the details of the data structure and you can queruy that like any other. In other cases it is special SQL keywords... or mixture of both... Check the doxcumentation carefully. Alan G. From cyresse at gmail.com Tue Feb 22 11:06:10 2005 From: cyresse at gmail.com (Liam Clarke) Date: Tue Feb 22 11:06:14 2005 Subject: [Tutor] Method/subclass Message-ID: <f2ff2d0502220206330ac19f@mail.gmail.com> Hi all, I'm working on my first object-based-from-the-ground-up project, and I have some queries. http://www.rafb.net/paste/results/lDUmWS78.html Here are my two classes here. For each different function, search, edit, view, etc. a different SQL operation will take place, and a different child window will be returned to the main window. Roughly speaking. I was going to create a method for each of the different functions in both class, but I was wondering if it would be better to subclass for each function. I've never done this before, so it's a little confusing. Incidentally, is this searchWin = genericChild an OK way to create a class instance of genericChild? It seems to work OK, and Pythoncard does funny things with __init__ for windows ( I can't figure out how to pass __init__ arguments for example.) But I'm worried that there's some unforeseen consequence of this kind of thing, it just seems strange not finishing with (). So yeah, should I do a method for each function, or subclass my generic classes? Regards, Liam Clarke -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From kraus at hagen-partner.de Tue Feb 22 11:14:46 2005 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Tue Feb 22 11:14:55 2005 Subject: [Tutor] Re: Method/subclass In-Reply-To: <f2ff2d0502220206330ac19f@mail.gmail.com> References: <f2ff2d0502220206330ac19f@mail.gmail.com> Message-ID: <cvf0fh$1os$1@sea.gmane.org> Liam Clarke wrote: > Hi all, > > > I'm working on my first object-based-from-the-ground-up project, and I > have some queries. > > http://www.rafb.net/paste/results/lDUmWS78.html > > Here are my two classes here. For each different function, search, > edit, view, etc. a different SQL operation will take place, and a > different child window will be returned to the main window. > Roughly speaking. > > I was going to create a method for each of the different functions in > both class, but I was wondering if it would be better to subclass for > each function. I've never done this before, so it's a little > confusing. > > Incidentally, is this > > searchWin = genericChild > > an OK way to create a class instance of genericChild? It seems to work > OK, and Pythoncard does funny things with __init__ for windows ( I > can't figure out how to pass __init__ arguments for example.) > > But I'm worried that there's some unforeseen consequence of this kind > of thing, it just seems strange not finishing with (). > > So yeah, should I do a method for each function, or subclass my generic classes? > > Regards, > > Liam Clarke > I didn't look at the rest of the code, but you want searchWin = genericChild() instead. (Do a print searchWin to see why ;-)) HTH, Wolfram From cmeesters at ucdavis.edu Tue Feb 22 11:25:39 2005 From: cmeesters at ucdavis.edu (Christian Meesters) Date: Tue Feb 22 11:25:47 2005 Subject: [Tutor] Initializing with a call like: someClass.open("someFile")? Message-ID: <200502221025.j1MAPdAQ021083@cucujus.ucdavis.edu> Thanks Guys, Guess I have to look once more into decorator functions - and guess it's worth doing so. Anyway: My problem is solved. Cheers Christian From bvande at po-box.mcgill.ca Tue Feb 22 11:27:48 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue Feb 22 11:28:58 2005 Subject: [Tutor] subclassing list -- slicing doesn't preserve type Message-ID: <421B0924.2050800@po-box.mcgill.ca> Hi all, I'm trying to figure out how to subclass the list built-in. .>>> class my_list(list): def __init__(self, sequence=None): list.__init__(self, sequence) self.spam = 1 .>>> mine = my_list((1,2,3,4)) .>>> mine.append(42) .>>> mine [1, 2, 3, 4, 42] .>>> type(mine) <class '__main__.my_list'> .>>> damn = mine[1:3] .>>> type(damn) <type 'list'> .>>> damn [2, 3] .>>> I had thought that by subsclassing list I got all list-like properties for free. Append (among others) are available for my_list instances. But slicing returns a list, rather than a my_list. I can see that this is list-like in it's way, but I'd rather have be so in mine ;-) I've read in the docs that UserList is discouraged, and in the Nutshell that the __getslice__, etc. special methods are depreciated. So, how can I get slicing to preserve the my_list type? And why does the above class get so much for free, but not slicing? Best, and thanks to all, Brian vdB From kent37 at tds.net Tue Feb 22 13:38:57 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Feb 22 13:39:05 2005 Subject: [Tutor] Method/subclass In-Reply-To: <f2ff2d0502220206330ac19f@mail.gmail.com> References: <f2ff2d0502220206330ac19f@mail.gmail.com> Message-ID: <421B27E1.9000206@tds.net> Liam Clarke wrote: > Hi all, > > > I'm working on my first object-based-from-the-ground-up project, and I > have some queries. > > http://www.rafb.net/paste/results/lDUmWS78.html > > Here are my two classes here. For each different function, search, > edit, view, etc. a different SQL operation will take place, and a > different child window will be returned to the main window. > Roughly speaking. > > I was going to create a method for each of the different functions in > both class, but I was wondering if it would be better to subclass for > each function. I've never done this before, so it's a little > confusing. I'm not really sure what you are trying to do, the code is pretty sketchy. It looks like you want to have a bunch of queries on your dataset, and the result of each query is displayed in a window. Is that right? Assuming it is, I'll continue... First, DO NOT put any references to your GUI classes into your data access classes!! NEVER ever do that! Excuse my shouting, but it is a really bad idea. Your data class methods should return data, not GUI objects. The less the data classes know about the rest of the application the better. Why? Because you want to be able to have different clients of the data classes. Here are some possible clients: - unit tests - utility programs that do some commonly needed manipulation of the database - reporting package - command-line clients - alternate GUIs (maybe you decide you don't like PythonCard, do you want to rewrite your data class to work with Tkinter / PyQT / whatever?) So, how should you organize this? I would probably have - a data access class (DAO) - probably some data container classes (domain objects). Your data access class methods will take domain objects as parameters and return them as results. The different parts of the app will communicate by passing domain objects around. If the domain data is very simple you might just use Python lists and dictionaries. - a class for the main window - classes for the display windows - a separate class for each kind of display. If all the displays are similar you might reuse a single class; if they are very different they will have their own classes. If there is shared behaviour you might have a common base class, otherwise inherit directly from the GUI classes. - possibly one or more controller classes - the classes that provide the glue between the gui and the data. Some of this logic will be in the main window, some you might want to put in its own class. A sample data flow might be - user enters a query into the main window and clicks a 'search' button - the search button handler is invoked. This might be a method of the main window class, or it might delegate to a helper class. - in either case, the handler class must have a reference to the data access class. It forwards the request to the DAO, gets the results back, and creates the new window to display the results. (The result object might be passed directly to the window class in its constructor or by a helper method.) By the way, DAO is just one pattern for database access, there are quite a few others. In particulary Active Record is used by SQLObject - in this pattern the domain object itself knows how to interact with the database. You might like to look into this. http://www.martinfowler.com/eaaCatalog/activeRecord.html http://sqlobject.org/ > > Incidentally, is this > > searchWin = genericChild > > an OK way to create a class instance of genericChild? It seems to work > OK, and Pythoncard does funny things with __init__ for windows ( I > can't figure out how to pass __init__ arguments for example.) No, this just makes searchWin an alias for the genericChild class, it doesn't create an instance fo the class. BTW typical Python usage is for class names to use InitialCapitalLetters, e.g. GenericChild. Kent > > But I'm worried that there's some unforeseen consequence of this kind > of thing, it just seems strange not finishing with (). > > So yeah, should I do a method for each function, or subclass my generic classes? > > Regards, > > Liam Clarke > > From sigurd at 12move.de Tue Feb 22 13:53:44 2005 From: sigurd at 12move.de (Karl =?iso-8859-1?Q?Pfl=E4sterer?=) Date: Tue Feb 22 13:55:37 2005 Subject: [Tutor] subclassing list -- slicing doesn't preserve type In-Reply-To: <421B0924.2050800@po-box.mcgill.ca> (Brian van den Broek's message of "Tue, 22 Feb 2005 05:27:48 -0500") References: <421B0924.2050800@po-box.mcgill.ca> Message-ID: <usm3olqbd.fsf@hamster.pflaesterer.de> On 22 Feb 2005, bvande@po-box.mcgill.ca wrote: > I'm trying to figure out how to subclass the list built-in. > > .>>> class my_list(list): > def __init__(self, sequence=None): > list.__init__(self, sequence) > self.spam = 1 > > .>>> mine = my_list((1,2,3,4)) > .>>> mine.append(42) > .>>> mine > [1, 2, 3, 4, 42] > .>>> type(mine) > <class '__main__.my_list'> > .>>> damn = mine[1:3] > .>>> type(damn) > <type 'list'> > .>>> damn > [2, 3] > .>>> > > I had thought that by subsclassing list I got all list-like properties > for free. Append (among others) are available for my_list instances. > But slicing returns a list, rather than a my_list. I can see that this > is list-like in it's way, but I'd rather have be so in mine ;-) > > I've read in the docs that UserList is discouraged, and in the > Nutshell that the __getslice__, etc. special methods are depreciated. But the problem is here: list() defines a __getslice__ method. > So, how can I get slicing to preserve the my_list type? And why does > the above class get so much for free, but not slicing? It gets also slicing for free but think about what happens when you call e.g. `append'; you *mutate an existing object in place* (i.e. a destructive operation). So you change the already existing object which is an instance of Mylist. On the other hand with slicing you get a *new* object back; you never told Python that you also wanted that new object to be of type Mylist. You could do it e.g. like that: class Mylist (list): def __init__(self, seq=None): super(self.__class__, self).__init__(seq) def __getslice__(self, start, stop): return self.__class__(super(self.__class__, self).__getslice__(start, stop)) def __getitem__(self, key): if isinstance(key, slice): return self.__class__(super(self.__class__, self).__getitem__(key)) else: return super(self.__class__, self).__getitem__(key) For simple slices Python calls `list.__getslice__' for extended slices list.__getitem__ gets called. So the above handles all cases. . >>> L = Mylist((1,2,3,4)) . >>> L[1] . 2 . >>> L[1:2] . [2] . >>> type(_) . <class '__main__.Mylist'> . >>> L[0:4:2] . [1, 3] . >>> type(_) . <class '__main__.Mylist'> . >>> You must also think about the other methods which return a newly allocated object. Karl -- Please do *not* send copies of replies to me. I read the list From kent37 at tds.net Tue Feb 22 14:09:43 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Feb 22 14:09:49 2005 Subject: [Tutor] subclassing list -- slicing doesn't preserve type In-Reply-To: <421B0924.2050800@po-box.mcgill.ca> References: <421B0924.2050800@po-box.mcgill.ca> Message-ID: <421B2F17.4040508@tds.net> Brian van den Broek wrote: > Hi all, > > I'm trying to figure out how to subclass the list built-in. > > .>>> class my_list(list): > def __init__(self, sequence=None): > list.__init__(self, sequence) > self.spam = 1 > > .>>> mine = my_list((1,2,3,4)) > .>>> mine.append(42) > .>>> mine > [1, 2, 3, 4, 42] > .>>> type(mine) > <class '__main__.my_list'> > .>>> damn = mine[1:3] > .>>> type(damn) > <type 'list'> > .>>> damn > [2, 3] > .>>> > > I had thought that by subsclassing list I got all list-like properties > for free. Append (among others) are available for my_list instances. > But slicing returns a list, rather than a my_list. I can see that this > is list-like in it's way, but I'd rather have be so in mine ;-) The problem is that the list methods that return a new list don't know to return an object of your class. You will have to override those methods with a new method that converts the new list to an instance of my_list. Or you can use UserList which does this for you: class my_list(list): def __init__(self, sequence=None): list.__init__(self, sequence) self.spam = 1 def __getslice__(self, i, j): return my_list(list.__getslice__(self, i, j)) print 'Subclass list:' mine = my_list((1,2,3,4)) mine.append(42) print 'mine:', mine print 'type(mine):', type(mine) print damn = mine[1:3] print 'damn', damn print 'type(damn):', type(damn) print from UserList import UserList class my_list2(UserList): def __init__(self, sequence=None): UserList.__init__(self, sequence) self.spam = 1 print 'Subclass UserList:' mine = my_list2((1,2,3,4)) mine.append(42) print 'mine:', mine print 'mine.__class__:', mine.__class__ print damn = mine[1:3] print 'damn', damn print 'damn.__class__:', damn.__class__ prints: Subclass list: mine: [1, 2, 3, 4, 42] type(mine): <class '__main__.my_list'> damn [2, 3] type(damn): <class '__main__.my_list'> Subclass UserList: mine: [1, 2, 3, 4, 42] mine.__class__: __main__.my_list2 damn [2, 3] damn.__class__: __main__.my_list2 If you decide to stick with subclassing list, UserList can still be your guide for which methods need wrappers. Look for the calls to self.__class__() in UserList.py. > > I've read in the docs that UserList is discouraged, and in the > Nutshell that the __getslice__, etc. special methods are depreciated. > > So, how can I get slicing to preserve the my_list type? And why does > the above class get so much for free, but not slicing? > > Best, and thanks to all, > > Brian vdB > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From mark.kels at gmail.com Tue Feb 22 19:29:50 2005 From: mark.kels at gmail.com (Mark Kels) Date: Tue Feb 22 19:29:55 2005 Subject: [Tutor] Help debuging a small program In-Reply-To: <421A26AF.5020906@tds.net> References: <c225925305022109366ee359b0@mail.gmail.com> <421A26AF.5020906@tds.net> Message-ID: <c225925305022210297b7fba06@mail.gmail.com> On Mon, 21 Feb 2005 13:21:35 -0500, Kent Johnson <kent37@tds.net> wrote: > How far does it get? How do you know? > > I would put some debug print statements in. Also you should call sk.close() in the else clause of > scan(). Finally, I don't think you will see any output in the result window until get_info() > returns; you have to give some time to mainloop() for it to be able to trigger the updates. I don't understand how to prevent the program from crashing right now... I'll deal with other bugs when I'll finish this one :) So, why does the program crashes and how can I prevent it ?? Thanks !! -- 1. The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners. 2. Unix is user friendly - it's just picky about it's friends. 3. Documentation is like sex: when it is good, it is very, very good. And when it is bad, it is better than nothing. - Dick Brandon From mwalsh at groktech.org Tue Feb 22 20:11:43 2005 From: mwalsh at groktech.org (Martin Walsh) Date: Tue Feb 22 20:11:46 2005 Subject: [Tutor] Help debuging a small program In-Reply-To: <c225925305022210297b7fba06@mail.gmail.com> References: <c225925305022109366ee359b0@mail.gmail.com> <421A26AF.5020906@tds.net> <c225925305022210297b7fba06@mail.gmail.com> Message-ID: <421B83EF.5040904@groktech.org> Mark Kels wrote: >On Mon, 21 Feb 2005 13:21:35 -0500, Kent Johnson <kent37@tds.net> wrote: > > >>How far does it get? How do you know? >> >>I would put some debug print statements in. Also you should call sk.close() in the else clause of >>scan(). Finally, I don't think you will see any output in the result window until get_info() >>returns; you have to give some time to mainloop() for it to be able to trigger the updates. >> >> >I don't understand how to prevent the program from crashing right now... >I'll deal with other bugs when I'll finish this one :) >So, why does the program crashes and how can I prevent it ?? > >Thanks !! > > > Hi Mark, I believe Kent has given you the solution, it's perhaps just not what you expected it to be. Adding debug print statements might have helped you to see. To demonstrate further try scanning only 1 or 2 ports. When your app appears to be frozen or crashing, I suspect it is happily scanning away. Looks like you have an overly ambitious while loop in the scan function, which isn't giving the Tk Text widget (result_t?) time to update. Someone more experienced that I will certainly have a better way, but you might try adding root.update() at the end (but inside) the while loop to force an update. # + ---The Scan--- def scan(host,start_port,end_port): sk=socket.socket(socket.AF_INET, socket.SOCK_STREAM) while start_port<=end_port: try: sk.connect((host,start_port)) except: result_t.insert(END,"Port",start_port,"is CLOSED on",host,"\n") else: result_t.insert(END,"Port",start_port,"is OPENED on",host,"\n") start_port=start_port+1 root.update() #<<-- add this and have a look here http://www.pythonware.com/library/tkinter/introduction/x9374-event-processing.htm >>> import Tkinter >>> help(Tkinter.Tk) Help on class Tk in module Tkinter: ... | | update(self) | Enter event loop until all pending events have been processed by Tcl. | | update_idletasks(self) | Enter event loop until all idle callbacks have been called. This | will update the display of windows but not process events caused by | the user. ... HTH, Marty From klappnase at freenet.de Tue Feb 22 20:26:59 2005 From: klappnase at freenet.de (Michael Lange) Date: Tue Feb 22 20:24:11 2005 Subject: [Tutor] UnicodeDecodeError Message-ID: <20050222202659.3e0c9675.klappnase@freenet.de> Hello list, I've encountered an (at least for me) weird error in the project I'm working on (see the traceback below). Unfortunately there are several of my application's modules involved, so I cannot post all of my code here. I hope I can explain in plain words what I'm doing. The line in the traceback that seems to cause the problems: if self.nextfile == _('No destination file selected'): "self.nextfile" is a variable that contains either the path to a file (the destination file for sound recording) or the gettext string you see above. For some reason I get the error below when "self.nextfile" contains a special character *and* the gettext string holds the german translation, which contains a special character, too (of course '\xe4' as 23rd character). It looks like there are no problems when I remove the german translation or when there are no special characters in the filename, but as soon as I have special characters on both sides of the equation the error occurs. ###################################################################### Error: 1 UnicodeDecodeError Exception in Tk callback Function: <bound method Snackrecorder.start of <snackrecorder.Snackrecorder instance at 0xb77fe24c>> (type: <type 'instancemethod'>) Args: () Traceback (innermost last): File "/usr/lib/python2.3/site-packages/Pmw/Pmw_1_2/lib/PmwBase.py", line 1747, in __call__ return apply(self.func, args) File "/usr/local/share/phonoripper/snackrecorder.py", line 305, in start if self.nextfile == _('No destination file selected'): UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 22: ordinal not in range(128) ###################################################################### I've looked into PmwBase.py, but I couldn't figure out what's going on, so I hope that someone here can give me a hint. Thanks in advance and best regards Michael From kent37 at tds.net Tue Feb 22 20:27:07 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Feb 22 20:27:14 2005 Subject: [Tutor] Help debuging a small program In-Reply-To: <c225925305022210297b7fba06@mail.gmail.com> References: <c225925305022109366ee359b0@mail.gmail.com> <421A26AF.5020906@tds.net> <c225925305022210297b7fba06@mail.gmail.com> Message-ID: <421B878B.4020407@tds.net> Mark Kels wrote: > On Mon, 21 Feb 2005 13:21:35 -0500, Kent Johnson <kent37@tds.net> wrote: > >>How far does it get? How do you know? >> >>I would put some debug print statements in. Also you should call sk.close() in the else clause of >>scan(). Finally, I don't think you will see any output in the result window until get_info() >>returns; you have to give some time to mainloop() for it to be able to trigger the updates. > > I don't understand how to prevent the program from crashing right now... > I'll deal with other bugs when I'll finish this one :) > So, why does the program crashes and how can I prevent it ?? I don't know either. Put some print statements in so you can see how far it is getting. Or you might be able to run it with the IDLE debugger, I don't know if that works to debug Tk programs. I would rewrite scan() like this and see what you get: def scan(host,start_port,end_port): print 'Scanning', host, start_port, end_port sk=socket.socket(socket.AF_INET, socket.SOCK_STREAM) while start_port<=end_port: try: print 'Trying port', start_port sk.connect((host,start_port)) except: import traceback trackback.print_exc() result_t.insert(END,"Port",start_port,"is CLOSED on",host,"\n") else: print "Port",start_port,"is OPENED" result_t.insert(END,"Port",start_port,"is OPENED on",host,"\n") start_port=start_port+1 Actually, I just tried the program and it didn't crash at all. I searched from port 80 to 90 and it returned correct info. It takes a long time, though - the timeout on the connection seems to be pretty long. It doesn't show any output until it is done, and the UI is dead, so it seems crashed but it isn't. Kent > > Thanks !! > From bvande at po-box.mcgill.ca Tue Feb 22 20:26:32 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue Feb 22 22:05:07 2005 Subject: [Tutor] subclassing list -- slicing doesn't preserve type In-Reply-To: <usm3olqbd.fsf@hamster.pflaesterer.de> References: <421B0924.2050800@po-box.mcgill.ca> <usm3olqbd.fsf@hamster.pflaesterer.de> Message-ID: <421B8768.7060207@po-box.mcgill.ca> Karl Pfl?sterer said unto the world upon 2005-02-22 07:53: > On 22 Feb 2005, bvande@po-box.mcgill.ca wrote: > > >>I'm trying to figure out how to subclass the list built-in. >> >>.>>> class my_list(list): >> def __init__(self, sequence=None): >> list.__init__(self, sequence) >> self.spam = 1 <SNIP my examples of behaviour: notably, slicing doesn't preserve my_list type> >>So, how can I get slicing to preserve the my_list type? And why does >>the above class get so much for free, but not slicing? > > > It gets also slicing for free but think about what happens when you call > e.g. `append'; you *mutate an existing object in place* (i.e. a > destructive operation). So you change the already existing object which > is an instance of Mylist. On the other hand with slicing you get a > *new* object back; you never told Python that you also wanted that new > object to be of type Mylist. > > You could do it e.g. like that: > > class Mylist (list): > def __init__(self, seq=None): > super(self.__class__, self).__init__(seq) > def __getslice__(self, start, stop): > return self.__class__(super(self.__class__, self).__getslice__(start, stop)) > def __getitem__(self, key): > if isinstance(key, slice): > return self.__class__(super(self.__class__, self).__getitem__(key)) > else: > return super(self.__class__, self).__getitem__(key) > > > For simple slices Python calls `list.__getslice__' for extended slices > list.__getitem__ gets called. So the above handles all cases. <SNIP Karl's similar output, but with desired behaviour ;-) > > You must also think about the other methods which return a newly > allocated object. > > > Karl Thanks Karl (and Kent in another response), use of super is new to me; from a quick glance at the docs, I am glad to have been pointed at it. For the quick and dirty, I think I will go the __getslice__ way, deprecation be damned. But, learning how to do it the way you have above is high on the list of things to do. Thanks and best, Brian vdB From administrata at hotmail.com Tue Feb 22 22:25:41 2005 From: administrata at hotmail.com (. ,) Date: Tue Feb 22 22:26:39 2005 Subject: [Tutor] How can i use both float and int? Message-ID: <BAY22-F290714B2F342F76F505982C8620@phx.gbl> like... number1 = raw_input(float int("Number1: ") But, I think error will occur... Cheers! :) _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From carroll at tjc.com Tue Feb 22 22:49:05 2005 From: carroll at tjc.com (Terry Carroll) Date: Tue Feb 22 22:49:09 2005 Subject: [Tutor] How can i use both float and int? In-Reply-To: <BAY22-F290714B2F342F76F505982C8620@phx.gbl> Message-ID: <Pine.LNX.4.44.0502221348090.21272-100000@violet.rahul.net> On Tue, 22 Feb 2005, . , wrote: > like... > > number1 = raw_input(float int("Number1: ") > > But, I think error will occur... You have some syntax issues here. What you want, I think, is to use raw_input to get input, and then convert that to float. try this: number1 = float(raw_input("Number1: ")) From misha.dunn at gmail.com Tue Feb 22 22:54:01 2005 From: misha.dunn at gmail.com (Michael Dunn) Date: Tue Feb 22 22:54:09 2005 Subject: [Tutor] How can i use both float and int? In-Reply-To: <BAY22-F290714B2F342F76F505982C8620@phx.gbl> References: <BAY22-F290714B2F342F76F505982C8620@phx.gbl> Message-ID: <e95c92e0050222135457744797@mail.gmail.com> Hi .,, An error will certainly occur (you should always try it and see). You could do something like: n = raw_input("Number1: ") try: number1 = int(n) except ValueError: number1 = float(n) This will make number1 an integer if possible, and a float otherwise. But (and wiser heads may correct me here) I'm not sure this is a good idea. Couldn't you just use floats throughout, given that floats are at least sometimes acceptable? I'm just guessing what you need here, but if you really are trying to avoid floats whereever possible, and if you're using python version 2.4, you might find that the decimal type is what you need. As I understand it, it allows you to specify the precision of your number, so 1 will be come out as to 1.00000000 and not 1.00000001 (or whatever). I'm not using 2.4 myself yet, so ask the list if you need examples or explanation. Michael On Tue, 22 Feb 2005 21:25:41 +0000, . , <administrata@hotmail.com> wrote: > like... > > number1 = raw_input(float int("Number1: ") > > But, I think error will occur... > > Cheers! :) > > _________________________________________________________________ > Express yourself instantly with MSN Messenger! Download today it's FREE! > http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From python at venix.com Tue Feb 22 22:58:57 2005 From: python at venix.com (Lloyd Kvam) Date: Tue Feb 22 22:59:02 2005 Subject: [Tutor] subclassing list -- slicing doesn't preserve type In-Reply-To: <20050222210546.144DF1E4007@bag.python.org> References: <20050222210546.144DF1E4007@bag.python.org> Message-ID: <1109109537.4882.103.camel@laptop.venix.com> > Message: 2 > Date: Tue, 22 Feb 2005 13:53:44 +0100 > From: sigurd@12move.de (Karl Pfl?sterer ) > Subject: Re: [Tutor] subclassing list -- slicing doesn't preserve type > To: tutor@python.org > Message-ID: <usm3olqbd.fsf@hamster.pflaesterer.de> > Content-Type: text/plain; charset=us-ascii > > On 22 Feb 2005, bvande@po-box.mcgill.ca wrote: > > > I'm trying to figure out how to subclass the list built-in. > You could do it e.g. like that: > > class Mylist (list): > def __init__(self, seq=None): > super(self.__class__, self).__init__(seq) > def __getslice__(self, start, stop): > return self.__class__(super(self.__class__, self).__getslice__(start, stop)) > def __getitem__(self, key): > if isinstance(key, slice): > return self.__class__(super(self.__class__, self).__getitem__(key)) > else: > return super(self.__class__, self).__getitem__(key) I've written code like this and then gotten burned. It's atractive in that you avoid hard-coding class names and it becomes simple boiler-plate that could be pasted anywhere. The problem comes when you create class Mybetterlist(Mylist): ... When a Mybetterclass instance provides the self, super(self.__class__, self) is Mylist. So you recurse into the same __getslice__ that you started with instead of getting Mylist's super class. I think (untested) that you really want return self.__class__(super(Mylist, self).__<method name>__(<args>) -- Lloyd Kvam Venix Corp From shitizb at yahoo.com Tue Feb 22 23:23:17 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Tue Feb 22 23:23:21 2005 Subject: [Tutor] killing a thread Message-ID: <20050222222318.53532.qmail@web53806.mail.yahoo.com> Hi, Is there a way to terminate a thread from another thread? Shitiz __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From bill.mill at gmail.com Wed Feb 23 00:08:53 2005 From: bill.mill at gmail.com (Bill Mill) Date: Wed Feb 23 00:08:55 2005 Subject: [Tutor] killing a thread In-Reply-To: <20050222222318.53532.qmail@web53806.mail.yahoo.com> References: <20050222222318.53532.qmail@web53806.mail.yahoo.com> Message-ID: <797fe3d4050222150873172c84@mail.gmail.com> If I recall correctly, there is not a direct way. Instead, you're going to want to have your worker thread check a queue it shares with the parent every so often to see if the supervisor thread has sent a "quit" message to it. Peace Bill Mill bill.mill at gmail.com On Tue, 22 Feb 2005 14:23:17 -0800 (PST), Shitiz Bansal <shitizb@yahoo.com> wrote: > Hi, > > Is there a way to terminate a thread from another > thread? > > Shitiz > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From isrgish at fastem.com Wed Feb 23 01:17:40 2005 From: isrgish at fastem.com (Isr Gish) Date: Wed Feb 23 01:18:14 2005 Subject: [Tutor] UnicodeDecodeError Message-ID: <20050223001813.1AFB01E4003@bag.python.org> Michael Lange"<klappnase@freenet.de> wrote: >Hello list, > [Snip] This part of the error is saying what the problem is. >UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 22: ordinal not in range(128) Thatthe ascii codec that's being used can't decode any ascii code above 128. And the code 0xe4 is higher then that. You would have to use a different encoding, like msbc. If i remmeber correctly you should do something like the following. self.nextfile = self.nextfile.encode('msbc') Then it should work. If it doesn't work try posting what error you get. All the best Irr From isrgish at fastem.com Wed Feb 23 01:27:14 2005 From: isrgish at fastem.com (Isr Gish) Date: Wed Feb 23 01:27:53 2005 Subject: [Tutor] UnicodeDecodeError Message-ID: <20050223002752.144871E4003@bag.python.org> Forgot something in previOuse post. You can set the defualt encoding to something other then 'ascii'. This is done with the function Qsys.setdefualtencoding('mbcs')". I think that this has to be done in the module sitecostomize, because the function is deleted after the module site is run. And this module gets run when yo_ start up python. All the best, Isr From dyoo at hkn.eecs.berkeley.edu Wed Feb 23 01:29:47 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Feb 23 01:29:51 2005 Subject: [Tutor] subclassing list -- slicing doesn't preserve type In-Reply-To: <1109109537.4882.103.camel@laptop.venix.com> Message-ID: <Pine.LNX.4.44.0502221614470.25709-100000@hkn.eecs.berkeley.edu> > > > I'm trying to figure out how to subclass the list built-in. > > > You could do it e.g. like that: > > > > class Mylist (list): > > def __init__(self, seq=None): > > super(self.__class__, self).__init__(seq) > > def __getslice__(self, start, stop): > > return self.__class__(super(self.__class__, self).__getslice__(start, stop)) > > def __getitem__(self, key): > > if isinstance(key, slice): > > return self.__class__(super(self.__class__, self).__getitem__(key)) > > else: > > return super(self.__class__, self).__getitem__(key) We might want to bring up that using inheritance here might be an inappropriate OOP construct here. It might be better to handle this sort of thing by wrapping a list in a wrapper, and work through delegation. In fact, that's essentially what UserList is. I'm not sure I agree with the documentation of: http://www.python.org/doc/lib/module-UserList.html where it says that subclassing 'list' is usually appropriate. It seems awfully messy to have to overload every method that can potentially produce a new list. And besides, all that work is being done in UserList already: ### >>> from UserList import UserList >>> class MyList(UserList): ... pass ... >>> l = MyList() >>> l.append('a') >>> l.append('b') >>> l.append('c') >>> l2 = l[1:] >>> isinstance(l2, MyList) True ### From maxnoel_fr at yahoo.fr Wed Feb 23 03:37:41 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Wed Feb 23 03:37:48 2005 Subject: [Tutor] killing a thread In-Reply-To: <797fe3d4050222150873172c84@mail.gmail.com> References: <20050222222318.53532.qmail@web53806.mail.yahoo.com> <797fe3d4050222150873172c84@mail.gmail.com> Message-ID: <b7a554dd1cb906e1cc2cb6f490c93f6c@yahoo.fr> On Feb 22, 2005, at 23:08, Bill Mill wrote: > If I recall correctly, there is not a direct way. Instead, you're > going to want to have your worker thread check a queue it shares with > the parent every so often to see if the supervisor thread has sent a > "quit" message to it. > > Peace > Bill Mill > bill.mill at gmail.com Using "direct" killing methods is not safe, because you never know at which point of its execution you terminate the thread. That's a Bad Thing(TM). So instead, the Right Thing is to implement an end() method in the object you're using as a thread. That end() method just sets a flag (say, isToTerminate) to True. Since the thread is running a loop, all you then have to do is have it check the isToTerminate flag at the beginning of each loop. If it's True, exit the loop (thus terminating the thread as it reaches the end of its run() method). -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From kent37 at tds.net Wed Feb 23 06:00:53 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Feb 23 06:00:58 2005 Subject: [Tutor] killing a thread In-Reply-To: <b7a554dd1cb906e1cc2cb6f490c93f6c@yahoo.fr> References: <20050222222318.53532.qmail@web53806.mail.yahoo.com> <797fe3d4050222150873172c84@mail.gmail.com> <b7a554dd1cb906e1cc2cb6f490c93f6c@yahoo.fr> Message-ID: <421C0E05.9060303@tds.net> Max Noel wrote: > > On Feb 22, 2005, at 23:08, Bill Mill wrote: > >> If I recall correctly, there is not a direct way. Instead, you're >> going to want to have your worker thread check a queue it shares with >> the parent every so often to see if the supervisor thread has sent a >> "quit" message to it. >> >> Peace >> Bill Mill >> bill.mill at gmail.com > > > Using "direct" killing methods is not safe, because you never know > at which point of its execution you terminate the thread. That's a Bad > Thing(TM). > > So instead, the Right Thing is to implement an end() method in the > object you're using as a thread. That end() method just sets a flag > (say, isToTerminate) to True. > Since the thread is running a loop, all you then have to do is have > it check the isToTerminate flag at the beginning of each loop. If it's > True, exit the loop (thus terminating the thread as it reaches the end > of its run() method). This recipe shows one way to do it: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65448 Kent > > -- Max > maxnoel_fr at yahoo dot fr -- ICQ #85274019 > "Look at you hacker... A pathetic creature of meat and bone, panting and > sweating as you run through my corridors... How can you challenge a > perfect, immortal machine?" > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From cyresse at gmail.com Wed Feb 23 07:13:00 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed Feb 23 07:19:43 2005 Subject: [Tutor] Method/subclass In-Reply-To: <421B27E1.9000206@tds.net> References: <f2ff2d0502220206330ac19f@mail.gmail.com> <421B27E1.9000206@tds.net> Message-ID: <f2ff2d050222221348b18bd7@mail.gmail.com> Kia ora, > > I'm not really sure what you are trying to do, the code is pretty sketchy. It looks like you want to > have a bunch of queries on your dataset, and the result of each query is displayed in a window. Is > that right? Assuming it is, I'll continue... What I'm doing here is very sketchy, both in my mind and code. So yeah, my apologies, I probably should have put more effort into the question. ESR would flame me for sure. > First, DO NOT put any references to your GUI classes into your data access classes!! NEVER ever do that! Point noted. That was me trying to grasp the concept of returning objects, and then I thought I could be clever.... > I would probably have > - a data access class (DAO) > - probably some data container classes (domain objects). Your data access class >methods will take domain objects as parameters and return them as results. The different >parts of the app will communicate by passing domain objects around. If the domain data >is very simple you might just use > Python lists and dictionaries. > - a class for the main window > - classes for the display windows - a separate class for each kind of display. If all the >displays are similar you might reuse a single class; if they are very different they will have >their own classes. If there is shared behaviour you might have a common base class, >otherwise inherit directly from the GUI classes. > - possibly one or more controller classes - the classes that provide the glue between the >gui and the data. Some of this logic will be in the main window, some you might want to >put in its own class. > > A sample data flow might be > - user enters a query into the main window and clicks a 'search' button > - the search button handler is invoked. This might be a method of the main window class, >or it might delegate to a helper class. > - in either case, the handler class must have a reference to the data access class. It >forwards the request to the DAO, gets the results back, and creates the new window to >display the results. (The result object might be passed directly to the window class in its >constructor or by a helper method.) Thank you for that Kent, your shouting has been heeded, and it makes perfect sense not to return GUI objects. Of course, hindsight is great like that, the answer to the cryptic crossword clue is obvious once you know the answer. I'm not sure I understand your response fully, so I've described how I would do this in accordance with my understandinf of the method described above. Any feedback/corrections are gratefully welcomed. But first, a wee bit of explanation. As I said, this is very sketchy. I've run into the issue of not knowing where to start. This is my first database type project, so I want to go about this the right way from the get go, which means my progress is quite hesitant/non-existent. Ultimately I want to follow good methods of coding as much as I can, as I dream of actually being able to make a living out of this at some stage. So, as I don't actually know how to do this, on account of never having done similar, I need to layout in my mind what I'm going to do, before I do it. I had a look at UML, but it doesn't look helpful . Perhaps it's a way of thinking that I need to learn that'll make UML useful. So, looking at your dataflow above Kent, I'm planning - my main GUI runs, and upon initialisation creates self.DAO a data access object. The handlers in the main and each child window, submit requests by calling an appropriate method of self.DAO (or self.parent.DAO) as the case may be, passing any needed data as a dictionary/list, as it's not going to be overly complicated. The DAO then creates an SQL request as necessary, and creates a dictionary/list out of any retrieved data, and returns it to the handler. (Or an acknowledgement if data was entered, or similar.) If a new window needs to be opened (in response to a query or requested table) then the handler then instantiates a new child window using the dictionary after it's been appropriately twiddled. (As a lot of handlers are going to be doing this, perhaps a function of my parent window can hold a method for the twiddling.) Is this going to violate any best practise type methodologies? Sheesh, I get so confused. I've spent all this time trying to keep 'logic and gui' separate, with the result that I stuck my gui related logic in daft places. I dunno, I was thinking perhaps do this one in Java, so I'm forced to learn how to use objects (particularly passing them around) properly. The temptation to use many, many, functions is there. I've never (consciously) used objects as arguments and returned values, aside from what 3rd party packages have required. To put it a better way, I've never written code where two objects I've written have passed an object that I've also written between them. Of course, then I'd have to rewrite this in Python once done as Swing is yuck, and I don't like waiting for five minutes for the JRE to kick in. Actually, I don't like Java at all. If anyone has any links to recommended OO best practises, I'd be grateful. I googled DAO, & domain objects, and found a lot of confusing stuff. Of course, it would probably help if I didn't have cold as well. Thanks in advance for any advice offered. Regards, Liam Clarke -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From shitizb at yahoo.com Wed Feb 23 10:06:44 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Wed Feb 23 10:06:47 2005 Subject: [Tutor] Python sizeof() Message-ID: <20050223090645.21645.qmail@web53810.mail.yahoo.com> Hi, Is there a python equivalent of c's sizeof function. If not, then what are the typical sizes of the BoundedSemaphore object in python? Shitiz __________________________________ Do you Yahoo!? Yahoo! Sports - Sign up for Fantasy Baseball. http://baseball.fantasysports.yahoo.com/ From kent37 at tds.net Wed Feb 23 12:40:14 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Feb 23 12:40:20 2005 Subject: [Tutor] Method/subclass In-Reply-To: <f2ff2d050222221348b18bd7@mail.gmail.com> References: <f2ff2d0502220206330ac19f@mail.gmail.com> <421B27E1.9000206@tds.net> <f2ff2d050222221348b18bd7@mail.gmail.com> Message-ID: <421C6B9E.7000209@tds.net> Liam Clarke wrote: > I'm not sure I understand your response fully, so I've described how > I would do this in accordance with my understandinf of the method > described above. Any feedback/corrections are gratefully welcomed. > > But first, a wee bit of explanation. As I said, this is very sketchy. > I've run into the issue of not knowing where to start. This is my > first database type project, so I want > to go about this the right way from the get go, which means my > progress is quite hesitant/non-existent. Ultimately I want to follow > good methods of coding as much as I can, as I dream of actually being > able to make a living out of this at some stage. Start small :-) Get a little bit of the database working. Write unit tests for it. Get a little piece of GUI working that uses that part of the database. Lather. Rinse. Repeat. Refactor as your understanding of the problem grows. It's been a long time since I even tried to figure out how a whole project would look before starting it. > > So, as I don't actually know how to do this, on account of never > having done similar, I need to layout in my mind what I'm going to do, > before I do it. I had a look at UML, but it doesn't look helpful . > Perhaps it's a way of thinking that I need to learn that'll make UML > useful. > > So, looking at your dataflow above Kent, I'm planning - > > my main GUI runs, and upon initialisation creates self.DAO a data access object. > > The handlers in the main and each child window, submit requests by > calling an appropriate method of self.DAO (or self.parent.DAO) as the > case may be, passing any needed data as a dictionary/list, as it's not > going to be overly complicated. I would pass the child a reference to the DAO rather than a reference to the parent. That's another of my fairly firm rules - don't tell children about their parents if you can avoid it. > > The DAO then creates an SQL request as necessary, and creates a > dictionary/list out of any retrieved data, and returns it to the > handler. (Or an acknowledgement if data was entered, or similar.) > > If a new window needs to be opened (in response to a query or > requested table) then the handler then instantiates a new child window > using the dictionary after it's been appropriately twiddled. (As a lot > of handlers are going to be doing this, perhaps a function of my > parent window can hold a method for the twiddling.) > > Is this going to violate any best practise type methodologies? Sheesh, > I get so confused. > I've spent all this time trying to keep 'logic and gui' separate, with > the result that I stuck my gui related logic in daft places. Other than the note above, this sounds good. > > I dunno, I was thinking perhaps do this one in Java, so I'm forced to > learn how to use objects (particularly passing them around) properly. Yuck. > The temptation to use many, many, functions is there. And the problem with that is what? Functions are good. Functions that work on the same data become classes. I've never > (consciously) used objects as arguments and returned values, > aside from what 3rd party packages have required. To put it a better > way, I've never written code where two objects I've written have > passed an object that I've also written between them. > > Of course, then I'd have to rewrite this in Python once done as Swing > is yuck, and I don't like waiting for five minutes for the JRE to kick > in. Actually, I don't like Java at all. > > If anyone has any links to recommended OO best practises, I'd be grateful. > I googled DAO, & domain objects, and found a lot of confusing stuff. The c2 wiki has a wealth of information about software patterns and extreme programming. http://c2.com/ Robert Martin's book "Agile Software Development: Principles, Patterns, and Practices" is one of the best I know of for teaching good OO practices. Quite a few sample chapters are available. http://www.objectmentor.com/resources/bookstore/books/AgileSoftwareDevelopmentPPP There are a lot of other good articles available from Object Mentor as well http://www.objectmentor.com/resources/articleIndex You might also like Martin Fowler's articles http://martinfowler.com/articles.html > > Of course, it would probably help if I didn't have cold as well. > > Thanks in advance for any advice offered. > > > Regards, > > Liam Clarke > > From klappnase at freenet.de Wed Feb 23 13:05:58 2005 From: klappnase at freenet.de (Michael Lange) Date: Wed Feb 23 13:03:14 2005 Subject: [Tutor] UnicodeDecodeError Message-ID: <20050223130558.01612fd6.klappnase@freenet.de> On Tue, 22 Feb 2005 19:17:40 -0500 "Isr Gish" <isrgish@fastem.com> wrote: > This part of the error is saying what the problem is. > > >UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 22: ordinal not in range(128) > > Thatthe ascii codec that's being used can't decode any ascii code above 128. And the code 0xe4 is higher then that. > You would have to use a different encoding, like msbc. > If i remmeber correctly you should do something like the following. > > self.nextfile = self.nextfile.encode('msbc') > Then it should work. > > If it doesn't work try posting what error you get. > > All the best > Irr > > Thanks for the reply, it looks to me however that the problem is rather the gettext part; once I discovered this problem I can produce similar errors at other points in my app that *seem* to only occur when a gettext string gets combined with a string that is returned by user input from some Tkinter widget. The final complaint in the traceback is always about a (german) special character in the translated gettext string: ############################################################################## UnicodeDecodeError Exception in Tk callback Function: <function <lambda> at 0xb72ec304> (type: <type 'function'>) Args: () Traceback (innermost last): File "/usr/lib/python2.3/site-packages/Pmw/Pmw_1_2/lib/PmwBase.py", line 1747, in __call__ return apply(self.func, args) File "/usr/lib/python2.3/site-packages/Pmw/Pmw_1_2/lib/PmwDialog.py", line 153, in <lambda> command=lambda self=self, name=name: self._doCommand(name)) File "/usr/lib/python2.3/site-packages/Pmw/Pmw_1_2/lib/PmwDialog.py", line 132, in _doCommand return command(name) File "/usr/local/share/phonoripper-0.6.2/widgets/FileSelectDialog.py", line 206, in go if not self.ok(): File "/usr/local/share/phonoripper-0.6.2/widgets/FileSelectDialog.py", line 201, in ok return self.fo_handler.create_ok(self.full_path) File "/usr/local/share/phonoripper-0.6.2/FileOperationHandler.py", line 43, in create_ok message=_('File already exists:\n"%s"\nDo you want to overwrite it?') % filename) UnicodeDecodeError: 'ascii' codec can't decode byte 0xfc in position 19: ordinal not in range(128) ############################################################################## The german translation of 'File already exists:\n"%s"\nDo you want to overwrite it?' contains a special character ('\xfc'), filename is of course simply the complete path to a file as it is returned by a "Save as..." dialog box. I get this error for some reason if I choose '\xe4.wav' as basename for "filename" but not if I choose 'A\xe4.wav' . Like I said in my first post, there are no errors if I remove the german .mo file, so gettext uses the english strings. What seems really weird to me here is that it looks like both the translated gettext string and the special characters in my "filename" variable *can* be decoded, but not both at a time - but only under (rare) circumstances ( setting "filename" to "/somepath/A\xe4.wav" works but "/somepath/\xe4.wav" not). I'm really lost here, so any further hints are very appreciated. Thanks and best regards Michael From kent37 at tds.net Wed Feb 23 13:21:40 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Feb 23 13:21:45 2005 Subject: [Tutor] UnicodeDecodeError In-Reply-To: <20050222202659.3e0c9675.klappnase@freenet.de> References: <20050222202659.3e0c9675.klappnase@freenet.de> Message-ID: <421C7554.4080309@tds.net> Michael Lange wrote: > Hello list, > > I've encountered an (at least for me) weird error in the project I'm working on (see the traceback below). > Unfortunately there are several of my application's modules involved, so I cannot post all of my code here. > I hope I can explain in plain words what I'm doing. > > The line in the traceback that seems to cause the problems: > > if self.nextfile == _('No destination file selected'): > > "self.nextfile" is a variable that contains either the path to a file (the destination file for sound recording) > or the gettext string you see above. > For some reason I get the error below when "self.nextfile" contains a special character *and* the gettext string > holds the german translation, which contains a special character, too (of course '\xe4' as 23rd character). > It looks like there are no problems when I remove the german translation or when there are no special characters > in the filename, but as soon as I have special characters on both sides of the equation the error occurs. This is a part of Python that still confuses me. I think what is happening is - self.nextfile is a Unicode string sometimes (when it includes special characters) - the gettext string is a byte string - to compare the two, the byte string is promoted to Unicode by decoding it with the system default encoding, which is generally 'ascii'. - the gettext string includes non-ascii characters and the codec raises an exception. I don't know what the best solution is. Two possibilities (substitute your favorite encoding for latin-1): - decode the gettext string, e.g. if self.nextfile == _('No destination file selected').decode('latin-1'): - set your default encoding to latin-1. (This solution is frowned on by the Python-Unicode cognoscenti and it makes your programs non-portable). Do this by creating a file site-packages/sitecustomize.py containing the lines import sys sys.setdefaultencoding('latin-1') Kent > > ###################################################################### > Error: 1 > UnicodeDecodeError Exception in Tk callback > Function: <bound method Snackrecorder.start of <snackrecorder.Snackrecorder instance at 0xb77fe24c>> (type: <type 'instancemethod'>) > Args: () > Traceback (innermost last): > File "/usr/lib/python2.3/site-packages/Pmw/Pmw_1_2/lib/PmwBase.py", line 1747, in __call__ > return apply(self.func, args) > File "/usr/local/share/phonoripper/snackrecorder.py", line 305, in start > if self.nextfile == _('No destination file selected'): > UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 22: ordinal not in range(128) > > ###################################################################### > > I've looked into PmwBase.py, but I couldn't figure out what's going on, so I hope that someone > here can give me a hint. > > Thanks in advance and best regards > > Michael > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From ismaelgf at adinet.com.uy Wed Feb 23 15:53:44 2005 From: ismaelgf at adinet.com.uy (Ismael Garrido) Date: Wed Feb 23 15:53:25 2005 Subject: Refactoring and Domain Objects was Re: [Tutor] Method/subclass In-Reply-To: <421C6B9E.7000209@tds.net> References: <f2ff2d0502220206330ac19f@mail.gmail.com> <421B27E1.9000206@tds.net> <f2ff2d050222221348b18bd7@mail.gmail.com> <421C6B9E.7000209@tds.net> Message-ID: <421C98F7.8080605@adinet.com.uy> Kent Johnson wrote: > Start small :-) > > Get a little bit of the database working. Write unit tests for it. Get > a little piece of GUI working that uses that part of the database. > Lather. Rinse. Repeat. Refactor as your understanding of the problem > grows. Talking about refactoring. I couldn't get Bicycle repair man to work with IDLE and python 2.4. Does anyone know if and how that works? You talk about Domain Objects. Could you explain more about their use? Or point to some URL with examples? (My googling didn't yield attractive webs) Thanks Ismael From shitizb at yahoo.com Wed Feb 23 18:50:43 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Wed Feb 23 18:50:46 2005 Subject: [Tutor] threads Message-ID: <20050223175043.97304.qmail@web53801.mail.yahoo.com> Hi, I am trying to build a traffic network simulator using python, for my degree project. I need to run at least 5-6000 cars simultaneously.I wanted to run each car in a separate thread. However , after about 400 threads i am unable to create new threads. Here's the code: >>> cars=range(1000) >>> for i in cars: cars[i]=cars[i]=car(1,10,2,1,adjls,juncls) >>> for i in cars: i.start() Traceback (most recent call last): File "<pyshell#24>", line 2, in -toplevel- i.start() error: can't start new thread Is there a way out.Also, are there any tips on performance issues? Here is the class car: class car(threading.Thread): def __init__(self,carid,speed,dest,orig,adjls,juncls): threading.Thread.__init__(self) self.speed=speed self.finished=0 self.carid=carid self.dest=dest self.orig=orig self.adjls=adjls self.juncls=juncls self.shortest=find_shortest_path(adjls,self.dest,self.orig) self.calc=findpaths(adjls,self.dest,self.orig) self.stats={'currtrsp':0,'avgspeed':0,'distcov':0,'totaltime':0} def traverse_track(self,p1,p2): counter=0 time=0 while self.adjls[p1][counter].to!=p2: counter=counter+1 self.track=self.adjls[p1][counter] self.pos=0 if self.speed>self.track.speed: speed=self.track.speed else: speed=self.speed while self.pos!=self.track.length: if self.track.state.has_key(self.pos): self.track.state[self.pos].acquire() else: self.track.state[self.pos]=threading.Semaphore(value=self.track.lanes) self.track.state[self.pos].acquire() if self.pos!=0: self.track.state[self.pos-1].release() self.pos=self.pos+1 sleep(1.0/speed) time=time+1.0/speed self.stats['currtrsp']=float(self.track.length)/time if self.stats['avgspeed']: self.stats['avgspeed']=float(self.stats['distcov']+self.track.length)/(self.stats['distcov']/self.stats['avgspeed']+self.track.length/self.stats['currtrsp']) else: self.stats['avgspeed']=self.stats['currtrsp'] self.stats['totaltime']=self.stats['totaltime']+time if self.track.stats['avgspeed']: self.track.stats['avgspeed']=(self.track.stats['avgspeed']*self.track.stats['traffictotal']+self.stats['currtrsp'])/(self.track.stats['traffictotal']+1) else: self.track.stats['avgspeed']=self.stats['currtrsp'] self.stats['distcov']=self.stats['distcov']+self.track.length self.track.stats['traffictotal']=self.track.stats['traffictotal']+1 def cross_junction(self,juncls,juncid,orig,dest): marker=str(orig)+'-'+str(dest) if juncls[juncid].free.has_key(marker): self.track.state[self.pos].release() else: while not juncls[juncid].signalled['green'].has_key(marker): sleep(0.2) self.track.state[self.pos-1].release() def run(self): path=self.shortest counter=1 for i in path[:1]: self.traverse_track(i,path[counter]) if not counter==len(path)-1: self.cross_junction(self.juncls,path[counter],i,path[counter+1]) counter=counter+1 self.finished=1 self.track.state[self.pos-1].release() __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From dyoo at hkn.eecs.berkeley.edu Wed Feb 23 19:30:06 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Feb 23 19:30:21 2005 Subject: [Tutor] Python sizeof() In-Reply-To: <20050223090645.21645.qmail@web53810.mail.yahoo.com> Message-ID: <Pine.LNX.4.44.0502231026470.20166-100000@hkn.eecs.berkeley.edu> On Wed, 23 Feb 2005, Shitiz Bansal wrote: > Is there a python equivalent of c's sizeof function. Unfortuntately, no, not as a standard builtin. However, there is a third-party library called mxTools that does include a sizeof() function: http://www.egenix.com/files/python/mxTools.html Best of wishes to you! From kent37 at tds.net Wed Feb 23 19:35:25 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Feb 23 19:37:13 2005 Subject: [Tutor] threads In-Reply-To: <20050223175043.97304.qmail@web53801.mail.yahoo.com> References: <20050223175043.97304.qmail@web53801.mail.yahoo.com> Message-ID: <421CCCED.3060204@tds.net> Shitiz Bansal wrote: > Hi, > > I am trying to build a traffic network simulator using > python, for my degree project. > > I need to run at least 5-6000 cars simultaneously.I > wanted to run each car in a separate thread. > However , after about 400 threads i am unable to > create new threads. There does seem to be a limit on how many threads you can create, mostly due to the memory allocated to each thread. Search comp.lang.python for "can't start new thread" - with quotes - or follow the link below to find some discussion. http://groups-beta.google.com/group/comp.lang.python/search?group=comp.lang.python&q=%22can%27t+start+new+thread%22&qt_g=1&searchnow=Search+this+group Could you implement your cars as state machines and have a loop that runs through all the cars and gives each one a chance to increment its state? Do you know about SimPy? http://simpy.sourceforge.net/ HTH Kent > > Here's the code: > >>>>cars=range(1000) >>>>for i in cars: > > cars[i]=cars[i]=car(1,10,2,1,adjls,juncls) > > > >>>>for i in cars: > > i.start() > > Traceback (most recent call last): > File "<pyshell#24>", line 2, in -toplevel- > i.start() > error: can't start new thread > > Is there a way out.Also, are there any tips on > performance issues? > > Here is the class car: > > class car(threading.Thread): > def > __init__(self,carid,speed,dest,orig,adjls,juncls): > threading.Thread.__init__(self) > self.speed=speed > self.finished=0 > self.carid=carid > self.dest=dest > self.orig=orig > self.adjls=adjls > self.juncls=juncls > > self.shortest=find_shortest_path(adjls,self.dest,self.orig) > self.calc=findpaths(adjls,self.dest,self.orig) > > self.stats={'currtrsp':0,'avgspeed':0,'distcov':0,'totaltime':0} > def traverse_track(self,p1,p2): > counter=0 > time=0 > while self.adjls[p1][counter].to!=p2: > counter=counter+1 > self.track=self.adjls[p1][counter] > self.pos=0 > if self.speed>self.track.speed: > speed=self.track.speed > else: > speed=self.speed > while self.pos!=self.track.length: > if self.track.state.has_key(self.pos): > self.track.state[self.pos].acquire() > else: > > self.track.state[self.pos]=threading.Semaphore(value=self.track.lanes) > self.track.state[self.pos].acquire() > if self.pos!=0: > self.track.state[self.pos-1].release() > self.pos=self.pos+1 > sleep(1.0/speed) > time=time+1.0/speed > > self.stats['currtrsp']=float(self.track.length)/time > if self.stats['avgspeed']: > > self.stats['avgspeed']=float(self.stats['distcov']+self.track.length)/(self.stats['distcov']/self.stats['avgspeed']+self.track.length/self.stats['currtrsp']) > else: > > self.stats['avgspeed']=self.stats['currtrsp'] > > self.stats['totaltime']=self.stats['totaltime']+time > if self.track.stats['avgspeed']: > > self.track.stats['avgspeed']=(self.track.stats['avgspeed']*self.track.stats['traffictotal']+self.stats['currtrsp'])/(self.track.stats['traffictotal']+1) > else: > > self.track.stats['avgspeed']=self.stats['currtrsp'] > > self.stats['distcov']=self.stats['distcov']+self.track.length > > self.track.stats['traffictotal']=self.track.stats['traffictotal']+1 > def cross_junction(self,juncls,juncid,orig,dest): > marker=str(orig)+'-'+str(dest) > if juncls[juncid].free.has_key(marker): > self.track.state[self.pos].release() > else: > while not > juncls[juncid].signalled['green'].has_key(marker): > sleep(0.2) > self.track.state[self.pos-1].release() > def run(self): > path=self.shortest > counter=1 > for i in path[:1]: > self.traverse_track(i,path[counter]) > if not counter==len(path)-1: > > self.cross_junction(self.juncls,path[counter],i,path[counter+1]) > counter=counter+1 > self.finished=1 > self.track.state[self.pos-1].release() > > > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From shitizb at yahoo.com Wed Feb 23 19:40:52 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Wed Feb 23 19:40:56 2005 Subject: [Tutor] threads In-Reply-To: <20050223175043.97304.qmail@web53801.mail.yahoo.com> Message-ID: <20050223184053.75732.qmail@web53806.mail.yahoo.com> Hi, Googling for my problem i found the following page: http://gnosis.cx/publish/programming/charming_python_b7.html It doesnt make much sense to me.It seems that the author is implementing a series of routines rather than running them sumultaneously as threads are supposed to do.Am i missing the point? Shitiz --- Shitiz Bansal <shitizb@yahoo.com> wrote: > Hi, > > I am trying to build a traffic network simulator > using > python, for my degree project. > > I need to run at least 5-6000 cars simultaneously.I > wanted to run each car in a separate thread. > However , after about 400 threads i am unable to > create new threads. > > Here's the code: > >>> cars=range(1000) > >>> for i in cars: > cars[i]=cars[i]=car(1,10,2,1,adjls,juncls) > > > >>> for i in cars: > i.start() > > Traceback (most recent call last): > File "<pyshell#24>", line 2, in -toplevel- > i.start() > error: can't start new thread > > Is there a way out.Also, are there any tips on > performance issues? > > Here is the class car: > > class car(threading.Thread): > def > __init__(self,carid,speed,dest,orig,adjls,juncls): > threading.Thread.__init__(self) > self.speed=speed > self.finished=0 > self.carid=carid > self.dest=dest > self.orig=orig > self.adjls=adjls > self.juncls=juncls > > self.shortest=find_shortest_path(adjls,self.dest,self.orig) > > self.calc=findpaths(adjls,self.dest,self.orig) > > self.stats={'currtrsp':0,'avgspeed':0,'distcov':0,'totaltime':0} > def traverse_track(self,p1,p2): > counter=0 > time=0 > while self.adjls[p1][counter].to!=p2: > counter=counter+1 > self.track=self.adjls[p1][counter] > self.pos=0 > if self.speed>self.track.speed: > speed=self.track.speed > else: > speed=self.speed > while self.pos!=self.track.length: > if self.track.state.has_key(self.pos): > self.track.state[self.pos].acquire() > else: > > self.track.state[self.pos]=threading.Semaphore(value=self.track.lanes) > self.track.state[self.pos].acquire() > if self.pos!=0: > > self.track.state[self.pos-1].release() > self.pos=self.pos+1 > sleep(1.0/speed) > time=time+1.0/speed > > self.stats['currtrsp']=float(self.track.length)/time > if self.stats['avgspeed']: > > self.stats['avgspeed']=float(self.stats['distcov']+self.track.length)/(self.stats['distcov']/self.stats['avgspeed']+self.track.length/self.stats['currtrsp']) > else: > > self.stats['avgspeed']=self.stats['currtrsp'] > > self.stats['totaltime']=self.stats['totaltime']+time > if self.track.stats['avgspeed']: > > self.track.stats['avgspeed']=(self.track.stats['avgspeed']*self.track.stats['traffictotal']+self.stats['currtrsp'])/(self.track.stats['traffictotal']+1) > else: > > self.track.stats['avgspeed']=self.stats['currtrsp'] > > self.stats['distcov']=self.stats['distcov']+self.track.length > > self.track.stats['traffictotal']=self.track.stats['traffictotal']+1 > def > cross_junction(self,juncls,juncid,orig,dest): > marker=str(orig)+'-'+str(dest) > if juncls[juncid].free.has_key(marker): > self.track.state[self.pos].release() > else: > while not > juncls[juncid].signalled['green'].has_key(marker): > sleep(0.2) > self.track.state[self.pos-1].release() > def run(self): > path=self.shortest > counter=1 > for i in path[:1]: > self.traverse_track(i,path[counter]) > if not counter==len(path)-1: > > self.cross_junction(self.juncls,path[counter],i,path[counter+1]) > counter=counter+1 > self.finished=1 > self.track.state[self.pos-1].release() > > > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam > protection around > http://mail.yahoo.com > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > __________________________________ Do you Yahoo!? Yahoo! Mail - now with 250MB free storage. Learn more. http://info.mail.yahoo.com/mail_250 From maxnoel_fr at yahoo.fr Wed Feb 23 19:43:49 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Wed Feb 23 19:43:54 2005 Subject: Fwd: [Tutor] threads Message-ID: <e8d908676f228ab4fa6ec3f1d2c666a6@yahoo.fr> Some day I'm actually going to learn how to hit the "Reply All" button. I swear. Begin forwarded message: > From: Max Noel <maxnoel_fr@yahoo.fr> > Date: February 23, 2005 18:42:37 GMT > To: Shitiz Bansal <shitizb@yahoo.com> > Subject: Re: [Tutor] threads > > > On Feb 23, 2005, at 17:50, Shitiz Bansal wrote: > >> Hi, >> >> I am trying to build a traffic network simulator using >> python, for my degree project. >> >> I need to run at least 5-6000 cars simultaneously.I >> wanted to run each car in a separate thread. > > Mmh... Sounds like a bad design decision to me. This doesn't scale up > well, slows your system down to a crawl (especially if it's > single-CPU), and some vehicles may never get to act if your OS doesn't > have an efficient scheduler. Not to mention that due to the way > threads are run, you probably won't ever get twice the same result > when running a given simulation multiple times with the same > parameters. > > Instead, you should fake it: have one thread running for all the > cars. This thread has a for loop that iterates over all the cars and > makes each of them "step". > > > Coincidentally, I'm writing something that's more or less similar for > my final-year project at Uni: a crowd simulation in a shopping center. > I released the code under the GPL on Sourceforge (I've become a CVS > addict), which you can find at http://sourceforge.net/projects/gmof/ . > It's Java, not Python, but it's well-commented and written in a > readable way (or at least I like to think so). Feel free to examine > it. What you're looking for, I guess, is the run() method in the Mall > class. > > -- Max > maxnoel_fr at yahoo dot fr -- ICQ #85274019 > "Look at you hacker... A pathetic creature of meat and bone, panting > and sweating as you run through my corridors... How can you challenge > a perfect, immortal machine?" > > -- maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From kent37 at tds.net Wed Feb 23 20:26:34 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Feb 23 20:28:29 2005 Subject: [Tutor] threads In-Reply-To: <20050223184053.75732.qmail@web53806.mail.yahoo.com> References: <20050223184053.75732.qmail@web53806.mail.yahoo.com> Message-ID: <421CD8EA.2010201@tds.net> Shitiz Bansal wrote: > Hi, > Googling for my problem i found the following page: > > http://gnosis.cx/publish/programming/charming_python_b7.html > > It doesnt make much sense to me.It seems that the > author is implementing a series of routines rather > than running them sumultaneously as threads are > supposed to do.Am i missing the point? The point is to maintain a list of independent, resumable 'processes' *without* using threads. It's a neat hack on generators. I suggest you read enough of this link http://www.python.org/doc/2.2.2/whatsnew/node5.html to understand what a generator is, then take a look at SimPy which takes the concepts that David Mertz is talking about and builds a user-friendly, well-documented simulation package around it. Kent From dyoo at hkn.eecs.berkeley.edu Wed Feb 23 20:32:12 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Feb 23 20:32:15 2005 Subject: [Tutor] threads In-Reply-To: <20050223175043.97304.qmail@web53801.mail.yahoo.com> Message-ID: <Pine.LNX.4.44.0502231030540.20166-100000@hkn.eecs.berkeley.edu> On Wed, 23 Feb 2005, Shitiz Bansal wrote: > I am trying to build a traffic network simulator using python, for my > degree project. > > I need to run at least 5-6000 cars simultaneously. I wanted to run each > car in a separate thread. However , after about 400 threads i am unable > to create new threads. Hello! Python is using your operating system's native thread implementation; it's possible that you're running into a platform-specific issue. >From looking at the error message: > Traceback (most recent call last): > File "<pyshell#24>", line 2, in -toplevel- > i.start() > error: can't start new thread I see the error message "error: can't start new thread". I did a Google search and found that Windows reports this error if we hit it with thousands of threads at a time: http://mail.python.org/pipermail/python-checkins/2003-July/036869.html You may need to raise the thread limit on your operating system. That being said, doing a simulation through threads might not be the easiest thing to do. Instead of representing each car as a thread, you may be able to make things work by keeping all car in a priority queue, and do a kind of discrete simulation without threads. For example, here is a program that simulates people who say that they are hungry: ###### import heapq import random """Demo of heapq for doing discrete simulation.""" class Scheduler: """A scheduler keeps track what the current time is, and what event should occur next.""" def __init__(self): self.currentTime = 0 ## self.queue will be a list of (scheduledTime, callable) tuples. self.queue = [] def after(self, delay, event): """Adds a new event to the queue.""" timeAndEvent = (self.currentTime + delay, event) heapq.heappush(self.queue, timeAndEvent) def hasNext(self): """Returns true if there are still events to be processed.""" return len(self.queue) > 0 def next(self): """Returns the time and next event to be executed. Precondition: we have more events.""" assert self.queue if self.queue: timeAndEvent = heapq.heappop(self.queue) self.currentTime = timeAndEvent[0] return timeAndEvent class Person: """A person knows their name, and what scheduler they belong to.""" def __init__(self, name, sched): self.name, self.sched = name, sched def neutralState(self): """In a neutral state, a person can either eat or get hungry.""" print self.name, "is making a choice..." nextState = random.choice([self.sleepingState, self.hungryState]) self.sched.after(4, nextState) def sleepingState(self): """A person will wake up in 12 minutes.""" print self.name, "snores..." self.sched.after(12, self.wakeState) def wakeState(self): print self.name, "wakes up!" self.sched.after(1, self.neutralState) def hungryState(self): print self.name, "is hungry. Food..." self.sched.after(3, self.eatingState) def eatingState(self): print self.name, "is eating. Yum." self.sched.after(10, self.neutralState) if __name__ == '__main__': scheduler = Scheduler() sam = Person("sam", scheduler) max = Person("max", scheduler) ## Let's start up the initial conditions: sam will be eating, and ## max will be sleeping. scheduler.after(0, sam.eatingState) scheduler.after(0, max.sleepingState) for i in range(10): time, event = scheduler.next() print "time:", time event() ###### This is a somewhat hacky program, but it's amusing to watch: ### time: 0 sam is eating. Yum. time: 0 max snores... time: 10 sam is making a choice... time: 12 max wakes up! time: 13 max is making a choice... time: 14 sam is hungry. Food... time: 17 sam is eating. Yum. time: 17 max snores... time: 27 sam is making a choice... time: 29 max wakes up! ### It sounds like you want to hit the road with your car simulation; a discrete simulation approach might be the most straightforward. If you make each event discrete enough, it should work ok. There are systems that support enormous amounts of concurrency; If you really want to simulate each car with a thread, you may want to try Stackless Python; it's a Python variant that supports the concept of lightweight "tasklets". http://www.stackless.com/ Also, you may want to also look at Erlang: http://www.erlang.org/ Erlang is a programming language that's designed with concurrency in mind, and I've heard that its concurrency support is second to none. I hope this helps! From klappnase at freenet.de Wed Feb 23 21:29:06 2005 From: klappnase at freenet.de (Michael Lange) Date: Wed Feb 23 21:26:17 2005 Subject: [Tutor] UnicodeDecodeError In-Reply-To: <421C7554.4080309@tds.net> References: <20050222202659.3e0c9675.klappnase@freenet.de> <421C7554.4080309@tds.net> Message-ID: <20050223212906.4e7ca77f.klappnase@freenet.de> On Wed, 23 Feb 2005 07:21:40 -0500 Kent Johnson <kent37@tds.net> wrote: > > This is a part of Python that still confuses me. I think what is happening is > - self.nextfile is a Unicode string sometimes (when it includes special characters) > - the gettext string is a byte string > - to compare the two, the byte string is promoted to Unicode by decoding it with the system default > encoding, which is generally 'ascii'. > - the gettext string includes non-ascii characters and the codec raises an exception. > Thanks Kent, now it looks like the total confusion seems to clear up (at least partially). After some googling it seems to me that the best bet is to use unicode strings exclusively. When I set the unicode flag in gettext.install() to 1 the gettext strings are unicode, however there's still a problem with the user input. As you guessed, "self.nextfile" is unicode only *sometimes*; I tried and changed the line from the old traceback into: if unicode(self.nextfile, 'iso8859-1') == _('No destination file selected'): Now when self.nextfile is an existing file "\xe4.wav" that was clicked on in the file dialog's file list this works, however when I type "\xe4.wav" into the file dialog's entry field I get: TypeError Exception in Tk callback Function: <bound method Snackrecorder.start of <snackrecorder.Snackrecorder instance at 0xb774518c>> (type: <type 'instancemethod'>) Args: () Traceback (innermost last): File "/usr/lib/python2.3/site-packages/Pmw/Pmw_1_2/lib/PmwBase.py", line 1747, in __call__ return apply(self.func, args) File "/usr/local/share/phonoripper-0.6.2/snackrecorder.py", line 304, in start if unicode(self.nextfile, 'iso8859-1') == _('No destination file selected'): TypeError: decoding Unicode is not supported At least this might explain why "A\xe4" worked and "\xe4" not as I mentioned in a previous post. Now the problem arises how to determine if self.nextfile is unicode or a byte string? Or maybe even better, make sure that self.nextfile is always a byte string so I can safely convert it to unicode later on. But how to convert unicode user input into byte strings when I don't even know the user's encoding ? I guess this will require some further research. > I don't know what the best solution is. Two possibilities (substitute your favorite encoding for > latin-1): > - decode the gettext string, e.g. > if self.nextfile == _('No destination file selected').decode('latin-1'): > > - set your default encoding to latin-1. (This solution is frowned on by the Python-Unicode > cognoscenti and it makes your programs non-portable). Do this by creating a file > site-packages/sitecustomize.py containing the lines > import sys > sys.setdefaultencoding('latin-1') > > Kent > Unfortunately the latter is no option, because I definitely need portability. I guess I should probably use utf-8. Thanks and best regards Michael > > > > ###################################################################### > > Error: 1 > > UnicodeDecodeError Exception in Tk callback > > Function: <bound method Snackrecorder.start of <snackrecorder.Snackrecorder instance at 0xb77fe24c>> (type: <type 'instancemethod'>) > > Args: () > > Traceback (innermost last): > > File "/usr/lib/python2.3/site-packages/Pmw/Pmw_1_2/lib/PmwBase.py", line 1747, in __call__ > > return apply(self.func, args) > > File "/usr/local/share/phonoripper/snackrecorder.py", line 305, in start > > if self.nextfile == _('No destination file selected'): > > UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 22: ordinal not in range(128) > > > > ###################################################################### > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From billk at fastmail.fm Thu Feb 24 00:21:52 2005 From: billk at fastmail.fm (Bill Kranec) Date: Thu Feb 24 00:21:50 2005 Subject: [Tutor] Method/subclass In-Reply-To: <f2ff2d050222221348b18bd7@mail.gmail.com> References: <f2ff2d0502220206330ac19f@mail.gmail.com> <421B27E1.9000206@tds.net> <f2ff2d050222221348b18bd7@mail.gmail.com> Message-ID: <421D1010.80603@fastmail.fm> This article might also be helpful, as it is a little more concrete: http://www.devx.com/dbzone/Article/22093. I found it by Googling for 'python database access object'. Is this the kind of thing that you are referring to, Kent? HTH, Bill Liam Clarke wrote: >Kia ora, > > > >>I'm not really sure what you are trying to do, the code is pretty sketchy. It looks like you want to >>have a bunch of queries on your dataset, and the result of each query is displayed in a window. Is >>that right? Assuming it is, I'll continue... >> >> > > >What I'm doing here is very sketchy, both in my mind and code. So >yeah, my apologies, I probably should have put more effort into the >question. ESR would flame me for sure. > > > >>First, DO NOT put any references to your GUI classes into your data access classes!! NEVER ever do that! >> >> > >Point noted. That was me trying to grasp the concept of returning >objects, and then I thought I could be clever.... > > > >>I would probably have >>- a data access class (DAO) >>- probably some data container classes (domain objects). Your data access class >methods will take domain objects as parameters and return them as results. The different >parts of the app will communicate by passing domain objects around. If the domain data >is very simple you might just use >>Python lists and dictionaries. >>- a class for the main window >>- classes for the display windows - a separate class for each kind of display. If all the >displays are similar you might reuse a single class; if they are very different they will have >their own classes. If there is shared behaviour you might have a common base class, >otherwise inherit directly from the GUI classes. >>- possibly one or more controller classes - the classes that provide the glue between the >gui and the data. Some of this logic will be in the main window, some you might want to >put in its own class. >> >>A sample data flow might be >>- user enters a query into the main window and clicks a 'search' button >>- the search button handler is invoked. This might be a method of the main window class, >or it might delegate to a helper class. >>- in either case, the handler class must have a reference to the data access class. It >forwards the request to the DAO, gets the results back, and creates the new window to >display the results. (The result object might be passed directly to the window class in its >constructor or by a helper method.) >> >> > > >Thank you for that Kent, your shouting has been heeded, and it makes >perfect sense not to return GUI objects. Of course, hindsight is great >like that, the answer to the cryptic crossword clue is obvious once >you know the answer. > > I'm not sure I understand your response fully, so I've described how >I would do this in accordance with my understandinf of the method >described above. Any feedback/corrections are gratefully welcomed. > >But first, a wee bit of explanation. As I said, this is very sketchy. >I've run into the issue of not knowing where to start. This is my >first database type project, so I want > to go about this the right way from the get go, which means my >progress is quite hesitant/non-existent. Ultimately I want to follow >good methods of coding as much as I can, as I dream of actually being >able to make a living out of this at some stage. > > So, as I don't actually know how to do this, on account of never >having done similar, I need to layout in my mind what I'm going to do, >before I do it. I had a look at UML, but it doesn't look helpful . >Perhaps it's a way of thinking that I need to learn that'll make UML >useful. > >So, looking at your dataflow above Kent, I'm planning - > >my main GUI runs, and upon initialisation creates self.DAO a data access object. > >The handlers in the main and each child window, submit requests by >calling an appropriate method of self.DAO (or self.parent.DAO) as the >case may be, passing any needed data as a dictionary/list, as it's not >going to be overly complicated. > >The DAO then creates an SQL request as necessary, and creates a >dictionary/list out of any retrieved data, and returns it to the >handler. (Or an acknowledgement if data was entered, or similar.) > >If a new window needs to be opened (in response to a query or >requested table) then the handler then instantiates a new child window >using the dictionary after it's been appropriately twiddled. (As a lot >of handlers are going to be doing this, perhaps a function of my >parent window can hold a method for the twiddling.) > >Is this going to violate any best practise type methodologies? Sheesh, >I get so confused. >I've spent all this time trying to keep 'logic and gui' separate, with >the result that I stuck my gui related logic in daft places. > >I dunno, I was thinking perhaps do this one in Java, so I'm forced to >learn how to use objects (particularly passing them around) properly. >The temptation to use many, many, functions is there. I've never >(consciously) used objects as arguments and returned values, >aside from what 3rd party packages have required. To put it a better >way, I've never written code where two objects I've written have >passed an object that I've also written between them. > >Of course, then I'd have to rewrite this in Python once done as Swing >is yuck, and I don't like waiting for five minutes for the JRE to kick >in. Actually, I don't like Java at all. > >If anyone has any links to recommended OO best practises, I'd be grateful. >I googled DAO, & domain objects, and found a lot of confusing stuff. > >Of course, it would probably help if I didn't have cold as well. > >Thanks in advance for any advice offered. > > >Regards, > >Liam Clarke > > > > From keridee at jayco.net Thu Feb 24 01:56:28 2005 From: keridee at jayco.net (Jacob S.) Date: Thu Feb 24 01:56:17 2005 Subject: [Tutor] Problems with test cgi script on windows XP/Apache References: <6.2.1.2.0.20050214113155.01f091a0@postman.johnsons-web.com> Message-ID: <008f01c51a0b$b77e7e50$a35328cf@JSLAPTOP> I find it's convenient to get rid of that problem. The easy thing to get to folder options You can 1) Go to control panel and click folder options 2) Open a folder, click the view menu, and choose folder options Either way it's the same screen. Now, in the middle tab, there is a checkmark about halfway in the viewable scrollbox that says something like "Hide extensions for known file types" Unclick that and click apply. Click OK. This should show all extensions, except the .lnk and .pif extensions on their appropriate shortcuts, and therefore you can change the file type and not cause the problem you have all by using rename! Much better and understandable IMHO. HTH, Jacob >>Date: Mon, 14 Feb 2005 10:25:28 -0900 >>From: Tim Johnson <tim@johnsons-web.com> >>Subject: Re: [Tutor] Problems with test cgi script on windows XP/Apache >>To: Tim Johnson <tim@johnsons-web.com> >>X-Mailer: QUALCOMM Windows Eudora Version 6.2.1.2 >> >>At 12:22 PM 2/13/2005, you wrote: >>>I'm attempting to run a test cgi script on windows xp with apache >>>as the http server. I keep getting a not found error from IE, and the >>>error log shows the following error message. >>>No such file or directory: script not found or unable to stat: c:/program >>>files/apache group/apache/cgi-bin/test.py >>>Another cgi script using a different interpreter (rebol) is running >>>properly. I was receiving >>>the same error message with the rebol script until I corrected the first >>>line (she-bang). >>>here is the code for the script: >>>#!d:\Python23\python >>>print "Content-type: text/html\n" >>>print "hello" >>>## I can confirm the the first line does contain the correct path to >>>## the python executable. I have tried it with and without the ".exe" > > This has been solved. Classic, just classic. I had created a test script, > and named it "test.py". Hah! windows renamed it "test.py.py", and it > was obfuscated when I edited it. One could say either: > 1)Dumb windows newbie > or > 2)Dumb windows strategy > I'll leave that one up to the reader. > ---- > tim > > > >>>_______________________________________________ >>>Tutor maillist - Tutor@python.org >>>http://mail.python.org/mailman/listinfo/tutor >>> >>>__________ NOD32 1.998 (20050212) Information __________ >>> >>>This message was checked by NOD32 Antivirus System. >>>http://www.nod32.com >> >> >>__________ NOD32 1.998 (20050212) Information __________ >> >>This message was checked by NOD32 Antivirus System. >>http://www.nod32.com >> > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From keridee at jayco.net Thu Feb 24 02:11:11 2005 From: keridee at jayco.net (Jacob S.) Date: Thu Feb 24 02:10:39 2005 Subject: [Tutor] Interpreter level objects Message-ID: <000301c51a0d$c02c8f90$a35328cf@JSLAPTOP> Hi everyone! Let's see, my topic of discussion for today is this. If the psyco package can work on an interpreter level--I don't know if that's the right terminology, but this is what it does. Say I put the code import psyco psyco.full() in sitecustomize.py and run a random file that I have already got an average execution time of. Then I run it again, with the above implemented. My execution time is has dropped. Which brings me to believe that psyco monitors all subprocesses and all subobjects. So this being the case, why haven't the volunteers set up from __import__ division so that you can put it in sitecustomize.py and get it to run whenever you start python? I know why it doesn't work,... because division is in the sitecustomize namespace. But why didn't they set it up like the psyco people (no pun intended--but it is pretty funny) did? Anyways, this all came up because several modules that used psyco.full() would greatly be hindered if they imported another module that did the same. So I got the great idea, why not put it in sitecustomize.py? Then I got the idea, why not put from __import__ division in the sitecustomize.py, too? psyco.full() worked, from __import__ division did not. Any ideas? Jacob From guillermo.fernandez.castellanos at gmail.com Thu Feb 24 03:37:58 2005 From: guillermo.fernandez.castellanos at gmail.com (guillermo.fernandez.castellanos@gmail.com) Date: Thu Feb 24 03:37:02 2005 Subject: [Tutor] threads Message-ID: <421D3E06.601@gmail.com> Nothing to do, but did you think about SimPy? http://simpy.sourceforge.net/ It may make your life much simpler. G On Wed, 23 Feb 2005 11:32:12 -0800 (PST), Danny Yoo <dyoo@hkn.eecs.berkeley.edu> wrote: > > > On Wed, 23 Feb 2005, Shitiz Bansal wrote: > > > I am trying to build a traffic network simulator using python, for my > > degree project. > > > > I need to run at least 5-6000 cars simultaneously. I wanted to run each > > car in a separate thread. However , after about 400 threads i am unable > > to create new threads. > > Hello! > > Python is using your operating system's native thread implementation; it's > possible that you're running into a platform-specific issue. > > >From looking at the error message: > > > Traceback (most recent call last): > > File "<pyshell#24>", line 2, in -toplevel- > > i.start() > > error: can't start new thread > > I see the error message "error: can't start new thread". I did a Google > search and found that Windows reports this error if we hit it with > thousands of threads at a time: > > http://mail.python.org/pipermail/python-checkins/2003-July/036869.html > > You may need to raise the thread limit on your operating system. That > being said, doing a simulation through threads might not be the easiest > thing to do. > > Instead of representing each car as a thread, you may be able to make > things work by keeping all car in a priority queue, and do a kind of > discrete simulation without threads. > > For example, here is a program that simulates people who say that they are > hungry: > > ###### > import heapq > import random > > """Demo of heapq for doing discrete simulation.""" > > class Scheduler: > """A scheduler keeps track what the current time is, and what > event should occur next.""" > def __init__(self): > self.currentTime = 0 > ## self.queue will be a list of (scheduledTime, callable) tuples. > self.queue = [] > > def after(self, delay, event): > """Adds a new event to the queue.""" > timeAndEvent = (self.currentTime + delay, event) > heapq.heappush(self.queue, timeAndEvent) > > def hasNext(self): > """Returns true if there are still events to be processed.""" > return len(self.queue) > 0 > > def next(self): > """Returns the time and next event to be executed. > Precondition: we have more events.""" > assert self.queue > if self.queue: > timeAndEvent = heapq.heappop(self.queue) > self.currentTime = timeAndEvent[0] > return timeAndEvent > > class Person: > """A person knows their name, and what scheduler they belong to.""" > def __init__(self, name, sched): > self.name, self.sched = name, sched > > def neutralState(self): > """In a neutral state, a person can either eat or get hungry.""" > print self.name, "is making a choice..." > nextState = random.choice([self.sleepingState, > self.hungryState]) > self.sched.after(4, nextState) > > def sleepingState(self): > """A person will wake up in 12 minutes.""" > print self.name, "snores..." > self.sched.after(12, self.wakeState) > > def wakeState(self): > print self.name, "wakes up!" > self.sched.after(1, self.neutralState) > > def hungryState(self): > print self.name, "is hungry. Food..." > self.sched.after(3, self.eatingState) > > def eatingState(self): > print self.name, "is eating. Yum." > self.sched.after(10, self.neutralState) > > if __name__ == '__main__': > scheduler = Scheduler() > sam = Person("sam", scheduler) > max = Person("max", scheduler) > ## Let's start up the initial conditions: sam will be eating, and > ## max will be sleeping. > scheduler.after(0, sam.eatingState) > scheduler.after(0, max.sleepingState) > > for i in range(10): > time, event = scheduler.next() > print "time:", time > event() > ###### > > This is a somewhat hacky program, but it's amusing to watch: > > ### > time: 0 > sam is eating. Yum. > time: 0 > max snores... > time: 10 > sam is making a choice... > time: 12 > max wakes up! > time: 13 > max is making a choice... > time: 14 > sam is hungry. Food... > time: 17 > sam is eating. Yum. > time: 17 > max snores... > time: 27 > sam is making a choice... > time: 29 > max wakes up! > ### > > It sounds like you want to hit the road with your car simulation; a > discrete simulation approach might be the most straightforward. If you > make each event discrete enough, it should work ok. > > There are systems that support enormous amounts of concurrency; If you > really want to simulate each car with a thread, you may want to try > Stackless Python; it's a Python variant that supports the concept of > lightweight "tasklets". > > http://www.stackless.com/ > > Also, you may want to also look at Erlang: > > http://www.erlang.org/ > > Erlang is a programming language that's designed with concurrency in mind, > and I've heard that its concurrency support is second to none. > > I hope this helps! > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Thu Feb 24 05:16:20 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Feb 24 05:16:23 2005 Subject: [Tutor] UnicodeDecodeError In-Reply-To: <20050223212906.4e7ca77f.klappnase@freenet.de> References: <20050222202659.3e0c9675.klappnase@freenet.de> <421C7554.4080309@tds.net> <20050223212906.4e7ca77f.klappnase@freenet.de> Message-ID: <421D5514.2050200@tds.net> Michael Lange wrote: > now it looks like the total confusion seems to clear up (at least partially). After some googling it > seems to me that the best bet is to use unicode strings exclusively. I think that is a good plan. When I set the unicode flag > in gettext.install() to 1 the gettext strings are unicode, however there's still a problem with the > user input. As you guessed, "self.nextfile" is unicode only *sometimes*; I tried and changed the line > from the old traceback into: > > if unicode(self.nextfile, 'iso8859-1') == _('No destination file selected'): How about n = self.nextfile if not isinstance(n, unicode): n = unicode(n, 'iso8859-1') ? > At least this might explain why "A\xe4" worked and "\xe4" not as I mentioned in a previous post. > Now the problem arises how to determine if self.nextfile is unicode or a byte string? > Or maybe even better, make sure that self.nextfile is always a byte string so I can safely convert > it to unicode later on. But how to convert unicode user input into byte strings when I don't even > know the user's encoding ? I guess this will require some further research. Why do you need to convert back to byte strings? You can find out the console encoding from sys.stdin and stdout: >>> import sys >>> sys.stdout.encoding 'cp437' >>> sys.stdin.encoding 'cp437' IIRC there is also an encoding associated with the current locale, I'm not sure how to use that. > Unfortunately the latter is no option, because I definitely need portability. I guess I should probably use > utf-8. UTF-8 is your friend :-) Kent From klappnase at freenet.de Thu Feb 24 11:27:13 2005 From: klappnase at freenet.de (Michael Lange) Date: Thu Feb 24 11:24:23 2005 Subject: [Tutor] Unicode issues (was: UnicodeDecodeError) In-Reply-To: <421D5514.2050200@tds.net> References: <20050222202659.3e0c9675.klappnase@freenet.de> <421C7554.4080309@tds.net> <20050223212906.4e7ca77f.klappnase@freenet.de> <421D5514.2050200@tds.net> Message-ID: <20050224112713.27bcd5f3.klappnase@freenet.de> On Wed, 23 Feb 2005 23:16:20 -0500 Kent Johnson <kent37@tds.net> wrote: > How about > n = self.nextfile > if not isinstance(n, unicode): > n = unicode(n, 'iso8859-1') > ? > > > At least this might explain why "A\xe4" worked and "\xe4" not as I mentioned in a previous post. > > Now the problem arises how to determine if self.nextfile is unicode or a byte string? > > Or maybe even better, make sure that self.nextfile is always a byte string so I can safely convert > > it to unicode later on. But how to convert unicode user input into byte strings when I don't even > > know the user's encoding ? I guess this will require some further research. > > Why do you need to convert back to byte strings? > > You can find out the console encoding from sys.stdin and stdout: > >>> import sys > >>> sys.stdout.encoding > 'cp437' > >>> sys.stdin.encoding > 'cp437' > I *thought* I would have to convert the user input which might be any encoding back into byte string first (remember, I got heavily confused, because user input was sometimes unicode and sometimes byte string), so I can convert it to "standard" unicode (utf-8) later on. I've added this test to the file selection method, where "result" holds the filename the user chose: if isinstance(result, unicode): result = result.encode('iso8859-1') return result later on self.nextfile is set to "result" . The idea was, if I could catch the user's encoding, I could do something like: if isinstance(result, unicode): result = result.encode(sys.stdin.encoding) result = unicode(result, 'utf-8') to avoid problems with unicode objects that have different encodings - or isn't this necessary at all ? I'm sorry if this is a dumb question, but I'm afraid I'm a complete encoding-idiot. Thanks and best regards Michael From kent37 at tds.net Thu Feb 24 13:51:04 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Feb 24 13:51:07 2005 Subject: [Tutor] Unicode issues In-Reply-To: <20050224112713.27bcd5f3.klappnase@freenet.de> References: <20050222202659.3e0c9675.klappnase@freenet.de> <421C7554.4080309@tds.net> <20050223212906.4e7ca77f.klappnase@freenet.de> <421D5514.2050200@tds.net> <20050224112713.27bcd5f3.klappnase@freenet.de> Message-ID: <421DCDB8.8050308@tds.net> Michael Lange wrote: > I *thought* I would have to convert the user input which might be any encoding back into > byte string first How are you getting the user input? Is it from the console or from a GUI? I think the best strategy is to try to keep all your strings as Unicode. Unicode is the only encoding that can represent characters from any locale. (That's the point of Unicode, actually.) So I would convert the user input to unicode, not to a byte string. > (remember, I got heavily confused, because user input was sometimes unicode and > sometimes byte string), so I can convert it to "standard" unicode (utf-8) later on. Careful! I wouldn't call utf-8 "standard unicode". UTF-8 is a standard *encoding* of Unicode. Unicode is a 16-bit code. > I've added this test to the file selection method, where "result" holds the filename the user chose: > > if isinstance(result, unicode): > result = result.encode('iso8859-1') > return result This will fail if result includes characters that are not in the iso8859-1 repertoire. > > later on self.nextfile is set to "result" . > > The idea was, if I could catch the user's encoding, I could do something like: > > if isinstance(result, unicode): > result = result.encode(sys.stdin.encoding) > result = unicode(result, 'utf-8') This is broken code that will corrupt your result string. Here is what it does: if result is a unicode string, convert it to a byte string in the standard encoding. Then, assume that the byte string is in utf-8 encoding and convert it back to Unicode. Do you see why that is unlikely to have a good result? If your intent is to create a unicode string, try this: if not isinstance(result, unicode): result = result.decode(sys.stdin.encoding) > > to avoid problems with unicode objects that have different encodings - or isn't this necessary at all ? > > I'm sorry if this is a dumb question, but I'm afraid I'm a complete encoding-idiot. This article gives a lot of good background: http://www.joelonsoftware.com/articles/Unicode.html I have written an essay about console encoding issues. At the end there is a collection of links to more general Python and Unicode articles. http://www.pycs.net/users/0000323/stories/14.html Kent > > Thanks and best regards > > Michael > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From jsmith at medplus.com Thu Feb 24 15:04:25 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Thu Feb 24 15:04:28 2005 Subject: [Tutor] Precompiling to bytecode Message-ID: <C4C644CF4ADA9448904C3E8BACC4B97C02FFCED6@medexch1.medplus.com> I notice that python only pre-compiles imported modules and not the main script. The only way I seem to be able to get this to happen is to run python -c "import mainscript" Am I missing something? Thanks, Jeff From hugonz-lists at h-lab.net Thu Feb 24 18:36:01 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Thu Feb 24 18:36:25 2005 Subject: [Tutor] threads In-Reply-To: <20050223175043.97304.qmail@web53801.mail.yahoo.com> References: <20050223175043.97304.qmail@web53801.mail.yahoo.com> Message-ID: <421E1081.4070104@h-lab.net> OK, as ignorant as I may be on threads, I have read a bit on Stackless Python's tasklets. Suppossedly they require much less memory than python's threads. Information is at www.stackless.com Hugo Shitiz Bansal wrote: > Hi, > > I am trying to build a traffic network simulator using > python, for my degree project. > > I need to run at least 5-6000 cars simultaneously.I > wanted to run each car in a separate thread. > However , after about 400 threads i am unable to > create new threads. > > Here's the code: > >>>>cars=range(1000) >>>>for i in cars: > > cars[i]=cars[i]=car(1,10,2,1,adjls,juncls) > > > >>>>for i in cars: > > i.start() > > Traceback (most recent call last): > File "<pyshell#24>", line 2, in -toplevel- > i.start() > error: can't start new thread > > Is there a way out.Also, are there any tips on > performance issues? > > Here is the class car: > > class car(threading.Thread): > def > __init__(self,carid,speed,dest,orig,adjls,juncls): > threading.Thread.__init__(self) > self.speed=speed > self.finished=0 > self.carid=carid > self.dest=dest > self.orig=orig > self.adjls=adjls > self.juncls=juncls > > self.shortest=find_shortest_path(adjls,self.dest,self.orig) > self.calc=findpaths(adjls,self.dest,self.orig) > > self.stats={'currtrsp':0,'avgspeed':0,'distcov':0,'totaltime':0} > def traverse_track(self,p1,p2): > counter=0 > time=0 > while self.adjls[p1][counter].to!=p2: > counter=counter+1 > self.track=self.adjls[p1][counter] > self.pos=0 > if self.speed>self.track.speed: > speed=self.track.speed > else: > speed=self.speed > while self.pos!=self.track.length: > if self.track.state.has_key(self.pos): > self.track.state[self.pos].acquire() > else: > > self.track.state[self.pos]=threading.Semaphore(value=self.track.lanes) > self.track.state[self.pos].acquire() > if self.pos!=0: > self.track.state[self.pos-1].release() > self.pos=self.pos+1 > sleep(1.0/speed) > time=time+1.0/speed > > self.stats['currtrsp']=float(self.track.length)/time > if self.stats['avgspeed']: > > self.stats['avgspeed']=float(self.stats['distcov']+self.track.length)/(self.stats['distcov']/self.stats['avgspeed']+self.track.length/self.stats['currtrsp']) > else: > > self.stats['avgspeed']=self.stats['currtrsp'] > > self.stats['totaltime']=self.stats['totaltime']+time > if self.track.stats['avgspeed']: > > self.track.stats['avgspeed']=(self.track.stats['avgspeed']*self.track.stats['traffictotal']+self.stats['currtrsp'])/(self.track.stats['traffictotal']+1) > else: > > self.track.stats['avgspeed']=self.stats['currtrsp'] > > self.stats['distcov']=self.stats['distcov']+self.track.length > > self.track.stats['traffictotal']=self.track.stats['traffictotal']+1 > def cross_junction(self,juncls,juncid,orig,dest): > marker=str(orig)+'-'+str(dest) > if juncls[juncid].free.has_key(marker): > self.track.state[self.pos].release() > else: > while not > juncls[juncid].signalled['green'].has_key(marker): > sleep(0.2) > self.track.state[self.pos-1].release() > def run(self): > path=self.shortest > counter=1 > for i in path[:1]: > self.traverse_track(i,path[counter]) > if not counter==len(path)-1: > > self.cross_junction(self.juncls,path[counter],i,path[counter+1]) > counter=counter+1 > self.finished=1 > self.track.state[self.pos-1].release() > > > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From luke.jordan at gmail.com Thu Feb 24 19:02:44 2005 From: luke.jordan at gmail.com (Luke Jordan) Date: Thu Feb 24 19:02:47 2005 Subject: [Tutor] Print text position problems when using triple quotes Message-ID: <ea0feb800502241002491ecad9@mail.gmail.com> Hi all, I've tried a lot of experimenting and searching through various tutorials, and I haven't been able to come up with a solution to this, ostensibly simple, problem. I'm writing a simple game (run in command line) in which narrative text is printed in response to a user's decisions. The problem I'm running into is that triple quotes used in an indented block preserves the indentation when it prints. I'm writing code like this: if userInput == 1: some stuff print """ texttexttexttexttexttexttexttext """ question within a question if userInput == 1: print """ texttexttexttexttexttexttexttext texttexttexttexttexttexttexttext """ elif userInput == 2: print """ owowowowowowowowowowow """ to preserve the text's position at left when I run it in the command-line. The blocks get distorted and it becomes painful to read. Is there a way to preserve the readability of the code and have printed text from indented blocks, say, nested conditionals, appear flush at left, not printed exactly where I've written them in the script? I know I can accomplish this using single quotes instead of triple quotes, but I'm holding out hope that I can avoid putting each sentence in a separate print statement. if userInput == 1: print "here's 80 characters" print "now another 80" etc. Also, I've tried string.ljust(), but either I'm doing it wrong or it isn't the trick I'm looking for. Thanks for the help. Luke -- "If you think that was good, wait 'til you taste the antidote!" From bill.mill at gmail.com Thu Feb 24 19:14:13 2005 From: bill.mill at gmail.com (Bill Mill) Date: Thu Feb 24 19:14:17 2005 Subject: [Tutor] Print text position problems when using triple quotes In-Reply-To: <ea0feb800502241002491ecad9@mail.gmail.com> References: <ea0feb800502241002491ecad9@mail.gmail.com> Message-ID: <797fe3d4050224101463310066@mail.gmail.com> On Thu, 24 Feb 2005 10:02:44 -0800, Luke Jordan <luke.jordan@gmail.com> wrote: > Hi all, > > I've tried a lot of experimenting and searching through various > tutorials, and I haven't been able to come up with a solution to this, > ostensibly simple, problem. > > I'm writing a simple game (run in command line) in which narrative > text is printed in response to a user's decisions. The problem I'm > running into is that triple quotes used in an indented block preserves > the indentation when it prints. I'm writing code like this: > > if userInput == 1: > some stuff > print """ > texttexttexttexttexttexttexttext > """ > question within a question > if userInput == 1: > print """ > texttexttexttexttexttexttexttext > texttexttexttexttexttexttexttext > """ > elif userInput == 2: > print """ > owowowowowowowowowowow > """ > > to preserve the text's position at left when I run it in the > command-line. The blocks get distorted and it becomes painful to read. > > Is there a way to preserve the readability of the code and have > printed text from indented blocks, say, nested conditionals, appear > flush at left, not printed exactly where I've written them in the > script? Why not just take them out of the block, and either make them global to the module or create a string module? i.e.: prompt1 = """This is a long string with %s string variables %s scattered all over the place as well as odd indentation %s and funny lines ------------------ ============""" class foo: def bar(self): print prompt1 % (var1, var2, var3) peace Bill Mill bill.mill at gmail.com From bill.mill at gmail.com Thu Feb 24 19:15:41 2005 From: bill.mill at gmail.com (Bill Mill) Date: Thu Feb 24 19:15:44 2005 Subject: [Tutor] Print text position problems when using triple quotes In-Reply-To: <797fe3d4050224101463310066@mail.gmail.com> References: <ea0feb800502241002491ecad9@mail.gmail.com> <797fe3d4050224101463310066@mail.gmail.com> Message-ID: <797fe3d4050224101523be309f@mail.gmail.com> On Thu, 24 Feb 2005 13:14:13 -0500, Bill Mill <bill.mill@gmail.com> wrote: > On Thu, 24 Feb 2005 10:02:44 -0800, Luke Jordan <luke.jordan@gmail.com> wrote: > > Hi all, > > > > I've tried a lot of experimenting and searching through various > > tutorials, and I haven't been able to come up with a solution to this, > > ostensibly simple, problem. > > > > I'm writing a simple game (run in command line) in which narrative > > text is printed in response to a user's decisions. The problem I'm > > running into is that triple quotes used in an indented block preserves > > the indentation when it prints. I'm writing code like this: > > > > if userInput == 1: > > some stuff > > print """ > > texttexttexttexttexttexttexttext > > """ > > question within a question > > if userInput == 1: > > print """ > > texttexttexttexttexttexttexttext > > texttexttexttexttexttexttexttext > > """ > > elif userInput == 2: > > print """ > > owowowowowowowowowowow > > """ > > > > to preserve the text's position at left when I run it in the > > command-line. The blocks get distorted and it becomes painful to read. > > > > Is there a way to preserve the readability of the code and have > > printed text from indented blocks, say, nested conditionals, appear > > flush at left, not printed exactly where I've written them in the > > script? > > Why not just take them out of the block, and either make them global > to the module or create a string module? i.e.: > > prompt1 = """This is a long string with %s string variables > %s scattered all over the place > as well as odd indentation %s > and funny lines > ------------------ > ============""" > > class foo: > def bar(self): Sorry, I forgot that if it's in the module, you should declare prompt1 as global by using "global prompt1" right here. > print prompt1 % (var1, var2, var3) > > peace > Bill Mill > bill.mill at gmail.com > From luke.jordan at gmail.com Thu Feb 24 19:57:24 2005 From: luke.jordan at gmail.com (Luke Jordan) Date: Thu Feb 24 19:57:28 2005 Subject: [Tutor] Print text position problems when using triple quotes In-Reply-To: <797fe3d4050224101523be309f@mail.gmail.com> References: <ea0feb800502241002491ecad9@mail.gmail.com> <797fe3d4050224101463310066@mail.gmail.com> <797fe3d4050224101523be309f@mail.gmail.com> Message-ID: <ea0feb80050224105748880bfc@mail.gmail.com> Execllent. Many Thanks, Luke On Thu, 24 Feb 2005 13:15:41 -0500, Bill Mill <bill.mill@gmail.com> wrote: > On Thu, 24 Feb 2005 13:14:13 -0500, Bill Mill <bill.mill@gmail.com> wrote: > > On Thu, 24 Feb 2005 10:02:44 -0800, Luke Jordan <luke.jordan@gmail.com> wrote: > > > Hi all, > > > > > > I've tried a lot of experimenting and searching through various > > > tutorials, and I haven't been able to come up with a solution to this, > > > ostensibly simple, problem. > > > > > > I'm writing a simple game (run in command line) in which narrative > > > text is printed in response to a user's decisions. The problem I'm > > > running into is that triple quotes used in an indented block preserves > > > the indentation when it prints. I'm writing code like this: > > > > > > if userInput == 1: > > > some stuff > > > print """ > > > texttexttexttexttexttexttexttext > > > """ > > > question within a question > > > if userInput == 1: > > > print """ > > > texttexttexttexttexttexttexttext > > > texttexttexttexttexttexttexttext > > > """ > > > elif userInput == 2: > > > print """ > > > owowowowowowowowowowow > > > """ > > > > > > to preserve the text's position at left when I run it in the > > > command-line. The blocks get distorted and it becomes painful to read. > > > > > > Is there a way to preserve the readability of the code and have > > > printed text from indented blocks, say, nested conditionals, appear > > > flush at left, not printed exactly where I've written them in the > > > script? > > > > Why not just take them out of the block, and either make them global > > to the module or create a string module? i.e.: > > > > prompt1 = """This is a long string with %s string variables > > %s scattered all over the place > > as well as odd indentation %s > > and funny lines > > ------------------ > > ============""" > > > > class foo: > > def bar(self): > > Sorry, I forgot that if it's in the module, you should declare prompt1 > as global by using "global prompt1" right here. > > > print prompt1 % (var1, var2, var3) > > > > peace > > Bill Mill > > bill.mill at gmail.com > > > -- "If you think that was good, wait 'til you taste the antidote!" From dyoo at hkn.eecs.berkeley.edu Thu Feb 24 20:04:49 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Feb 24 20:04:57 2005 Subject: [Tutor] Precompiling to bytecode In-Reply-To: <C4C644CF4ADA9448904C3E8BACC4B97C02FFCED6@medexch1.medplus.com> Message-ID: <Pine.LNX.4.44.0502241058330.14680-100000@hkn.eecs.berkeley.edu> On Thu, 24 Feb 2005, Smith, Jeff wrote: > I notice that python only pre-compiles imported modules and not the main > script. The only way I seem to be able to get this to happen is to run > > python -c "import mainscript" Hi Jeff, Python automatically tries to compile module code on an 'import' statement: http://www.python.org/doc/2.2.3/tut/node8.html#SECTION008120000000000000000 Main programs aren't automatically imported, so that's why you're not seeing bytecode for them. Hope this helps! From dyoo at hkn.eecs.berkeley.edu Thu Feb 24 20:23:25 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Feb 24 20:23:30 2005 Subject: [Tutor] Interpreter level objects In-Reply-To: <000301c51a0d$c02c8f90$a35328cf@JSLAPTOP> Message-ID: <Pine.LNX.4.44.0502241106560.14680-100000@hkn.eecs.berkeley.edu> On Wed, 23 Feb 2005, Jacob S. wrote: > Say I put the code > > import psyco > psyco.full() > > in sitecustomize.py and run a random file that I have already got an > average execution time of. Then I run it again, with the above > implemented. My execution time is has dropped. Which brings me to > believe that psyco monitors all subprocesses and all subobjects. Hi Jacob, Yes, psyco.full() will do so, by patching itself in the Python runtime. But normally, people will run psyco on specific functions that they know are hot-spots in their code by using psyco.bind(). > So this being the case, why haven't the volunteers set up from > __import__ division so that you can put it in sitecustomize.py and get > it to run whenever you start python? One thing is that psyco only works on the x86 platform. It's also a bit experimental; in the Drawbacks section in Psyco's introduction: http://psyco.sourceforge.net/introduction.html the page mentions that the behavior of certain programs will change under Psyco, and that's not ideal. Finally, Psyco uses a lot of memory, and that's probably the biggest drawback. In short, Psyco is intrusive enough that it's probably not a good idea to turn it on by default. > Anyways, this all came up because several modules that used psyco.full() > would greatly be hindered if they imported another module that did the > same. So I got the great idea, why not put it in sitecustomize.py? I think the current thinking is that individual modules are responsible for calling psyco on themselves --- that is, the authors of a module would know best what functions would benefit most from Psyco's JIT compilation. Calling Psyco on everything is probably not a good idea, just because it does use a lot of memory, and because there is a time cost involved in doing the JIT stuff itself. If some code is going to be run just once anyway, there's really not much gain in JIT-ing it first, since all that analysis is probably going to cost more than running the code once. Psyco can work wonders on things like inner loops, but it's not so effective on top-level code. > Then I got the idea, why not put from __import__ division in the > sitecustomize.py, too? psyco.full() worked, from __import__ division > did not. The statement: ### from __future__ import division ### is module specific; it won't automatically affect division throughout the system, but limits itself to the particular module where it's been declared. So in your example, new-style division actually is being turned on only for sitecustomize.py. This is briefly mentioned in: http://www.python.org/peps/pep-0238.html with: """ - The future division statement, spelled "from __future__ import division", will change the / operator to mean true division throughout the module. """ If we want to make new-style division work throughout the system, we can call Python with the '-Q new' command line argument. Best of wishes to you! From kent37 at tds.net Thu Feb 24 20:23:28 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Feb 24 20:23:33 2005 Subject: [Tutor] Print text position problems when using triple quotes In-Reply-To: <797fe3d4050224101523be309f@mail.gmail.com> References: <ea0feb800502241002491ecad9@mail.gmail.com> <797fe3d4050224101463310066@mail.gmail.com> <797fe3d4050224101523be309f@mail.gmail.com> Message-ID: <421E29B0.7010404@tds.net> Bill Mill wrote: >>class foo: >> def bar(self): > > > Sorry, I forgot that if it's in the module, you should declare prompt1 > as global by using "global prompt1" right here. > > >> print prompt1 % (var1, var2, var3) No, you only need the global statement if you want to assign to a global variable. Read-only reference will work without the global. Kent From dyoo at hkn.eecs.berkeley.edu Thu Feb 24 20:34:34 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Feb 24 20:34:38 2005 Subject: [Tutor] Print text position problems when using triple quotes In-Reply-To: <ea0feb80050224105748880bfc@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0502241123590.14680-100000@hkn.eecs.berkeley.edu> > > > > I'm writing a simple game (run in command line) in which narrative > > > > text is printed in response to a user's decisions. The problem I'm > > > > running into is that triple quotes used in an indented block > > > > preserves the indentation when it prints. [text cut] > > > Why not just take them out of the block, and either make them global > > > to the module or create a string module? [text cut] > Excellent. Side note: one other nice thing about Bill's solution is that it becomes easier to just pass that 'string module' off to someone else for maintenence. Your game can be easily translated to other languages! (GNU gettext, for example, is a system for internationalizing programs, and it keeps a program's messages in language-specific message files.) This approach is also the heart of things like "template" languages. From s.varun at gmail.com Thu Feb 24 20:45:29 2005 From: s.varun at gmail.com (Varun Soundararajan) Date: Thu Feb 24 20:45:39 2005 Subject: [Tutor] Python Online Programming Contest Message-ID: <32b5ee76050224114510c9cd5e@mail.gmail.com> Hi Friends, Department of Information Technology, Madras Institute of Technology, Anna University is conducting a technical symposium, Samhita. As a part of samhita, an Online Programming Contest is scheduled on Sunday, 27 Feb 2005. This is the first Online Programming Contest in India to support Python !!!!. Other languages supported are C and C++. For Registration and Rules of the contest, http://www.samhita.info/opc For details about samhita http://www.samhita.info/ Regards, -Online Programming Contest team From bill.mill at gmail.com Thu Feb 24 20:51:35 2005 From: bill.mill at gmail.com (Bill Mill) Date: Thu Feb 24 20:51:39 2005 Subject: [Tutor] Print text position problems when using triple quotes In-Reply-To: <421E29B0.7010404@tds.net> References: <ea0feb800502241002491ecad9@mail.gmail.com> <797fe3d4050224101463310066@mail.gmail.com> <797fe3d4050224101523be309f@mail.gmail.com> <421E29B0.7010404@tds.net> Message-ID: <797fe3d40502241151290e6aa6@mail.gmail.com> On Thu, 24 Feb 2005 14:23:28 -0500, Kent Johnson <kent37@tds.net> wrote: > Bill Mill wrote: > >>class foo: > >> def bar(self): > > > > > > Sorry, I forgot that if it's in the module, you should declare prompt1 > > as global by using "global prompt1" right here. > > > > > >> print prompt1 % (var1, var2, var3) > > No, you only need the global statement if you want to assign to a global variable. Read-only > reference will work without the global. This is correct. I do it for myself, just to be as explicit as possible about it, since it's something I don't like to do. Putting the strings into another module is really a much better solution. Thanks for the correction. Peace Bill Mill bill.mill at gmail.com From klappnase at freenet.de Thu Feb 24 21:10:21 2005 From: klappnase at freenet.de (Michael Lange) Date: Thu Feb 24 21:07:29 2005 Subject: [Tutor] Unicode issues In-Reply-To: <421DCDB8.8050308@tds.net> References: <20050222202659.3e0c9675.klappnase@freenet.de> <421C7554.4080309@tds.net> <20050223212906.4e7ca77f.klappnase@freenet.de> <421D5514.2050200@tds.net> <20050224112713.27bcd5f3.klappnase@freenet.de> <421DCDB8.8050308@tds.net> Message-ID: <20050224211021.1a1b6f17.klappnase@freenet.de> On Thu, 24 Feb 2005 07:51:04 -0500 Kent Johnson <kent37@tds.net> wrote: > Michael Lange wrote: > > I *thought* I would have to convert the user input which might be any encoding back into > > byte string first > > How are you getting the user input? Is it from the console or from a GUI? > It's a (Tkinter) gui, but anyway, I think I now understand why this idea is total nonsense. > If your intent is to create a unicode string, try this: > if not isinstance(result, unicode): > result = result.decode(sys.stdin.encoding) > Ok, user input must be checked whether it's unicode or not and if necessary be decoded to unicode with system encoding. For internal operations I should then use only unicode strings and if I need to print something to stdout I must encode it again with system encoding, right? > This article gives a lot of good background: > http://www.joelonsoftware.com/articles/Unicode.html > > I have written an essay about console encoding issues. At the end there is a collection of links to > more general Python and Unicode articles. > http://www.pycs.net/users/0000323/stories/14.html > > Kent > That's great! Exactly the kind of articles I've been looking for but couldn't find. Thanks!!! Michael From kent37 at tds.net Thu Feb 24 21:22:38 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Feb 24 21:22:35 2005 Subject: [Tutor] Unicode issues In-Reply-To: <20050224211021.1a1b6f17.klappnase@freenet.de> References: <20050222202659.3e0c9675.klappnase@freenet.de> <421C7554.4080309@tds.net> <20050223212906.4e7ca77f.klappnase@freenet.de> <421D5514.2050200@tds.net> <20050224112713.27bcd5f3.klappnase@freenet.de> <421DCDB8.8050308@tds.net> <20050224211021.1a1b6f17.klappnase@freenet.de> Message-ID: <421E378E.9060204@tds.net> Michael Lange wrote: > Ok, user input must be checked whether it's unicode or not and if necessary be decoded to > unicode with system encoding. For internal operations I should then use only unicode strings > and if I need to print something to stdout I must encode it again with system encoding, right? I think that is the best plan. Kent From misha.dunn at gmail.com Thu Feb 24 21:48:17 2005 From: misha.dunn at gmail.com (Michael Dunn) Date: Thu Feb 24 21:48:23 2005 Subject: [Tutor] Print text position problems when using triple quotes In-Reply-To: <ea0feb800502241002491ecad9@mail.gmail.com> References: <ea0feb800502241002491ecad9@mail.gmail.com> Message-ID: <e95c92e005022412483236abee@mail.gmail.com> Hi Luke, > Is there a way to preserve the readability of the code and have > printed text from indented blocks, say, nested conditionals, appear > flush at left, not printed exactly where I've written them in the > script? you can use the textwrap module for this. >>> from textwrap import dedent >>> print dedent("""\ ... some ... indented ... text""") some indented text >>> "dedent" is a utility function of the textwrap module that trims every line by an equal amount. The trick here is the backslash so that the first line doesn't count. The "fill" and "wrap" functions of textwrap might also interest you: http://www.python.org/doc/2.3.5/lib/module-textwrap.html. Cheers, Michael From kabads at gmail.com Thu Feb 24 23:19:42 2005 From: kabads at gmail.com (Adam Cripps) Date: Thu Feb 24 23:19:45 2005 Subject: [Tutor] Recursive Tkinter buttons Message-ID: <c7ff3855050224141925d5dc88@mail.gmail.com> I'm trying to create recursive Tkinter buttons with: for i in range(0,10): print i buttonlabel = "field " +str(i) button[i] = Button (text=buttonlabel) button[i].grid(column=3, row = i+3) However, Tkinter doesn't seem to like it with Traceback (most recent call last): File "report.py", line 83, in ? app = Application(root) File "report.py", line 28, in __init__ self.createWidgets() File "report.py", line 79, in createWidgets button[i] = Button (text=buttonlabel) File "C:\PYTHON24\lib\lib-tk\Tkinter.py", line 1146, in __setitem__ self.configure({key: value}) File "C:\PYTHON24\lib\lib-tk\Tkinter.py", line 1139, in configure return self._configure('configure', cnf, kw) File "C:\PYTHON24\lib\lib-tk\Tkinter.py", line 1130, in _configure self.tk.call(_flatten((self._w, cmd)) + self._options(cnf)) File "C:\PYTHON24\lib\lib-tk\Tkinter.py", line 997, in _options if k[-1] == '_': k = k[:-1] TypeError: unsubscriptable object What is a good method for producing recursive Tk widgets? TIA. Adam -- http://www.monkeez.org PGP key: 0x7111B833 From misha.dunn at gmail.com Thu Feb 24 23:43:20 2005 From: misha.dunn at gmail.com (Michael Dunn) Date: Thu Feb 24 23:43:23 2005 Subject: [Tutor] Reading Tutor with gmail: monospace fonts Message-ID: <e95c92e005022414435eeabf1b@mail.gmail.com> Hi all, This is slightly off topic, but I've noticed a lot of people are using gmail accounts to post to tutor and I just wanted to share a useful trick I just learned for making gmail display and edit mail with a monospace rather than proportional font. I'm sure anyone who's tried it agrees that significant whitespace means that python and proportional fonts don't play well together... Basically, you need to get your browser to override the stylesheet of the page with the following snippet of css: div.msg div.mb, .cm, .tb { font-family: monospace !important; font-size: 12px !important; } In Firefox, you add it to the userContent.css file in your preferences (you'll probably have to create this, see http://www.mozilla.org/support/firefox/edit). With Safari on MacOSX you make a css file anywhere you like (I used ~/Library/Safari/MyPrefs.css), add this snippet, and then select the file from the "Advanced" tab in Safari's Preferences. I don't know about other browsers, but the same sort of thing is almost certainly possible. Cheers, Michael From dyoo at hkn.eecs.berkeley.edu Thu Feb 24 23:50:11 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Feb 24 23:50:14 2005 Subject: [Tutor] Recursive Tkinter buttons In-Reply-To: <c7ff3855050224141925d5dc88@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0502241438380.5338-100000@hkn.eecs.berkeley.edu> On Thu, 24 Feb 2005, Adam Cripps wrote: > I'm trying to create recursive Tkinter buttons with: > > for i in range(0,10): > print i > buttonlabel = "field " +str(i) > button[i] = Button (text=buttonlabel) > button[i].grid(column=3, row = i+3) Hi Adam, I'm not quite sure I understand what you mean by "recursive" buttons. I'll assume, for the moment, that you mean composing widgets within widgets. I think that only widgets that are designated as "containers" can contain other widgets. A Frame is an example of a widget that can contain other widgets: ### >>> from Tkinter import * >>> root = Tk() >>> frame = Frame(root) >>> for i in range(5): ... b = Button(frame, text="button " + str(i)) ... b.pack() ... >>> frame.pack() ### There's an object hierarchy here that we construct: root <----- frame <------ button 0 button 1 button 2 button 3 button 4 As far as I can tell, only Frames and Toplevels can contain other widgets in Tkinter. Extensions to Tkinter (like Python MegaWidgets) may have extended the system with more container types. Best of wishes to you! From jfouhy at paradise.net.nz Fri Feb 25 00:07:42 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Fri Feb 25 00:07:48 2005 Subject: [Tutor] Recursive Tkinter buttons In-Reply-To: <Pine.LNX.4.44.0502241438380.5338-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0502241438380.5338-100000@hkn.eecs.berkeley.edu> Message-ID: <1109286462.421e5e3eb4e5d@www.paradise.net.nz> Quoting Danny Yoo <dyoo@hkn.eecs.berkeley.edu>: > I think that only widgets that are designated as "containers" can > contain other widgets. A Frame is an example of a widget that can contain > other widgets: This is (I think) true; but the root can also contain widgets, and it is the default if no other master is specified. For example: >>> from Tkinter import * >>> def foo(): ... print 'foo' ... >>> Button(text='foo', command=foo).pack() This will produce a window with a button which, when clicked, will print 'foo' to stdout. To be honest, I'm a bit stumped by Adam's problem. Here is some code I just wrote which works perfectly (it produces a window with a column of buttons labeled 'field 0' through 'field 9'; each button (when clicked) prints out its number): >>> from Tkinter import * >>> def p(x): ... print x ... >>> for i in xrange(10): ... buttonName = 'field ' + str(i) ... b = Button(text=buttonName, command=lambda i=i: p(i)) ... b.grid(row=i) ... >>> -- John. From johnp at milwaukielumber.com Fri Feb 25 00:15:47 2005 From: johnp at milwaukielumber.com (John Purser) Date: Fri Feb 25 00:15:53 2005 Subject: [Tutor] Reading Tutor with gmail: monospace fonts In-Reply-To: <e95c92e005022414435eeabf1b@mail.gmail.com> Message-ID: <200502242315.j1ONFmxA007292@mail.morseintranet.com> Thanks for the tip. John Purser -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of Michael Dunn Sent: Thursday, February 24, 2005 14:43 To: tutor@python.org Subject: [Tutor] Reading Tutor with gmail: monospace fonts Hi all, This is slightly off topic, but I've noticed a lot of people are using gmail accounts to post to tutor and I just wanted to share a useful trick I just learned for making gmail display and edit mail with a monospace rather than proportional font. I'm sure anyone who's tried it agrees that significant whitespace means that python and proportional fonts don't play well together... Basically, you need to get your browser to override the stylesheet of the page with the following snippet of css: div.msg div.mb, .cm, .tb { font-family: monospace !important; font-size: 12px !important; } In Firefox, you add it to the userContent.css file in your preferences (you'll probably have to create this, see http://www.mozilla.org/support/firefox/edit). With Safari on MacOSX you make a css file anywhere you like (I used ~/Library/Safari/MyPrefs.css), add this snippet, and then select the file from the "Advanced" tab in Safari's Preferences. I don't know about other browsers, but the same sort of thing is almost certainly possible. Cheers, Michael _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Fri Feb 25 03:26:29 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Feb 25 03:26:34 2005 Subject: [Tutor] Recursive Tkinter buttons In-Reply-To: <c7ff3855050224141925d5dc88@mail.gmail.com> References: <c7ff3855050224141925d5dc88@mail.gmail.com> Message-ID: <421E8CD5.3080708@tds.net> Adam Cripps wrote: > I'm trying to create recursive Tkinter buttons with: > > for i in range(0,10): > print i > buttonlabel = "field " +str(i) > button[i] = Button (text=buttonlabel) > button[i].grid(column=3, row = i+3) > > However, Tkinter doesn't seem to like it with Please show us the whole program. This works for me: from Tkinter import * root = Tk() button = {} for i in range(0,10): print i buttonlabel = "field " +str(i) button[i] = Button (text=buttonlabel) button[i].grid(column=3, row = i+3) root.mainloop() Kent > > Traceback (most recent call last): > File "report.py", line 83, in ? > app = Application(root) > File "report.py", line 28, in __init__ > self.createWidgets() > File "report.py", line 79, in createWidgets > button[i] = Button (text=buttonlabel) > File "C:\PYTHON24\lib\lib-tk\Tkinter.py", line 1146, in __setitem__ > self.configure({key: value}) > File "C:\PYTHON24\lib\lib-tk\Tkinter.py", line 1139, in configure > return self._configure('configure', cnf, kw) > File "C:\PYTHON24\lib\lib-tk\Tkinter.py", line 1130, in _configure > self.tk.call(_flatten((self._w, cmd)) + self._options(cnf)) > File "C:\PYTHON24\lib\lib-tk\Tkinter.py", line 997, in _options > if k[-1] == '_': k = k[:-1] > TypeError: unsubscriptable object > > What is a good method for producing recursive Tk widgets? > > TIA. > Adam From ismaelgf at adinet.com.uy Fri Feb 25 07:08:43 2005 From: ismaelgf at adinet.com.uy (Ismael Garrido) Date: Fri Feb 25 07:08:19 2005 Subject: [Tutor] SubClassing Message-ID: <421EC0EB.9070301@adinet.com.uy> Hello My code is like this: class Parent: def __init__(self, bunch, of, variables): self.bunch, self.of, self.variables = bunch, of, variables class Son(Parent): def __init__(self, bunch, of, variables, new): self.bunch, self.of, self.variables, self.new = bunch, of, variables, new What I want to know is, is there a better way to write Son class? One in which I don't have to copy&paste the parent's init? Thanks Ismael From shaleh at speakeasy.net Fri Feb 25 07:45:40 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Fri Feb 25 07:46:47 2005 Subject: [Tutor] SubClassing In-Reply-To: <421EC0EB.9070301@adinet.com.uy> References: <421EC0EB.9070301@adinet.com.uy> Message-ID: <421EC994.6000407@speakeasy.net> Ismael Garrido wrote: > Hello > > My code is like this: > > class Parent: > def __init__(self, bunch, of, variables): > self.bunch, self.of, self.variables = bunch, of, variables > > class Son(Parent): > def __init__(self, bunch, of, variables, new): > self.bunch, self.of, self.variables, self.new = bunch, of, > variables, new > > What I want to know is, is there a better way to write Son class? One in > which I don't have to copy&paste the parent's init? > yep. call 'Parent.__init__(this, that)' then do 'self.new = new' def __init__(self, this, that, new): Parent.__init__(this, that) self.new = new From kabads at gmail.com Fri Feb 25 07:53:56 2005 From: kabads at gmail.com (Adam Cripps) Date: Fri Feb 25 07:53:59 2005 Subject: [Tutor] Recursive Tkinter buttons In-Reply-To: <421E8CD5.3080708@tds.net> References: <c7ff3855050224141925d5dc88@mail.gmail.com> <421E8CD5.3080708@tds.net> Message-ID: <c7ff3855050224225377dd598b@mail.gmail.com> On Thu, 24 Feb 2005 21:26:29 -0500, Kent Johnson <kent37@tds.net> wrote: > Adam Cripps wrote: > > I'm trying to create recursive Tkinter buttons with: > > > > for i in range(0,10): > > print i > > buttonlabel = "field " +str(i) > > button[i] = Button (text=buttonlabel) > > button[i].grid(column=3, row = i+3) > > > > However, Tkinter doesn't seem to like it with > > Please show us the whole program. This works for me: > > from Tkinter import * > > root = Tk() > button = {} > for i in range(0,10): > print i > buttonlabel = "field " +str(i) > button[i] = Button (text=buttonlabel) > button[i].grid(column=3, row = i+3) > > root.mainloop() > > Kent Sorry guys for not be clear - recursive isn't the correct term - that's what you get when you fire off an email late at night. I want to create 10 buttons through a loop, each with different text and passing a different var to another function. My current code is: (the bit I'm currently working on is near the bottom) #!/usr/bin/env python from Tkinter import * from tkFont import * from string import * from sys import* from re import * class Application(Frame): def __init__(self, master=None, geometry="500x200"): """Starts the application off""" Frame.__init__(self,master) self.grid() self.addMenu() self.createWidgets() def quit(self): self.master.quit() def save(self): print "saving..." def open(self): print "opening..." def about(self): print "about" def addMenu(self): menu = Menu(root) root.config(menu=menu) filemenu = Menu(menu, tearoff=0) menu.add_cascade(label="File", menu=filemenu) filemenu.add_command(label="Open", command=self.open) filemenu.add_command(label="Save...", command=self.save) filemenu.add_separator() filemenu.add_command(label="Exit", command=self.quit) helpmenu = Menu(menu, tearoff=0) menu.add_cascade(label="Help", menu=helpmenu) helpmenu.add_command(label="About...", command=self.about) def createWidgets(self): """This creates all the widgets in the main frame""" titleLabel = Label(text="Squawk report generator") titleLabel.grid(column = 0, row=0) firstNameLabel = Label(text="First name: ") firstNameLabel.grid(column = 0, row = 3, sticky = NW) self.firstname = StringVar() firstNameEntry = Entry(textvariable = self.firstname) firstNameEntry.grid(column =1, row=3, sticky = NW) surNameLabel = Label(text="Surname: ") surNameLabel.grid(column = 0, row = 4, sticky = NW) self.surname= StringVar() surNameEntry = Entry(textvariable=self.surname) surNameEntry.grid(column = 1, row=4, stick=NW) button = Button(text ="hello") #Now we will loop around showing the entry fields button = [] for i in range(0,10): print i buttonlabel = "field " +str(i) button[i].append = Button (text=buttonlabel) button[i].grid(column=3, row = i+3) root = Tk() app = Application(root) app.master.title("Squawk Report Generator") app.mainloop() The current error is: File "report.py", line 80, in createWidgets button[i].append = Button (text=buttonlabel) IndexError: list index out of range TIA Adam -- http://www.monkeez.org PGP key: 0x7111B833 From cyresse at gmail.com Fri Feb 25 08:19:15 2005 From: cyresse at gmail.com (Liam Clarke) Date: Fri Feb 25 08:19:18 2005 Subject: [Tutor] Recursive Tkinter buttons In-Reply-To: <c7ff3855050224225377dd598b@mail.gmail.com> References: <c7ff3855050224141925d5dc88@mail.gmail.com> <421E8CD5.3080708@tds.net> <c7ff3855050224225377dd598b@mail.gmail.com> Message-ID: <f2ff2d05022423194d795e69@mail.gmail.com> > > for i in range(0,10): > print i > buttonlabel = "field " +str(i) > button[i].append = Button (text=buttonlabel) > button[i].grid(column=3, row = i+3) > > The current error is: > > File "report.py", line 80, in createWidgets > button[i].append = Button (text=buttonlabel) > IndexError: list index out of range > button = [] for i in range(0,10): print i print button[i] Will cause the exact same error as button[i].append. Why? button=[], it has no index. Perhaps you just mean button[i] = Button (text=buttonlabel)? Regards, Liam Clarke On Fri, 25 Feb 2005 06:53:56 +0000, Adam Cripps <kabads@gmail.com> wrote: > On Thu, 24 Feb 2005 21:26:29 -0500, Kent Johnson <kent37@tds.net> wrote: > > Adam Cripps wrote: > > > I'm trying to create recursive Tkinter buttons with: > > > > > > for i in range(0,10): > > > print i > > > buttonlabel = "field " +str(i) > > > button[i] = Button (text=buttonlabel) > > > button[i].grid(column=3, row = i+3) > > > > > > However, Tkinter doesn't seem to like it with > > > > Please show us the whole program. This works for me: > > > > from Tkinter import * > > > > root = Tk() > > button = {} > > for i in range(0,10): > > print i > > buttonlabel = "field " +str(i) > > button[i] = Button (text=buttonlabel) > > button[i].grid(column=3, row = i+3) > > > > root.mainloop() > > > > Kent > > Sorry guys for not be clear - recursive isn't the correct term - > that's what you get when you fire off an email late at night. > > I want to create 10 buttons through a loop, each with different text > and passing a different var to another function. My current code is: > (the bit I'm currently working on is near the bottom) > > #!/usr/bin/env python > from Tkinter import * > from tkFont import * > from string import * > from sys import* > from re import * > > class Application(Frame): > def __init__(self, master=None, geometry="500x200"): > """Starts the application off""" > Frame.__init__(self,master) > self.grid() > self.addMenu() > self.createWidgets() > > def quit(self): > self.master.quit() > > def save(self): > print "saving..." > > def open(self): > print "opening..." > > def about(self): > print "about" > > def addMenu(self): > menu = Menu(root) > root.config(menu=menu) > > filemenu = Menu(menu, tearoff=0) > menu.add_cascade(label="File", menu=filemenu) > filemenu.add_command(label="Open", command=self.open) > filemenu.add_command(label="Save...", command=self.save) > filemenu.add_separator() > filemenu.add_command(label="Exit", command=self.quit) > > helpmenu = Menu(menu, tearoff=0) > menu.add_cascade(label="Help", menu=helpmenu) > helpmenu.add_command(label="About...", command=self.about) > > def createWidgets(self): > """This creates all the widgets in the main frame""" > titleLabel = Label(text="Squawk report generator") > titleLabel.grid(column = 0, row=0) > firstNameLabel = Label(text="First name: ") > firstNameLabel.grid(column = 0, row = 3, sticky = NW) > self.firstname = StringVar() > firstNameEntry = Entry(textvariable = self.firstname) > firstNameEntry.grid(column =1, row=3, sticky = NW) > surNameLabel = Label(text="Surname: ") > surNameLabel.grid(column = 0, row = 4, sticky = NW) > self.surname= StringVar() > surNameEntry = Entry(textvariable=self.surname) > surNameEntry.grid(column = 1, row=4, stick=NW) > button = Button(text ="hello") > > #Now we will loop around showing the entry fields > TIA > Adam > -- > http://www.monkeez.org > PGP key: 0x7111B833 > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From ismaelgf at adinet.com.uy Fri Feb 25 08:53:54 2005 From: ismaelgf at adinet.com.uy (Ismael Garrido) Date: Fri Feb 25 08:53:36 2005 Subject: [Fwd: Re: [Tutor] Recursive Tkinter buttons] Message-ID: <421ED992.4080804@adinet.com.uy> Sent only to Liam... Forwading.. -------- Original Message -------- Subject: Re: [Tutor] Recursive Tkinter buttons Date: Fri, 25 Feb 2005 05:45:00 -0200 From: Ismael Garrido <ismaelgf@adinet.com.uy> To: Liam Clarke <cyresse@gmail.com> References: <c7ff3855050224141925d5dc88@mail.gmail.com> <421E8CD5.3080708@tds.net> <c7ff3855050224225377dd598b@mail.gmail.com> <f2ff2d05022423194d795e69@mail.gmail.com> Liam Clarke wrote: >> >> for i in range(0,10): >> print i >> buttonlabel = "field " +str(i) >> button[i].append = Button (text=buttonlabel) >> button[i].grid(column=3, row = i+3) >> >>The current error is: >> >> File "report.py", line 80, in createWidgets >> button[i].append = Button (text=buttonlabel) >>IndexError: list index out of range >> >> >> > button = [] >for i in range(0,10): > print i > print button[i] > > >Will cause the exact same error as button[i].append. Why? button=[], >it has no index. >Perhaps you just mean button[i] = Button (text=buttonlabel)? > > Nope, that will give an Array Out of Bounds exception. Remember buttons = [] What he meant is: button.append( Button(text=buttonlabel) ) (I tested it, too!) Bye Ismael From ismaelgf at adinet.com.uy Fri Feb 25 08:54:39 2005 From: ismaelgf at adinet.com.uy (Ismael Garrido) Date: Fri Feb 25 08:54:12 2005 Subject: [Tutor] SubClassing In-Reply-To: <421EC994.6000407@speakeasy.net> References: <421EC0EB.9070301@adinet.com.uy> <421EC994.6000407@speakeasy.net> Message-ID: <421ED9BF.9010005@adinet.com.uy> Sean Perry wrote: > yep. call 'Parent.__init__(this, that)' then do 'self.new = new' > > def __init__(self, this, that, new): > Parent.__init__(this, that) > self.new = new Thanks. Though it should be: def __init__(self, this, that, new): Parent.__init__(self, this, that) #note self self.new = new Thanks again! Ismael From shaleh at speakeasy.net Fri Feb 25 09:01:07 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Fri Feb 25 09:02:12 2005 Subject: [Tutor] SubClassing In-Reply-To: <421ED9BF.9010005@adinet.com.uy> References: <421EC0EB.9070301@adinet.com.uy> <421EC994.6000407@speakeasy.net> <421ED9BF.9010005@adinet.com.uy> Message-ID: <421EDB43.6020909@speakeasy.net> Ismael Garrido wrote: > Sean Perry wrote: > >> yep. call 'Parent.__init__(this, that)' then do 'self.new = new' >> >> def __init__(self, this, that, new): >> Parent.__init__(this, that) >> self.new = new > > > Thanks. > > Though it should be: > def __init__(self, this, that, new): > Parent.__init__(self, this, that) #note self > self.new = new > been doing a bunch of C++ programming. C++ -> python I always forget about self. python -> c++ I always forget the semicolons (-: From cyresse at gmail.com Fri Feb 25 09:45:05 2005 From: cyresse at gmail.com (Liam Clarke) Date: Fri Feb 25 09:45:10 2005 Subject: [Fwd: Re: [Tutor] Recursive Tkinter buttons] In-Reply-To: <421ED992.4080804@adinet.com.uy> References: <421ED992.4080804@adinet.com.uy> Message-ID: <f2ff2d0502250045429e0173@mail.gmail.com> *click* Oh yeah. What you said. Oops. :\ Liam On Fri, 25 Feb 2005 05:53:54 -0200, Ismael Garrido <ismaelgf@adinet.com.uy> wrote: > Sent only to Liam... Forwading.. > > -------- Original Message -------- > Subject: Re: [Tutor] Recursive Tkinter buttons > Date: Fri, 25 Feb 2005 05:45:00 -0200 > From: Ismael Garrido <ismaelgf@adinet.com.uy> > To: Liam Clarke <cyresse@gmail.com> > References: <c7ff3855050224141925d5dc88@mail.gmail.com> > <421E8CD5.3080708@tds.net> <c7ff3855050224225377dd598b@mail.gmail.com> > <f2ff2d05022423194d795e69@mail.gmail.com> > > Liam Clarke wrote: > > >> > >> for i in range(0,10): > >> print i > >> buttonlabel = "field " +str(i) > >> button[i].append = Button (text=buttonlabel) > >> button[i].grid(column=3, row = i+3) > >> > >>The current error is: > >> > >> File "report.py", line 80, in createWidgets > >> button[i].append = Button (text=buttonlabel) > >>IndexError: list index out of range > >> > >> > >> > > button = [] > >for i in range(0,10): > > print i > > print button[i] > > > > > >Will cause the exact same error as button[i].append. Why? button=[], > >it has no index. > >Perhaps you just mean button[i] = Button (text=buttonlabel)? > > > > > Nope, that will give an Array Out of Bounds exception. Remember buttons = [] > > What he meant is: > > button.append( Button(text=buttonlabel) ) > > (I tested it, too!) > > Bye > Ismael > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cyresse at gmail.com Fri Feb 25 10:24:56 2005 From: cyresse at gmail.com (Liam Clarke) Date: Fri Feb 25 10:25:00 2005 Subject: [Tutor] OT SQL (but through Python...) Message-ID: <f2ff2d05022501241fa0b007@mail.gmail.com> Hi, Hope I don't annoy anyone by asking this here, if I do, let me know. When you're doing a SQL select statement, what would be better? Say you're searching by name, should I do - j = cx.execute j('select * from foo where first == %s and last == %s') % (a,b) q = cx.fetchall() if not q: j('select * from foo where first like %s%% and last like %s%%') % (a,b) or just use j('select * from foo where first like %s%% and last like %s%%') % (a,b) straight off the bat? The first method gives me direct match, and searches for alternatives if none are found, the second may not give me a direct match if there is one. i.e first last Tim Johns Timothy Johnston the 1st method will find the 1st row for a='Tim' b = 'Johns's, but the 2nd method will find both. I'm asking more from a user perspective really, would the quicker action of the first outweigh the inconstant UI resulting from a search? I ask because a database I use heavily at work obviously uses 'like %s%', which is great for the lazy typers such as myself, but sometime I wish it would go directly to the only legitimate match, when it has x number of precisely matching fields. S'pose it's one of those better/best practises things. I remember reading somewhere regarding Linux this pithy saying - 'The problem (with KDE/Gnome etc. ) is that programmers can't design UI.' After my experiences with KDE, I would tend to agree. Regards, Liam Clarke 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From kent37 at tds.net Fri Feb 25 11:50:44 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Feb 25 11:50:49 2005 Subject: [Tutor] Recursive Tkinter buttons In-Reply-To: <c7ff3855050224225377dd598b@mail.gmail.com> References: <c7ff3855050224141925d5dc88@mail.gmail.com> <421E8CD5.3080708@tds.net> <c7ff3855050224225377dd598b@mail.gmail.com> Message-ID: <421F0304.900@tds.net> Adam Cripps wrote: > button = [] > for i in range(0,10): > print i > buttonlabel = "field " +str(i) > button[i].append = Button (text=buttonlabel) > button[i].grid(column=3, row = i+3) You are misusing the button list. You can't use an index until you have added the item to the list. The above two lines should be written something like this: aButton = Button (text=buttonlabel) aButton.grid(column=3, row = i+3) button.append(aButton) By the way you are reusing the name button (you use the name for the 'hello' button) and if you are not going to use the button list you don't need to create it (just omit 'button.append(aButton)') Kent From kent37 at tds.net Fri Feb 25 12:15:05 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Feb 25 12:15:09 2005 Subject: [Tutor] OT SQL (but through Python...) In-Reply-To: <f2ff2d05022501241fa0b007@mail.gmail.com> References: <f2ff2d05022501241fa0b007@mail.gmail.com> Message-ID: <421F08B9.5090608@tds.net> Liam Clarke wrote: > Hi, > > Hope I don't annoy anyone by asking this here, if I do, let me know. > > When you're doing a SQL select statement, what would be better? Say > you're searching by name, should I do - > j = cx.execute > j('select * from foo where first == %s and last == %s') % (a,b) > q = cx.fetchall() > if not q: > j('select * from foo where first like %s%% and last like %s%%') % (a,b) > > or just use > > j('select * from foo where first like %s%% and last like %s%%') % (a,b) > > straight off the bat? First, a code correction. You should never substitute user values into your SQL. Use the database driver's capabilities instead. That will ensure that special characters are escaped correctly. The syntax to do this varies for each database - the 'paramstyle' attribute of the database driver will tell you which style to use; the docs should also mention it. IIRC you are using SQLite, which says, >>> import sqlite >>> sqlite.paramstyle 'pyformat' The docs have this example: >>> cu.execute("insert into test(u1, u2) values (%s, %s)", (u"\x99sterreich", u"Ungarn")) so I think your code should be j('select * from foo where first == %s and last == %s', (a,b)) (note the final '%' is now a comma and (a, b) is a parameter passed to j.) Why should you care? Imagine a user searches for "Tim" "John'son". Then your SQL becomes select * from foo where first == Tim and last == John'son which will probably give you a syntax errer. Worse, this opens you up to malicious attacks. What if I search for "Tim" "Johnson; delete table foo"? Now your SQL is select * from foo where first == Tim and last == Johnson; delete table foo ...oops Finally, some databases will optimize repeated queries. If you substitute the string yourself you don't get this benefit because the query string is different each time. Two more minor notes about the SQL - I use =, not == - actually I'm surprised == works. And if you are going to have string literals in your SQL put them in 'quotes'. > > The first method gives me direct match, and searches for alternatives > if none are found, > the second may not give me a direct match if there is one. > > i.e > > first last > > Tim Johns > Timothy Johnston > > the 1st method will find the 1st row for a='Tim' b = 'Johns's, but the > 2nd method will find both. > > I'm asking more from a user perspective really, would the quicker > action of the first outweigh the inconstant UI resulting from a > search? This isn't really a database question but a UI question. Who are the users? Can you ask them what they would prefer? If it is just for you, what do you prefer? Maybe you want an "Exact match" checkbox in your GUI? I wouldn't decide on the basis of speed, for any decent database you won't notice the difference. Kent From klappnase at freenet.de Fri Feb 25 12:21:18 2005 From: klappnase at freenet.de (Michael Lange) Date: Fri Feb 25 12:18:25 2005 Subject: [Tutor] Recursive Tkinter buttons In-Reply-To: <f2ff2d05022423194d795e69@mail.gmail.com> References: <c7ff3855050224141925d5dc88@mail.gmail.com> <421E8CD5.3080708@tds.net> <c7ff3855050224225377dd598b@mail.gmail.com> <f2ff2d05022423194d795e69@mail.gmail.com> Message-ID: <20050225122118.4fe893ad.klappnase@freenet.de> On Fri, 25 Feb 2005 20:19:15 +1300 Liam Clarke <cyresse@gmail.com> wrote: > > > > for i in range(0,10): > > print i > > buttonlabel = "field " +str(i) > > button[i].append = Button (text=buttonlabel) > > button[i].grid(column=3, row = i+3) > > > > The current error is: > > > > File "report.py", line 80, in createWidgets > > button[i].append = Button (text=buttonlabel) > > IndexError: list index out of range > > > button = [] > for i in range(0,10): > print i > print button[i] > > > Will cause the exact same error as button[i].append. Why? button=[], > it has no index. > Perhaps you just mean button[i] = Button (text=buttonlabel)? > > Regards, > > Or : buttonlist = [] for i in range(0, 10): print i buttonlabel = "field" + str(i) b = Button(text=buttonlabel) b.grid(column=3, row=i+3) buttonlist.append(b) Remember what you are doing when you call "button[i].append = Button(text=buttonlabel)": button is a list of Tkinter.Button objects, so button[i] is the "i-th" item in this list and that's exactly one more than the list actually contains, so you get an IndexError . However, if this IndexError wouldn't occur, it didn't help much, because you would probably get an AttributeError, saying something like "Tkinter.Button instance has no attribute 'append'". Even without this AttributeError nothing would be won, because the list's append() method returns None, so you would have: None = Button(text=buttonlabel) which is probably not what you intended. You see, in my example above I called the list "buttonlist" instead of "button"; maybe this naming helps avoid confusion . Best regards Michael From cyresse at gmail.com Fri Feb 25 12:38:00 2005 From: cyresse at gmail.com (Liam Clarke) Date: Fri Feb 25 12:38:04 2005 Subject: [Tutor] OT SQL (but through Python...) In-Reply-To: <421F08B9.5090608@tds.net> References: <f2ff2d05022501241fa0b007@mail.gmail.com> <421F08B9.5090608@tds.net> Message-ID: <f2ff2d050225033865970f85@mail.gmail.com> A light dawns, and I now understand how SQL code injection attacks can happen. Looks like I'm going to have to rethink & re-examine some docs.... Cheers, Liam On Fri, 25 Feb 2005 06:15:05 -0500, Kent Johnson <kent37@tds.net> wrote: > Liam Clarke wrote: > > Hi, > > > > Hope I don't annoy anyone by asking this here, if I do, let me know. > > > > When you're doing a SQL select statement, what would be better? Say > > you're searching by name, should I do - > > j = cx.execute > > j('select * from foo where first == %s and last == %s') % (a,b) > > q = cx.fetchall() > > if not q: > > j('select * from foo where first like %s%% and last like %s%%') % (a,b) > > > > or just use > > > > j('select * from foo where first like %s%% and last like %s%%') % (a,b) > > > > straight off the bat? > > First, a code correction. You should never substitute user values into your SQL. Use the database > driver's capabilities instead. That will ensure that special characters are escaped correctly. > > The syntax to do this varies for each database - the 'paramstyle' attribute of the database driver > will tell you which style to use; the docs should also mention it. > > IIRC you are using SQLite, which says, > >>> import sqlite > >>> sqlite.paramstyle > 'pyformat' > > The docs have this example: > >>> cu.execute("insert into test(u1, u2) values (%s, %s)", (u"\x99sterreich", u"Ungarn")) > > so I think your code should be > j('select * from foo where first == %s and last == %s', (a,b)) > > (note the final '%' is now a comma and (a, b) is a parameter passed to j.) > > Why should you care? Imagine a user searches for "Tim" "John'son". Then your SQL becomes > select * from foo where first == Tim and last == John'son > which will probably give you a syntax errer. > > Worse, this opens you up to malicious attacks. What if I search for "Tim" "Johnson; delete table > foo"? Now your SQL is > select * from foo where first == Tim and last == Johnson; delete table foo > > ...oops > > Finally, some databases will optimize repeated queries. If you substitute the string yourself you > don't get this benefit because the query string is different each time. > > Two more minor notes about the SQL - I use =, not == - actually I'm surprised == works. And if you > are going to have string literals in your SQL put them in 'quotes'. > > > > > The first method gives me direct match, and searches for alternatives > > if none are found, > > the second may not give me a direct match if there is one. > > > > i.e > > > > first last > > > > Tim Johns > > Timothy Johnston > > > > the 1st method will find the 1st row for a='Tim' b = 'Johns's, but the > > 2nd method will find both. > > > > I'm asking more from a user perspective really, would the quicker > > action of the first outweigh the inconstant UI resulting from a > > search? > > This isn't really a database question but a UI question. Who are the users? Can you ask them what > they would prefer? If it is just for you, what do you prefer? > > Maybe you want an "Exact match" checkbox in your GUI? > > I wouldn't decide on the basis of speed, for any decent database you won't notice the difference. > > Kent > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cyresse at gmail.com Fri Feb 25 15:24:48 2005 From: cyresse at gmail.com (Liam Clarke) Date: Fri Feb 25 15:24:52 2005 Subject: [Tutor] OT SQL (but through Python...) In-Reply-To: <f2ff2d050225033865970f85@mail.gmail.com> References: <f2ff2d05022501241fa0b007@mail.gmail.com> <421F08B9.5090608@tds.net> <f2ff2d050225033865970f85@mail.gmail.com> Message-ID: <f2ff2d05022506243196cee6@mail.gmail.com> Hi, Well thanks Kent, after a bit of puzzlement I feel like I'm getting it. Pysqlite takes care of correct quotation marks for me, but it's only good for parameters. so to generate 'select * from foo if A = "Bat"' I can hand cx.execute 'Bat', but I still have to insert A. So, my select statement generation now looks like this, bit rough at mo. def searchTable(self, table, fields): initReq = 'select * from %s where ' % table reqs=[] flatTuples=[] for (column, values) in fields.items(): if not values: #Don't search for None/NULLs continue reqs.append('%s = %%s' % column) values = self.checkForBad(values) flatTuples.append(values) request = initReq + " and ".join(reqs) table_data = self.execRequest(request, flatTuples) table_data.append(self.tableColumns[table]) return table_data So it'll pass a string stating 'select * from foo where A = %s and B = %s' to execute, along with the two parameters to insert. But, it runs each user entered value through this first: def checkForBad(stringA): if ';' in stringA: stringA.replace(';', '') return stringA to catch semi-colons, there will be no legitimate reason for them in this db. Are there any other special characters I should be checking for? Is there anyway to allow semi-colons without opening up the nasty vunerability, as I may need semicolons galore one day... This is execRequest, for completeness - def execRequest(self, request, params = None): cx = self.connection.cursor() if params: cx.execute(request, params) else: cx.execute(request) data = cx.fetchall() cx.close() return data Thanks ever so much for the pointers. Regards, Liam Clarke On Sat, 26 Feb 2005 00:38:00 +1300, Liam Clarke <cyresse@gmail.com> wrote: > A light dawns, and I now understand how SQL code injection attacks can happen. > > Looks like I'm going to have to rethink & re-examine some docs.... > > Cheers, > > Liam > > On Fri, 25 Feb 2005 06:15:05 -0500, Kent Johnson <kent37@tds.net> wrote: > > Liam Clarke wrote: > > > Hi, > > > > > > Hope I don't annoy anyone by asking this here, if I do, let me know. > > > > > > When you're doing a SQL select statement, what would be better? Say > > > you're searching by name, should I do - > > > j = cx.execute > > > j('select * from foo where first == %s and last == %s') % (a,b) > > > q = cx.fetchall() > > > if not q: > > > j('select * from foo where first like %s%% and last like %s%%') % (a,b) > > > > > > or just use > > > > > > j('select * from foo where first like %s%% and last like %s%%') % (a,b) > > > > > > straight off the bat? > > > > First, a code correction. You should never substitute user values into your SQL. Use the database > > driver's capabilities instead. That will ensure that special characters are escaped correctly. > > > > The syntax to do this varies for each database - the 'paramstyle' attribute of the database driver > > will tell you which style to use; the docs should also mention it. > > > > IIRC you are using SQLite, which says, > > >>> import sqlite > > >>> sqlite.paramstyle > > 'pyformat' > > > > The docs have this example: > > >>> cu.execute("insert into test(u1, u2) values (%s, %s)", (u"\x99sterreich", u"Ungarn")) > > > > so I think your code should be > > j('select * from foo where first == %s and last == %s', (a,b)) > > > > (note the final '%' is now a comma and (a, b) is a parameter passed to j.) > > > > Why should you care? Imagine a user searches for "Tim" "John'son". Then your SQL becomes > > select * from foo where first == Tim and last == John'son > > which will probably give you a syntax errer. > > > > Worse, this opens you up to malicious attacks. What if I search for "Tim" "Johnson; delete table > > foo"? Now your SQL is > > select * from foo where first == Tim and last == Johnson; delete table foo > > > > ...oops > > > > Finally, some databases will optimize repeated queries. If you substitute the string yourself you > > don't get this benefit because the query string is different each time. > > > > Two more minor notes about the SQL - I use =, not == - actually I'm surprised == works. And if you > > are going to have string literals in your SQL put them in 'quotes'. > > > > > > > > The first method gives me direct match, and searches for alternatives > > > if none are found, > > > the second may not give me a direct match if there is one. > > > > > > i.e > > > > > > first last > > > > > > Tim Johns > > > Timothy Johnston > > > > > > the 1st method will find the 1st row for a='Tim' b = 'Johns's, but the > > > 2nd method will find both. > > > > > > I'm asking more from a user perspective really, would the quicker > > > action of the first outweigh the inconstant UI resulting from a > > > search? > > > > This isn't really a database question but a UI question. Who are the users? Can you ask them what > > they would prefer? If it is just for you, what do you prefer? > > > > Maybe you want an "Exact match" checkbox in your GUI? > > > > I wouldn't decide on the basis of speed, for any decent database you won't notice the difference. > > > > Kent > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > -- > 'There is only one basic human right, and that is to do as you damn well please. > And with it comes the only basic human duty, to take the consequences. > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From kent37 at tds.net Fri Feb 25 15:47:59 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Feb 25 15:48:06 2005 Subject: [Tutor] OT SQL (but through Python...) In-Reply-To: <f2ff2d05022506243196cee6@mail.gmail.com> References: <f2ff2d05022501241fa0b007@mail.gmail.com> <421F08B9.5090608@tds.net> <f2ff2d050225033865970f85@mail.gmail.com> <f2ff2d05022506243196cee6@mail.gmail.com> Message-ID: <421F3A9F.7060104@tds.net> Liam Clarke wrote: > Hi, > > Well thanks Kent, after a bit of puzzlement I feel like I'm getting it. > Pysqlite takes care of correct quotation marks for me, but it's only > good for parameters. Right, you still hard-code the rest of the query. > > so to generate 'select * from foo if A = "Bat"' I can hand cx.execute > 'Bat', but I still have to > insert A. Yes, assuming you mean 'still have to insert A into the SQL' > So, my select statement generation now looks like this, bit rough at mo. > > def searchTable(self, table, fields): > initReq = 'select * from %s where ' % table > reqs=[] > flatTuples=[] > for (column, values) in fields.items(): > if not values: > #Don't search for None/NULLs > continue > reqs.append('%s = %%s' % column) > values = self.checkForBad(values) > flatTuples.append(values) > > request = initReq + " and ".join(reqs) > table_data = self.execRequest(request, flatTuples) > table_data.append(self.tableColumns[table]) > return table_data Looks good. > > So it'll pass a string stating 'select * from foo where A = %s and B = > %s' to execute, along with the two parameters to insert. But, it runs > each user entered value through this first: > > def checkForBad(stringA): > if ';' in stringA: > stringA.replace(';', '') > return stringA Should be stringA = stringA.replace(...) as strings are immutable. > > to catch semi-colons, there will be no legitimate reason for them in this db. > Are there any other special characters I should be checking for? Is > there anyway to allow semi-colons without opening up the nasty > vunerability, as I may need semicolons galore one day... I don't think you need checkForBad() at all. When you pass the parameters to the db, it becomes the db's responsibility to do any necessary quoting. Kent From shitizb at yahoo.com Fri Feb 25 17:17:42 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Fri Feb 25 17:17:46 2005 Subject: [Tutor] threads In-Reply-To: <421E1081.4070104@h-lab.net> Message-ID: <20050225161742.59141.qmail@web53805.mail.yahoo.com> Hi, Thanx everyone for all your suggestions.I used a separate thread for every car as I wanted my cars to run in real time, to coordinate effectively with other systems like traffic lights for eg. which I cant edit, hence which cant use the variable time defined by me. I figured out two ways to achieve this.... On Linux... ulimit -s 64, limits the stacksize of each thread to 64Kb, and i was able to generate 8000 threads.However upgrading my program to support more cars was a problem. Another way was to spawn 1000 threads, handling abt 10 cars each...this way the diff in real time and my program time was limited. I tried my hands at Stackless too... but still had problems implementing the concept. Can anyone guide me on how to spawn simultaneously( or pseudo simultaneously) running microthreads using stackless. Here is what i tried.. ef gencars(num,origin,dest,speed): global adjls global cars global juncls for i in range(num): cars.append(car(orig,dest,speed) task=tasklet(cars[i].run()) task.setup('Bind using Setup') Now this is what i copied from somewhere...i dont claim to understand fully what is happening.Here car.run() is a process which takes a long time to execute. What happens on execution is....One car is initialised and then the program waits for its run method to complete before proceeding. I also feel that there is no clear documentation on stackless. Show me the light. Shitiz --- Hugo González Monteverde <hugonz-lists@h-lab.net> wrote: > OK, as ignorant as I may be on threads, I have read > a bit on Stackless > Python's tasklets. Suppossedly they require much > less memory than > python's threads. > > Information is at www.stackless.com > > Hugo > > Shitiz Bansal wrote: > > Hi, > > > > I am trying to build a traffic network simulator > using > > python, for my degree project. > > > > I need to run at least 5-6000 cars > simultaneously.I > > wanted to run each car in a separate thread. > > However , after about 400 threads i am unable to > > create new threads. > > > > Here's the code: > > > >>>>cars=range(1000) > >>>>for i in cars: > > > > cars[i]=cars[i]=car(1,10,2,1,adjls,juncls) > > > > > > > >>>>for i in cars: > > > > i.start() > > > > Traceback (most recent call last): > > File "<pyshell#24>", line 2, in -toplevel- > > i.start() > > error: can't start new thread > > > > Is there a way out.Also, are there any tips on > > performance issues? > > > > Here is the class car: > > > > class car(threading.Thread): > > def > > __init__(self,carid,speed,dest,orig,adjls,juncls): > > threading.Thread.__init__(self) > > self.speed=speed > > self.finished=0 > > self.carid=carid > > self.dest=dest > > self.orig=orig > > self.adjls=adjls > > self.juncls=juncls > > > > > self.shortest=find_shortest_path(adjls,self.dest,self.orig) > > > self.calc=findpaths(adjls,self.dest,self.orig) > > > > > self.stats={'currtrsp':0,'avgspeed':0,'distcov':0,'totaltime':0} > > def traverse_track(self,p1,p2): > > counter=0 > > time=0 > > while self.adjls[p1][counter].to!=p2: > > counter=counter+1 > > self.track=self.adjls[p1][counter] > > self.pos=0 > > if self.speed>self.track.speed: > > speed=self.track.speed > > else: > > speed=self.speed > > while self.pos!=self.track.length: > > if self.track.state.has_key(self.pos): > > > self.track.state[self.pos].acquire() > > else: > > > > > self.track.state[self.pos]=threading.Semaphore(value=self.track.lanes) > > > self.track.state[self.pos].acquire() > > if self.pos!=0: > > > self.track.state[self.pos-1].release() > > self.pos=self.pos+1 > > sleep(1.0/speed) > > time=time+1.0/speed > > > > > self.stats['currtrsp']=float(self.track.length)/time > > if self.stats['avgspeed']: > > > > > self.stats['avgspeed']=float(self.stats['distcov']+self.track.length)/(self.stats['distcov']/self.stats['avgspeed']+self.track.length/self.stats['currtrsp']) > > else: > > > > self.stats['avgspeed']=self.stats['currtrsp'] > > > > > self.stats['totaltime']=self.stats['totaltime']+time > > if self.track.stats['avgspeed']: > > > > > self.track.stats['avgspeed']=(self.track.stats['avgspeed']*self.track.stats['traffictotal']+self.stats['currtrsp'])/(self.track.stats['traffictotal']+1) > > else: > > > > > self.track.stats['avgspeed']=self.stats['currtrsp'] > > > > > self.stats['distcov']=self.stats['distcov']+self.track.length > > > > > self.track.stats['traffictotal']=self.track.stats['traffictotal']+1 > > def > cross_junction(self,juncls,juncid,orig,dest): > > marker=str(orig)+'-'+str(dest) > > if juncls[juncid].free.has_key(marker): > > self.track.state[self.pos].release() > > else: > > while not > > juncls[juncid].signalled['green'].has_key(marker): > > sleep(0.2) > > self.track.state[self.pos-1].release() > > def run(self): > > path=self.shortest > > counter=1 > > for i in path[:1]: > > self.traverse_track(i,path[counter]) > > if not counter==len(path)-1: > > > > > self.cross_junction(self.juncls,path[counter],i,path[counter+1]) > > counter=counter+1 > > self.finished=1 > > self.track.state[self.pos-1].release() > > > > > > > > __________________________________________________ > > Do You Yahoo!? > > Tired of spam? Yahoo! Mail has the best spam > protection around > > http://mail.yahoo.com > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From bill.mill at gmail.com Fri Feb 25 18:04:42 2005 From: bill.mill at gmail.com (Bill Mill) Date: Fri Feb 25 18:04:47 2005 Subject: [Tutor] threads In-Reply-To: <20050225161742.59141.qmail@web53805.mail.yahoo.com> References: <421E1081.4070104@h-lab.net> <20050225161742.59141.qmail@web53805.mail.yahoo.com> Message-ID: <797fe3d405022509045048272d@mail.gmail.com> Hi Hugo, <snip> > I tried my hands at Stackless too... but still had > problems implementing the concept. > > Can anyone guide me on how to spawn simultaneously( or > pseudo simultaneously) running microthreads using > stackless. > > Here is what i tried.. > > ef gencars(num,origin,dest,speed): > global adjls > global cars > global juncls > for i in range(num): > > cars.append(car(orig,dest,speed) > task=tasklet(cars[i].run()) > task.setup('Bind using Setup') > > Now this is what i copied from somewhere...i dont > claim to understand fully what is happening.Here > car.run() is a process which takes a long time to > execute. > > What happens on execution is....One car is initialised > and then the program waits for its run method to > complete before proceeding. > > I also feel that there is no clear documentation on > stackless. > > Show me the light. > You might want to tighten this question up and ask it on python-list. This is pretty specialized knowledge for the python-tutors list, and I know for a fact that there are several people who have used greenlets on python-list. Just a thought. Peace Bill Mill bill.mill at gmail.com From ternary at gmail.com Fri Feb 25 19:00:16 2005 From: ternary at gmail.com (Mike Bell) Date: Fri Feb 25 19:00:21 2005 Subject: [Tutor] threads In-Reply-To: <20050225161742.59141.qmail@web53805.mail.yahoo.com> References: <421E1081.4070104@h-lab.net> <20050225161742.59141.qmail@web53805.mail.yahoo.com> Message-ID: <82975b0c050225100017383ee3@mail.gmail.com> If what you want is something that scales up, then you're attacking the Wrong Problem. Rather than focus on getting your thread overhead as small as possible in order to support as much real-time concurrency as you can, you should (as has been suggested) try to get simulation-time concurrency without worrying about what happens in real-time. Then you can have arbitrarily many things happening at once. This introduction to discrete event simulation explains the idea: http://www.dmem.strath.ac.uk/~pball/simulation/simulate.html mike From luke.jordan at gmail.com Fri Feb 25 20:04:11 2005 From: luke.jordan at gmail.com (Luke Jordan) Date: Fri Feb 25 20:04:13 2005 Subject: [Tutor] Functions Calling Functions Message-ID: <ea0feb80050225110447b82205@mail.gmail.com> Hi - I'm working on a command-line game. Is there anything wrong with having each 'chapter' of the game be a function that links to other chapters by calling them? I only ask because when a recent traceback returned about 40 lines worth of error message, I realized that the functions are all being run 'within each other' (ah-ha!). Thanks! -- "If you think that was good, wait 'til you taste the antidote!" From bill.mill at gmail.com Fri Feb 25 20:10:22 2005 From: bill.mill at gmail.com (Bill Mill) Date: Fri Feb 25 20:10:25 2005 Subject: [Tutor] Functions Calling Functions In-Reply-To: <ea0feb80050225110447b82205@mail.gmail.com> References: <ea0feb80050225110447b82205@mail.gmail.com> Message-ID: <797fe3d40502251110333a3cbc@mail.gmail.com> Luke, On Fri, 25 Feb 2005 11:04:11 -0800, Luke Jordan <luke.jordan@gmail.com> wrote: > Hi - > > I'm working on a command-line game. Is there anything wrong with > having each 'chapter' of the game be a function that links to other > chapters by calling them? I only ask because when a recent traceback > returned about 40 lines worth of error message, I realized that the > functions are all being run 'within each other' (ah-ha!). > for your own debugging sanity, you'll likely want to have a supervisor function which calls the chapter functions in order. There's nothing technically wrong with what you're doing, as long as you don't exceed the maximum recursion depth, but it's a pain to debug and takes up a whole bunch of memory you don't need. Peace Bill Mill bill.mill at gmail.com From kent37 at tds.net Fri Feb 25 20:29:37 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Feb 25 20:29:55 2005 Subject: [Tutor] Functions Calling Functions In-Reply-To: <ea0feb80050225110447b82205@mail.gmail.com> References: <ea0feb80050225110447b82205@mail.gmail.com> Message-ID: <421F7CA1.7000703@tds.net> Luke Jordan wrote: > Hi - > > I'm working on a command-line game. Is there anything wrong with > having each 'chapter' of the game be a function that links to other > chapters by calling them? I only ask because when a recent traceback > returned about 40 lines worth of error message, I realized that the > functions are all being run 'within each other' (ah-ha!). Technically it's OK but conceptually it isn't really right. After all, when you finish a chapter you don't go back to the chapter you came from! I would use a central dispatcher. Each chapter function could return a token indicating which chapter is next, or it could return the actual next chapter function. Here is a simple example: ######### def dispatch(chapter): while chapter is not None: chapter = chapter() def chapter1(): print 'This is chapter 1' raw_input('Press return to continue') return chapter2 def chapter2(): print 'You see a heffalump.' yn = raw_input('Do you kill the heffalump? ') if yn == 'y': return chapter3 else: return chapter4 def chapter3(): print 'The heffalump is dead. Congratulations, you win!' return None def chapter4(): print 'The heffalump kills you and eats you.' print 'You have died!' return None dispatch(chapter1) ############# Kent From project5 at redrival.net Fri Feb 25 21:11:42 2005 From: project5 at redrival.net (Andrei) Date: Fri Feb 25 21:12:08 2005 Subject: [Tutor] Re: Functions Calling Functions References: <ea0feb80050225110447b82205@mail.gmail.com> Message-ID: <bt03779pw50r$.1k8doa41wd81q$.dlg@40tude.net> Luke Jordan wrote on Fri, 25 Feb 2005 11:04:11 -0800: Hi Luke, > I'm working on a command-line game. Is there anything wrong with > having each 'chapter' of the game be a function that links to other > chapters by calling them? I only ask because when a recent traceback > returned about 40 lines worth of error message, I realized that the > functions are all being run 'within each other' (ah-ha!). For a quick'n'dirty prototype while learning Python, I'd say it's acceptable - although it's likely to end up costing you more time than if you took a more thought-out approach. If it's something that you intend to develop, distribute and maintain, I think it's not a good idea at all. It would be better to find the functionality that your game offers, split it into separate functions and call those functions using data form a dictionary/list/database. E.g. let's say you have a game with three rooms arranged in a triangle. In each room the user can play some mini-game or go to one of the connected rooms. Having functions call each other could end up in the program crashing if the user just walks from room to room, because you've in effect got a recursive function going on, basically doing this: >>> def a(): c() >>> def c(): a() a() # huge traceback here Instead, you could have the data in a format like this: rooms = { 1: ['First room', guess, 2, 3], 2: ['Second room', hangman, 3, 1], 3: ['Third room', safecracker, 1, 2], } The keys in the dictionary are the room numbers. The properties of each room are described in the form of a list, giving a room name, a mini-game (which is the name of a function implementing the actual mini-game), the number of the room to the left and the number of the room to the right. Now all you'd need is to impelement a "while True" main loop which would call a function DiplayRoom using one of the room-lists as argument. DisplayRoom would display the name of the room and offer the user the choice to play the mini-game or leave to the left or to the right. Once the user chooses to leave, the new room number is returned as result and the main loop calls DisplayRoom again, but this time using the properties list of the new room. This approach offers the following advantages: - you'll never be more than three functions deep or so (depending on the precise implementation), so it's impossible for the user to crash your program just by walking around. - it's very easy to extend the program with new rooms or re-arrange the 'map', since you just have to modify the data. Modifying data is safer and easier than modifying code. - it's easier to debug than when you have a billion lines of call stack. - I expect it to consume less memory -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From uselinux34 at yahoo.co.uk Fri Feb 25 22:35:57 2005 From: uselinux34 at yahoo.co.uk (Richard gelling) Date: Fri Feb 25 22:36:01 2005 Subject: [Tutor] sys.argv[1: ] help Message-ID: <421F9A3D.5040108@yahoo.co.uk> Hi, I am reading ' Learning Python second edition' by Mark Lutz and David Ascher, and I trying the code examples as I go along. However I am having a problem with the following, which I don't seem to be able to resolve :- # test.py import sys print sys[ 1: ] This I believe is supposed to print the 1st argument passed to the program. However if I try test.py fred All I get at the command line is [] If I try :- python test.py fred I get ['fred'] as I believe you are supposed to. I can run other examples,I have typed in by just using the file name, but not this particular example. Could anyone shine any light on what I am missing or have not configured correctly. I am runnung Python 2.4 on a windows XP box. Thanks a lot Richard G. From TValone at DMV.CA.gov Fri Feb 25 23:14:59 2005 From: TValone at DMV.CA.gov (Valone, Toren W.) Date: Fri Feb 25 23:14:15 2005 Subject: [Tutor] Newbie simple question Message-ID: <5AE0A72A4C0AD711806A000255FC47DB2A15F6@dmv-ent-ex07.dmv.ca.gov> I need to know how to read the next line while in the "for line in" loop. Readline does not read the next line (I watched it in debug) I think it has something to do with the for line loop but I have not found any documentation in the doc's or tutor for any functions for line.. Thanks, please forgive the sloppy code. #This Python App will simply remail emails that cannot be remailed from the MF import smtplib from string import * from Email import * #def main(): #define function or class main # Email the results # Email('Tvalone@dmv.ca.gov', # R emailTo, # sub, # results) remailfile = open('remail2.txt', 'r') #future address/file from outlook resendfile = open('resend.txt', 'w') #currently these files are in Python24 EmailReport = open('erprt.txt', 'w') #Report of bad emails etc fromaddr='Tvalone@dmv.ca.gov' for line in remailfile: #loops thru all emails, #print "test" if line.startswith("Subject: Undeliverable Mail"): EmailReport.write(line) elif line.startswith("MVSSY4.TEALE.CA.GOV unable to deliver following"): #line.readline() remailfile.readline() toaddr = line[4:80] #Set line to email #toaddr = lstrip("<") #Strip less than #toaddr = rstrip(">") #Strip greater than print len(toaddr) elif line.startswith("TO:"): #if toaddr != '': #toaddr = line[4:25] #toaddr = lstrip(toaddr) #resendfile.write(line) remailfile.readline() #read the next line to get subject #print RemailTo elif line.startswith("SUBJECT:"): subj = line[9:30] #Strip out Subject #print sub resendfile.write(line) remailfile.readline() #need to read line elif line.startswith("At"): remailfile.readline() elif line.startswith("Date:"): remailfile.readline() elif line.startswith("From:"): remailfile.readline() elif not line: remailfile.readline() elif line.startswith("We"): body = line resendfile.write(line) elif line.startswith("File"): body = line remailfile.readline() resendfile.write(line) elif line.startswith("with"): body = body + line resendfile.write(line) #print results #print len(fromaddr) #print len(toaddr) #print len(subj) #print len(body) Email(fromaddr,toaddr,subj,body) remailfile.close() resendfile.close() From python at jayloden.com Sat Feb 26 04:33:50 2005 From: python at jayloden.com (Jay Loden) Date: Fri Feb 25 23:36:25 2005 Subject: [Tutor] sys.argv[1: ] help In-Reply-To: <421F9A3D.5040108@yahoo.co.uk> References: <421F9A3D.5040108@yahoo.co.uk> Message-ID: <200502252233.50835.python@jayloden.com> Should be: import sys def main(): '''prints out the first command line argument''' print sys.argv[1] main() On Friday 25 February 2005 04:35 pm, Richard gelling wrote: > Hi, > > I am reading ' Learning Python second edition' by Mark Lutz and David > Ascher, and I trying the code examples as I go along. However I am > having a problem with the following, which I don't seem to be able to > resolve :- > > # test.py > import sys > > print sys[ 1: ] > > This I believe is supposed to print the 1st argument passed to the > program. However if I try > > test.py fred > > All I get at the command line is > > [] > > If I try :- > > python test.py fred > > I get > > ['fred'] > > as I believe you are supposed to. I can run other examples,I have typed > in by just using the file name, but not this particular example. Could > anyone shine any light on what I am missing or have not configured > correctly. I am runnung Python 2.4 on a windows XP box. > > Thanks a lot > > Richard G. > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From python at jayloden.com Sat Feb 26 04:37:44 2005 From: python at jayloden.com (Jay Loden) Date: Fri Feb 25 23:40:18 2005 Subject: [Tutor] Newbie simple question In-Reply-To: <5AE0A72A4C0AD711806A000255FC47DB2A15F6@dmv-ent-ex07.dmv.ca.gov> References: <5AE0A72A4C0AD711806A000255FC47DB2A15F6@dmv-ent-ex07.dmv.ca.gov> Message-ID: <200502252237.44813.python@jayloden.com> You want readlines() not readline() and it should work something like this: remailfile = open("remail2.txt", r) remails = remailfile.readlines() for line in remails: #do something -Jay On Friday 25 February 2005 05:14 pm, Valone, Toren W. wrote: > I need to know how to read the next line while in the "for line in" loop. > Readline does not read the next line (I watched it in debug) I think it has > something to do with the for line loop but I have not found any > documentation in the doc's or tutor for any functions for line.. > > Thanks, please forgive the sloppy code. From project5 at redrival.net Fri Feb 25 23:50:00 2005 From: project5 at redrival.net (Andrei) Date: Fri Feb 25 23:50:42 2005 Subject: [Tutor] Re: Newbie simple question References: <5AE0A72A4C0AD711806A000255FC47DB2A15F6@dmv-ent-ex07.dmv.ca.gov> Message-ID: <y90irctm5ya6$.14z0y33x0fjy2.dlg@40tude.net> Valone, Toren W. wrote on Fri, 25 Feb 2005 14:14:59 -0800: > I need to know how to read the next line while in the "for line in" loop. If you want to skip some of the lines (whatever their source may be), I think you should *not* use a for..in loop, but a while loop, in which you read/skip lines manually as needed. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From cyresse at gmail.com Sat Feb 26 00:30:18 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sat Feb 26 00:30:21 2005 Subject: [Tutor] sys.argv[1: ] help In-Reply-To: <200502252233.50835.python@jayloden.com> References: <421F9A3D.5040108@yahoo.co.uk> <200502252233.50835.python@jayloden.com> Message-ID: <f2ff2d0502251530646b5b90@mail.gmail.com> Remember computers count from 0, so sys[1] is the 2nd argument, sys[0] is always the filename. On Fri, 25 Feb 2005 22:33:50 -0500, Jay Loden <python@jayloden.com> wrote: > Should be: > > import sys > > def main(): > '''prints out the first command line argument''' > print sys.argv[1] > > main() > > On Friday 25 February 2005 04:35 pm, Richard gelling wrote: > > Hi, > > > > I am reading ' Learning Python second edition' by Mark Lutz and David > > Ascher, and I trying the code examples as I go along. However I am > > having a problem with the following, which I don't seem to be able to > > resolve :- > > > > # test.py > > import sys > > > > print sys[ 1: ] > > > > This I believe is supposed to print the 1st argument passed to the > > program. However if I try > > > > test.py fred > > > > All I get at the command line is > > > > [] > > > > If I try :- > > > > python test.py fred > > > > I get > > > > ['fred'] > > > > as I believe you are supposed to. I can run other examples,I have typed > > in by just using the file name, but not this particular example. Could > > anyone shine any light on what I am missing or have not configured > > correctly. I am runnung Python 2.4 on a windows XP box. > > > > Thanks a lot > > > > Richard G. > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From dyoo at hkn.eecs.berkeley.edu Sat Feb 26 00:57:24 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Feb 26 00:57:28 2005 Subject: [Tutor] sys.argv[1: ] help In-Reply-To: <200502252233.50835.python@jayloden.com> Message-ID: <Pine.LNX.4.44.0502251548410.1712-100000@hkn.eecs.berkeley.edu> > > I am reading ' Learning Python second edition' by Mark Lutz and David > > Ascher, and I trying the code examples as I go along. However I am > > having a problem with the following, which I don't seem to be able to > > resolve :- > > # test.py > > import sys > > > > print sys[ 1: ] > > > > This I believe is supposed to print the 1st argument passed to the > > program. However if I try > > > > test.py fred > > > > All I get at the command line is > > > > [] Hi Jay, Are you sure that is what your program contained? I'm surprised that this didn't error out! The program: ###### import sys print sys[1:] ###### should raise a TypeError because 'sys' is a module, and not a list of elements, and modules don't support slicing. Just out of curiosity, can you confirm that you aren't getting an error message? (I know I'm being a bit silly about asking about what looks like a simple email typo, but computer programming bugs are all-too-often about typos. *grin* When you write about a program, try using cut-and-paste to ensure that the program that you're running is the same as the program you're showing us.) Best of wishes to you! From shitizb at yahoo.com Sat Feb 26 01:08:10 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Sat Feb 26 01:08:14 2005 Subject: [Tutor] threads In-Reply-To: <20050225161742.59141.qmail@web53805.mail.yahoo.com> Message-ID: <20050226000810.98746.qmail@web53809.mail.yahoo.com> I have run into a problem again. I thought about simulation time concurrency and figured an inherent problem with the approach. The main objective of my project is to simulate traffic behavious under congested conditions.Hence I was using semaphores to lock the areas already occupied by the cars.A car wanting to move ahead acquires the semaphore right ahead, releases the semaphore on its old position, and so on... Now, if i use the one thread approach, or use pseudo threads like greenlets or tasklets, a deadlock occurs. A car cant acquire the next semaphore until it is released by the next car. The next car on the other hand cant release it because the thread of control is busy trying to acquire the semaphore inside the old car's run method. The way out could be maintaining a database of every position on the road, in binary format, which would be more efficient memory wise as well. Any comments? Another issue is...since the speed of every car is not same but follows a random distribution,I was updating the car positions after every 1/speed seconds. To be able to apply the above database (or even semaphoes for that matter)i would need a fixed number of car positions.Hence I have to continue updating the position after every 1/speed second. Hence I would need a HCF(fraction) of all the 1/speeds(which are actually floats, but approximations can be made). How do i calculate this HCF?? Remember that I am generating cars even while the simulation is running, hence calculating this HCF at the beginning is not going to work. Any comments? --- Shitiz Bansal <shitizb@yahoo.com> wrote: > Hi, > Thanx everyone for all your suggestions.I used a > separate thread for every car as I wanted my cars to > run in real time, to coordinate effectively with > other > systems like traffic lights for eg. which I cant > edit, > hence which cant use the variable time defined by > me. > > I figured out two ways to achieve this.... > > On Linux... ulimit -s 64, limits the stacksize of > each > thread to 64Kb, and i was able to generate 8000 > threads.However upgrading my program to support more > cars was a problem. > > Another way was to spawn 1000 threads, handling abt > 10 > cars each...this way the diff in real time and my > program time was limited. > > I tried my hands at Stackless too... but still had > problems implementing the concept. > > Can anyone guide me on how to spawn simultaneously( > or > pseudo simultaneously) running microthreads using > stackless. > > Here is what i tried.. > > ef gencars(num,origin,dest,speed): > global adjls > global cars > global juncls > for i in range(num): > > > cars.append(car(orig,dest,speed) > task=tasklet(cars[i].run()) > task.setup('Bind using Setup') > > Now this is what i copied from somewhere...i dont > claim to understand fully what is happening.Here > car.run() is a process which takes a long time to > execute. > > What happens on execution is....One car is > initialised > and then the program waits for its run method to > complete before proceeding. > > I also feel that there is no clear documentation on > stackless. > > Show me the light. > > Shitiz > > > --- Hugo González Monteverde > <hugonz-lists@h-lab.net> > wrote: > > > OK, as ignorant as I may be on threads, I have > read > > a bit on Stackless > > Python's tasklets. Suppossedly they require much > > less memory than > > python's threads. > > > > Information is at www.stackless.com > > > > Hugo > > > > Shitiz Bansal wrote: > > > Hi, > > > > > > I am trying to build a traffic network simulator > > using > > > python, for my degree project. > > > > > > I need to run at least 5-6000 cars > > simultaneously.I > > > wanted to run each car in a separate thread. > > > However , after about 400 threads i am unable to > > > create new threads. > > > > > > Here's the code: > > > > > >>>>cars=range(1000) > > >>>>for i in cars: > > > > > > cars[i]=cars[i]=car(1,10,2,1,adjls,juncls) > > > > > > > > > > > >>>>for i in cars: > > > > > > i.start() > > > > > > Traceback (most recent call last): > > > File "<pyshell#24>", line 2, in -toplevel- > > > i.start() > > > error: can't start new thread > > > > > > Is there a way out.Also, are there any tips on > > > performance issues? > > > > > > Here is the class car: > > > > > > class car(threading.Thread): > > > def > > > > __init__(self,carid,speed,dest,orig,adjls,juncls): > > > threading.Thread.__init__(self) > > > self.speed=speed > > > self.finished=0 > > > self.carid=carid > > > self.dest=dest > > > self.orig=orig > > > self.adjls=adjls > > > self.juncls=juncls > > > > > > > > > self.shortest=find_shortest_path(adjls,self.dest,self.orig) > > > > > self.calc=findpaths(adjls,self.dest,self.orig) > > > > > > > > > self.stats={'currtrsp':0,'avgspeed':0,'distcov':0,'totaltime':0} > > > def traverse_track(self,p1,p2): > > > counter=0 > > > time=0 > > > while self.adjls[p1][counter].to!=p2: > > > counter=counter+1 > > > self.track=self.adjls[p1][counter] > > > self.pos=0 > > > if self.speed>self.track.speed: > > > speed=self.track.speed > > > else: > > > speed=self.speed > > > while self.pos!=self.track.length: > > > if > self.track.state.has_key(self.pos): > > > > > self.track.state[self.pos].acquire() > > > else: > > > > > > > > > self.track.state[self.pos]=threading.Semaphore(value=self.track.lanes) > > > > > self.track.state[self.pos].acquire() > > > if self.pos!=0: > > > > > self.track.state[self.pos-1].release() > > > self.pos=self.pos+1 > > > sleep(1.0/speed) > > > time=time+1.0/speed > > > > > > > > > self.stats['currtrsp']=float(self.track.length)/time > > > if self.stats['avgspeed']: > > > > > > > > > self.stats['avgspeed']=float(self.stats['distcov']+self.track.length)/(self.stats['distcov']/self.stats['avgspeed']+self.track.length/self.stats['currtrsp']) > > > else: > > > > > > self.stats['avgspeed']=self.stats['currtrsp'] > > > > > > > > > self.stats['totaltime']=self.stats['totaltime']+time > > > if self.track.stats['avgspeed']: > > > > > > > > > self.track.stats['avgspeed']=(self.track.stats['avgspeed']*self.track.stats['traffictotal']+self.stats['currtrsp'])/(self.track.stats['traffictotal']+1) > > > else: > > > > > > > > > self.track.stats['avgspeed']=self.stats['currtrsp'] > > > > > > > > > self.stats['distcov']=self.stats['distcov']+self.track.length > > > > > > > > > self.track.stats['traffictotal']=self.track.stats['traffictotal']+1 > > > def > > cross_junction(self,juncls,juncid,orig,dest): > > > marker=str(orig)+'-'+str(dest) > > > if juncls[juncid].free.has_key(marker): > > > self.track.state[self.pos].release() > > > else: > > > while not > > > > juncls[juncid].signalled['green'].has_key(marker): > > > sleep(0.2) > > > > self.track.state[self.pos-1].release() > > > def run(self): > > > path=self.shortest > > > counter=1 > > > for i in path[:1]: > > > self.traverse_track(i,path[counter]) > > > if not counter==len(path)-1: > > > > > > > > > self.cross_junction(self.juncls,path[counter],i,path[counter+1]) > > > counter=counter+1 > > > self.finished=1 > > > self.track.state[self.pos-1].release() > > > > > > > > > > > > > __________________________________________________ > > > Do You Yahoo!? > > > Tired of spam? Yahoo! Mail has the best spam > > protection around > > > http://mail.yahoo.com > > > _______________________________________________ > > > Tutor maillist - Tutor@python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam > protection around > http://mail.yahoo.com > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > __________________________________ Do you Yahoo!? Yahoo! Mail - Easier than ever with enhanced search. Learn more. http://info.mail.yahoo.com/mail_250 From amonroe at columbus.rr.com Sat Feb 26 01:14:13 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sat Feb 26 01:14:55 2005 Subject: [Tutor] threads In-Reply-To: <20050226000810.98746.qmail@web53809.mail.yahoo.com> References: <20050226000810.98746.qmail@web53809.mail.yahoo.com> Message-ID: <16-2037921306.20050225191413@columbus.rr.com> > Remember that I am generating cars even while the > simulation is running, hence calculating this HCF at > the beginning is not going to work. > Any comments? This won't help you much in writing your program, but you might find it interesting and vaguely similar to what you're doing: www.simutrans.de Alan From michael.hall at critterpixstudios.com Sat Feb 26 01:18:46 2005 From: michael.hall at critterpixstudios.com (Mike Hall) Date: Sat Feb 26 01:18:55 2005 Subject: [Tutor] gensuitemodule? Message-ID: <493cbb23901d63d9b5ec4c21ac70c2e8@critterpixstudios.com> I'm seeing it used in a Python/Applescript tutorial, though am unclear on it's exact purpose or usage. Can someone fill me in? From kent37 at tds.net Sat Feb 26 02:36:47 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat Feb 26 02:36:52 2005 Subject: [Tutor] Functions Calling Functions In-Reply-To: <421F7CA1.7000703@tds.net> References: <ea0feb80050225110447b82205@mail.gmail.com> <421F7CA1.7000703@tds.net> Message-ID: <421FD2AF.7070907@tds.net> Kent Johnson wrote: > I would use a central dispatcher. Each chapter function could return a > token indicating which chapter is next, or it could return the actual > next chapter function. Look here for an *extensive* example of this style: http://homepage.mac.com/spkane/python/paranoia.py Kent From kent37 at tds.net Sat Feb 26 02:40:50 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat Feb 26 02:40:57 2005 Subject: [Tutor] Newbie simple question In-Reply-To: <5AE0A72A4C0AD711806A000255FC47DB2A15F6@dmv-ent-ex07.dmv.ca.gov> References: <5AE0A72A4C0AD711806A000255FC47DB2A15F6@dmv-ent-ex07.dmv.ca.gov> Message-ID: <421FD3A2.8060704@tds.net> Valone, Toren W. wrote: > I need to know how to read the next line while in the "for line in" loop. > Readline does not read the next line (I watched it in debug) I think it has > something to do with the for line loop but I have not found any > documentation in the doc's or tutor for any functions for line.. I think line = remailfile.next() will do what you want. Give it a try. Kent From mark.kels at gmail.com Sat Feb 26 14:12:53 2005 From: mark.kels at gmail.com (Mark Kels) Date: Sat Feb 26 14:12:59 2005 Subject: [Tutor] 3 questions for my port scanner project Message-ID: <c225925305022605124e9cdc0a@mail.gmail.com> Hi list. Here are the questions (-: 1. How do I make a progress bar in Tkinter ? 2. I got a while loop which does the port scan itself. How can I end it while its working ? 3. For some reason the scan is too slow (2-3 seconds for a port). Is there a way to make it faster (other port scanner work allot faster... ) ? Thanks in advance !! -- 1. The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners. 2. Unix is user friendly - it's just picky about it's friends. 3. Documentation is like sex: when it is good, it is very, very good. And when it is bad, it is better than nothing. - Dick Brandon From nick at javacat.f2s.com Sat Feb 26 14:46:12 2005 From: nick at javacat.f2s.com (Nick Lunt) Date: Sat Feb 26 14:45:04 2005 Subject: [Tutor] 3 questions for my port scanner project In-Reply-To: <c225925305022605124e9cdc0a@mail.gmail.com> References: <c225925305022605124e9cdc0a@mail.gmail.com> Message-ID: <1109425572.7233.0.camel@fuzzbox.local> Nr 3. If your using python sockets try socket.settimeout(x) Nick . On Sat, 2005-02-26 at 15:12 +0200, Mark Kels wrote: > Hi list. > > Here are the questions (-: > 1. How do I make a progress bar in Tkinter ? > 2. I got a while loop which does the port scan itself. How can I end > it while its working ? > 3. For some reason the scan is too slow (2-3 seconds for a port). Is > there a way to make it faster (other port scanner work allot faster... > ) ? > > Thanks in advance !! > From mwalsh at groktech.org Sat Feb 26 16:28:03 2005 From: mwalsh at groktech.org (Martin Walsh) Date: Sat Feb 26 16:28:10 2005 Subject: [Tutor] 3 questions for my port scanner project In-Reply-To: <c225925305022605124e9cdc0a@mail.gmail.com> References: <c225925305022605124e9cdc0a@mail.gmail.com> Message-ID: <42209583.7050202@groktech.org> Mark Kels wrote: >Hi list. > > > > Hi Mark, >2. I got a while loop which does the port scan itself. How can I end >it while its working ? > > previous message with code: *http://tinyurl.com/3lobo* **I'm not totally sure of this, but you might try adding another conditional to your while loop that can be toggled by a Scan and Stop button in your Tkinter app. global ok_to_scan ok_to_scan = 1 # or True while (start_port <= end_port) and ok_to_scan: # ... do scan ... root.update() then bind a function to a Stop button which toggles 'ok_to_scan' to 0 (or False), also as previously suggested you should close the sockets that find an open port (sk.close()) inside your while loop. HTH, Marty From kabads at gmail.com Sat Feb 26 20:48:25 2005 From: kabads at gmail.com (Adam Cripps) Date: Sat Feb 26 20:48:30 2005 Subject: [Tutor] Recursive Tkinter buttons In-Reply-To: <20050225122118.4fe893ad.klappnase@freenet.de> References: <c7ff3855050224141925d5dc88@mail.gmail.com> <421E8CD5.3080708@tds.net> <c7ff3855050224225377dd598b@mail.gmail.com> <f2ff2d05022423194d795e69@mail.gmail.com> <20050225122118.4fe893ad.klappnase@freenet.de> Message-ID: <c7ff3855050226114835e7f4ad@mail.gmail.com> On Fri, 25 Feb 2005 12:21:18 +0100, Michael Lange <snip> > > You see, in my example above I called the list "buttonlist" instead of "button"; maybe this naming > helps avoid confusion . > > Best regards > > Michael Many thanks for the help here. I got all my buttons displayed and stored in the list with: for i in range (1, 11): submittext = ">>> " self.s = Button(text=submittext, command = self.showButton) self.s.grid(column=4, row=i+4) submitlist.append(self.s) - however, when I click the button, I want self.showButton to know which one of them was pressed. I've seen in other gui programming the idea of an id or identifier - I can't see that here. Ideally, I would like to know the value of i in self.showButtons - but when I use self.showButtons(i) showButtons gets called straight at run time. Any ideas? TIA Adam -- http://www.monkeez.org PGP key: 0x7111B833 From shitizb at yahoo.com Sun Feb 27 12:24:30 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Sun Feb 27 12:24:33 2005 Subject: [Tutor] 3 questions for my port scanner project In-Reply-To: <c225925305022605124e9cdc0a@mail.gmail.com> Message-ID: <20050227112430.31275.qmail@web53803.mail.yahoo.com> > 2. I got a while loop which does the port scan > itself. How can I end > it while its working ? using the break statement anywhere inside the loop will exit the loop. > 3. For some reason the scan is too slow (2-3 seconds > for a port). Is > there a way to make it faster (other port scanner > work allot faster... The ports which do not respond are the ones which take most of the time.You can use the timer object to fix the time for each port.For eg. if a port does not respond within .1 sec it can reasonably be expected to be closed.The exact implementation will depend upon your code.You can also use threads to ping more than one port simultaneously. And I loved your microsoft quote :). Cheers > -- > 1. The day Microsoft makes something that doesn't > suck is probably the > day they start making vacuum cleaners. > 2. Unix is user friendly - it's just picky about > it's friends. > 3. Documentation is like sex: when it is good, it is > very, very good. > And when it is bad, it is better than nothing. - > Dick Brandon > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > __________________________________ Do you Yahoo!? Read only the mail you want - Yahoo! Mail SpamGuard. http://promotions.yahoo.com/new_mail From klappnase at freenet.de Sun Feb 27 15:38:14 2005 From: klappnase at freenet.de (Michael Lange) Date: Sun Feb 27 15:35:20 2005 Subject: [Tutor] Recursive Tkinter buttons In-Reply-To: <c7ff3855050226114835e7f4ad@mail.gmail.com> References: <c7ff3855050224141925d5dc88@mail.gmail.com> <421E8CD5.3080708@tds.net> <c7ff3855050224225377dd598b@mail.gmail.com> <f2ff2d05022423194d795e69@mail.gmail.com> <20050225122118.4fe893ad.klappnase@freenet.de> <c7ff3855050226114835e7f4ad@mail.gmail.com> Message-ID: <20050227153814.1dd880d2.klappnase@freenet.de> On Sat, 26 Feb 2005 19:48:25 +0000 Adam Cripps <kabads@gmail.com> wrote: > On Fri, 25 Feb 2005 12:21:18 +0100, Michael Lange > <snip> > > > > You see, in my example above I called the list "buttonlist" instead of "button"; maybe this naming > > helps avoid confusion . > > > > Best regards > > > > Michael > > Many thanks for the help here. > > I got all my buttons displayed and stored in the list with: > > for i in range (1, 11): > submittext = ">>> " > self.s = Button(text=submittext, command = self.showButton) > self.s.grid(column=4, row=i+4) > submitlist.append(self.s) > Hi Adam, note that there's no use in making the button an attribute of its parent class with self.s = Button(text=submittext, command = self.showButton) because self.s gets overridden on every iteration in the for-loop; it's not a bug, but might be a source of confusion, when you try to access self.s later in your code; you don't need the reference anyway, because you keep the references to all buttons in the list. > > - however, when I click the button, I want self.showButton to know > which one of them was pressed. I've seen in other gui programming the > idea of an id or identifier - I can't see that here. Ideally, I would > like to know the value of i in self.showButtons - but when I use > self.showButtons(i) showButtons gets called straight at run time. > > Any ideas? You have two options here: 1. use a lambda expression as button command, lambda allows you to pass an argument to the callback: s = Button(text=submittext, command = lambda index=i: self.showButton(index)) 2. if you don't like lambdas, you can use the button's bind() method instead of the command option: s = Button(text=submittext) s.bind('<ButtonRelease-1>', self.showButton) s.bind('<KeyRelease-space>', self.showButton) bind() passes an event to the callback which allows you to find out which widget sent the event via the event's widget attribute: def showButton(self, event): button = event.widget print button['text'] I hope this helps Michael From alan.gauld at freenet.co.uk Sun Feb 27 17:00:12 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Feb 27 16:59:39 2005 Subject: [Tutor] 3 questions for my port scanner project References: <c225925305022605124e9cdc0a@mail.gmail.com> Message-ID: <00b701c51ce5$6bf39060$a6388651@xp> > Here are the questions (-: > 1. How do I make a progress bar in Tkinter ? One option: Use a set up gif images and update the image periodically OR Use a canvas and redraw a rectangle slightly larger every time through the scanning loop. The first is easiest the second smoother but much more work! > 2. I got a while loop which does the port scan itself. How can I end > it while its working ? The best way is to have the loop running in a seperate thread to the GUI and checking a flag on each iteration. Then you can have a stop button on the GUI that sets the flag. Its generally a bad idea in a GUI to have long running processes within an event handler, better to put them in a separate thread. Unfortunately this is a lesson that Microsoft's programmers don't appear to have learned yet! Alan G. From alan.gauld at freenet.co.uk Sun Feb 27 17:06:32 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Feb 27 17:05:52 2005 Subject: [Tutor] Recursive Tkinter buttons References: <c7ff3855050224141925d5dc88@mail.gmail.com><421E8CD5.3080708@tds.net> <c7ff3855050224225377dd598b@mail.gmail.com><f2ff2d05022423194d795e69@mail.gmail.com><20050225122118.4fe893ad.klappnase@freenet.de> <c7ff3855050226114835e7f4ad@mail.gmail.com> Message-ID: <00be01c51ce6$4ef5e200$a6388651@xp> > - however, when I click the button, I want self.showButton to know > which one of them was pressed. I've seen in other gui programming the > idea of an id or identifier - I can't see that here. Ideally, I would > like to know the value of i in self.showButtons - but when I use > self.showButtons(i) showButtons gets called straight at run time. The easy way to do this is to use a defrault parameter in a lambda: submittext = ">>> " for i in range (1, 11): b = Button(text=submittext, command = lambda n=i: self.showButton(n)) b.rid(column=4, row=i+4) submitlist.append(b) Notice the button creation line now uses a lambda with default parameter set to i. That lambda calls your method but now passes in the value of i for that button. (You need to modify your method to accept that value of course!) HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From mark.kels at gmail.com Sun Feb 27 17:16:02 2005 From: mark.kels at gmail.com (Mark Kels) Date: Sun Feb 27 17:16:06 2005 Subject: [Tutor] 3 questions for my port scanner project In-Reply-To: <20050227112407.7577.qmail@web53801.mail.yahoo.com> References: <c225925305022605124e9cdc0a@mail.gmail.com> <20050227112407.7577.qmail@web53801.mail.yahoo.com> Message-ID: <c2259253050227081665adb59e@mail.gmail.com> On Sun, 27 Feb 2005 03:24:07 -0800 (PST), Shitiz Bansal <shitizb@yahoo.com> wrote: > > The ports which do not respond are the ones which take > most of the time.You can use the timer object to fix > the time for each port.For eg. if a port does not > respond within .1 sec it can reasonably be expected to > be closed.The exact implementation will depend upon > your code.You can also use threads to ping more than > one port simultaneously. > Thank you very much for yuor help !! Now I only need to figure out how to make a progress bar and my trubles are over :) -- 1. The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners. 2. Unix is user friendly - it's just picky about it's friends. 3. Documentation is like sex: when it is good, it is very, very good. And when it is bad, it is better than nothing. - Dick Brandon From uselinux34 at yahoo.co.uk Sun Feb 27 17:45:56 2005 From: uselinux34 at yahoo.co.uk (Richard gelling) Date: Sun Feb 27 17:45:59 2005 Subject: [Tutor] sys.argv[1: ] help In-Reply-To: <Pine.LNX.4.44.0502251548410.1712-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0502251548410.1712-100000@hkn.eecs.berkeley.edu> Message-ID: <4221F944.6080308@yahoo.co.uk> Danny Yoo wrote: > > >>>I am reading ' Learning Python second edition' by Mark Lutz and David >>>Ascher, and I trying the code examples as I go along. However I am >>>having a problem with the following, which I don't seem to be able to >>>resolve :- >>> >>> > > > >>># test.py >>>import sys >>> >>>print sys[ 1: ] >>> >>>This I believe is supposed to print the 1st argument passed to the >>>program. However if I try >>> >>>test.py fred >>> >>>All I get at the command line is >>> >>>[] >>> >>> > > >Hi Jay, > >Are you sure that is what your program contained? I'm surprised that this >didn't error out! The program: > >###### >import sys >print sys[1:] >###### > >should raise a TypeError because 'sys' is a module, and not a list of >elements, and modules don't support slicing. Just out of curiosity, can >you confirm that you aren't getting an error message? > > > >(I know I'm being a bit silly about asking about what looks like a simple >email typo, but computer programming bugs are all-too-often about typos. >*grin* > >When you write about a program, try using cut-and-paste to ensure that the >program that you're running is the same as the program you're showing us.) > > >Best of wishes to you! > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > Hi, Sorry for the late response, I tried all of the the suggestions, including correcting my typo of print sys[1:] and tried print sys,argv[1:], this does now work as long as I run 'python test.py fred joe' it returns all the arguments. If I try just test.py all I get is '[]' . Is there something wrong with my environmental variables in Windows XP, I would like to be able to just use the file name rather than having to type python each time. Any help would be gratefully received. Richard G. From nick at javacat.f2s.com Sun Feb 27 18:05:49 2005 From: nick at javacat.f2s.com (Nick Lunt) Date: Sun Feb 27 18:04:38 2005 Subject: [Tutor] sys.argv[1: ] help In-Reply-To: <4221F944.6080308@yahoo.co.uk> References: <Pine.LNX.4.44.0502251548410.1712-100000@hkn.eecs.berkeley.edu> <4221F944.6080308@yahoo.co.uk> Message-ID: <1109523949.8105.4.camel@fuzzbox.local> Richard, if you try to print sys.argv[1:] when sys.argv only contain sys.argv[0] then you are bound to get an empty list returned, [] . Im not sure I understand the problem you think you've got but here's what happens with sys.argv for me, and it's correct. [argl.py] $ cat argl.py #!/usr/bin/python import sys print sys.argv[1:] ./argl.py [] ./argl.py a b c ['a', 'b', 'c'] Is that what your getting ? > Sorry for the late response, I tried all of the the suggestions, > including correcting my typo of print sys[1:] and tried print > sys,argv[1:], this does now work as long as I run 'python test.py fred > joe' it returns all the arguments. If I try just test.py all I get is > '[]' . Is there something wrong with my environmental variables in > Windows XP, I would like to be able to just use the file name rather > than having to type python each time. Any help would be gratefully received. > > Richard G. > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From xifxif at gmail.com Sun Feb 27 18:07:07 2005 From: xifxif at gmail.com (Xif) Date: Sun Feb 27 18:07:09 2005 Subject: [Tutor] How do you share a method (function) among several objects? Message-ID: <4221FE3B.9010304@gmail.com> Hello There are several different objects. However, they all share the same function. Since they are not the same or similar, it's not logical to use a common superclass. So I'm asking, what's a good way to allow those objects to share that function? The best solution I've found so far is to put that function in a module, and have all objects import and use it. But I doubt that's a good use-case for modules; writing and importing a module that contains just a single function seems like an abuse. Thanks, Xif From javier at ruere.com.ar Sun Feb 27 18:46:35 2005 From: javier at ruere.com.ar (Javier Ruere) Date: Sun Feb 27 18:44:26 2005 Subject: [Tutor] Re: How do you share a method (function) among several objects? In-Reply-To: <4221FE3B.9010304@gmail.com> References: <4221FE3B.9010304@gmail.com> Message-ID: <cvt0kd$v30$1@sea.gmane.org> Xif wrote: > Hello > > There are several different objects. However, they all share the same > function. > > Since they are not the same or similar, it's not logical to use a > common superclass. > > So I'm asking, what's a good way to allow those objects to share that > function? > > The best solution I've found so far is to put that function in a > module, and have all objects import and use it. But I doubt that's a > good use-case for modules; writing and importing a module that contains > just a single function seems like an abuse. > > Thanks, > Xif Could you give an example? Javier From uselinux34 at yahoo.co.uk Sun Feb 27 18:55:54 2005 From: uselinux34 at yahoo.co.uk (Richard gelling) Date: Sun Feb 27 18:56:04 2005 Subject: [Tutor] sys.argv[1: ] help In-Reply-To: <1109523949.8105.4.camel@fuzzbox.local> References: <Pine.LNX.4.44.0502251548410.1712-100000@hkn.eecs.berkeley.edu> <4221F944.6080308@yahoo.co.uk> <1109523949.8105.4.camel@fuzzbox.local> Message-ID: <422209AA.409@yahoo.co.uk> Hi, No What I get if I was to type in ./arg1.py a b c All I get is [] If i type at the command prompt python arg1.py a b c I get ['a','b','c'] as expected All the other programs and examples I have typed in work fine just by typing in the file name, I don't have to preced the file name with python, only this example. I hope this makes it clearer Richard G. Nick Lunt wrote: >Richard, > >if you try to print sys.argv[1:] when sys.argv only contain sys.argv[0] >then you are bound to get an empty list returned, [] . > >Im not sure I understand the problem you think you've got but here's >what happens with sys.argv for me, and it's correct. > >[argl.py] > >$ cat argl.py >#!/usr/bin/python > >import sys >print sys.argv[1:] > > >./argl.py >[] > >./argl.py a b c >['a', 'b', 'c'] > >Is that what your getting ? > > > > > > >>Sorry for the late response, I tried all of the the suggestions, >>including correcting my typo of print sys[1:] and tried print >>sys,argv[1:], this does now work as long as I run 'python test.py fred >>joe' it returns all the arguments. If I try just test.py all I get is >>'[]' . Is there something wrong with my environmental variables in >>Windows XP, I would like to be able to just use the file name rather >>than having to type python each time. Any help would be gratefully received. >> >>Richard G. >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> >> > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > From xifxif at gmail.com Sun Feb 27 19:20:19 2005 From: xifxif at gmail.com (Xif) Date: Sun Feb 27 19:20:34 2005 Subject: [Tutor] Re: How do you share a method (function) among several objects? In-Reply-To: <cvt0kd$v30$1@sea.gmane.org> References: <4221FE3B.9010304@gmail.com> <cvt0kd$v30$1@sea.gmane.org> Message-ID: <42220F63.1090606@gmail.com> Javier Ruere wrote: > Xif wrote: > >> Hello >> >> There are several different objects. However, they all share the same >> function. >> >> Since they are not the same or similar, it's not logical to use a >> common superclass. >> >> So I'm asking, what's a good way to allow those objects to share that >> function? >> >> The best solution I've found so far is to put that function in a >> module, and have all objects import and use it. But I doubt that's a >> good use-case for modules; writing and importing a module that contains >> just a single function seems like an abuse. >> >> Thanks, >> Xif > > > Could you give an example? > > Javier > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > +++++++++++++++++++++++++++++++++++++++++++ > This Mail Was Scanned By Mail-seCure System > at the Tel-Aviv University CC. > Sure, I can describe my particular case. It's a program that retrieves / updates Microsoft Excel spreadsheet data. There are two major classes: 1) an Excel class, that represents of the whole Excel program 2) a Cells class, that abstracts retrieval and editing of cells. Both classes use a function called getCells() as part of their __getitem__() methods. getCells() parses the __getitem__() call arguments, and returns an iterator over the appropriate cells. The difference between the 2 classes is that a Cells instance just converts the generator into a list and returns it: #<code> return list(getCells(self.sheet, cells)) #</code> while an Excel instance returns the values of the cells: #<code> return [cell.Value for cell in getCells(self.sheet, cells)] #</code> As you can see, both use the getCells() function. So my question is, where is the best way to put it so instances of both classes can use it? Xif From cyresse at gmail.com Sun Feb 27 19:22:49 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sun Feb 27 19:22:54 2005 Subject: [Tutor] sys.argv[1: ] help In-Reply-To: <422209AA.409@yahoo.co.uk> References: <Pine.LNX.4.44.0502251548410.1712-100000@hkn.eecs.berkeley.edu> <4221F944.6080308@yahoo.co.uk> <1109523949.8105.4.camel@fuzzbox.local> <422209AA.409@yahoo.co.uk> Message-ID: <f2ff2d050227102268a2dd5a@mail.gmail.com> Are you using XP still? I've never seen this before - > ./arg1.py a b c But anyhoo, I tried out just 'c:\python23\foo.py' as opposed to 'c:\python23\python foo.py' and while foo.py will run, it doesn't echo to the console, as on my machine running a .py file runs it through pythonw.exe - I'd check it out for your machine, it's probably the same. You'd need to change the association to python.exe, but that would mean that you always got a DOS box for every Python script you ran, which is annoying with GUIs. Erm, if you don't want to type in python each time, either change the association or create a batch file called x or a or something that runs Python and stick it in a directory that's in your PATH system variable. Only problem with that is passing command line variables.... ...might just be better to type python.... Good Luck, Liam Clarke On Sun, 27 Feb 2005 17:55:54 +0000, Richard gelling <uselinux34@yahoo.co.uk> wrote: > > Hi, > > No What I get if I was to type in > ./arg1.py a b c > > All I get is > [] > > If i type at the command prompt > > python arg1.py a b c > > I get ['a','b','c'] as expected > > All the other programs and examples I have typed in work fine just by > typing in the file name, I don't have to preced the file name with > python, only this example. I hope this makes it clearer > > Richard G. > > > Nick Lunt wrote: > > >Richard, > > > >if you try to print sys.argv[1:] when sys.argv only contain sys.argv[0] > >then you are bound to get an empty list returned, [] . > > > >Im not sure I understand the problem you think you've got but here's > >what happens with sys.argv for me, and it's correct. > > > >[argl.py] > > > >$ cat argl.py > >#!/usr/bin/python > > > >import sys > >print sys.argv[1:] > > > > > >./argl.py > >[] > > > >./argl.py a b c > >['a', 'b', 'c'] > > > >Is that what your getting ? > > > > > > > > > > > > > > >>Sorry for the late response, I tried all of the the suggestions, > >>including correcting my typo of print sys[1:] and tried print > >>sys,argv[1:], this does now work as long as I run 'python test.py fred > >>joe' it returns all the arguments. If I try just test.py all I get is > >>'[]' . Is there something wrong with my environmental variables in > >>Windows XP, I would like to be able to just use the file name rather > >>than having to type python each time. Any help would be gratefully received. > >> > >>Richard G. > >>_______________________________________________ > >>Tutor maillist - Tutor@python.org > >>http://mail.python.org/mailman/listinfo/tutor > >> > >> > > > >_______________________________________________ > >Tutor maillist - Tutor@python.org > >http://mail.python.org/mailman/listinfo/tutor > > > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cyresse at gmail.com Sun Feb 27 19:25:44 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sun Feb 27 19:25:47 2005 Subject: [Tutor] Re: How do you share a method (function) among several objects? In-Reply-To: <42220F63.1090606@gmail.com> References: <4221FE3B.9010304@gmail.com> <cvt0kd$v30$1@sea.gmane.org> <42220F63.1090606@gmail.com> Message-ID: <f2ff2d050227102553ae5334@mail.gmail.com> You could a real generic superclass for the classes, it only needs to contain that one function. Personally, I see nothing wrong with chucking one function in a module on it's own, it's whatever works for you. You could create a class for it also, and give each of the other classes an instance of that function's class. Regards, Liam Clarke On Sun, 27 Feb 2005 20:20:19 +0200, Xif <xifxif@gmail.com> wrote: > Javier Ruere wrote: > > > Xif wrote: > > > >> Hello > >> > >> There are several different objects. However, they all share the same > >> function. > >> > >> Since they are not the same or similar, it's not logical to use a > >> common superclass. > >> > >> So I'm asking, what's a good way to allow those objects to share that > >> function? > >> > >> The best solution I've found so far is to put that function in a > >> module, and have all objects import and use it. But I doubt that's a > >> good use-case for modules; writing and importing a module that contains > >> just a single function seems like an abuse. > >> > >> Thanks, > >> Xif > > > > > > Could you give an example? > > > > Javier > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > +++++++++++++++++++++++++++++++++++++++++++ > > This Mail Was Scanned By Mail-seCure System > > at the Tel-Aviv University CC. > > > Sure, I can describe my particular case. > > It's a program that retrieves / updates Microsoft Excel spreadsheet data. > > There are two major classes: > > 1) an Excel class, that represents of the whole Excel program > 2) a Cells class, that abstracts retrieval and editing of cells. > > Both classes use a function called getCells() as part of their > __getitem__() methods. > > getCells() parses the __getitem__() call arguments, and returns an > iterator over the appropriate cells. > > The difference between the 2 classes is that a Cells instance just > converts the generator into a list and returns it: > > #<code> > return list(getCells(self.sheet, cells)) > #</code> > > while an Excel instance returns the values of the cells: > > #<code> > return [cell.Value for cell in getCells(self.sheet, cells)] > #</code> > > As you can see, both use the getCells() function. > > So my question is, where is the best way to put it so instances of both > classes can use it? > > Xif > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From uselinux34 at yahoo.co.uk Sun Feb 27 19:28:18 2005 From: uselinux34 at yahoo.co.uk (Richard gelling) Date: Sun Feb 27 19:28:30 2005 Subject: [Tutor] sys.argv[1: ] help In-Reply-To: <f2ff2d050227102268a2dd5a@mail.gmail.com> References: <Pine.LNX.4.44.0502251548410.1712-100000@hkn.eecs.berkeley.edu> <4221F944.6080308@yahoo.co.uk> <1109523949.8105.4.camel@fuzzbox.local> <422209AA.409@yahoo.co.uk> <f2ff2d050227102268a2dd5a@mail.gmail.com> Message-ID: <42221142.5020509@yahoo.co.uk> Hi, Yes, I use both Wndows XP and Linux( at work ) . I left that in by mistake I am actually just typing in arg1,py a b c at the windows XP command prompt Sorry for the confusion. Liam Clarke wrote: >Are you using XP still? I've never seen this before - > > >>./arg1.py a b c >> >> > >But anyhoo, I tried out just >'c:\python23\foo.py' >as opposed to >'c:\python23\python foo.py' and >while foo.py will run, it doesn't echo to the console, as on my >machine running a .py file runs it through pythonw.exe - I'd check it >out for your machine, it's probably the same. You'd need to change the >association to python.exe, but that would mean that you always got a >DOS box for every Python script you ran, which is annoying with GUIs. > >Erm, if you don't want to type in python each time, either change the >association or create a batch file called x or a or something that >runs Python and stick it in a directory that's in your PATH system >variable. Only problem with that is passing command line variables.... > >...might just be better to type python.... > >Good Luck, > >Liam Clarke > >On Sun, 27 Feb 2005 17:55:54 +0000, Richard gelling ><uselinux34@yahoo.co.uk> wrote: > > >>Hi, >> >>No What I get if I was to type in >>./arg1.py a b c >> >>All I get is >>[] >> >>If i type at the command prompt >> >>python arg1.py a b c >> >>I get ['a','b','c'] as expected >> >>All the other programs and examples I have typed in work fine just by >>typing in the file name, I don't have to preced the file name with >>python, only this example. I hope this makes it clearer >> >>Richard G. >> >> >>Nick Lunt wrote: >> >> >> >>>Richard, >>> >>>if you try to print sys.argv[1:] when sys.argv only contain sys.argv[0] >>>then you are bound to get an empty list returned, [] . >>> >>>Im not sure I understand the problem you think you've got but here's >>>what happens with sys.argv for me, and it's correct. >>> >>>[argl.py] >>> >>>$ cat argl.py >>>#!/usr/bin/python >>> >>>import sys >>>print sys.argv[1:] >>> >>> >>>./argl.py >>>[] >>> >>>./argl.py a b c >>>['a', 'b', 'c'] >>> >>>Is that what your getting ? >>> >>> >>> >>> >>> >>> >>> >>> >>>>Sorry for the late response, I tried all of the the suggestions, >>>>including correcting my typo of print sys[1:] and tried print >>>>sys,argv[1:], this does now work as long as I run 'python test.py fred >>>>joe' it returns all the arguments. If I try just test.py all I get is >>>>'[]' . Is there something wrong with my environmental variables in >>>>Windows XP, I would like to be able to just use the file name rather >>>>than having to type python each time. Any help would be gratefully received. >>>> >>>>Richard G. >>>>_______________________________________________ >>>>Tutor maillist - Tutor@python.org >>>>http://mail.python.org/mailman/listinfo/tutor >>>> >>>> >>>> >>>> >>>_______________________________________________ >>>Tutor maillist - Tutor@python.org >>>http://mail.python.org/mailman/listinfo/tutor >>> >>> >>> >>> >>> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> >> >> > > > > From cyresse at gmail.com Sun Feb 27 19:33:26 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sun Feb 27 19:33:29 2005 Subject: [Tutor] sys.argv[1: ] help In-Reply-To: <42221142.5020509@yahoo.co.uk> References: <Pine.LNX.4.44.0502251548410.1712-100000@hkn.eecs.berkeley.edu> <4221F944.6080308@yahoo.co.uk> <1109523949.8105.4.camel@fuzzbox.local> <422209AA.409@yahoo.co.uk> <f2ff2d050227102268a2dd5a@mail.gmail.com> <42221142.5020509@yahoo.co.uk> Message-ID: <f2ff2d05022710338924b87@mail.gmail.com> Yeah, right click on a .py and check if it's associated with pythonw or python.exe GL, Liam Clarke On Sun, 27 Feb 2005 18:28:18 +0000, Richard gelling <uselinux34@yahoo.co.uk> wrote: > Hi, > Yes, I use both Wndows XP and Linux( at work ) . I left that in by > mistake I am actually just typing in > > arg1,py a b c > > at the windows XP command prompt > > Sorry for the confusion. > > > Liam Clarke wrote: > > >Are you using XP still? I've never seen this before - > > > > > >>./arg1.py a b c > >> > >> > > > >But anyhoo, I tried out just > >'c:\python23\foo.py' > >as opposed to > >'c:\python23\python foo.py' and > >while foo.py will run, it doesn't echo to the console, as on my > >machine running a .py file runs it through pythonw.exe - I'd check it > >out for your machine, it's probably the same. You'd need to change the > >association to python.exe, but that would mean that you always got a > >DOS box for every Python script you ran, which is annoying with GUIs. > > > >Erm, if you don't want to type in python each time, either change the > >association or create a batch file called x or a or something that > >runs Python and stick it in a directory that's in your PATH system > >variable. Only problem with that is passing command line variables.... > > > >...might just be better to type python.... > > > >Good Luck, > > > >Liam Clarke > > > >On Sun, 27 Feb 2005 17:55:54 +0000, Richard gelling > ><uselinux34@yahoo.co.uk> wrote: > > > > > >>Hi, > >> > >>No What I get if I was to type in > >>./arg1.py a b c > >> > >>All I get is > >>[] > >> > >>If i type at the command prompt > >> > >>python arg1.py a b c > >> > >>I get ['a','b','c'] as expected > >> > >>All the other programs and examples I have typed in work fine just by > >>typing in the file name, I don't have to preced the file name with > >>python, only this example. I hope this makes it clearer > >> > >>Richard G. > >> > >> > >>Nick Lunt wrote: > >> > >> > >> > >>>Richard, > >>> > >>>if you try to print sys.argv[1:] when sys.argv only contain sys.argv[0] > >>>then you are bound to get an empty list returned, [] . > >>> > >>>Im not sure I understand the problem you think you've got but here's > >>>what happens with sys.argv for me, and it's correct. > >>> > >>>[argl.py] > >>> > >>>$ cat argl.py > >>>#!/usr/bin/python > >>> > >>>import sys > >>>print sys.argv[1:] > >>> > >>> > >>>./argl.py > >>>[] > >>> > >>>./argl.py a b c > >>>['a', 'b', 'c'] > >>> > >>>Is that what your getting ? > >>> > >>> > >>> > >>> > >>> > >>> > >>> > >>> > >>>>Sorry for the late response, I tried all of the the suggestions, > >>>>including correcting my typo of print sys[1:] and tried print > >>>>sys,argv[1:], this does now work as long as I run 'python test.py fred > >>>>joe' it returns all the arguments. If I try just test.py all I get is > >>>>'[]' . Is there something wrong with my environmental variables in > >>>>Windows XP, I would like to be able to just use the file name rather > >>>>than having to type python each time. Any help would be gratefully received. > >>>> > >>>>Richard G. > >>>>_______________________________________________ > >>>>Tutor maillist - Tutor@python.org > >>>>http://mail.python.org/mailman/listinfo/tutor > >>>> > >>>> > >>>> > >>>> > >>>_______________________________________________ > >>>Tutor maillist - Tutor@python.org > >>>http://mail.python.org/mailman/listinfo/tutor > >>> > >>> > >>> > >>> > >>> > >>_______________________________________________ > >>Tutor maillist - Tutor@python.org > >>http://mail.python.org/mailman/listinfo/tutor > >> > >> > >> > > > > > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From pierre.barbier at cirad.fr Sun Feb 27 19:42:33 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Sun Feb 27 19:40:51 2005 Subject: [Tutor] Re: How do you share a method (function) among several objects? In-Reply-To: <42220F63.1090606@gmail.com> References: <4221FE3B.9010304@gmail.com> <cvt0kd$v30$1@sea.gmane.org> <42220F63.1090606@gmail.com> Message-ID: <42221499.6070508@cirad.fr> Well, for me, the more logical answer is : multi-inheritance ! If part of your class is the same, (same semantic, same implementation), then you want to have a base class for that. If you dislike this kindof inheritance, then your function should be an external one. Even more because it's 'just' an implementation function. The user don't need it as a method ... So why bother add it to your object ? Pierre Xif a ?crit : > Javier Ruere wrote: > >> Xif wrote: >> >>> Hello >>> >>> There are several different objects. However, they all share the same >>> function. >>> >>> Since they are not the same or similar, it's not logical to use a >>> common superclass. >>> >>> So I'm asking, what's a good way to allow those objects to share that >>> function? >>> >>> The best solution I've found so far is to put that function in a >>> module, and have all objects import and use it. But I doubt that's a >>> good use-case for modules; writing and importing a module that contains >>> just a single function seems like an abuse. >>> >>> Thanks, >>> Xif >> >> >> >> Could you give an example? >> >> Javier >> >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> +++++++++++++++++++++++++++++++++++++++++++ >> This Mail Was Scanned By Mail-seCure System >> at the Tel-Aviv University CC. >> > Sure, I can describe my particular case. > > It's a program that retrieves / updates Microsoft Excel spreadsheet data. > > There are two major classes: > > 1) an Excel class, that represents of the whole Excel program > 2) a Cells class, that abstracts retrieval and editing of cells. > > Both classes use a function called getCells() as part of their > __getitem__() methods. > > getCells() parses the __getitem__() call arguments, and returns an > iterator over the appropriate cells. > > The difference between the 2 classes is that a Cells instance just > converts the generator into a list and returns it: > > #<code> > return list(getCells(self.sheet, cells)) > #</code> > > while an Excel instance returns the values of the cells: > > #<code> > return [cell.Value for cell in getCells(self.sheet, cells)] > #</code> > > As you can see, both use the getCells() function. > > So my question is, where is the best way to put it so instances of both > classes can use it? > > Xif > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 From uselinux34 at yahoo.co.uk Sun Feb 27 19:41:19 2005 From: uselinux34 at yahoo.co.uk (Richard gelling) Date: Sun Feb 27 19:41:30 2005 Subject: [Tutor] sys.argv[1: ] help In-Reply-To: <f2ff2d05022710338924b87@mail.gmail.com> References: <Pine.LNX.4.44.0502251548410.1712-100000@hkn.eecs.berkeley.edu> <4221F944.6080308@yahoo.co.uk> <1109523949.8105.4.camel@fuzzbox.local> <422209AA.409@yahoo.co.uk> <f2ff2d050227102268a2dd5a@mail.gmail.com> <42221142.5020509@yahoo.co.uk> <f2ff2d05022710338924b87@mail.gmail.com> Message-ID: <4222144F.6020308@yahoo.co.uk> Hi, It is actually associated with just 'python', changed it to associate with 'pythonw' and I got nothing on the same example not even the [], so I am assuming that 'python' is the correct one? Liam Clarke wrote: >Yeah, right click on a .py and check if it's associated with pythonw >or python.exe > >GL, > >Liam Clarke > > >On Sun, 27 Feb 2005 18:28:18 +0000, Richard gelling ><uselinux34@yahoo.co.uk> wrote: > > >>Hi, >>Yes, I use both Wndows XP and Linux( at work ) . I left that in by >>mistake I am actually just typing in >> >>arg1,py a b c >> >>at the windows XP command prompt >> >>Sorry for the confusion. >> >> >>Liam Clarke wrote: >> >> >> >>>Are you using XP still? I've never seen this before - >>> >>> >>> >>> >>>>./arg1.py a b c >>>> >>>> >>>> >>>> >>>But anyhoo, I tried out just >>>'c:\python23\foo.py' >>>as opposed to >>>'c:\python23\python foo.py' and >>>while foo.py will run, it doesn't echo to the console, as on my >>>machine running a .py file runs it through pythonw.exe - I'd check it >>>out for your machine, it's probably the same. You'd need to change the >>>association to python.exe, but that would mean that you always got a >>>DOS box for every Python script you ran, which is annoying with GUIs. >>> >>>Erm, if you don't want to type in python each time, either change the >>>association or create a batch file called x or a or something that >>>runs Python and stick it in a directory that's in your PATH system >>>variable. Only problem with that is passing command line variables.... >>> >>>...might just be better to type python.... >>> >>>Good Luck, >>> >>>Liam Clarke >>> >>>On Sun, 27 Feb 2005 17:55:54 +0000, Richard gelling >>><uselinux34@yahoo.co.uk> wrote: >>> >>> >>> >>> >>>>Hi, >>>> >>>>No What I get if I was to type in >>>>./arg1.py a b c >>>> >>>>All I get is >>>>[] >>>> >>>>If i type at the command prompt >>>> >>>>python arg1.py a b c >>>> >>>>I get ['a','b','c'] as expected >>>> >>>>All the other programs and examples I have typed in work fine just by >>>>typing in the file name, I don't have to preced the file name with >>>>python, only this example. I hope this makes it clearer >>>> >>>>Richard G. >>>> >>>> >>>>Nick Lunt wrote: >>>> >>>> >>>> >>>> >>>> >>>>>Richard, >>>>> >>>>>if you try to print sys.argv[1:] when sys.argv only contain sys.argv[0] >>>>>then you are bound to get an empty list returned, [] . >>>>> >>>>>Im not sure I understand the problem you think you've got but here's >>>>>what happens with sys.argv for me, and it's correct. >>>>> >>>>>[argl.py] >>>>> >>>>>$ cat argl.py >>>>>#!/usr/bin/python >>>>> >>>>>import sys >>>>>print sys.argv[1:] >>>>> >>>>> >>>>>./argl.py >>>>>[] >>>>> >>>>>./argl.py a b c >>>>>['a', 'b', 'c'] >>>>> >>>>>Is that what your getting ? >>>>> >>>>> >>>>> >>>>> >>>>> >>>>> >>>>> >>>>> >>>>> >>>>> >>>>>>Sorry for the late response, I tried all of the the suggestions, >>>>>>including correcting my typo of print sys[1:] and tried print >>>>>>sys,argv[1:], this does now work as long as I run 'python test.py fred >>>>>>joe' it returns all the arguments. If I try just test.py all I get is >>>>>>'[]' . Is there something wrong with my environmental variables in >>>>>>Windows XP, I would like to be able to just use the file name rather >>>>>>than having to type python each time. Any help would be gratefully received. >>>>>> >>>>>>Richard G. >>>>>>_______________________________________________ >>>>>>Tutor maillist - Tutor@python.org >>>>>>http://mail.python.org/mailman/listinfo/tutor >>>>>> >>>>>> >>>>>> >>>>>> >>>>>> >>>>>> >>>>>_______________________________________________ >>>>>Tutor maillist - Tutor@python.org >>>>>http://mail.python.org/mailman/listinfo/tutor >>>>> >>>>> >>>>> >>>>> >>>>> >>>>> >>>>> >>>>_______________________________________________ >>>>Tutor maillist - Tutor@python.org >>>>http://mail.python.org/mailman/listinfo/tutor >>>> >>>> >>>> >>>> >>>> >>> >>> >>> >>> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> >> >> > > > > From uselinux34 at yahoo.co.uk Sun Feb 27 19:57:30 2005 From: uselinux34 at yahoo.co.uk (Richard gelling) Date: Sun Feb 27 19:57:35 2005 Subject: [Tutor] sys.argv[1: ] help In-Reply-To: <f2ff2d05022710338924b87@mail.gmail.com> References: <Pine.LNX.4.44.0502251548410.1712-100000@hkn.eecs.berkeley.edu> <4221F944.6080308@yahoo.co.uk> <1109523949.8105.4.camel@fuzzbox.local> <422209AA.409@yahoo.co.uk> <f2ff2d050227102268a2dd5a@mail.gmail.com> <42221142.5020509@yahoo.co.uk> <f2ff2d05022710338924b87@mail.gmail.com> Message-ID: <4222181A.90403@yahoo.co.uk> Hi, It is actually associated with just 'python', changed it to associate with 'pythonw' and I got nothing on the same example not even the [], so I am assuming that 'python' is the correct one? Liam Clarke wrote: >Yeah, right click on a .py and check if it's associated with pythonw >or python.exe > >GL, > >Liam Clarke > > >On Sun, 27 Feb 2005 18:28:18 +0000, Richard gelling ><uselinux34@yahoo.co.uk> wrote: > > >>Hi, >>Yes, I use both Wndows XP and Linux( at work ) . I left that in by >>mistake I am actually just typing in >> >>arg1,py a b c >> >>at the windows XP command prompt >> >>Sorry for the confusion. >> >> >>Liam Clarke wrote: >> >> >> >>>Are you using XP still? I've never seen this before - >>> >>> >>> >>> >>>>./arg1.py a b c >>>> >>>> >>>> >>>> >>>But anyhoo, I tried out just >>>'c:\python23\foo.py' >>>as opposed to >>>'c:\python23\python foo.py' and >>>while foo.py will run, it doesn't echo to the console, as on my >>>machine running a .py file runs it through pythonw.exe - I'd check it >>>out for your machine, it's probably the same. You'd need to change the >>>association to python.exe, but that would mean that you always got a >>>DOS box for every Python script you ran, which is annoying with GUIs. >>> >>>Erm, if you don't want to type in python each time, either change the >>>association or create a batch file called x or a or something that >>>runs Python and stick it in a directory that's in your PATH system >>>variable. Only problem with that is passing command line variables.... >>> >>>...might just be better to type python.... >>> >>>Good Luck, >>> >>>Liam Clarke >>> >>>On Sun, 27 Feb 2005 17:55:54 +0000, Richard gelling >>><uselinux34@yahoo.co.uk> wrote: >>> >>> >>> >>> >>>>Hi, >>>> >>>>No What I get if I was to type in >>>>./arg1.py a b c >>>> >>>>All I get is >>>>[] >>>> >>>>If i type at the command prompt >>>> >>>>python arg1.py a b c >>>> >>>>I get ['a','b','c'] as expected >>>> >>>>All the other programs and examples I have typed in work fine just by >>>>typing in the file name, I don't have to preced the file name with >>>>python, only this example. I hope this makes it clearer >>>> >>>>Richard G. >>>> >>>> >>>>Nick Lunt wrote: >>>> >>>> >>>> >>>> >>>> >>>>>Richard, >>>>> >>>>>if you try to print sys.argv[1:] when sys.argv only contain sys.argv[0] >>>>>then you are bound to get an empty list returned, [] . >>>>> >>>>>Im not sure I understand the problem you think you've got but here's >>>>>what happens with sys.argv for me, and it's correct. >>>>> >>>>>[argl.py] >>>>> >>>>>$ cat argl.py >>>>>#!/usr/bin/python >>>>> >>>>>import sys >>>>>print sys.argv[1:] >>>>> >>>>> >>>>>./argl.py >>>>>[] >>>>> >>>>>./argl.py a b c >>>>>['a', 'b', 'c'] >>>>> >>>>>Is that what your getting ? >>>>> >>>>> >>>>> >>>>> >>>>> >>>>> >>>>> >>>>> >>>>> >>>>> >>>>>>Sorry for the late response, I tried all of the the suggestions, >>>>>>including correcting my typo of print sys[1:] and tried print >>>>>>sys,argv[1:], this does now work as long as I run 'python test.py fred >>>>>>joe' it returns all the arguments. If I try just test.py all I get is >>>>>>'[]' . Is there something wrong with my environmental variables in >>>>>>Windows XP, I would like to be able to just use the file name rather >>>>>>than having to type python each time. Any help would be gratefully received. >>>>>> >>>>>>Richard G. >>>>>>_______________________________________________ >>>>>>Tutor maillist - Tutor@python.org >>>>>>http://mail.python.org/mailman/listinfo/tutor >>>>>> >>>>>> >>>>>> >>>>>> >>>>>> >>>>>> >>>>>_______________________________________________ >>>>>Tutor maillist - Tutor@python.org >>>>>http://mail.python.org/mailman/listinfo/tutor >>>>> >>>>> >>>>> >>>>> >>>>> >>>>> >>>>> >>>>_______________________________________________ >>>>Tutor maillist - Tutor@python.org >>>>http://mail.python.org/mailman/listinfo/tutor >>>> >>>> >>>> >>>> >>>> >>> >>> >>> >>> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> >> >> > > > > From xifxif at gmail.com Sun Feb 27 19:58:09 2005 From: xifxif at gmail.com (Xif) Date: Sun Feb 27 19:58:30 2005 Subject: [Tutor] Re: How do you share a method (function) among several objects? In-Reply-To: <42221499.6070508@cirad.fr> References: <4221FE3B.9010304@gmail.com> <cvt0kd$v30$1@sea.gmane.org> <42220F63.1090606@gmail.com> <42221499.6070508@cirad.fr> Message-ID: <42221841.8010608@gmail.com> Ok, so keeping getCells() as an external function makes sense. But where exactly do you recommend I'd put it? In a seperate module, like I currently do, even though it's going to be the only piece of code contained inside that module? Xif Pierre Barbier de Reuille wrote: > Well, for me, the more logical answer is : multi-inheritance ! > If part of your class is the same, (same semantic, same > implementation), then you want to have a base class for that. > > If you dislike this kindof inheritance, then your function should be > an external one. Even more because it's 'just' an implementation > function. The user don't need it as a method ... So why bother add it > to your object ? > > Pierre > > Xif a ?crit : > >> Javier Ruere wrote: >> >>> Xif wrote: >>> >>>> Hello >>>> >>>> There are several different objects. However, they all share the same >>>> function. >>>> >>>> Since they are not the same or similar, it's not logical to use a >>>> common superclass. >>>> >>>> So I'm asking, what's a good way to allow those objects to share that >>>> function? >>>> >>>> The best solution I've found so far is to put that function in a >>>> module, and have all objects import and use it. But I doubt that's a >>>> good use-case for modules; writing and importing a module that >>>> contains >>>> just a single function seems like an abuse. >>>> >>>> Thanks, >>>> Xif >>> >>> >>> >>> >>> Could you give an example? >>> >>> Javier >>> >>> _______________________________________________ >>> Tutor maillist - Tutor@python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> +++++++++++++++++++++++++++++++++++++++++++ >>> This Mail Was Scanned By Mail-seCure System >>> at the Tel-Aviv University CC. >>> >> Sure, I can describe my particular case. >> >> It's a program that retrieves / updates Microsoft Excel spreadsheet >> data. >> >> There are two major classes: >> >> 1) an Excel class, that represents of the whole Excel program >> 2) a Cells class, that abstracts retrieval and editing of cells. >> >> Both classes use a function called getCells() as part of their >> __getitem__() methods. >> >> getCells() parses the __getitem__() call arguments, and returns an >> iterator over the appropriate cells. >> >> The difference between the 2 classes is that a Cells instance just >> converts the generator into a list and returns it: >> >> #<code> >> return list(getCells(self.sheet, cells)) >> #</code> >> >> while an Excel instance returns the values of the cells: >> >> #<code> >> return [cell.Value for cell in getCells(self.sheet, cells)] >> #</code> >> >> As you can see, both use the getCells() function. >> >> So my question is, where is the best way to put it so instances of >> both classes can use it? >> >> Xif >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> > From mark.kels at gmail.com Sun Feb 27 20:14:54 2005 From: mark.kels at gmail.com (Mark Kels) Date: Sun Feb 27 20:14:57 2005 Subject: [Tutor] 3 questions for my port scanner project In-Reply-To: <00b701c51ce5$6bf39060$a6388651@xp> References: <c225925305022605124e9cdc0a@mail.gmail.com> <00b701c51ce5$6bf39060$a6388651@xp> Message-ID: <c225925305022711141237c3d@mail.gmail.com> On Sun, 27 Feb 2005 16:00:12 -0000, Alan Gauld <alan.gauld@freenet.co.uk> wrote: > One option: > Use a set up gif images and update the image periodically > OR > Use a canvas and redraw a rectangle slightly larger every > time through the scanning loop. Thats think this is the easy part... The hard part is to make the bar move "with" the program (so every port it finishes the bar will slightly move, which depends on the total number of ports to scan...). > The best way is to have the loop running in a seperate thread > to the GUI and checking a flag on each iteration. Then you can > have a stop button on the GUI that sets the flag. > Its generally a bad idea in a GUI to have long running processes > within an event handler, better to put them in a separate thread. > Unfortunately this is a lesson that Microsoft's programmers don't > appear to have learned yet! I knew I will have to learn threads some day... Are they hard ? Can you give me some good and simple tutorials ? (I found some, but they look scary) > Alan G. -- 1. The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners. 2. Unix is user friendly - it's just picky about it's friends. 3. Documentation is like sex: when it is good, it is very, very good. And when it is bad, it is better than nothing. - Dick Brandon From kabads at gmail.com Sun Feb 27 20:32:27 2005 From: kabads at gmail.com (Adam Cripps) Date: Sun Feb 27 20:32:30 2005 Subject: [Tutor] Recursive Tkinter buttons In-Reply-To: <00be01c51ce6$4ef5e200$a6388651@xp> References: <c7ff3855050224141925d5dc88@mail.gmail.com> <421E8CD5.3080708@tds.net> <c7ff3855050224225377dd598b@mail.gmail.com> <f2ff2d05022423194d795e69@mail.gmail.com> <20050225122118.4fe893ad.klappnase@freenet.de> <c7ff3855050226114835e7f4ad@mail.gmail.com> <00be01c51ce6$4ef5e200$a6388651@xp> Message-ID: <c7ff3855050227113269bdbdc@mail.gmail.com> On Sun, 27 Feb 2005 16:06:32 -0000, Alan Gauld <alan.gauld@freenet.co.uk> wrote: > > - however, when I click the button, I want self.showButton to know > > which one of them was pressed. I've seen in other gui programming > the > > idea of an id or identifier - I can't see that here. Ideally, I > would > > like to know the value of i in self.showButtons - but when I use > > self.showButtons(i) showButtons gets called straight at run time. > > The easy way to do this is to use a defrault parameter in a lambda: > > submittext = ">>> " > for i in range (1, 11): > b = Button(text=submittext, command = lambda n=i: > self.showButton(n)) > b.rid(column=4, row=i+4) > submitlist.append(b) > > Notice the button creation line now uses a lambda with default > parameter set to i. That lambda calls your method but now passes > in the value of i for that button. (You need to modify your method > to accept that value of course!) > > HTH, > > Alan G > Author of the Learn to Program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld Yay! Thanks for the tips Michael/Alan - works a treat, although I must admit, I'm not sure what Lambda does. Adam -- http://www.monkeez.org PGP key: 0x7111B833 From godoy at ieee.org Sun Feb 27 20:22:33 2005 From: godoy at ieee.org (Jorge Godoy) Date: Sun Feb 27 20:34:56 2005 Subject: [Tutor] Re: How do you share a method (function) among several objects? References: <4221FE3B.9010304@gmail.com> <cvt0kd$v30$1@sea.gmane.org> <42220F63.1090606@gmail.com> <42221499.6070508@cirad.fr> <42221841.8010608@gmail.com> Message-ID: <87wtstzu2u.fsf@jupiter.g2ctech> Xif <xifxif@gmail.com> writes: > Ok, so keeping getCells() as an external function makes sense. > > But where exactly do you recommend I'd put it? > > In a seperate module, like I currently do, even though it's going to be the > only piece of code contained inside that module? I don't see any problem with this. If this is all you need to share, why not? Be seeing you, Godoy. From pierre.barbier at cirad.fr Sun Feb 27 20:39:41 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Sun Feb 27 20:38:01 2005 Subject: [Tutor] Re: How do you share a method (function) among several objects? In-Reply-To: <42221841.8010608@gmail.com> References: <4221FE3B.9010304@gmail.com> <cvt0kd$v30$1@sea.gmane.org> <42220F63.1090606@gmail.com> <42221499.6070508@cirad.fr> <42221841.8010608@gmail.com> Message-ID: <422221FD.5010802@cirad.fr> The position to put it is a design choice and there is no single best solution. What I'd do is to gather all the small "homeless" functions in a single separate module. And if they come to be too numerous, I'll sort them in some modules, ... But that's because I don't like having a single function in a module ^_^ Of course, if this is a complex function, that can make sense ... I hope I helped and didn't make things worst ;) Pierre Xif a ?crit : > Ok, so keeping getCells() as an external function makes sense. > > But where exactly do you recommend I'd put it? > > In a seperate module, like I currently do, even though it's going to be > the only piece of code contained inside that module? > > Xif > > Pierre Barbier de Reuille wrote: > >> Well, for me, the more logical answer is : multi-inheritance ! >> If part of your class is the same, (same semantic, same >> implementation), then you want to have a base class for that. >> >> If you dislike this kindof inheritance, then your function should be >> an external one. Even more because it's 'just' an implementation >> function. The user don't need it as a method ... So why bother add it >> to your object ? >> >> Pierre >> >> Xif a ?crit : >> >>> Javier Ruere wrote: >>> >>>> Xif wrote: >>>> >>>>> Hello >>>>> >>>>> There are several different objects. However, they all share the same >>>>> function. >>>>> >>>>> Since they are not the same or similar, it's not logical to use a >>>>> common superclass. >>>>> >>>>> So I'm asking, what's a good way to allow those objects to share that >>>>> function? >>>>> >>>>> The best solution I've found so far is to put that function in a >>>>> module, and have all objects import and use it. But I doubt that's a >>>>> good use-case for modules; writing and importing a module that >>>>> contains >>>>> just a single function seems like an abuse. >>>>> >>>>> Thanks, >>>>> Xif >>>> >>>> >>>> >>>> >>>> >>>> Could you give an example? >>>> >>>> Javier >>>> >>>> _______________________________________________ >>>> Tutor maillist - Tutor@python.org >>>> http://mail.python.org/mailman/listinfo/tutor >>>> >>>> +++++++++++++++++++++++++++++++++++++++++++ >>>> This Mail Was Scanned By Mail-seCure System >>>> at the Tel-Aviv University CC. >>>> >>> Sure, I can describe my particular case. >>> >>> It's a program that retrieves / updates Microsoft Excel spreadsheet >>> data. >>> >>> There are two major classes: >>> >>> 1) an Excel class, that represents of the whole Excel program >>> 2) a Cells class, that abstracts retrieval and editing of cells. >>> >>> Both classes use a function called getCells() as part of their >>> __getitem__() methods. >>> >>> getCells() parses the __getitem__() call arguments, and returns an >>> iterator over the appropriate cells. >>> >>> The difference between the 2 classes is that a Cells instance just >>> converts the generator into a list and returns it: >>> >>> #<code> >>> return list(getCells(self.sheet, cells)) >>> #</code> >>> >>> while an Excel instance returns the values of the cells: >>> >>> #<code> >>> return [cell.Value for cell in getCells(self.sheet, cells)] >>> #</code> >>> >>> As you can see, both use the getCells() function. >>> >>> So my question is, where is the best way to put it so instances of >>> both classes can use it? >>> >>> Xif >>> _______________________________________________ >>> Tutor maillist - Tutor@python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >> > -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 From cyresse at gmail.com Sun Feb 27 22:40:06 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sun Feb 27 22:40:10 2005 Subject: [Tutor] sys.argv[1: ] help In-Reply-To: <4222181A.90403@yahoo.co.uk> References: <Pine.LNX.4.44.0502251548410.1712-100000@hkn.eecs.berkeley.edu> <4221F944.6080308@yahoo.co.uk> <1109523949.8105.4.camel@fuzzbox.local> <422209AA.409@yahoo.co.uk> <f2ff2d050227102268a2dd5a@mail.gmail.com> <42221142.5020509@yahoo.co.uk> <f2ff2d05022710338924b87@mail.gmail.com> <4222181A.90403@yahoo.co.uk> Message-ID: <f2ff2d0502271340768ef8c4@mail.gmail.com> Yeah, python.exe is the right one... bizarre... I'll have a poke at it when I get home from work. Sorry I haven't been more helpful. Cheers, Liam Clarke On Sun, 27 Feb 2005 18:57:30 +0000, Richard gelling <uselinux34@yahoo.co.uk> wrote: > > Hi, > > It is actually associated with just 'python', changed it to associate > with 'pythonw' and I got nothing on the same example not even the [], so > I am assuming that 'python' is the correct one? > > Liam Clarke wrote: > > >Yeah, right click on a .py and check if it's associated with pythonw > >or python.exe > > > >GL, > > > >Liam Clarke > > > > > >On Sun, 27 Feb 2005 18:28:18 +0000, Richard gelling > ><uselinux34@yahoo.co.uk> wrote: > > > > > >>Hi, > >>Yes, I use both Wndows XP and Linux( at work ) . I left that in by > >>mistake I am actually just typing in > >> > >>arg1,py a b c > >> > >>at the windows XP command prompt > >> > >>Sorry for the confusion. > >> > >> > >>Liam Clarke wrote: > >> > >> > >> > >>>Are you using XP still? I've never seen this before - > >>> > >>> > >>> > >>> > >>>>./arg1.py a b c > >>>> > >>>> > >>>> > >>>> > >>>But anyhoo, I tried out just > >>>'c:\python23\foo.py' > >>>as opposed to > >>>'c:\python23\python foo.py' and > >>>while foo.py will run, it doesn't echo to the console, as on my > >>>machine running a .py file runs it through pythonw.exe - I'd check it > >>>out for your machine, it's probably the same. You'd need to change the > >>>association to python.exe, but that would mean that you always got a > >>>DOS box for every Python script you ran, which is annoying with GUIs. > >>> > >>>Erm, if you don't want to type in python each time, either change the > >>>association or create a batch file called x or a or something that > >>>runs Python and stick it in a directory that's in your PATH system > >>>variable. Only problem with that is passing command line variables.... > >>> > >>>...might just be better to type python.... > >>> > >>>Good Luck, > >>> > >>>Liam Clarke > >>> > >>>On Sun, 27 Feb 2005 17:55:54 +0000, Richard gelling > >>><uselinux34@yahoo.co.uk> wrote: > >>> > >>> > >>> > >>> > >>>>Hi, > >>>> > >>>>No What I get if I was to type in > >>>>./arg1.py a b c > >>>> > >>>>All I get is > >>>>[] > >>>> > >>>>If i type at the command prompt > >>>> > >>>>python arg1.py a b c > >>>> > >>>>I get ['a','b','c'] as expected > >>>> > >>>>All the other programs and examples I have typed in work fine just by > >>>>typing in the file name, I don't have to preced the file name with > >>>>python, only this example. I hope this makes it clearer > >>>> > >>>>Richard G. > >>>> > >>>> > >>>>Nick Lunt wrote: > >>>> > >>>> > >>>> > >>>> > >>>> > >>>>>Richard, > >>>>> > >>>>>if you try to print sys.argv[1:] when sys.argv only contain sys.argv[0] > >>>>>then you are bound to get an empty list returned, [] . > >>>>> > >>>>>Im not sure I understand the problem you think you've got but here's > >>>>>what happens with sys.argv for me, and it's correct. > >>>>> > >>>>>[argl.py] > >>>>> > >>>>>$ cat argl.py > >>>>>#!/usr/bin/python > >>>>> > >>>>>import sys > >>>>>print sys.argv[1:] > >>>>> > >>>>> > >>>>>./argl.py > >>>>>[] > >>>>> > >>>>>./argl.py a b c > >>>>>['a', 'b', 'c'] > >>>>> > >>>>>Is that what your getting ? > >>>>> > >>>>> > >>>>> > >>>>> > >>>>> > >>>>> > >>>>> > >>>>> > >>>>> > >>>>> > >>>>>>Sorry for the late response, I tried all of the the suggestions, > >>>>>>including correcting my typo of print sys[1:] and tried print > >>>>>>sys,argv[1:], this does now work as long as I run 'python test.py fred > >>>>>>joe' it returns all the arguments. If I try just test.py all I get is > >>>>>>'[]' . Is there something wrong with my environmental variables in > >>>>>>Windows XP, I would like to be able to just use the file name rather > >>>>>>than having to type python each time. Any help would be gratefully received. > >>>>>> > >>>>>>Richard G. > >>>>>>_______________________________________________ > >>>>>>Tutor maillist - Tutor@python.org > >>>>>>http://mail.python.org/mailman/listinfo/tutor > >>>>>> > >>>>>> > >>>>>> > >>>>>> > >>>>>> > >>>>>> > >>>>>_______________________________________________ > >>>>>Tutor maillist - Tutor@python.org > >>>>>http://mail.python.org/mailman/listinfo/tutor > >>>>> > >>>>> > >>>>> > >>>>> > >>>>> > >>>>> > >>>>> > >>>>_______________________________________________ > >>>>Tutor maillist - Tutor@python.org > >>>>http://mail.python.org/mailman/listinfo/tutor > >>>> > >>>> > >>>> > >>>> > >>>> > >>> > >>> > >>> > >>> > >>_______________________________________________ > >>Tutor maillist - Tutor@python.org > >>http://mail.python.org/mailman/listinfo/tutor > >> > >> > >> > > > > > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From jeffshannon at gmail.com Sun Feb 27 22:56:24 2005 From: jeffshannon at gmail.com (Jeff Shannon) Date: Sun Feb 27 22:56:28 2005 Subject: [Tutor] SubClassing In-Reply-To: <421ED9BF.9010005@adinet.com.uy> References: <421EC0EB.9070301@adinet.com.uy> <421EC994.6000407@speakeasy.net> <421ED9BF.9010005@adinet.com.uy> Message-ID: <5d0204a10502271356649674db@mail.gmail.com> On Fri, 25 Feb 2005 05:54:39 -0200, Ismael Garrido <ismaelgf@adinet.com.uy> wrote: > def __init__(self, this, that, new): > Parent.__init__(self, this, that) #note self > self.new = new If the paren's init t has a lot of possible arguments, it may be easier to do things this way: class Child(Parent): def __init__(self, new, *args, **kwargs): Parent.__init__(self, *args, **kwargs) self.new = new This way, the Child class doesn't need to know or care about what parameters get passed on to Parent; it uses the ones it needs, and passes all the rest on. Jeff Shannon From cyresse at gmail.com Sun Feb 27 23:04:13 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sun Feb 27 23:04:16 2005 Subject: [Tutor] Re: How do you share a method (function) among several objects? In-Reply-To: <422221FD.5010802@cirad.fr> References: <4221FE3B.9010304@gmail.com> <cvt0kd$v30$1@sea.gmane.org> <42220F63.1090606@gmail.com> <42221499.6070508@cirad.fr> <42221841.8010608@gmail.com> <422221FD.5010802@cirad.fr> Message-ID: <f2ff2d05022714043f3048c3@mail.gmail.com> yeah, I do the same thing for those useful functions that don't really fit anywhere else. I call it helperFunctions or something, so when your're importing helperFunctions and calling helperFunctions.getCells() it's pretty obvious what's happening. Liam Clarke On Sun, 27 Feb 2005 20:39:41 +0100, Pierre Barbier de Reuille <pierre.barbier@cirad.fr> wrote: > The position to put it is a design choice and there is no single best > solution. What I'd do is to gather all the small "homeless" functions in > a single separate module. And if they come to be too numerous, I'll sort > them in some modules, ... > > But that's because I don't like having a single function in a module ^_^ > Of course, if this is a complex function, that can make sense ... > > I hope I helped and didn't make things worst ;) > > Pierre > > Xif a ?crit : > > Ok, so keeping getCells() as an external function makes sense. > > > > But where exactly do you recommend I'd put it? > > > > In a seperate module, like I currently do, even though it's going to be > > the only piece of code contained inside that module? > > > > Xif > > > > Pierre Barbier de Reuille wrote: > > > >> Well, for me, the more logical answer is : multi-inheritance ! > >> If part of your class is the same, (same semantic, same > >> implementation), then you want to have a base class for that. > >> > >> If you dislike this kindof inheritance, then your function should be > >> an external one. Even more because it's 'just' an implementation > >> function. The user don't need it as a method ... So why bother add it > >> to your object ? > >> > >> Pierre > >> > >> Xif a ?crit : > >> > >>> Javier Ruere wrote: > >>> > >>>> Xif wrote: > >>>> > >>>>> Hello > >>>>> > >>>>> There are several different objects. However, they all share the same > >>>>> function. > >>>>> > >>>>> Since they are not the same or similar, it's not logical to use a > >>>>> common superclass. > >>>>> > >>>>> So I'm asking, what's a good way to allow those objects to share that > >>>>> function? > >>>>> > >>>>> The best solution I've found so far is to put that function in a > >>>>> module, and have all objects import and use it. But I doubt that's a > >>>>> good use-case for modules; writing and importing a module that > >>>>> contains > >>>>> just a single function seems like an abuse. > >>>>> > >>>>> Thanks, > >>>>> Xif > >>>> > >>>> > >>>> > >>>> > >>>> > >>>> Could you give an example? > >>>> > >>>> Javier > >>>> > >>>> _______________________________________________ > >>>> Tutor maillist - Tutor@python.org > >>>> http://mail.python.org/mailman/listinfo/tutor > >>>> > >>>> +++++++++++++++++++++++++++++++++++++++++++ > >>>> This Mail Was Scanned By Mail-seCure System > >>>> at the Tel-Aviv University CC. > >>>> > >>> Sure, I can describe my particular case. > >>> > >>> It's a program that retrieves / updates Microsoft Excel spreadsheet > >>> data. > >>> > >>> There are two major classes: > >>> > >>> 1) an Excel class, that represents of the whole Excel program > >>> 2) a Cells class, that abstracts retrieval and editing of cells. > >>> > >>> Both classes use a function called getCells() as part of their > >>> __getitem__() methods. > >>> > >>> getCells() parses the __getitem__() call arguments, and returns an > >>> iterator over the appropriate cells. > >>> > >>> The difference between the 2 classes is that a Cells instance just > >>> converts the generator into a list and returns it: > >>> > >>> #<code> > >>> return list(getCells(self.sheet, cells)) > >>> #</code> > >>> > >>> while an Excel instance returns the values of the cells: > >>> > >>> #<code> > >>> return [cell.Value for cell in getCells(self.sheet, cells)] > >>> #</code> > >>> > >>> As you can see, both use the getCells() function. > >>> > >>> So my question is, where is the best way to put it so instances of > >>> both classes can use it? > >>> > >>> Xif > >>> _______________________________________________ > >>> Tutor maillist - Tutor@python.org > >>> http://mail.python.org/mailman/listinfo/tutor > >>> > >> > > > > -- > Pierre Barbier de Reuille > > INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP > Botanique et Bio-informatique de l'Architecture des Plantes > TA40/PSII, Boulevard de la Lironde > 34398 MONTPELLIER CEDEX 5, France > > tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From gltewalt at yahoo.com Sun Feb 27 23:08:55 2005 From: gltewalt at yahoo.com (Greg T) Date: Sun Feb 27 23:08:58 2005 Subject: [Tutor] Learning python as a thing to do Message-ID: <20050227220855.80947.qmail@web52909.mail.yahoo.com> Hi, I am a Rubyist, but I've decided to learn Python so that when a conversation springs up about the merits of the two languages amd how they compare, I will be well informed. As it stands now, what you usually see is people well versed in one or the other, making generalizations when they dont really know the other language. At any rate, so far Python seems to be a very good language. Not a great language, but still very good. So far, some things I dont care for and have me scratching my head: immutable strings no case statement lack of internal iterators The mixing of functions and methods Some things that I like: -list comprehensions -the indentation scheme (I know alot of people dont like it at first experience, but I do) -'one way to do it' philosophy (I dont have a problem with 'more than one way to do it', but it makes a language easier to learn with a 'one way' philosophy) Question(s): Are there any good books/documents that actually examine the ruby way vs python way? (by someone that knows both languages) The other day I saw a post from a gentleman trying to do a basic prompt and add type of calculator. He wanted to assign the +, or * operator to a variable to use, but I believe he was told you have to use the literal +, or *. Are these operators constanst in Python? If so, is there not a way to send that constant to act apon another variable or variables that refer to numbers? In ruby, you can rerence the * operator operator = :* num1 = 4 num2 = 6 num1.send(operator,num2) which returns 24 Have a nice day :-) __________________________________ Do you Yahoo!? Yahoo! Mail - now with 250MB free storage. Learn more. http://info.mail.yahoo.com/mail_250 From jeffshannon at gmail.com Sun Feb 27 23:12:06 2005 From: jeffshannon at gmail.com (Jeff Shannon) Date: Sun Feb 27 23:12:09 2005 Subject: [Tutor] Re: How do you share a method (function) among several objects? In-Reply-To: <42220F63.1090606@gmail.com> References: <4221FE3B.9010304@gmail.com> <cvt0kd$v30$1@sea.gmane.org> <42220F63.1090606@gmail.com> Message-ID: <5d0204a105022714122ede04db@mail.gmail.com> On Sun, 27 Feb 2005 20:20:19 +0200, Xif <xifxif@gmail.com> wrote: > There are two major classes: > > 1) an Excel class, that represents of the whole Excel program > 2) a Cells class, that abstracts retrieval and editing of cells. > > [...] > > The difference between the 2 classes is that a Cells instance just > converts the generator into a list and returns it: > > #<code> > return list(getCells(self.sheet, cells)) > #</code> > > while an Excel instance returns the values of the cells: > > #<code> > return [cell.Value for cell in getCells(self.sheet, cells)] > #</code> Why not have the Excel class make use of the Cells class? That is, you construct a Cells object with the appropriate parameters, use it to get the list of cells, and then iterate over that list getting values? You could probably find many other places in the Excel class where it could be simplified by delegating to a Cells instance, too... Jeff Shannon From dyoo at hkn.eecs.berkeley.edu Sun Feb 27 23:28:08 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Feb 27 23:28:13 2005 Subject: [Tutor] sys.argv[1: ] help In-Reply-To: <4221F944.6080308@yahoo.co.uk> Message-ID: <Pine.LNX.4.44.0502271359540.1588-100000@hkn.eecs.berkeley.edu> > >(I know I'm being a bit silly about asking about what looks like a > >simple email typo, but computer programming bugs are all-too-often > >about typos. *grin* > > Sorry for the late response, I tried all of the the suggestions, > including correcting my typo of print sys[1:] and tried print > sys,argv[1:], Hi Richard, Please, please copy and paste your code literally whenever you're talking about code. You have another email typo here, when you put a comma instead of a period in: sys,argv[1:] I know that's not what you meant, but I'm really trying to stress the idea that computers are not forgiving of typos. There are actually a large class of programming bugs that are simple typos. Make things easier for us: just copy and paste the code that you're talking about, and we'll be better able to replicate the situation that's on your side. I think there's been a lot of confusion on this thread, so let's backtrack again and make sure we're on the same page. I'll assume for the moment that your program looks like this: ###### import sys print sys.argv[1:] ###### > this does now work as long as I run 'python test.py fred joe' it returns > all the arguments. I expect to see: ### ['fred', 'joe'] ### because sys.argv should contain the list: ['test.py', 'fred', 'joe'] > If I try just test.py all I get is '[]'. Ok, this is also expected. If we give no command line arguments to our program, then we should get back an empty list from sys.argv[1:]. So at the moment, I actually have no clue what problem you're running into. *grin* What exactly are you getting stuck on? > Is there something wrong with my environmental variables in Windows XP, > I would like to be able to just use the file name rather than having to > type python each time. Wait. Ok, I think I understand the question now. I think you are trying to say that if you enter the command: ### C:\> test.py fred joe ### at your Windows command prompt, that Python responds with: ### [] ### Does this sound right? If so, then you are asking a question that's specific to Windows. The Windows command shell has a bug that has bitten folks before: Windows doesn't appear to correctly pass command line arguments to Python programs if we try to call the program directly. A workaround is to create a '.CMD' wrapper for your Python program. Add a file called 'test.cmd' in the same directory as your 'test.py' program with the following content: ### python test.cmd %* ### Once you have this file, try: ### C:\> test fred joe ### at your command line. You may find the discussion underneath: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/366355 useful, as the folks there further discuss this issue. Let's backtrack for a moment again: the reason we were not able to answer your question better was precisely because you were paraphrasing way too much: > ... as I run 'python test.py fred joe' it returns all the arguments. If > I try just test.py all I get is '[]'. If you had shown us exactly what you were entering into the command line, we would have caught the real cause of the problem much earlier. Ok, I'll stop ranting about this now. *grin* Best of wishes to you. From dyoo at hkn.eecs.berkeley.edu Sun Feb 27 23:35:34 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Feb 27 23:35:38 2005 Subject: [Tutor] sys.argv[1: ] help In-Reply-To: <Pine.LNX.4.44.0502271359540.1588-100000@hkn.eecs.berkeley.edu> Message-ID: <Pine.LNX.4.44.0502271433380.1588-100000@hkn.eecs.berkeley.edu> > Add a file called 'test.cmd' in the same directory as your 'test.py' > program with the following content: > > ### > python test.cmd %* > ### Scratch that! *grin* Sorry, meant to write that the test.cmd should contain: ### python test.py %* ### Darn it, but I don't have a Windows box handy to test this. Can someone double check this to make sure I haven't screwed up again? Sorry about that; I should never post anything without testing it first. From dyoo at hkn.eecs.berkeley.edu Mon Feb 28 00:00:41 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Feb 28 00:00:45 2005 Subject: [Tutor] Learning python as a thing to do In-Reply-To: <20050227220855.80947.qmail@web52909.mail.yahoo.com> Message-ID: <Pine.LNX.4.44.0502271435450.1588-100000@hkn.eecs.berkeley.edu> On Sun, 27 Feb 2005, Greg T wrote: > I am a Rubyist, but I've decided to learn Python so that when a > conversation springs up about the merits of the two languages amd how > they compare, I will be well informed. Hi Greg, Welcome aboard! That sounds great; you can help us understand Ruby better when we have questions. *grin* > So far, some things I dont care for and have me scratching my head: Ok, we'll try addressing some of your head-scratching questions: > immutable strings Immutable strings aren't unique to Python: technically, string literals in C are also supposed to be immutable (that's why GCC supports the '-fno-const-strings' flag!) , and they're also immutable in Java. The other thing is that Python follows a model where values are objects, and variable names are just references to values. So when we do something like: ### >>> message = "hello world" >>> anotherMsg = message ### Both 'message' and 'anotherMsg' both refer to a single string value. We can see this using the id() function: ### >>> id(message) 3607272 >>> id(anotherMsg) 3607272 ### So there isn't any string copying going on here. We can simulate mutable strings by turning a string into a list: ### >>> myBuffer = list("hello world") >>> myBuffer[1] = 'a' >>> msg = ''.join(myBuffer) >>> msg 'hallo world' ### > no case statement If you're doing a case analysis based on a single value, then a dispatch table may be able to do what you want. You may find: http://mail.python.org/pipermail/tutor/2004-December/033728.html helpful. > lack of internal iterators I'm not quite sure what you mean by "internal iterators". There is an iterator protocol that objects can support: http://www.python.org/doc/lib/typeiter.html where lists, files, and strings conform to the protocol and can be iterated across with a 'for' loop. > Question(s): > > Are there any good books/documents that actually examine the ruby way vs > python way? (by someone that knows both languages) I haven't seen one yet; if you find one, let us know. I'm actually quite interested in Ruby, since a friend of mine is writing Ruby code that I'll probably have to maintain soon. *grin* > The other day I saw a post from a gentleman trying to do a basic prompt > and add type of calculator. He wanted to assign the +, or * operator to > a variable to use, but I believe he was told you have to use the literal > +, or *. The 'infix' operators aren't first-class in Python. That being said, there are first-class function equivalents in the 'operator' module: http://www.python.org/doc/lib/module-operator.html and these are first class, so it's possible to writing something like this: ### >>> import operator >>> sumOfNumbersUpToTen = reduce(operator.add, range(1, 11)) >>> factorialTen = reduce(operator.mul, range(1, 11)) >>> sumOfNumbersUpToTen 55 >>> factorialTen 3628800 ### > In ruby, you can rerence the * operator > operator = :* > num1 = 4 > num2 = 6 > num1.send(operator,num2) > which returns 24 Ok, I see, so in Ruby, numbers can receive a 'multiply' message. This can happen in Python too, although it's really not quite Pythonic: ### >>> num1 = 4 >>> num1.__mul__(6) 24 ### Numbers in Python do have a fixed list of methods that they respond to: http://www.python.org/doc/ref/numeric-types.html but most Python numeric code will just use infix operators on numbers and avoid an explicit message-passing style. Best of wishes to you! From jeffshannon at gmail.com Mon Feb 28 00:12:21 2005 From: jeffshannon at gmail.com (Jeff Shannon) Date: Mon Feb 28 00:12:26 2005 Subject: [Tutor] sys.argv[1: ] help In-Reply-To: <422209AA.409@yahoo.co.uk> References: <Pine.LNX.4.44.0502251548410.1712-100000@hkn.eecs.berkeley.edu> <4221F944.6080308@yahoo.co.uk> <1109523949.8105.4.camel@fuzzbox.local> <422209AA.409@yahoo.co.uk> Message-ID: <5d0204a105022715123a1e236@mail.gmail.com> On Sun, 27 Feb 2005 17:55:54 +0000, Richard gelling <uselinux34@yahoo.co.uk> wrote: > > No What I get if I was to type in > ./arg1.py a b c > > All I get is > [] It sounds as though the command shell is not passing along the additional parameters. Try opening Windows Explorer, and go to the Folder Options (in the Tools menu, IIRC). Go to the "File Types" tab, find PY (Python File), and click the "Advanced" button. In the resulting dialog, select the "open" action and click "edit", then look at the command line that it's using. You want something that looks like: "C:\Python23\python.exe" "%1" %* The '%*' bit at the end is what I suspect may be missing in your settings. (There's some chance that cmd.exe uses a different set of settings than Windows Explorer does, in which case you'll have to research that independently. I know that you can use the "assoc" command to associate the .py extension with the Python.File filetype, but I'm not sure how to create filetypes or change actions that are taken upon filetypes if it's different from the Explorer settings....) Jeff Shannon From keridee at jayco.net Mon Feb 28 00:27:59 2005 From: keridee at jayco.net (Jacob S.) Date: Mon Feb 28 00:27:32 2005 Subject: [Tutor] How do you share a method (function) among several objects? References: <4221FE3B.9010304@gmail.com> Message-ID: <000801c51d23$ff201280$a35428cf@JSLAPTOP> Is it possible to put all of those objects in their own module, having the function you describe as a module defined function? For example pseudo code.... ### Lib.py ### def function(x): return stuff class C1: def __init__(self): init stuff def funct(self,arg): return function(arg) class C2: def __init__(self): init stuff for this class def clone(self,arg): return function(arg) ###################### Usage of this module could be simple enough. import Lib a = Lib.C1() a.funct("a") b = Lib.C2() b.clone("a") The methods defined funct and clone do the same things. HTH, Jacob > Hello > > There are several different objects. However, they all share the same > function. > > Since they are not the same or similar, it's not logical to use a > common superclass. > > So I'm asking, what's a good way to allow those objects to share that > function? > > The best solution I've found so far is to put that function in a > module, and have all objects import and use it. But I doubt that's a > good use-case for modules; writing and importing a module that contains > just a single function seems like an abuse. > > Thanks, > Xif > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From keridee at jayco.net Mon Feb 28 00:42:50 2005 From: keridee at jayco.net (Jacob S.) Date: Mon Feb 28 00:42:21 2005 Subject: [Tutor] Recursive Tkinter buttons References: <c7ff3855050224141925d5dc88@mail.gmail.com><421E8CD5.3080708@tds.net> <c7ff3855050224225377dd598b@mail.gmail.com><f2ff2d05022423194d795e69@mail.gmail.com><20050225122118.4fe893ad.klappnase@freenet.de><c7ff3855050226114835e7f4ad@mail.gmail.com><00be01c51ce6$4ef5e200$a6388651@xp> <c7ff3855050227113269bdbdc@mail.gmail.com> Message-ID: <001701c51d26$115800f0$a35428cf@JSLAPTOP> > Yay! Thanks for the tips Michael/Alan - works a treat, although I must > admit, I'm not sure what Lambda does. > > Adam Lambda is basically a function without a name that can be used inline. Take for example, this code. def funct(x): return sin(x) is the same as funct = lambda x: sin(x) There seems to be a running debate over whether lambdas are worth the trouble. I believe it's a matter of preference. HTH, Jacob From alan.gauld at freenet.co.uk Mon Feb 28 01:20:38 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Feb 28 01:19:59 2005 Subject: [Tutor] 3 questions for my port scanner project References: <c225925305022605124e9cdc0a@mail.gmail.com> <00b701c51ce5$6bf39060$a6388651@xp> <c225925305022711141237c3d@mail.gmail.com> Message-ID: <00c801c51d2b$55fab4a0$a6388651@xp> > > Use a canvas and redraw a rectangle slightly larger every > > time through the scanning loop. > > Thats think this is the easy part... > The hard part is to make the bar move "with" the program (so every > port it finishes the bar will slightly move, which depends on the > total number of ports to scan...). But since you know the range of ports you can calculate the total number. If you keep a count of how many scanned you can work out the percentage scanned. You then draw a rectangle the same percentage of the total width. After each port scanned recalculate the percentage and redraw the rectangle. Where's the problem? :-) Alan G. From alan.gauld at freenet.co.uk Mon Feb 28 01:53:26 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Feb 28 01:52:36 2005 Subject: [Tutor] Learning python as a thing to do References: <20050227220855.80947.qmail@web52909.mail.yahoo.com> Message-ID: <013101c51d2f$ea15e8e0$a6388651@xp> > I am a Rubyist, but I've decided to learn Python Welcome, could be interesting. I'm a pythonista and have learned Ruby but not used it for anything significant yet. > At any rate, so far Python seems to be a very good > language. Not a great language, but still very good. There is only one great language: Lisp :-) > So far, some things I dont care for... > immutable strings > no case statement Yes, most folks find those concepts pretty strange. Personally I don't miss case statements (see a recent thread) I usually find Pythons stricture means I rethink the design and usually manage to avoid the need (and potential bugs that are inherent in case structures...) but mutable strings would be nice, although potentially dangerous for dictionary keys. > lack of internal iterators NOt sure what you mean by this one, can you expand? > The mixing of functions and methods You mean the fact that Python doesn't insist on everything being an object? That simply reflects that Python can be used in several difreent paradigms. Functional Programming is the biggest "modern" alternative to OOP and support for functions as first class objects supports that style. Ruby can fake it with its top level "invisible" object, but Python just makes that style a natural part of the language. OTOH if you mean the inconsistencies in the use of methods versus functions in the base language (eg files have a close method but an open function) then I agree and Python is slowly removing those with each release. The biggest step being the introduction of strings as objects/methods and another step forward being the new-style classes in v2.x This is one area where Matz learned lessons from Perl/Python when he invented Ruby - the advantage of going second (or third or fourth...) > Question(s): > Are there any good books/documents that actually > examine the ruby way vs python way? (by someone that > knows both languages) NOt that I know of. > The other day I saw a post from a gentleman trying to > do a basic prompt and add type of calculator. > He wanted to assign the +, or * operator to a variable > to use, but I believe he was told you have to use the > literal +, or *. Thats possible using the operator module. > Are these operators constanst in Python? Not really, in that you can override them (__add__, __Sub__, __mul__ etc) and the operator module gives access to the common ones in a generic kind of way. > If so, is there not a way to send that constant to > act apon another variable or variables that refer to > numbers? I didn't see the post but it sounds as if the poster should have been able to do what [s]he wanted. > In ruby, you can rerence the * operator > operator = :* > num1 = 4 > num2 = 6 > num1.send(operator,num2) In Python: import operator num1 = 4 num2 = 6 operator.mul(num1,num2) Alan G. > which returns 24 > > Have a nice day :-) > > > > > __________________________________ > Do you Yahoo!? > Yahoo! Mail - now with 250MB free storage. Learn more. > http://info.mail.yahoo.com/mail_250 > > From linux236r4 at hotpop.com Mon Feb 28 00:18:16 2005 From: linux236r4 at hotpop.com (dm) Date: Mon Feb 28 07:10:37 2005 Subject: [Tutor] open a socket from a named file on linux Message-ID: <1109546297.14526.9.camel@bioblue> Hello, I am trying to open a socket connection to a named file on my computer and can not seem to get it working. Any help or advice would be great. The details I attempting to control xfmedia, http://spuriousinterrupt.org/projects/xfmedia/ , via it's remote from python and I can not get a connection. connection information from readme file <quote> Xfmedia has a remote control system, which consists of a UNIX socket in /tmp, xfmedia_remote.$UID.$SESSION_ID, where $UID is the uid of the user running xfmedia, and $SESSION_ID is a number (starting from zero) corresponding to the instance of xfmedia. (For example, if you're running one copy of xfmedia, $SESSION_ID will be 0. If you start a second instance, its $SESSION_ID will be 1. And so on.) </quote> when attempting to creat a connection with this command s = socket.fromfd('/tmp/xfmedia_remote.1001.0', socket.AF_UNIX, socket.SOCK_STREAM) i get this error </xfmedia_remote.1001.0', socket.AF_UNIX, socket.SOCK_STREAM) Traceback (most recent call last): File "<stdin>", line 1, in ? which i understand i need to use the file descripter instead but i can not not get the file descripter because when i attempt to open /tmp/xfmedia_remote.1001.o with the open command i get an error f = open('/tmp/xfmedia_remote.1001.0') Traceback (most recent call last): File "<stdin>", line 1, in ? IOError: [Errno 6] No such device or address: '/tmp/xfmedia_remote.1001.0' yet ls shows the file exists, xfmedia is working fine. From bvande at po-box.mcgill.ca Mon Feb 28 08:02:22 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon Feb 28 08:27:32 2005 Subject: [Tutor] puzzling traceback -- what to do with it? Message-ID: <4222C1FE.1040606@po-box.mcgill.ca> Hi all, I just ran a program of mine and got the traceback: >>> Traceback (most recent call last): File "C:\PYTHON24\lib\idlelib\rpc.py", line 233, in asyncqueue self.putmessage((seq, request)) File "C:\PYTHON24\lib\idlelib\rpc.py", line 333, in putmessage raise IOError IOError This stumps me, as I've almost no idea what rpc.py, putmessage, and asyncqueue are. (A quick glance at the code made me realize my code-reading skills and knowledge of IDLE aren't up to tracking this down on my own.) Furthermore, the code that produced this runs just fine via other methods (running from within SciTe, the python command line, etc.) And, sometimes, but not always, closing the offending code, running something else, and then trying again with the code that caused the traceback makes it work. I'm thinking IDLE bug, but also that it would be a good idea to solicit opinions/expertise here before running off screaming BUG to the IDLE folks :-) Any suggestions for what the problem might be, or how to narrow it down before reporting? Thanks and best, Brian vdB From potus98 at yahoo.com Mon Feb 28 15:05:44 2005 From: potus98 at yahoo.com (John Christian) Date: Mon Feb 28 15:05:47 2005 Subject: [Tutor] variable name based on variables (expansion?) Message-ID: <20050228140544.98647.qmail@web54707.mail.yahoo.com> a python 2.3 noob asks: # I have some lists GameLogic.varList0=[1,1,1,1] GameLogic.varList1=[1,1,1,1] GameLogic.varList3=[1,1,1,1] # I want to change specific list elements GameLogic.varList0[2]=0 print GameLogic.varList0 [1,1,0,1] # But I want the assignment # to be based on variables LIST=1 POSITION=2 GameLogic.varList$LIST[$POSITION]=0 # But the variable assignment above does not work. # Python complains of a syntax error. # I've also tried variations of eval(), single ticks, # back ticks, quotes, etc... but I just can't seem # to get the syntax right. # # Can someone please provide a working example? # In case it matters, here are additional details: # My python script imports a module named GameLogic. # My script is called fresh every time it's used; # therefore, some variables must be stored in locations # such as GameLogic.varA, GameLogic.varB, etc... so # they are available for later use. It all works fine # if I hardcode things, but I'd rather use variables # since I will eventually have 20 lists with at least # 10 positions in each list. TIA! -potus98 __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From mwalsh at groktech.org Mon Feb 28 15:44:47 2005 From: mwalsh at groktech.org (Martin Walsh) Date: Mon Feb 28 15:44:50 2005 Subject: [Tutor] variable name based on variables (expansion?) In-Reply-To: <20050228140544.98647.qmail@web54707.mail.yahoo.com> References: <20050228140544.98647.qmail@web54707.mail.yahoo.com> Message-ID: <42232E5F.3080100@groktech.org> John Christian wrote: ># But I want the assignment ># to be based on variables >LIST=1 >POSITION=2 > >GameLogic.varList$LIST[$POSITION]=0 > > > >>> help(getattr) Help on built-in function getattr: getattr(...) getattr(object, name[, default]) -> value Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y. When a default argument is given, it is returned when the attribute doesn't exist; without it, an exception is raised in that case. from http://docs.python.org/lib/built-in-funcs.html *getattr*( object, name[, default]) Return the value of the named attributed of object. name must be a string. If the string is the name of one of the object's attributes, the result is the value of that attribute. For example, |getattr(x, 'foobar')| is equivalent to |x.foobar|. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised. #--------------------------- LIST = 1 POSITION = 2 getattr(GameLogic, 'varList'+str(LIST))[POSITION] = 0 > >__________________________________________________ >Do You Yahoo!? >Tired of spam? Yahoo! Mail has the best spam protection around >http://mail.yahoo.com >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > From bill.mill at gmail.com Mon Feb 28 16:38:40 2005 From: bill.mill at gmail.com (Bill Mill) Date: Mon Feb 28 16:38:45 2005 Subject: [Tutor] variable name based on variables (expansion?) In-Reply-To: <20050228140544.98647.qmail@web54707.mail.yahoo.com> References: <20050228140544.98647.qmail@web54707.mail.yahoo.com> Message-ID: <797fe3d4050228073828c0d8bf@mail.gmail.com> John, On Mon, 28 Feb 2005 06:05:44 -0800 (PST), John Christian <potus98@yahoo.com> wrote: > a python 2.3 noob asks: > > # I have some lists > GameLogic.varList0=[1,1,1,1] > GameLogic.varList1=[1,1,1,1] > GameLogic.varList3=[1,1,1,1] > > # I want to change specific list elements > GameLogic.varList0[2]=0 > print GameLogic.varList0 > [1,1,0,1] > > # But I want the assignment > # to be based on variables > LIST=1 > POSITION=2 > > GameLogic.varList$LIST[$POSITION]=0 > Most likely you want to have a 2-dimensional list. Like so: #note the lists inside a list GameLogic.varMatrix=[[1,1,1,1], [1,1,1,1], [1,1,1,1]] Then, to get to the second element in the first list, do: GameLogic.varMatrix[0][1] Or the third element of the second list: GameLogic.varMatrix[1][2] In general, using zero-based counting of rows and columns, accessing the array is done with: GameLogic.varMatrix[row][column] so access like you have above is just: GameLogic.varMatrix[LIST][POSITION] Assuming that LIST and POSITION are zero-based counts. Also note that all-CAPS variables in python are traditionally used only for constants. This is a pretty strong tradition which, if you break, will confuse anyone trying to read your code. Variables are traditionally either camel case or all lower-case with underscores. > # But the variable assignment above does not work. > # Python complains of a syntax error. > # I've also tried variations of eval(), single ticks, > # back ticks, quotes, etc... but I just can't seem > # to get the syntax right. > # > # Can someone please provide a working example? > the $ is not a syntactic character in python. Single quotes simply delimit strings in python. Back ticks are equivalent to the str() function which creates strings (or is it repr()? I can't remember; it's generally bad form to use back ticks anyway). Double quotes are the same as single quotes. Please read the tutorial at http://docs.python.org/tut/tut.html . Peace Bill Mill bill.mill at gmail.com From bill.mill at gmail.com Mon Feb 28 16:49:33 2005 From: bill.mill at gmail.com (Bill Mill) Date: Mon Feb 28 16:49:36 2005 Subject: [Tutor] puzzling traceback -- what to do with it? In-Reply-To: <4222C1FE.1040606@po-box.mcgill.ca> References: <4222C1FE.1040606@po-box.mcgill.ca> Message-ID: <797fe3d405022807495f46daac@mail.gmail.com> On Mon, 28 Feb 2005 02:02:22 -0500, Brian van den Broek <bvande@po-box.mcgill.ca> wrote: > Hi all, > > I just ran a program of mine and got the traceback: > > >>> > Traceback (most recent call last): > File "C:\PYTHON24\lib\idlelib\rpc.py", line 233, in asyncqueue > self.putmessage((seq, request)) > File "C:\PYTHON24\lib\idlelib\rpc.py", line 333, in putmessage > raise IOError > IOError > > This stumps me, as I've almost no idea what rpc.py, putmessage, and > asyncqueue are. (A quick glance at the code made me realize my > code-reading skills and knowledge of IDLE aren't up to tracking this > down on my own.) > > Furthermore, the code that produced this runs just fine via other > methods (running from within SciTe, the python command line, etc.) > And, sometimes, but not always, closing the offending code, running > something else, and then trying again with the code that caused the > traceback makes it work. > > I'm thinking IDLE bug, but also that it would be a good idea to > solicit opinions/expertise here before running off screaming BUG to > the IDLE folks :-) > Looks like an IDLE bug to me. Either it's a bug with them, or you're interfering with something they do; either way it looks like those guys are likely gonna have to help you out. The fact that the errors are in idlelib leads me to this conclusion - unless you're importing idlelib into your program, an error there is an error with idle. Having used IDLE (maybe) once or twice, you should take this with a grain of salt, but asking them about this error seems to be a good bet. > Any suggestions for what the problem might be, or how to narrow it > down before reporting? I would just give them a link to the smallest bit of source code you can get to reproduce this problem, and an exact list of steps for how to repeat it consistently. Also tell them your OS, python version, and IDLE version. I'm also assuming you already googled the traceback and searched their mailing list to see if it's a well-known problem. Peace Bill Mill bill.mill at gmail.com From jsmith at medplus.com Mon Feb 28 18:57:30 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Mon Feb 28 18:57:34 2005 Subject: [Tutor] sys.argv[1: ] help Message-ID: <C4C644CF4ADA9448904C3E8BACC4B97C02FFD08D@medexch1.medplus.com> Richard, I have no problems running your example. It would be helpful in the future ot let us know which version and variant of Python you are running. I am using the canonical (as oppose to ActiveState) Python 2.4. >From the command prompt, type assoc .py and you should see .py=Python.File Then type ftype Python.File which should return Python.File="C:\Python24\python.exe" "%1" %* If the last one isn't correct (with approriate path and assoc type associations) then you can correct it with ftype ASSOCTYPE=PATHSTUFF As an added bonus, you can also create a system environment variable called PATHEXT and set it to .py and you won't even have to type the .py to execute the script. I added all the following to my PATHEXT: .py;.pyw;.pys;.pyo;.pyc While you're at it, you should also check the assoc/ftype for .pyw as .pyw=Python.NoConFile Python.NoConFile="C:\Python24\pythonw.exe" "%1" %* Good luck, Jeff -----Original Message----- From: Richard gelling [mailto:uselinux34@yahoo.co.uk] Sent: Sunday, February 27, 2005 1:41 PM To: tutor@python.org Subject: Re: [Tutor] sys.argv[1: ] help Hi, It is actually associated with just 'python', changed it to associate with 'pythonw' and I got nothing on the same example not even the [], so I am assuming that 'python' is the correct one? Liam Clarke wrote: >Yeah, right click on a .py and check if it's associated with pythonw or >python.exe > >GL, > >Liam Clarke > > >On Sun, 27 Feb 2005 18:28:18 +0000, Richard gelling ><uselinux34@yahoo.co.uk> wrote: > > >>Hi, >>Yes, I use both Wndows XP and Linux( at work ) . I left that in by >>mistake I am actually just typing in >> >>arg1,py a b c >> >>at the windows XP command prompt >> >>Sorry for the confusion. >> >> >>Liam Clarke wrote: >> >> >> >>>Are you using XP still? I've never seen this before - >>> >>> >>> >>> >>>>./arg1.py a b c >>>> >>>> >>>> >>>> >>>But anyhoo, I tried out just >>>'c:\python23\foo.py' >>>as opposed to >>>'c:\python23\python foo.py' and >>>while foo.py will run, it doesn't echo to the console, as on my >>>machine running a .py file runs it through pythonw.exe - I'd check it >>>out for your machine, it's probably the same. You'd need to change >>>the association to python.exe, but that would mean that you always >>>got a DOS box for every Python script you ran, which is annoying with >>>GUIs. >>> >>>Erm, if you don't want to type in python each time, either change the >>>association or create a batch file called x or a or something that >>>runs Python and stick it in a directory that's in your PATH system >>>variable. Only problem with that is passing command line >>>variables.... >>> >>>...might just be better to type python.... >>> >>>Good Luck, >>> >>>Liam Clarke >>> >>>On Sun, 27 Feb 2005 17:55:54 +0000, Richard gelling >>><uselinux34@yahoo.co.uk> wrote: >>> >>> >>> >>> >>>>Hi, >>>> >>>>No What I get if I was to type in >>>>./arg1.py a b c >>>> >>>>All I get is >>>>[] >>>> >>>>If i type at the command prompt >>>> >>>>python arg1.py a b c >>>> >>>>I get ['a','b','c'] as expected >>>> >>>>All the other programs and examples I have typed in work fine just >>>>by typing in the file name, I don't have to preced the file name >>>>with python, only this example. I hope this makes it clearer >>>> >>>>Richard G. >>>> >>>> >>>>Nick Lunt wrote: >>>> >>>> >>>> >>>> >>>> >>>>>Richard, >>>>> >>>>>if you try to print sys.argv[1:] when sys.argv only contain >>>>>sys.argv[0] then you are bound to get an empty list returned, [] . >>>>> >>>>>Im not sure I understand the problem you think you've got but >>>>>here's what happens with sys.argv for me, and it's correct. >>>>> >>>>>[argl.py] >>>>> >>>>>$ cat argl.py >>>>>#!/usr/bin/python >>>>> >>>>>import sys >>>>>print sys.argv[1:] >>>>> >>>>> >>>>>./argl.py >>>>>[] >>>>> >>>>>./argl.py a b c >>>>>['a', 'b', 'c'] >>>>> >>>>>Is that what your getting ? >>>>> >>>>> >>>>> >>>>> >>>>> >>>>> >>>>> >>>>> >>>>> >>>>> >>>>>>Sorry for the late response, I tried all of the the suggestions, >>>>>>including correcting my typo of print sys[1:] and tried print >>>>>>sys,argv[1:], this does now work as long as I run 'python test.py >>>>>>fred joe' it returns all the arguments. If I try just test.py all >>>>>>I get is '[]' . Is there something wrong with my environmental >>>>>>variables in Windows XP, I would like to be able to just use the >>>>>>file name rather than having to type python each time. Any help >>>>>>would be gratefully received. >>>>>> >>>>>>Richard G. _______________________________________________ From jsmith at medplus.com Mon Feb 28 19:03:42 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Mon Feb 28 19:03:50 2005 Subject: [Tutor] gensuitemodule? Message-ID: <C4C644CF4ADA9448904C3E8BACC4B97C02FFD090@medexch1.medplus.com> http://www.python.org/doc/2.3.5/mac/module-gensuitemodule.html -----Original Message----- From: Mike Hall [mailto:michael.hall@critterpixstudios.com] Sent: Friday, February 25, 2005 7:19 PM To: tutor@python.org Subject: [Tutor] gensuitemodule? I'm seeing it used in a Python/Applescript tutorial, though am unclear on it's exact purpose or usage. Can someone fill me in? _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From uselinux34 at yahoo.co.uk Mon Feb 28 20:21:05 2005 From: uselinux34 at yahoo.co.uk (Richard gelling) Date: Mon Feb 28 20:21:09 2005 Subject: [Tutor] sys.argv[1: ] help In-Reply-To: <C4C644CF4ADA9448904C3E8BACC4B97C02FFD08D@medexch1.medplus.com> References: <C4C644CF4ADA9448904C3E8BACC4B97C02FFD08D@medexch1.medplus.com> Message-ID: <42236F21.3060002@yahoo.co.uk> Hi, Thanks a lot to everyone that replied. I was missing the %* in the following line, in the File associations I just had upto the "%1". Adding %* cured my problem. Python.File="C:\Python24\python.exe" "%1" %* Sorry for the typos in some of my examples, every keyboard I've tried appears to have the same fault on it! Anyway thanks a lot again, Richard G. Smith, Jeff wrote: >Richard, > >I have no problems running your example. It would be helpful in the >future ot let us know which version and variant of Python you are >running. I am using the canonical (as oppose to ActiveState) Python >2.4. > >>From the command prompt, type > >assoc .py > >and you should see > >.py=Python.File > >Then type > >ftype Python.File > >which should return > >Python.File="C:\Python24\python.exe" "%1" %* > > >If the last one isn't correct (with approriate path and assoc type >associations) then you can correct it with > >ftype ASSOCTYPE=PATHSTUFF > >As an added bonus, you can also create a system environment variable >called PATHEXT and set it to .py and you won't even have to type the .py >to execute the script. I added all the following to my PATHEXT: >.py;.pyw;.pys;.pyo;.pyc > >While you're at it, you should also check the assoc/ftype for .pyw as > >.pyw=Python.NoConFile >Python.NoConFile="C:\Python24\pythonw.exe" "%1" %* > >Good luck, >Jeff > >-----Original Message----- >From: Richard gelling [mailto:uselinux34@yahoo.co.uk] >Sent: Sunday, February 27, 2005 1:41 PM >To: tutor@python.org >Subject: Re: [Tutor] sys.argv[1: ] help > > > >Hi, > >It is actually associated with just 'python', changed it to associate >with 'pythonw' and I got nothing on the same example not even the [], so > >I am assuming that 'python' is the correct one? > > > > > > > > > > > > > >Liam Clarke wrote: > > > >>Yeah, right click on a .py and check if it's associated with pythonw or >> >> > > > >>python.exe >> >>GL, >> >>Liam Clarke >> >> >>On Sun, 27 Feb 2005 18:28:18 +0000, Richard gelling >><uselinux34@yahoo.co.uk> wrote: >> >> >> >> >>>Hi, >>>Yes, I use both Wndows XP and Linux( at work ) . I left that in by >>>mistake I am actually just typing in >>> >>>arg1,py a b c >>> >>>at the windows XP command prompt >>> >>>Sorry for the confusion. >>> >>> >>>Liam Clarke wrote: >>> >>> >>> >>> >>> >>>>Are you using XP still? I've never seen this before - >>>> >>>> >>>> >>>> >>>> >>>> >>>>>./arg1.py a b c >>>>> >>>>> >>>>> >>>>> >>>>> >>>>> >>>>But anyhoo, I tried out just >>>>'c:\python23\foo.py' >>>>as opposed to >>>>'c:\python23\python foo.py' and >>>>while foo.py will run, it doesn't echo to the console, as on my >>>>machine running a .py file runs it through pythonw.exe - I'd check it >>>> >>>> > > > >>>>out for your machine, it's probably the same. You'd need to change >>>>the association to python.exe, but that would mean that you always >>>>got a DOS box for every Python script you ran, which is annoying with >>>> >>>> > > > >>>>GUIs. >>>> >>>>Erm, if you don't want to type in python each time, either change the >>>> >>>> > > > >>>>association or create a batch file called x or a or something that >>>>runs Python and stick it in a directory that's in your PATH system >>>>variable. Only problem with that is passing command line >>>>variables.... >>>> >>>>...might just be better to type python.... >>>> >>>>Good Luck, >>>> >>>>Liam Clarke >>>> >>>>On Sun, 27 Feb 2005 17:55:54 +0000, Richard gelling >>>><uselinux34@yahoo.co.uk> wrote: >>>> >>>> >>>> >>>> >>>> >>>> >>>>>Hi, >>>>> >>>>>No What I get if I was to type in >>>>>./arg1.py a b c >>>>> >>>>>All I get is >>>>>[] >>>>> >>>>>If i type at the command prompt >>>>> >>>>>python arg1.py a b c >>>>> >>>>>I get ['a','b','c'] as expected >>>>> >>>>>All the other programs and examples I have typed in work fine just >>>>>by typing in the file name, I don't have to preced the file name >>>>>with python, only this example. I hope this makes it clearer >>>>> >>>>>Richard G. >>>>> >>>>> >>>>>Nick Lunt wrote: >>>>> >>>>> >>>>> >>>>> >>>>> >>>>> >>>>> >>>>>>Richard, >>>>>> >>>>>>if you try to print sys.argv[1:] when sys.argv only contain >>>>>>sys.argv[0] then you are bound to get an empty list returned, [] . >>>>>> >>>>>>Im not sure I understand the problem you think you've got but >>>>>>here's what happens with sys.argv for me, and it's correct. >>>>>> >>>>>>[argl.py] >>>>>> >>>>>>$ cat argl.py >>>>>>#!/usr/bin/python >>>>>> >>>>>>import sys >>>>>>print sys.argv[1:] >>>>>> >>>>>> >>>>>>./argl.py >>>>>>[] >>>>>> >>>>>>./argl.py a b c >>>>>>['a', 'b', 'c'] >>>>>> >>>>>>Is that what your getting ? >>>>>> >>>>>> >>>>>> >>>>>> >>>>>> >>>>>> >>>>>> >>>>>> >>>>>> >>>>>> >>>>>> >>>>>> >>>>>>>Sorry for the late response, I tried all of the the suggestions, >>>>>>>including correcting my typo of print sys[1:] and tried print >>>>>>>sys,argv[1:], this does now work as long as I run 'python test.py >>>>>>>fred joe' it returns all the arguments. If I try just test.py all >>>>>>>I get is '[]' . Is there something wrong with my environmental >>>>>>>variables in Windows XP, I would like to be able to just use the >>>>>>>file name rather than having to type python each time. Any help >>>>>>>would be gratefully received. >>>>>>> >>>>>>>Richard G. _______________________________________________ >>>>>>> >>>>>>> > > > From administrata at hotmail.com Mon Feb 28 20:48:00 2005 From: administrata at hotmail.com (. ,) Date: Mon Feb 28 20:51:06 2005 Subject: [Tutor] Edonkey Automatic Search Program?! Message-ID: <BAY22-F3413B8AC3564F145C86CA6C8580@phx.gbl> Hi, I just want to know whether this program can be programmed by python or not. p2p program like edonkey is very very complicated (I think so..) but, is searching program for edonkey complicated too? Should the search program be connected to edonkey? (I think so..) The Edonkey Automatic Search Program should be like... i input some words and the prgram automatically download files which are related to words by days, hours. I'm looking forward to see your replys... Cheers! :) _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From john.ertl at fnmoc.navy.mil Mon Feb 28 21:00:09 2005 From: john.ertl at fnmoc.navy.mil (Ertl, John) Date: Mon Feb 28 20:58:18 2005 Subject: [Tutor] Python and a web image map Message-ID: <E338ADD616B66043824B9ABF5CA6EF2332C541@lanexc107p.fnmoc.navy.mil> All, I have been doing Python for a bit now but I am trying to make a clickable map of the world on a web page that gives me the latitude and longitude of a location selected. I have done little with HTML beyond forms and have done no Java script. Is this a problem Python can solve or is this a HTML / Java script issue. Thanks, John Ertl From cyresse at gmail.com Mon Feb 28 22:10:02 2005 From: cyresse at gmail.com (Liam Clarke) Date: Mon Feb 28 22:10:06 2005 Subject: [Tutor] Edonkey Automatic Search Program?! In-Reply-To: <BAY22-F3413B8AC3564F145C86CA6C8580@phx.gbl> References: <BAY22-F3413B8AC3564F145C86CA6C8580@phx.gbl> Message-ID: <f2ff2d050228131039172d1e@mail.gmail.com> You sure could write a client for the eDonkey p2p protocol using Python, the original BitTorrent protocol and client was written in Python. You can download the source somewhere on www.bittorrent.org. But yeah, good luck with that. Regards, Liam Clarke On Mon, 28 Feb 2005 19:48:00 +0000, . , <administrata@hotmail.com> wrote: > Hi, > > I just want to know whether this program can be programmed by python or not. > > p2p program like edonkey is very very complicated (I think so..) > > but, is searching program for edonkey complicated too? > > Should the search program be connected to edonkey? (I think so..) > > The Edonkey Automatic Search Program should be like... > > i input some words and the prgram automatically download files > > which are related to words by days, hours. > > I'm looking forward to see your replys... > > > Cheers! :) > > _________________________________________________________________ > Express yourself instantly with MSN Messenger! Download today it's FREE! > http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From alan.gauld at freenet.co.uk Mon Feb 28 22:19:39 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Feb 28 22:18:35 2005 Subject: [Tutor] variable name based on variables (expansion?) References: <20050228140544.98647.qmail@web54707.mail.yahoo.com> Message-ID: <017d01c51ddb$37afd240$a6388651@xp> > # I have some lists > GameLogic.varList0=[1,1,1,1] > GameLogic.varList1=[1,1,1,1] > GameLogic.varList3=[1,1,1,1] Pythonically: GameLogic.varLists = [[1,1,1,1], [1,1,1,1], [1,1,1,1]] > # But I want the assignment > # to be based on variables > LIST=1 > POSITION=2 > > GameLogic.varList$LIST[$POSITION]=0 GameLogic.varlists[LIST][POSITION] = 0 > # I've also tried variations of eval(), single ticks, > # back ticks, quotes, etc... but I just can't seem > # to get the syntax right. You could use eval but its nasty and should be avoided if possible. Its usually better to eitrher use lists or dictionaries. > # if I hardcode things, but I'd rather use variables > # since I will eventually have 20 lists with at least > # 10 positions in each list. In that case using variables will be messy, far better to use a single variable which is a container. If for some reason your lists cannot be contigious then you should opt for a dictionary and manipulate the key names: GameLogic.varLists = {'list0' : [1,1,1,1], 'list1' : [1,1,1,1], 'list3' : [1,1,1,1]} key = 'list' + str(LIST) GameLogic.varlists[key][POSITION] = 0 HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Mon Feb 28 22:23:14 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Feb 28 22:22:11 2005 Subject: [Tutor] sys.argv[1: ] help References: <C4C644CF4ADA9448904C3E8BACC4B97C02FFD08D@medexch1.medplus.com> Message-ID: <018801c51ddb$b6c00cd0$a6388651@xp> > As an added bonus, you can also create a system environment variable > called PATHEXT and set it to .py and you won't even have to type the .py Well, well, well, you live and learn! :-) Thanks for that neat tip. Alan G. From cyresse at gmail.com Mon Feb 28 22:27:17 2005 From: cyresse at gmail.com (Liam Clarke) Date: Mon Feb 28 22:27:20 2005 Subject: [Tutor] Python and a web image map In-Reply-To: <E338ADD616B66043824B9ABF5CA6EF2332C541@lanexc107p.fnmoc.navy.mil> References: <E338ADD616B66043824B9ABF5CA6EF2332C541@lanexc107p.fnmoc.navy.mil> Message-ID: <f2ff2d05022813277188e4d4@mail.gmail.com> I would say it's best done as a Javascript thing. <html> <head> <script type = "text/javascript"> function goFunc(e){ x = e.clientX y = e.clientY alert("X=" + x + " Y=" + y) } </script> </head> <body> <script type = "text/javascript"> window.onload = function(e){document.onclick = goFunc;}; </script> Javascript or Python? </body> </html> Save the above as an HTM and click, it should give you the x,y co-ords for the browser window excluding scrolbars etc. Shouldn't be too hard to create a window that matches the size of your map, and convert window co-ords into image co-ords. Good luck with that, though, Javascript is a funny beast, but there's some good tutorials out there. Regards, Liam Clarke On Mon, 28 Feb 2005 12:00:09 -0800, Ertl, John <john.ertl@fnmoc.navy.mil> wrote: > > > All, > > I have been doing Python for a bit now but I am trying to make a clickable > map of the world on a web page that gives me the latitude and longitude of a > location selected. I have done little with HTML beyond forms and have done > no Java script. Is this a problem Python can solve or is this a HTML / Java > script issue. > > Thanks, > > John Ertl > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From john.ertl at fnmoc.navy.mil Mon Feb 28 22:43:14 2005 From: john.ertl at fnmoc.navy.mil (Ertl, John) Date: Mon Feb 28 22:41:24 2005 Subject: [Tutor] Python and a web image map Message-ID: <E338ADD616B66043824B9ABF5CA6EF2332C542@lanexc107p.fnmoc.navy.mil> Liam, Thanks for the code chunk and the advice. Java script here I come. John Ertl -----Original Message----- From: Liam Clarke [mailto:cyresse@gmail.com] Sent: Monday, February 28, 2005 13:27 To: Tutor Tutor Subject: Re: [Tutor] Python and a web image map I would say it's best done as a Javascript thing. <html> <head> <script type = "text/javascript"> function goFunc(e){ x = e.clientX y = e.clientY alert("X=" + x + " Y=" + y) } </script> </head> <body> <script type = "text/javascript"> window.onload = function(e){document.onclick = goFunc;}; </script> Javascript or Python? </body> </html> Save the above as an HTM and click, it should give you the x,y co-ords for the browser window excluding scrolbars etc. Shouldn't be too hard to create a window that matches the size of your map, and convert window co-ords into image co-ords. Good luck with that, though, Javascript is a funny beast, but there's some good tutorials out there. Regards, Liam Clarke On Mon, 28 Feb 2005 12:00:09 -0800, Ertl, John <john.ertl@fnmoc.navy.mil> wrote: > > > All, > > I have been doing Python for a bit now but I am trying to make a clickable > map of the world on a web page that gives me the latitude and longitude of a > location selected. I have done little with HTML beyond forms and have done > no Java script. Is this a problem Python can solve or is this a HTML / Java > script issue. > > Thanks, > > John Ertl > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From alipolatel at yahoo.com Tue Feb 1 09:20:19 2005 From: alipolatel at yahoo.com (Ali Polatel) Date: Fri Mar 4 07:38:18 2005 Subject: [Tutor] Programming challenge (C++ and Python) Message-ID: <20050201082017.44023.qmail@web61002.mail.yahoo.com> Dear Python friends, I need a favor.I play chess at a chess server with the name ICC(www.chessclub.com). I want to write a plugin for their interface using Python. I don't have any idea about how to write a plugin but I found out that the server administrator has written a Plugin Development Kit in C++ for those who wish to write plugins for the interface.I don't know C++ so I cannot convert this kit into python scripts.Can anyone do this for me? or can anyone examine those scripts and tell me a way how to write those with python?The development kit is avaliable at the site ftp://ftp.chessclub.com/pub/icc/interface/blitzin2/plugins/ under the name PluginDevkit.zip Any kind of help is appreciated. Regards, Ali Polatel --------------------------------- Do you Yahoo!? Yahoo! Search presents - Jib Jab's 'Second Term' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050201/8d74c1dc/attachment.html From cchuiernieliew at yahoo.com Sat Feb 26 07:25:09 2005 From: cchuiernieliew at yahoo.com (liew choon chui) Date: Fri Mar 4 07:41:45 2005 Subject: [Tutor] Re: Q & A Message-ID: <20050226062509.47947.qmail@web51603.mail.yahoo.com> Here are two question to need some solution. 1. Explain the difference between an object and a class (Objec Class). Give one specific example. 2. What is the differences between white box testing and black box testing approches. Thank You. Regards, Ernie Liew __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050225/ba7ecdba/attachment.htm