Re: import not working?
On Mon, 23 Feb 2009 19:24:46 -, Lionel lionel.ke...@gmail.com wrote: sys.path.append(C:\DataFileTypes) Just so that we're clear, this is a *really* *bad* habit to get into. Not appending to sys.path, though that isn't often a good idea, but failing to escape your backslashes. This works because '\D' happens not to be a valid escape sequence: if your directory had instead been called newtypes then C:\newtypes would not have had the result you were expecting at all. If you really mean a backslash to be in any literal string, you should always double it: sys.path.append(C:\\DataFileTypes) IMHO, Python is somewhat inconsistent in not producing a compile-type error (or at least an annoying compile-time warning) when presented with invalid escape sequences. What it does, even though it's well-documented and usually the right guess, is to encourage bad habits. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: more on unescaping escapes
On Mon, 23 Feb 2009 22:05:42 -, bvdp b...@mellowood.ca wrote: So, we think something is working and send of a bug fix to our client :) I'm not sure I understand this at all and wonder if there is bug? a=c:\\Program\x20Files\\test a 'c:\\Program Files\\test' so far, so good. a.decode(string-escape) 'c:\\Program Files\test' Umm, not so good? The \\ before the P is okay, but the \\t is change to \t Well yes, that's what you asked it to do. The string-escape decoder reads the string and replaces escape sequences with the corresponding characters. Bear in mind that it's the string as it really is that is being operated on, not the representation of it that you displayed above. In other words: b = a.decode(string-escape) is equivalent to: b = C:\Program Files\test \P isn't a valid escape sequence, so it doesn't get replaced. \t represents a tab, so it does. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: more on unescaping escapes
On Tue, 24 Feb 2009 00:26:29 -, bvdp b...@mellowood.ca wrote: So, in this case I'm assuming that the interpreter is converting the escapes on assignment. The compiler converts the escapes on creating its internal representation of the string, before assignment ever gets involved. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Python AppStore / Marketplace
On Mon, 23 Feb 2009 22:12:09 -, Steve Holden st...@holdenweb.com wrote: Michael Torrie wrote: Steve Holden wrote: Unfortunately I have no idea what a souq is, so I suspect this may be linguistically biased against English speakers. Or perhaps I'm just ignorant. Nah. Not biased against English speakers. Just biased against the un-traveled. :) Don't think so. I've visited roughly twenty-five difference countries and traveled I-don't-know-how-many miles, but certainly over a million. Unless you'd like to redefine un-traveled ... ? But I do (still) speak English (of a kind). A souq is a bazaar :-) Well, close enough anyway. It's another arabic word that translates as market in both the mercantile and financial senses, I believe. Maybe I've just read too much arabic-themed fiction, but I was surprised not to find the word in my trusty Chambers. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: thanks very much indeed for your help is there a better way to do this (python3) newby
On Mon, 23 Feb 2009 23:33:31 -, Gary Wood woody...@sky.com wrote: '''exercise to complete and test this function''' import string def joinStrings(items): '''Join all the strings in stringList into one string, and return the result. For example: print joinStrings(['very', 'hot', 'day']) 'veryhotday' ''' for i in items: return (''.join(items)) As I'm sure your teacher will point out, this is sub-optimal :-) That for-loop isn't doing anything, because you always return out of it at the first iteration. I suspect that you're expected to concatenate the strings together by hand and return the resulting string once you've done them all. Trying writing it that way. PS: it helps a lot if what you say in the doc string matches what you write in the rest of the code. In this case you call your input string items, but then say Join all the strings in *stringList*... -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: more on unescaping escapes
On Tue, 24 Feb 2009 00:46:34 -, bvdp b...@mellowood.ca wrote: Just because I never really thought too much about it :) I'm doing my work on a linux box and my user is on windows ... and he's used to using '\' ... but, you are absolutely right! Just use '/' on both systems and be done with it. Of course I still need to use \x20 for spaces, but that is easy. Erm, no. \x20 is exactly the same as in a string literal. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: pep 8 constants
On Wed, 25 Feb 2009 08:48:27 -, Bruno Desthuilliers bruno.42.desthuilli...@websiteburo.invalid wrote: Ben Finney a écrit : (snip - about using ALL_CAPS for pseudo-constants) Perhaps I'd even argue for an update to PEP 8 that endorses this as conventional. +1 I've been a bit surprised last time I checked PEP8 to find out this wasn't already the case - I would have sweared it was. It is. Aahz added it a few weeks ago. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: code challenge: generate minimal expressions using only digits 1,2,3
On Thu, 26 Feb 2009 23:10:20 -, Jonathan Gardner jgard...@jonathangardner.net wrote: [snip] For each iteration, you take each surviving walker and spawn a new walker that takes a step in each possible direction. Then you check if any of those walkers found the value you are looking for. If so, you've found the answer. If they hit a value you've already seen, you drop that walker from the set. This relies each value having the same set of next states no matter how it's reached. Unfortunately that's not true. Consider what happens when you walk on from (1+3) and (2+2): One possible step from (1+3) is ((1/3)+3) == 3.33... There's no single step from (2+2) that can get you to the same place. The only hanging point is parentheses. What you can do here is instead of building a linear expression, build a tree expression that shows the operations and the values they operate. It should be trivial to calculate all the different new trees that are one digit longer than a previous tree. Trivial yes, but the number of different new trees is large when you're dealing with four digits, and ridiculous with 5. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: why cannot assign to function call
On Fri, 27 Feb 2009 23:55:43 -, Ethan Furman et...@stoneleaf.us wrote: I'm not Mark, but you did post to the whole group! [snippety snip] Specifically, how is a new name (pbr) different, in Python, from a new name initialized as if by assignment (pbv)? It seems to me than you end up with the same thing in either case (in Python, at least), making the distinction non-existent. def func(bar): bar.pop() Pass-by-reference: foo = ['Ethan','Furman'] func(foo)# bar = foo Pass-by-value: foo = ['Python','Rocks!'] func(foo)# bar is new name for foo With true pass-by-value, this comment is not true. Bar would be a copy of foo, not a new name. What happens to bar is then not reflected in foo (depending on how deep the copy is), which is the objective of pass-by-value. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: what does this mean....?
On Sat, 28 Feb 2009 05:17:41 -, zaheer.ag...@gmail.com wrote: I am trying to download a file from the server, I am getting this error,what does this mean localFile = open(localFileName, 'wb') TypeError: coercing to Unicode: need string or buffer, type found The rest of the traceback and enough of your code to make sense of it would have helped. Without context, my best guess is that localFileName isn't actually a string. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for a General Method to Configure Tkinter Widgets
On Tue, 03 Mar 2009 18:58:47 -, W. eWatson notval...@sbcglobal.net wrote: I'm probably confused too. Let's try this. In s=dialog.stopVar.get() I'd like to eliminate the statement and replace it with something like: s=dialog. + stopV.get() )and execute that--I'm aware of the exec operation--problems) where StopV is a string name taken from the config file. That is, in the config file there would be something like: stop_time = 18:00:00, stopV. I'm trying to think of a case where opening up this security hole is even marginally wise, and I'm failing. If you absolutely must prat around with indirections like this, wouldn't s = getattr(dialog, variable_containing_the_string_stopV).get() be a much less unsafe idea? -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie - pass variable to cscript
On Tue, 03 Mar 2009 15:22:20 -, plsulliv...@gmail.com wrote: It's not firing off the vbs script. Have I got the syntax correct? Thanks. My latest attempt: vBS = C:\\Program Files\\nasa\\nmail.vbs os.system('cscript /from:wrk-...@pittcountync.gov / to:plsulli...@pittcountync.gov /sub:TEST /msg:hello ' + vBS) Your problem is that vBS has a space in it, so the Windows command interpreter is interpreting it as two separate arguments, rC:\Program and rFiles\nasa\nmail.vbs. Gabriel has already posted two solutions (which I won't repeat), but he forgot to mention the problem itself! -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about binary file reading
On Wed, 04 Mar 2009 22:58:38 -, vibgyorbits bka...@gmail.com wrote: I'm writing a tool to do some binary file comparisons. I'm opening the file using fd=open(filename,'rb') # Need to seek to 0x80 (hex 80th) location fd.seek(0x80) # Need to read just 8 bytes and get the result back in hex format. x=fd.read(8) print x This prints out garbage. I would like to know what am i missing here. Your bytes are being interpreted as characters when you print the buffer, and the chance of them being meaningful text is probably small. Try the following: for b in x: print hex(ord(b)) Does that look more like what you were expecting? -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about binary file reading
On Wed, 04 Mar 2009 23:28:32 -, Tino Wildenhain t...@wildenhain.de wrote: Rhodri James wrote: On Wed, 04 Mar 2009 22:58:38 -, vibgyorbits bka...@gmail.com wrote: I'm writing a tool to do some binary file comparisons. I'm opening the file using fd=open(filename,'rb') # Need to seek to 0x80 (hex 80th) location fd.seek(0x80) # Need to read just 8 bytes and get the result back in hex format. x=fd.read(8) print x This prints out garbage. I would like to know what am i missing here. Your bytes are being interpreted as characters when you print the buffer, and the chance of them being meaningful text is probably small. Try the following: for b in x: print hex(ord(b)) better: print x.encode(hex) Encodings make my head hurt :-) While there are programmatic purposes I'd leap at the hex encoder for, it doesn't make for the most human- readable output. I'll stick with the for loop, if you don't mind. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: help understanding class or function
Please don't top-post. On Fri, 06 Mar 2009 01:09:48 -, Vincent Davis vinc...@vincentdavis.net wrote: I guess I am thinking of it as an operation that I am preforming on a list and not making a new list. Also looking to learn better methods. This is difficult when you are working alone. It is difficult to know where to improve. The actual functions I am making are more complicated than this example. Whether you want to change the list in-place or not will depend on several things. Most importantly, it will depend on your data usage. If your list crops up in several places and you want the changes you're about to make to propagate to them all, then you must change the list in-place (possibly using the [:] slicing trick). If you don't want the changes to be reflected elsewhere, you must build a new list instead. If you don't care (which is the normal case, hopefully), then it depends on what your function is supposed to be doing. If it's changing every element of the list, doing the changes in-place should be a doddle. If it's filtering some elements out (like your example of omitting every other element) then it's much easier to build a new list. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: create boolean
On Fri, 06 Mar 2009 15:34:08 -, Grant Edwards inva...@invalid wrote: On 2009-03-06, Fencer no.s...@plz.ok wrote: Hi, I need a boolean b to be true if the variable n is not None and not an empty list, otherwise b should be false. I ended up with: b = n is not None and not not n I'd do it like this: b = (n is not None) and (n != []) The second comparison isn't actually necessary, since an empty list is True and a non-empty one False. b = (n is not None) and n Putting the comparison in does make the code slightly less magic, though, so it's not a bad idea to do it! -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: create boolean
On Sat, 07 Mar 2009 05:03:08 -, Grant Edwards gra...@visi.com wrote: On 2009-03-07, Rhodri James rho...@wildebst.demon.co.uk wrote: On Fri, 06 Mar 2009 15:34:08 -, Grant Edwards inva...@invalid wrote: On 2009-03-06, Fencer no.s...@plz.ok wrote: Hi, I need a boolean b to be true if the variable n is not None and not an empty list, otherwise b should be false. I ended up with: b = n is not None and not not n I'd do it like this: b = (n is not None) and (n != []) The second comparison isn't actually necessary, since an empty list is True and a non-empty one False. b = (n is not None) and n Putting the comparison in does make the code slightly less magic, though, so it's not a bad idea to do it! Putting in the second comparison in makes the code match the stated requirement. Otherwise you have to start making assumptions about what n might be besides None or the empty list. The OP stated that we *could* assume that n was None or a list, so I stand by what I said. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: A Dangling Tk Entry
On Tue, 10 Mar 2009 04:14:51 -, W. eWatson notval...@sbcglobal.net wrote: Marc 'BlackJack' Rintsch wrote: On Mon, 09 Mar 2009 04:22:57 -0700, W. eWatson wrote: Marc 'BlackJack' Rintsch wrote: On Sun, 08 Mar 2009 22:20:09 -0700, W. eWatson wrote: You didn't answer my question why entry is necessary at all. The original author thought it was necessary to return entry. I'll give you a peek at a segment of the code I'm working with here: class Enter_Data_Dialog(tkSimpleDialog.Dialog): def __init__(self, parent, sdict): self.sdict = sdict tkSimpleDialog.Dialog.__init__(self, parent) def body(self,master): self.title(Set a Number Entry Dialog) Label( master, text=Number ).grid(row=0, sticky=W) self.anumberVar = StringVar() entry = Entry(master, width=10, textvariable=self.anumberVar).grid(row=0, column=1) self.anumberVar.set( %d % self.sdict[anumber] ) return entry `entry` is unnecessary here. But that was not obvious from your previous example, as you trimmed the code. Now it is clear that `entry` is always `None` because that's what `grid()` returns. But according to the docs this method should return the widget, that should get the focus, so maybe the author really wanted to return the `Entry` instance here, instead of `None`. He's got to return something, because he uses it upon return, as here: `entry` is always `None`, so it is the same as returning nothing because every function has an implicit ``return None`` at the end. def Set_Enter_Data(self): sdict = {} sdict[ ok ] = False sdict[ anumber ] = self.anumber dialog = Enter_Data_Dialog( self.master, sdict ) --- returning That's not a call to the `body()` method so that ``return`` is irrelevant here. Here an instance of `Enter_Data_Dialog` is created. No ``return`` involved. BTW if this is really just a dialog to enter a number, the functions `askinteger()` or `askfloat()` from the `tkSimpleDialog` module can be used. Ciao, Marc 'BlackJack' Rintsch What you are seeing here as an example, is a paired down version of the 2000 line program to focus on the particular problem at hand. The full code uses up to 20 variable of various types, via the dialog object. It uses them successfully to get the values the user has entered. How can it be irrelevant if it works? The author thought this was the way to do it. It's not my invention. It's no fluke. He does the same thing in another dialog that brings back about 6 values. def body(self,master): [snip] You're misunderstanding. The line that you arrowed above has absolutely nothing whatsoever to do with the method body(), so keeping on showing us ever fuller version of that isn't going to prove anything. Now if you were to show us a line like something = dialog.body(something_else) then you might be onto something, but personally I suspect you're going to find that rather hard. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: A Dangling Tk Entry
On Tue, 10 Mar 2009 12:41:07 -, W. eWatson notval...@sbcglobal.net wrote: [snippety snip] Rhodri James wrote: You're misunderstanding. The line that you arrowed above has absolutely nothing whatsoever to do with the method body(), so keeping on showing us ever fuller version of that isn't going to prove anything. Now if you were to show us a line like something = dialog.body(something_else) then you might be onto something, but personally I suspect you're going to find that rather hard. I'd be happy to comply. Perhaps I'm mistaken as what I was responding to in the entanglement of responses, but I think I was making a point (again) that the technique by the author works. This should clear matters up completely. Here's the full 80+ lines of the example code. Note wrapped lines. from Tkinter import * import tkSimpleDialog import tkMessageBox class IntVar_GUI: def __init__(self, master): master.title('Control Variable Fun') self.frame = Frame(master,takefocus=1, highlightthickness=2, highlightcolor='blue') self.frame.configure(height=200,width=200) self.frame.pack() #self.frame.bind(KeyPress, self.HandleKey) self.anumber = 123 # Want name and value to be configurable self.master = master menu = Menu(master) master.config(menu=menu) self.mainMenu = Menu(menu) menu.add_cascade(label=My Menu,menu=self.mainMenu) self.mainMenu.add_command(label=Enter Data, command=self.Set_Enter_Data) self.mainMenu.add_command(label=Exit,underline=1,command=self.Quit) self.Focus() def Set_Enter_Data(self): sdict = {} sdict[ ok ] = False sdict[ anumber ] = self.anumber dialog = Enter_Data_Dialog( self.master, sdict ) self.Focus() print Howdy, set data. Number is:, dialog.anumberVar.get() print dict:, dialog.sdict if not dialog.sdict[ok]: return try: self.anumber = int(eval(dialog.anumberVar.get())) print OK except: print Not OK pass print self.anumber:, self.anumber def Quit(self): self.running = False #self.master.quit() self.master.destroy() def Focus( self ): self.frame.focus_set() class Enter_Data_Dialog(tkSimpleDialog.Dialog): def __init__(self, parent, sdict): self.sdict = sdict tkSimpleDialog.Dialog.__init__(self, parent) def body(self,master): self.title(Set a Number Entry Dialog) Label( master, text=Number ).grid(row=0, sticky=W) self.anumberVar = StringVar() entry = Entry(master, width=10, textvariable=self.anumberVar).grid(row=0, column=1) entry.insert(0,11) self.anumberVar.set( %d % self.sdict[anumber] ) return entry def apply(self): self.sdict[ok] = True def Process(): root = Tk() app = IntVar_GUI(root) root.mainloop() if __name__ == __main__: Process() Because I'm operating out for a command prompt, I don't seem to be able to copy all the error msgs, but here is the last one shown involving line 68, AttributeError: None Type' object has no attribute 'insert' Line 68 is entry.insert(0,11) I'm operating from the command line too. The traceback is: Exception in Tkinter callback Traceback (most recent call last): File /usr/lib/python2.5/lib-tk/Tkinter.py, line 1406, in __call__ return self.func(*args) File temp.py, line 34, in Set_Enter_Data dialog = Enter_Data_Dialog( self.master, sdict ) File temp.py, line 60, in __init__ tkSimpleDialog.Dialog.__init__(self, parent) File /usr/lib/python2.5/lib-tk/tkSimpleDialog.py, line 64, in __init__ self.initial_focus = self.body(body) File temp.py, line 68, in body entry.insert(0,11) AttributeError: 'NoneType' object has no attribute 'insert' In other words entry is None. This is the entry that's a local variable in the Enter_Data_Dialog class body method (called automatically by tkSimpleDialog.Dialog.__init__, it turns out, so my apologies for implying that it wasn't called at all), the one that's created by the line entry = Entry(master,...).grid(row=0,...) Given that this is what grid is expected to return, this shouldn't be the shock that apparently it is. This entry is also the return value from body, which won't be helpful. The Dialog documentation says this: body(self, master) create dialog body. return widget that should have initial focus. This method should be overridden, and is called by the __init__ method. This suggests that the code originally looked like this: entry = Entry(master,...) entry.grid(row=0,...) and someone decided to optimise it. Put it back the way
Re: Behaviour of os.rename()
On Wed, 11 Mar 2009 14:35:01 -, venutaurus...@gmail.com venutaurus...@gmail.com wrote: On Mar 11, 7:20 pm, Tim Golden m...@timgolden.me.uk wrote: venutaurus...@gmail.com wrote: Hello all, I got a suspicion on the behaviour of os.rename (src,dst).If the src is the path of a file and dst is a new filename this os.rename() function is infact creating a new file with the dst name in the current working directory and leaving the src as it is. Is this the expected behavior? Yes, though part of this is Windows being bloody-minded. It is always the case that if you don't give a rooted pathname (one starting with r\) to pretty much any built-in function expecting a filename (in pretty much any language, come to that), the pathname will be assumed to be relative to the current working directory. Windows complicates this by having a current drive too, and per-drive working directories to go with them, so file.txt, D:file.txt, r\path\to\file.txt and rD:\path\to\file.txt could well all be different files in different places. If i want the actual source file in its orignal location to be renamed without doing os.chdir() to that directory, is that possible? Yes. Give the full pathname, with drive letters and everything. os.rename on windows calls the Windows MoveFile API: http://msdn.microsoft.com/en-us/library/aa365239(VS.85).aspx Have a look at the details on that page to see what the limitations / actions are. But remember -- as I've indicated elsewhere -- to use the ur\\?\c:\... form of the file names. And let us know if that works :) That actually was an illustration. As you've told in another chain, it isn't working even after appending \\?\ Tim's point was that you should read the MS documentation. To be fair it doesn't mention doing a copy and (failing to) delete instead of moving the file when doing cross-volume renames, but that's what the OS will have to do. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: A Dangling Tk Entry
On Thu, 12 Mar 2009 04:34:57 -, W. eWatson notval...@sbcglobal.net wrote: I happened to notice that BJ and Rhondi started a small subthread to Nice to know your observation skills are up to scratch :-( this, so I thought I'd explore it. It led to interesting things, but not for its content. I reviewed some things. I'll do you the courtesy or wrapping this up. I'll get straight to the point and be a minimal as possible in my response, without accusing or implying anyone of anything. My guess is that the first culprit was here: entry = Entry(master, width=10, ... entry.insert(0,self.slowdown) --- no affect. Erm, no. You stated (and showed us the code) that it was entry = Entry(master,...).grid(...) *big* difference, and entry.insert(0, self.slowdown) *raises an exception*, which is a long way from having no effect. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Special keyword argument lambda syntax
On Fri, 13 Mar 2009 14:49:17 -, Beni Cherniavsky beni.cherniav...@gmail.com wrote: Specification = Allow keyword arguments in function call to take this form: NAME ( ARGUMENTS ) = EXPRESSION which is equivallent to the following: NAME = lambda ARGUMENTS: EXPRESSION except that NAME is also assigned as the function's `__name__`. My first instinct on seeing the example was that key(n) was a function *call*, not a function definition, and to remember the thread a month or two ago about assigning to the result of a function call. I'm inclined to think this would add confusion rather than remove it. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Special keyword argument lambda syntax
On Fri, 13 Mar 2009 16:39:16 -, Scott David Daniels scott.dani...@acm.org wrote: The original proposal was initially appealing to me until I saw this comment. That means a relatively invisible typo would turn into good syntax. Possibley this is exactly what Rhodri James is talking about, but just to be explicit, one of these is probably a mistake: somefun(something, key(x)==5) somefun(something, key(x)=5) Right now a syntax error makes you look there, after your extension, only test cases will show these problems. Oo, no, I'd missed that! Good catch. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Special keyword argument lambda syntax
On Fri, 13 Mar 2009 15:33:26 -, MRAB goo...@mrabarnett.plus.com wrote: Rhodri James wrote: On Fri, 13 Mar 2009 14:49:17 -, Beni Cherniavsky beni.cherniav...@gmail.com wrote: Specification = Allow keyword arguments in function call to take this form: NAME ( ARGUMENTS ) = EXPRESSION which is equivallent to the following: NAME = lambda ARGUMENTS: EXPRESSION except that NAME is also assigned as the function's `__name__`. My first instinct on seeing the example was that key(n) was a function *call*, not a function definition, and to remember the thread a month or two ago about assigning to the result of a function call. I'm inclined to think this would add confusion rather than remove it. Guido wants to keep the syntax LL(1), so you're not the only one who has a problem with it! :-) I think that: def NAME ( ARGUMENTS ): EXPRESSION is still LL(1). Yes, but at this point we're arguing about how to spell lambda, and Python's already got one perfectly good way of spelling it. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Style question - defining immutable class data members
On Sun, 15 Mar 2009 13:26:17 -, Matthew Woodcraft matt...@woodcraft.me.uk wrote: [snip Gary Herron's explanation of instance attribute lookup falling back to class attribute lookup] It seems clear to me that Maxim understood all this when he asked his original question (you need to understand this subtlety to know why the trick he was asking about only works for immutable values). It seems equally clear to me that Maxim didn't understand any of this when he asked his original question, since he appeared to view class attributes purely as initialisers. Given that either of us could be right, Gary's assumption of less understanding rather than more is clearly the safer one to take. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Style question - defining immutable class data members
On Sun, 15 Mar 2009 15:05:04 -, Matthew Woodcraft matt...@woodcraft.me.uk wrote: Rhodri James rho...@wildebst.demon.co.uk writes: On Sun, 15 Mar 2009 13:26:17 -, Matthew Woodcraft It seems clear to me that Maxim understood all this when he asked his original question (you need to understand this subtlety to know why the trick he was asking about only works for immutable values). It seems equally clear to me that Maxim didn't understand any of this when he asked his original question, since he appeared to view class attributes purely as initialisers. Not at all. He said: Look, here's a tricky way to use a class attribute as an initialiser. Is this good style? . What was there in his post that makes you think he viewed class attributes purely as initialisers? My lack of sleep :-( -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Rough draft: Proposed format specifier for a thousands separator
On Sat, 14 Mar 2009 08:20:21 -, Hendrik van Rooyen m...@microcorp.co.za wrote: Tim Rowe digil.com wrote: 8 - . If Finance users and non-professional programmers find the locale approach to be frustrating, arcane and non-obvious then by all means propose a way of making it simpler and clearer, but not a bodge that will increase the amount of bad software in the world. I do not follow the reasoning behind this. It seems to be based on an assumption that the locale approach is some sort of holy grail that solves these problems, and that anybody who does not like or use it is automatically guilty of writing crap code. No account seems to be taken of the fact that the locale approach is a global one that forces uniformity on everything done on a PC or by a user. Like unicode, locales should make using your computer with your own cultural settings a one-time configuration, and make using your computer in another setting possible. By and large they do this. Like unicode, locales fail in as much as they make cross-cultural usage difficult. Unlike unicode, there is a lot of failure in the standard locale library, which is almost entirely the fault of the standard C locale library it uses. Nobody's defending the implementation, as far as I've noticed (which isn't saying much at the moment, but still...). A bit of poking around in the cheese shop suggests that Babel (http://www.babel.edgewall.org/) would be better, and Babel with a context manager would be better yet. On the other hand, we have a small addition to format strings. Unfortunately it's a small addition that doesn't feel terribly natural in a mini-language that already runs the risk of looking like line noise when you pull the stops out. Not meaning the term particularly unkindly, it is a bodge; it's quick and dirty, syntactic saccharin rather than sugar for doing one particular thing for one particular interest group, and which looks deceptively like the right thing to do for everyone else. That's a bad thing to do. If we ever do get round to fixing localisation (i.e. making overriding bits of locales easy), it becomes a feature that's automatically present that we have to discourage normal programmers from using despite it's apparent usefulness. Frankly, I'd much rather fix the locale system and extend the format syntax to override the default locale. Perhaps something like financial = Locale(group_sep=,, grouping=[3]) print(my number is {0:10n:financial}.format(1234567)) It's hard to think of a way of extending % format strings to cope with this that won't look utterly horrid, though! -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Style question - defining immutable class data members
On Sun, 15 Mar 2009 17:55:25 -, Aaron Brady castiro...@gmail.com wrote: On Mar 15, 12:39 pm, John Posner jjpos...@snet.net wrote: (My apologies if the thread has already covered this.) I believe I understand the WHAT in this situation, but I don't understand the WHY ... [snip] My question is ... WHY does the interpreter silently create the instance attribute at this point, causing a surprising decoupling from the class attribute? WHY doesn't the interpreter behave as it would with a simple, non-instance variable: python Python 2.6.1 ... Type help, copyright, credits or license for more information. x += 1 Traceback (most recent call last): File stdin, line 1, in module NameError: name 'x' is not defined Is there a beneficial effect of silently creating the instance attribute, which outweighs the detrimental effects: (1) inconsistency, (2) the surprising decoupling? Yes. If you access an attribute, you want the search to go like this: - check instance for attribute - check class for attribute - check base classes for attribute But do you, though? The only occasion I can think of that I'd want the search to go past the instance is this auto-initialisation, and frankly I'd rather do that in an __init__ anyway. Perhaps static methods or class methods work that way, I don't know how the innards of the interpreter handle that. Is there any actual advantage to self.attribute picking up Class.attribute instead of raising a NameError? If you write an attribute, you want it stored in the attribute, not ^ the class or base classes. I think you meant instance there :-) Actually what I want is for the attribute to be stored where I told it, which could well be in the class. If the attribute is specified as self.attribute, then yes, put it in the instance. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Rough draft: Proposed format specifier for a thousands separator
On Sun, 15 Mar 2009 19:00:43 -, MRAB goo...@mrabarnett.plus.com wrote: Rhodri James wrote: [snip] Frankly, I'd much rather fix the locale system and extend the format syntax to override the default locale. Perhaps something like financial = Locale(group_sep=,, grouping=[3]) print(my number is {0:10n:financial}.format(1234567)) It's hard to think of a way of extending % format strings to cope with this that won't look utterly horrid, though! The problem with your example is that it magically looks for the locale name financial in the current namespace. True, to an extent. The counter-argument of Is it so much more magical than '{keyword}' looking up the object in the parameter list suggests a less magical approach would be to make the locale a parameter itself: print(my number is {0:10n:{1}}.format(1234567, financial) Perhaps the name should be registered somewhere like this: locale.predefined[financial] = Locale(group_sep=,, grouping=[3]) print(my number is {0:10n:financial}.format(1234567)) I'm not sure that I don't think that *more* magical than my first stab! Regardless of the exact syntax, do you think that being able to specify an overriding locale object (and let's wave our hands over what one of those is too) is the right approach? -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Style question - defining immutable class data members
On Sun, 15 Mar 2009 23:26:04 -, Aaron Brady castiro...@gmail.com wrote: On Mar 15, 1:50 pm, Rhodri James rho...@wildebst.demon.co.uk wrote: On Sun, 15 Mar 2009 17:55:25 -, Aaron Brady castiro...@gmail.com wrote: On Mar 15, 12:39 pm, John Posner jjpos...@snet.net wrote: (My apologies if the thread has already covered this.) I believe I understand the WHAT in this situation, but I don't understand the WHY [snip] Yes. If you access an attribute, you want the search to go like this: - check instance for attribute - check class for attribute - check base classes for attribute But do you, though? The only occasion I can think of that I'd want the search to go past the instance is this auto-initialisation, and frankly I'd rather do that in an __init__ anyway. Perhaps static methods or class methods work that way, I don't know how the innards of the interpreter handle that. As Bruno stated, yes, for resolving 'self.method', and other descriptors. You acknowledge that 'foo.jam' would need to identify itself as coming from an instance, class, or base, since the only entries in 'foo's dictionary are those attributes which are particular to 'foo'. No, I don't acknowledge that. (Note that John's original question was *WHY*, and you effectively gave him a *HOW* answer by asserting that it's what he wants. I'm playing Devil's Advocate to an extent.) self.method is not the same object as Class.method; one's bound and the other isn't, for starters. It's therefore by no means obvious that method lookup isn't being done via the instance's dictionary. After all, some kind of binding has to be done at instance creation time. If you're telling me that it's time- efficient (or at least space-efficient and not horribly time- inefficient) to use the class dictionary and magically know to wrapper the call, then we've that makes things different and gives us a reason for wanting that search order. It's the same story with descriptors; in fact they mask rather more of the detail of what they're doing and look at first glance more tightly bound to the instance than the class. Further steps get you to the same why answer, but they are further steps. Class attributes are grouped together in the class dictionary, instance attributes are grouped together in the instance dictionary, and instances need to see both. True, but they don't need to see both with instance attribute syntax. That they can is what we're trying to justify here. If you have a counter-proposal, either for a wishlist for behavior, or a way of arranging its implementation, I for one would entertain it, even on the c-l-python newsgroup, and even though it wouldn't have much of a chance of making it in to Python. Nope, no proposal. Mildly considering one, but I thought I'd try understanding why what happens is considered a good thing before I let my hare-brainedness off the leash. As a side note, this argument of 'whose methods am I seeing?' has an inconvenient artifact: the behavior of 'foo.method'. 'foo.method' needs to refer to an instance method, due to not needing the 'self' attribute respecified; while 'foo.__class__.method' needs to refer to a plain function. Python's solution is a skeleton type, that just redirects 'foo.method( )' to an append of the arguments plus call. As I said, this inconvenient artefact is exactly why I didn't think assuming instance method lookup happened via the *class* dictionary was safe! Actually what I want is for the attribute to be stored where I told it, which could well be in the class. If the attribute is specified as self.attribute, then yes, put it in the instance. The way C++ works is by allocating storage for the data and method pointers in a class. class X { int foo; char jam[ 12 ]; int foojam( int y, int z ) { ...; } }; X requires 20 bytes: 4 for 'foo', 12 for 'jam', and 4 for 'foojam'... under a 32-bit target. (The 4 for 'foojam' come from a virtual function table, for polymorphic objects er, technically.) I'm sorry, I'm utterly baffled. Why is this relevant to my bit of pedantry? You get what you want: attributes are stored where you tell them. But where are they read from? No, *why*. These questions aren't about what the search order is, they're about why there is a search order. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Rough draft: Proposed format specifier for a thousands separator
On Mon, 16 Mar 2009 02:36:43 -, MRAB goo...@mrabarnett.plus.com wrote: The field name can be an integer or an identifier, so the locale could be too, provided that you know where to look it up! financial = Locale(group_sep=,, grouping=[3]) print(my number is {0:10n:{fin}}.format(1234567, fin=financial)) Then again, shouldn't that be: fin = Locale(group_sep=,, grouping=[3]) print(my number is {0:{fin}}.format(1234567, fin=financial)) Except that loses you the format, since the locale itself is a collection of parameters the format uses. The locale knows how to do groupings, but not whether to do them, nor what the field width should be. Come to think of it, it doesn't know whether to use the LC_NUMERIC grouping information or the LC_MONETARY grouping information. Hmm. I can't believe I'm even suggesting this, but how about: print(my number is {fin.format(10d, {0}, True)}.format(1235467, fin=financial)) assuming the locale.format() method remains unchanged? That's horrible, and I'm pretty sure it can't be right, but I'm too tired to think of anything more sensible right now. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Style question - defining immutable class data members
On Mon, 16 Mar 2009 09:31:59 -, Aaron Brady castiro...@gmail.com wrote: [snippety snip] Otherwise, either /1, every instance has its own entries for class functions, and subsequent changes to the class don't affect existing instances, or /2, every method call is of the form x.__class__.foo ( ). They're both bad. (...unless that's a false dilemma.) I must admit I was envisaging a horribly inefficient (in space terms) version of (1) in which the instance entries were binding stubs that referenced the class entries, but that still falls over when new methods get dynamically added to the class. I blame having two hours of sleep in three days for this particular bit of dimness, sorry. P.S. Do you pronounce 'wildebeeste' like 'vildebeeste'? No, with a w not a v. It's just one of those titles that stick with you no matter what you do. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Rough draft: Proposed format specifier for a thousands separator
On Mon, 16 Mar 2009 23:04:58 -, MRAB goo...@mrabarnett.plus.com wrote: It should probably(?) be: financial = Locale(group_sep=,, grouping=[3]) print(my number is {0:10n:fin}.format(1234567, fin=financial)) The format 10n says whether to use separators or a decimal point; the locale fin says what the separator and the decimal point look like. That works, and isn't an abomination on the face of the existing syntax. Excellent. I'm rather presuming that the n presentation type does grouping. I've only got Python 2.5 here, so I can't check it out (no str.format() method and %n isn't supported by % formatting). If it does, an m type to do the same thing only with the LC_MONETARY group settings instead of the LC_NUMERIC ones would be a good idea. This would be my preferred solution to Raymond's original comma-in-the-format-string proposal, by the way: add an m presentation type as above, and tell people to override the LC_MONETARY group settings in the global locale. It's clear that it's a bodge, and weaning users onto local locales (!) wouldn't be so hard later on. Anyway, time I stopped hypothesising about locales and started looking at the actual code-base, methinks. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Rough draft: Proposed format specifier for a thousands separator
On Tue, 17 Mar 2009 01:47:32 -, MRAB goo...@mrabarnett.plus.com wrote: I'm not against putting a comma in the format to indicate that grouping should be used just as a dot indicates that a decimal point should be used. The locale would say what characters would be used for them. I would prefer the format to have a fixed default so that if you don't specify the locale the result is predictable. Shouldn't that be the global locale? -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Rough draft: Proposed format specifier for a thousands separator
On Tue, 17 Mar 2009 02:41:23 -, MRAB goo...@mrabarnett.plus.com wrote: Rhodri James wrote: On Tue, 17 Mar 2009 01:47:32 -, MRAB goo...@mrabarnett.plus.com wrote: I'm not against putting a comma in the format to indicate that grouping should be used just as a dot indicates that a decimal point should be used. The locale would say what characters would be used for them. I would prefer the format to have a fixed default so that if you don't specify the locale the result is predictable. Shouldn't that be the global locale? Other parts of the language, such as str.upper, aren't locale-sensitive, so I think that format shouldn't be either. If you want it to be locale-sensitive, then specify the locale, even if it's the system locale. Yes, but the format type 'n' is currently defined as taking its cues from the global locale, so in that sense format already is locale-sensitive. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: How complex is complex?
On Wed, 18 Mar 2009 17:30:45 -, Kottiyath n.kottiy...@gmail.com wrote: When we say readability counts over complexity, how do we define what level of complexity is ok? We don't. There is no One True Way that defines for us what complexity is, never mind how much of it is too much. It's a judgement call that is very personal, and as with all these things involves trade-offs. Some potentially helpful rules of thumb: * Am I going to understand this code when I come back to it in half an hour? If not, I'm probably better off with a more readable version or (if I really must) a page and a half of comments explaning the complex version. * Am I going to understand this code when I come back to it in six months? Similar reasoning applies, though I'm more likely to comment than replace in this case. * Is someone else going to understand this code in six months time when I won't be around to help them. A rather higher bar than the previous one, which pushes back towards readability again. * Does it look incredibly ugly? If so, it's probably a bad idea no matter what. * (with respect to your example) Does it do the same thing as the more readable version, and do it at least as efficiently? If not, there's no point in being clever, do it the readable way. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: can someone help me (again) stuck on ' hands on python'
On Thu, 19 Mar 2009 14:40:55 -, Gary Wood python...@sky.com wrote: #i adjusted the main function helps me see the code as the program runs Put it back the way it was (you've broken it rather thoroughly there), and put the debug print calls in printLocations where they stand some chance of showing you what's going on! -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Preparing teaching materials
On Fri, 20 Mar 2009 11:58:18 -, grkunt...@gmail.com wrote: I am considering teaching a beginning programming course using Python. I would like to prepare my class handouts in such a way that I can import the Python code from real .py files directly into the documents. This way I can run real unit tests on the code to confirm that they work as expected. I am considering using LaTeX to write the handouts and then converting them to PDF files. I will probably use a Makefile to convert the LaTeX with embedded Python code into the PDF files using pdflatex. I will probably organize my directory structure into sub-directories py-src, py-test, doc-src, and doc-dist. I will be starting out using Windows Vista/cygwin and hopefully switch to a Macbook this summer. Any thoughts? Decide right now whether you're using Python 2.x or Python 3.x. The switch from print-as-statement to print-as-function is one of the things that will throw beginners very badly indeed if your handouts and computers don't make the same assumptions! -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: file open fails.
On Tue, 24 Mar 2009 22:48:30 -, Wes James compte...@gmail.com wrote: On Tue, Mar 24, 2009 at 4:32 PM, Wes James compte...@gmail.com wrote: \T might mean the same thing as \t (tab), but I thought it would be different... I guess not: http://docs.python.org/reference/lexical_analysis.html#string-literals Wonder why when I do print test\Ttest vs print test\ttest \T just get printed? Because \T has no special meaning, so is just a two character sequence like any other in the literal. 'print' just prints the string. print repr(test\Ttest), repr(test\ttest) might be illuminating? -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Introducing Python to others
On Thu, 26 Mar 2009 09:35:55 -, Paddy O'Loughlin patrick.olough...@gmail.com wrote: Because of this, I was thinking of making sure I included exceptions and handling, the richness of the python library and a pointing out how many modules there were out there to do almost anything one could think of. Once you've shown them exceptions, show them context managers briefly. It's amazing how much they can simplify some types of exception handling. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Odd behavior regarding a list
On Thu, 26 Mar 2009 17:01:40 -, Edd Barrett vex...@gmail.com wrote: On Mar 26, 4:21 pm, Steven D'Aprano st...@remove-this- cybersource.com.au wrote: A few more comments, based on your code. def __classdef_integer(self): Double-underscore name mangling is often more trouble than it is worth. Unless you really need it, not just think you will need it, it is generally considered poor style. It was an attempt at encapsulation. I didn't want my parser to call internals willy-nilly. Is there a better way? The usual convention is to use a single leading underscore to mean this is private, please don't call/use/alter this. Then don't call/use/alter it from outside the class. You don't really need anything stronger than convention unless for some odd reason you don't trust yourself. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing wx.TextCtrl after refactoring
On Fri, 27 Mar 2009 21:51:19 -, alex ale...@bluewin.ch wrote: Hi all I am working on a Dialog window for a gui in wxPython and started refactoring it, below code is a simplified version of it. def createInput1 should create a static text, a button and a textcontrol using the information in def box1Labels. def makeStaticBox1 then arranges all widgets in staticbox1. My problem is that it works fine for the static text and the button label but I cant rename self.txtctrl that it becomes self.txtctrl_inpath or self.txtctrl_outpath for getting the path from either def BrowseInDlg or def BrowseOutDlg. You need the special __setattr__ method. A normal object attribute assignment like: self.wombat = go is equivalent to a call of self.__setattr__(wombat, go) So in your createInput1 method, once the widgets have been created and all the dust has settled, if you add the line: self.__setattr__(txtctrl_path, self.txtctrl) it will do exactly what you're after! -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing wx.TextCtrl after refactoring
On Sat, 28 Mar 2009 00:51:04 -, Rhodri James rho...@wildebst.demon.co.uk wrote: On Fri, 27 Mar 2009 21:51:19 -, alex ale...@bluewin.ch wrote: Hi all I am working on a Dialog window for a gui in wxPython and started refactoring it, below code is a simplified version of it. def createInput1 should create a static text, a button and a textcontrol using the information in def box1Labels. def makeStaticBox1 then arranges all widgets in staticbox1. My problem is that it works fine for the static text and the button label but I cant rename self.txtctrl that it becomes self.txtctrl_inpath or self.txtctrl_outpath for getting the path from either def BrowseInDlg or def BrowseOutDlg. You need the special __setattr__ method. A normal object attribute assignment like: self.wombat = go is equivalent to a call of self.__setattr__(wombat, go) So in your createInput1 method, once the widgets have been created and all the dust has settled, if you add the line: self.__setattr__(txtctrl_path, self.txtctrl) it will do exactly what you're after! or in a slightly less magic way: setattr(self, txtctrl_path, self.txtctrl) -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing wx.TextCtrl after refactoring
On Sat, 28 Mar 2009 13:55:39 -, alex ale...@bluewin.ch wrote: Rhodri thank you very much for your answer. I had read about setattr but the useage was not completely clear to me. Now I will study it again. I inserted it in def createInput1 def createInput1(self, label, pth_btn_label, txtctrl_path): self.stattxt = wx.StaticText(self, -1, label) self.pth_Btn = wx.Button(self, -1, pth_btn_label) self.txtctrl = wx.TextCtrl(self, -1, , size=(300, -1)) setattr(self, self.txtctrl_path, self.txtctrl) Unfortunately I get the following error File C:\Temp\Test\pydlg.py, line 22, in box1Labels return ((Input Path:, Browse, self.BrowseInDlg, txtctrl_inpath), NameError: global name 'txtctrl_inpath' is not defined setattr() expects a string for the second parameter (which should be just txtctrl_path, not self.txtctrl_path, by the way!). So what box1Labels needs to return is ((Input Path:, Browse, self.BrowseInDlg, txtctrl_inpath), ... -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: How to access object created in Main?
On Sun, 29 Mar 2009 19:12:23 +0100, Muddy Coder cosmo_gene...@yahoo.com wrote: Hi Folks, I need to update the text field of a Label created in Main, but can't find a way to do it. Please take a look at my code: from Tkinter import * def makemenu(r) amenu = Menu(r) amenu.add_command(., command=update_label) def update_label(): how to access mesg created in __main__ ? if __name__ == '__main__': root = Tk() mesg = Label(root, text='foo\nbar\nfoo') mesg.pack(expand=YES, fill=BOTH) root.mainloop() A style point: the if __name__ == '__main__' construct implies that you expect your file to be included as a module at some time in the future. When that time comes, having your menu structure rely on module globals that will not exist (because the mesg = Label() doesn't get run) will cause your program to explode messily in a deeply confusing way. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: i have to change default tab length in pydev
On Sat, 28 Mar 2009 11:30:36 -, Coonay fla...@gmail.com wrote: during last few days, i code python using notepad++ or pydev, the compiler always complain there is a problem with Indentation,in my eyes ,there is no Indentation problem at all,because i format the code to make it comply with python style guide strictly,but after i change the default tab length ,it works. If you're mixing tabs and spaces, which from your description you are, then you aren't complying strictly with the Python style guide. PEP 8 says: Tabs or Spaces? Never mix tabs and spaces. Clearly the compiler was considering tabs to be a different width to your editor's initial setting. Where you saw: Line starting with 8 spaces Line starting with a tab in the editor window, the compiler instead saw: Line starting with 8 spaces Line starting with a tab or something like that. Running with python -t will warn you about this sort of thing. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: tkinter questions: behavior of StringVar, etc
On Sun, 29 Mar 2009 22:37:24 +0100, Alan G Isaac alan.is...@gmail.com wrote: On 3/29/2009 2:46 PM Scott David Daniels apparently wrote: You ask, What exactly is the role of ..., rather than saying something like, I don't understand the role of ..., and continue to ask why the code is not architected the way you first expected it to be architected, calling those things you do not understand magic (not magically which would at least invoke a sense of wonder, rather than indignation). Clearly there are some cultural differences here. I am not a CS type. I would not presume to criticize the architecture, and in my world, questions are generally assumed to be what they appear to be: questions. A question does not stop being a question just because it is arrogant or respectful, terse or verbose, or whatever else it manages to communicate. In this case, your choice of wording (the nearest thing we have in print to tone of voice) did not inspire me to go digging around in source that you have just as easy access to, in order to answer questions that I'm not particularly interested in. -- Rhodri James *-* Wildebeeste Herder to the Masses (Also a bit grumpy this weekend. It must be the weather.) -- http://mail.python.org/mailman/listinfo/python-list
Re: if there is a return type of a method definition like java does
On Sat, 28 Mar 2009 03:11:20 -, Coonay fla...@gmail.com wrote: if there is a return type of a method definition,that would lead to faster decision to do with the method called,do you think so? A method definition always returns a function object. There. Less facetiously, I don't see how knowing the return type of a function or method affects decision speed in calling it at all. I suppose it might allow some optimisation of subsequent operations on the result, but given the dynamic typing nature of Python I can't see that being worth the considerable effort. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: dict view to list
On Sun, 29 Mar 2009 08:39:10 +0100, Aaron Brady castiro...@gmail.com wrote: I guess there are two arguments for the change. 1. Flat is better than nested. I don't think that's really what this is refering to. 2. It interferes with the way people read text. Insert some before people and I'd have to agree. The order of events are: First, get the view. Then convert it to a list. Hence, dictA.get_view( ).to_list( ). Alternatively, get the list of dictA's view, or list(dictA.get_view()). Both are legitimate text, after all. This may call for a more fundamental change to a programming language than Python should make; and it may have to wait for another generation. It entails that function applications should be of the form '( x )f' instead of 'f( x )', in a pretty general way. Sorry, but if what you're describing isn't essentially calling a method, then I don't understand the point you're trying to make. If it is, you still need to address Terry's point about why lists get the special treatment and not other built-in types. I also recognize that natural language and thus human thinking does admit of a certain depth of nesting. English, notably, has two means of nesting, at least in the possessive case. 'The mother of invention' and invention's mother. Here is a predicate example too: 'The cat is on the mat' and 'On the mat is the cat', although the late is mostly unattested-to these days. Erm, this isn't what I understand by 'nesting' in language, which has more to do with how many subclauses, like these, you can cope with being active at any one time before you forgot what the sentence started off being about :-) -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: tkinter questions: behavior of StringVar, etc
On Mon, 30 Mar 2009 00:13:46 +0100, Alan G Isaac alan.is...@gmail.com wrote: Since you did not address my question about the nuance of magic, I'm inclined to treat you as a no vote. And you'd be wrong. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: tkinter questions: behavior of StringVar, etc
On Mon, 30 Mar 2009 00:45:41 +0100, Alan G Isaac alan.is...@gmail.com wrote: On 3/29/2009 6:49 PM Scott David Daniels apparently wrote: What happens to your TV when you change the channel before turning it on? I think we can agree this is a safe action, but the result depends on the kind of TV (and on what turning it on means). So I think your analogy makes my point: allowing the state of the variable to be registered at use rather than creation is feasible, although it would perhaps not be best. (E.g., it would not be simplest.) s/simplest/safest/. The chances of something going wrong if you have a staggered setup like that are quite high. The chances of someone trying to use a ???Var before any of the rest of the system is set up (and, if they're lucky, seg-faulting) shouldn't be overlooked either. Amusingly, I'm just old enough to remember when the answer to Scott's question was you probably get static, because the odds of turning the dial to exactly the right spot are small. Printing a StrVar is not the same as printing the contents of a StrVar. Having magic conversions happen for you when they can be useful simply allows you to make mistakes about what things are what. This sounds like an argument against duck typing, and maybe even an argument for eliminating most of the special method names, although I'm sure you did not mean it to be this. ;-) When you're talking implementation details (which is most of what we're doing), duck typing does allow you to make mistakes about what's actually happening. That's the whole point of it. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: global name 'self' is not defined - noob trying to learn
On Mon, 30 Mar 2009 18:57:01 +0100, mark.sea...@gmail.com wrote: Thanks Scott. I think you are saying don't try to subclass from type long, because it is immutable (cannot be changed). If I subclass from type object, then the value can be changed, but I still can't print without explicitely casting back to long in the main routine. Is this a catch 22 scenario, or am I just overlooking some method of long to override to change it's return value? I'm not sure what you mean by I still can't print without explicitly casting back to long in the main routine. print takes whatever thing.__str__() gives it (or thing.__repr__() if __str__ doesn't exist). Here is what I currently have morphed to: Works to change self.val but not self from ctypes import * class REG_INFO(Structure): _fields_ = [ ('address', c_ubyte), ('message', c_char * 256), ('size', c_ubyte), ('init', c_ulong) ] class BigNumber(long): def __new__(class_, init_val, size): print 'printing size: %d' % size self = long.__new__(class_, init_val) self.size = size self.val = self return self # def __repr__(self): print 'from __repr__: %s' % self return '%s(%s)' % (type(self).__name__, self) # def __getitem__(self, index): # gets a single bit if index = self.size: return self.val Really? Surely that can't be sensible behaviour. return (self.val index) 1 # def __get__(self): # gets a single bit return self.val Fix the comment :-) A little debugging tells me that this doesn't get called anyway. # def __setitem__(self,index,value): # sets a single bit if index = self.size: self.val = value return Ouch! No! This sets the single bit you're asking for, but wipes out all the others. value = (value1L)index mask = (1L)index self.val = (self.val ~mask) | value return # def __int__(self): return self.val # def __long__(self): return long(self.val) Hmm. These don't seem to get called either. I wonder where Python's getting the integer value of BigNumber from... but not enough to go look at the source :-) class HugeNumber(BigNumber): def __new__(class_, reg): return BigNumber.__new__(class_, reg.init, reg.size) [snip tests] I think you need to get away from the idea that your register is a number. It isn't, not really; it's a sequence of bits which happens to have a number as a conveniently usable form. You ought to think about *not* subclassing from long, but instead overloading whatever arithmetic operators you want. You also ought to think about raising an exception when __getitem__ or __setitem__ are presented with an index larger than their size. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: i have to change default tab length in pydev
i understand that you get request token,and you need to get Access tokens after that, my question is about Access tokens:which mechanism do u use to tore access tokens for future use I'm sorry, I have no idea what you're talking about or how it relates to bad indent levels. What *exactly* (including the *whole* traceback) is Python saying to you? -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Thoughts on language-level configuration support?
On Mon, 30 Mar 2009 16:59:12 +0100, jfager jfa...@gmail.com wrote: It's the configuration problem. Right now you would use something like ConfigParser or optparse to populate some configuration object, which you would then pass around and extract values from. This would provide two advantages over these approaches: it would separate what can be configured from the mechanism by which it is configured - i.e., I, programmer, don't have to make a decision about what the end user has to do to give me those values. This would be a interesting idea, but ultimately no more than a veneer over the current set of configuration possibilities. Quite how such a system would tell whether to get configuration data from command line parameters, a config file somewhere, or just pull bytes off the Z-wave from Mars, I'm not at all clear. And it would allow the configurable surface of the program to be discoverable; I wouldn't have to poke through code or documentation that was maintained separate from the source code. Except that you still do. You've just specified a different way in which you have to do this, one that's a good deal less visible in the code and a lot less self-documenting because it's spread out all over the place. It also has the major disadvantage from my point of view of requiring Python to do magic in the background to figure out just what is being configured. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Stripping non-numbers from a file parse without nested lists?
On Tue, 31 Mar 2009 06:51:33 +0100, daku9...@gmail.com wrote: There has got to be a better way of doing this: I'm reading in a file that has a lot of garbage, but eventually has something that looks similar to: (some lines of garbage) dip/dir. (some more lines of garbage) 55/158 (some more lines of garbage) 33/156 etc. and I'm stripping out the 55/158 values (with error checking removed): -- def read_data(filename): fh = open(filename, r, encoding=ascii) for line in fh: for word in line.lower().split(): if / in word and dip not in word: temp = word.partition(/) dip.append(temp[0]) dir.append(temp[2]) - I can't figure out a nicer way of doing it without turning the thing into a nested list (non-ideal). I could put the entire tuple inside of a list, but that gets ugly with retrieval. I'm sure there is an easier way to store this. I was having trouble with dictionary's due to non-uniquie keys when I tried that route. Any ideas for a better way to store it? This ultimately parses a giant amount of data (ascii dxf's) and spits the information into a csv, and I find the writing of nested lists cumbersome and I'm sure I'm missing something as I'm quite new to Python. What you're doing (pace error checking) seems fine for the data structures that you're using. I'm not entirely clear what your usage pattern for dip and dir is once you've got them, so I can't say whether there's a more appropriate shape for them. I am a bit curious though as to why a nested list is non-ideal? ... if / in word and dip not in word: dip_n_dir.append(word.split(/, 1)) is marginally shorter, and has the virtue of making it harder to use unrelated dip and dir values together. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Thoughts on language-level configuration support?
On Tue, 31 Mar 2009 07:06:50 +0100, jfager jfa...@gmail.com wrote: On Mar 30, 9:31 pm, Rhodri James rho...@wildebst.demon.co.uk wrote: On Mon, 30 Mar 2009 16:59:12 +0100, jfager jfa...@gmail.com wrote: It's the configuration problem. Right now you would use something like ConfigParser or optparse to populate some configuration object, which you would then pass around and extract values from. This would provide two advantages over these approaches: it would separate what can be configured from the mechanism by which it is configured - i.e., I, programmer, don't have to make a decision about what the end user has to do to give me those values. This would be a interesting idea, but ultimately no more than a veneer over the current set of configuration possibilities. Quite how such a system would tell whether to get configuration data from command line parameters, a config file somewhere, or just pull bytes off the Z-wave from Mars, I'm not at all clear. Not a veneer over; a foundation under. As I acknowledged in my blog post, this would require a small bit of bootstrapping, to configure which end-user configuration system was used. But this would simply point to an adapter, that would map from the desired configuration interface into the canonical standard api provided by the language system. By magic: see later The problem with the current set of configuration possibilities is that there's nothing really constant between them, unless the programmer explicitly codes it, even though they're basically accomplishing the same thing. There's nothing amazingly special about this proposal, it's just saying: that basic thing that we do in a lot of different ways, let's make as much of that as possible standard. I think that cutoff point is below the end-user interface, since there are a lot of valid ways to want to actually inject config data (command line, local files, from a db, etc.), but there's no reason that the end-user interfaces can't rest on top of a lower-level common format that the programmer can rely on. There is actually. The reason is that those different configuration interfaces are actually accomplishing different things. You're lumping together both config files (wherever they may be and whatever format they may be in) with command line parameters and GUI command interfaces when the one is providing long-term defaults and the other short-term overrides. The level of detail that you can have in a config file is something that you never want to see on a command line. When you do, as with say gcc, the results are rather mind-numbing. This distinction is something that your reduction of configuration to a single black box fails to capture. And it would allow the configurable surface of the program to be discoverable; I wouldn't have to poke through code or documentation that was maintained separate from the source code. Except that you still do. No, you don't. If you do, then this proposal hasn't been implemented (and the little code snippet I provided in my post, please don't consider that a full implementation, it was just a sketch I threw together in a really short time). I'm not saying discoverability magically arises; I'm saying that it's one the main points that would be deliberately put into place. Yes you do. This spread-about inline style of configuration is in no sense discoverable to the casual reader, who isn't going to know that a particular config option even exists unless he or she chances upon the line where it's registered. I'm not commenting on your code snippet here -- or I'd be here all night, and you really wouldn't like me at the end of it -- but I am commenting on the usage style it's obviously built to support. That usage style is much less visible than any of the common (or uncommon, for that matter) styles of getting config input, and discourages documentation habits that would otherwise mitigate it. You've just specified a different way in which you have to do this, one that's a good deal less visible in the code Why would it be less visible? If it's syntax, you would know exactly where it was just by looking. I would argue that it's more clear - no more boilerplate code spent shuffling around config objects that you peel values out of, just write the code that does the work you're actually trying to accomplish, with a small bit of syntax to mark that the end user can provide an alternate value. As I said, it's less visible because it's decentralised. The moment you do that, you lose all hope of centralising the documentation, and the visibility of your options plummets. and a lot less self-documenting because it's spread out all over the place. Actually, you get the best of both worlds. You get to see clearly in the code how the configured values are actually used, and you get the gathered summary of configurable values from the discoverability implementation. What discoverability? You still haven't
Re: python for loop
On Wed, 01 Apr 2009 03:37:41 +0100, Lada Kugis lada.ku...@gmail.com wrote: On Tue, 31 Mar 2009 19:29:56 -0700, Chris Rebert c...@rebertia.com wrote: Sort of, but it's *really* not idiomatic. You'd have to declare the arrays to be one longer than they actually are so that array[N] is a valid index. And then you'd end up not using the true first element of the array. Not to mention most library functions use 0-numbering, so you'd have to work around that as well. So, it can be done, but you're going against the grain of the language. I use fortran libraries, so that is not a problem for me. I only make the change once, while transferring the elements ... uhmm, make that twice. Two opportunities to forget to lie about how big your array is :-) I wrote in my other post, 0 is weird to me, I have model of solution on paper ... if I keep 0 then all comes out different. And while comparing, I always get them mixed up. That's why I always try to adapt it to the paper situation. Ever considered adapting the paper situation to it? You might find that the results come out more naturally. Alternatively, idiomatic Python seems to have a strong tendency not to need subscripting, since you spend most of your time iterating through lists instead. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: python for loop
On Wed, 01 Apr 2009 04:15:00 +0100, Lada Kugis lada.ku...@gmail.com wrote: On Wed, 01 Apr 2009 03:59:36 +0100, Rhodri James rho...@wildebst.demon.co.uk wrote: Two opportunities to forget to lie about how big your array is It is rank 3, meaning a33 is the last element. I don't see how any alternative can be simpler than that. You were saying about translating between C programs and FORTRAN libraries. C arrays are 0-based, FORTRANs are 1-based. The entry and exit points therefore give you two opportunities to forget that you need to translate. I don't rate that as simple, myself. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: python for loop
On Wed, 01 Apr 2009 03:58:48 +0100, Lada Kugis lada.ku...@gmail.com wrote: I thoughts high level languages were created primarily so we don't have to think about what happens inside a programming language, memory offsets and the like. Different programming languages were created for different purposes. FORTRAN was built (and rebuilt, and rebuilt again) for crunching numerical data, and there are only a limited number of ways that knowing what's going on under the hood will help you write better programs. C, on the other hand, was built for writing tools for Unix. It gives you very little insulation from what's going on inside, and knowing about that can be critical to the efficiency of your programs. Why do we try to create languages that are intuitive to humans, then ? To attempt to minimise the number of mistakes our intuition would otherwise cause. Which rather begs the question of how varied intuition is, and where that causes clashes we have to retreat to that unintuitive beast, logic. Dragging this back to the original topic, you clearly find starting list indices from zero unintuitive. To me, with a mathematical background, it's not just intuitive, it's correct. All sorts of useful properties fall out from that, not the least of which is the fact that a[0:len(a)] slices the whole of a list. You want the first three items of a list? a[:3] will do nicely, sir. With 1-based indexing you start having to apply offsets in nonintuitive ways more often than you might hope. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: how to handle/generate pcap file
On Wed, 01 Apr 2009 14:53:34 +0100, Evan xdi...@gmail.com wrote: Hello - I'm trying to decode the pcap file which is packet capture by tcpdump or wireshark. Is there a python module that I can use it for this problem? Can python-libpcap or pycap or dpkt do that? A quick browse of the pypcap website suggests that yes, it can. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: python for loop
On Wed, 01 Apr 2009 15:12:27 +0100, Lada Kugis lada.ku...@gmail.com wrote: On 01 Apr 2009 08:06:28 GMT, Steven D'Aprano ste...@remove.this.cybersource.com.au wrote: There are advantages and disadvantages to both systems, but on balance, I think that zero-based is a better system for programming, and one-based for natural language. Nicely put. Yes, along with some of your other arguments, I think I can agree that this sums it up best. I'll just have to adapt myself to natural language thinking at one side, and programming thinking at the other. I always think it's sad that the concept of zero arrived too late to influence our fundamentally latinate language for ordinal numbers. (In other words, don't go thinking that there's anything logical about natural language :-) -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Thoughts on language-level configuration support?
On Wed, 01 Apr 2009 05:15:19 +0100, jfager jfa...@gmail.com wrote: On Mar 31, 10:44 pm, Rhodri James rho...@wildebst.demon.co.uk wrote: [...] What restrictions can be put on the value you get back? What can the help system say about this, or do we have to go back to doing all that by hand? Now translate all those questions into the very different environment of a config file. Repeat with a database, and all it's quirks. By the time your colossus has acquired enough parameters to at least hint at the desirable answers to these questions, you've effectively duplicated the interfaces to all of the config mechanisms you're trying to replace and you've still lost a whole heap of flexibility. Yes, you're right, the code that actually injects the configuration isn't trivial. I never intended to imply that it was. But it would probably only have to be written once (people would only write their own if they had a special need). The win is that the underlying code doesn't have to change just because the end-user configuration format did. On the contrary, because the configurable items can be introduced pretty much anywhere in module, class or function, the code that injects the configuration ends up having to be written over and over and over again. None of the questions I asked are rocket science, most of them apply to all configurables differently, and none of them can be interpolated from the name being assigned to the object produced by the config and the default. This is not going to be a win. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Introducing Python to others
On Thu, 02 Apr 2009 17:02:30 +0100, David C. Ullrich dullr...@sprynet.com wrote: Sometime I gotta get around to actually learning this 2.x stuff. Thought I had an idea how 1.x worked... 3.x may come as a bit of a surprise :-) -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Iteratoration question
On Thu, 02 Apr 2009 23:14:49 +0100, grocery_stocker cdal...@gmail.com wrote: Give the following code.. class it: ...def __init__(self): ...self.count = -1 ...def next(self): ...self.count +=1 ...if self.count 4: ...return self.count ...else: ...raise StopIteration ... def some_func(): ... return it() ... iterator = some_func() iterator __main__.it instance at 0xb7f482ac some_func function some_func at 0xb7f45e64 some_func() __main__.it instance at 0xb7f4862c How come when I call some_func().next(), the counter doesn't get incremented? some_func().next() 0 some_func().next() 0 some_func().next() 0 Here, you are creating an instance of the class it, incrementing and returning that instance's counter, then throwing the instance away. But when I call iterator.next(), it does. iterator.next() 0 iterator.next() 1 iterator.next() 2 iterator.next() 3 Here you already have a single instance, and you don't throw it away after incrementing its counter. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Iteratoration question
On Thu, 02 Apr 2009 23:37:16 +0100, grocery_stocker cdal...@gmail.com wrote: in summary: iterator is bound to one instance of it, while some_func() returns a new instance each time it is called. BUT while what you are doing is interesting, it is not the same as Python's iterators, which use yield from a function and don't require storing a value in a class. look for yield in the python docs. this comment may be irrelevant; i am just worried you are confusing the above (which apart from the mistake about instances is perfectly ok) and python's iterators (which use next(), yield, etc). Okay, one last question for now [snip] How comes I can;t go over 'value' like in the following for x in value: ... print x ... Traceback (most recent call last): File stdin, line 1, in ? TypeError: iteration over non-sequence I refer you back to Andrew's answer. Your value object isn't an iterator and doesn't obey the Iteration protocol. Expecting to be able to iterate over it is a tad optimistic. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: pygame and socket.recv
On Thu, 02 Apr 2009 23:55:48 +0100, Aaron Brady castiro...@gmail.com wrote: I switched to UDP. My average round-trip time is at 50 trips/sec, but my worst round-trip time is still in the 10-20 range. I also tried buffer sizes of 2**8 and 2**12, with about the same results. So, UDP might free up some processor time, but it still leaves me with the problem of retroactive model updates. You are dealing with a network. Errors *will* happen. Plan for them from the start, or they will turn your design into spaghetti :-) -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Goes Mercurial
On Thu, 02 Apr 2009 19:24:49 +0100, Kay Schluehr kay.schlu...@gmx.net wrote: Good to know. Uninstalling a major feature that enhances usability just to make it usable isn't much less ironic though. Meh. Use the command line like God intended. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Iteratoration question
On Fri, 03 Apr 2009 02:07:38 +0100, grocery_stocker cdal...@gmail.com wrote: Okay, I was thinking more about this. I think this is also what is irking me. Say I have the following.. a = [1,2,3,4] for x in a: ... print x ... 1 2 3 4 Would 'a' somehow call __iter__ and next()? If so, does python just perform this magically? No. It's for that invokes the iteration protocol; that's pretty much the definition of it. You have read the iteration protocol after it's been mentioned so many times now, haven't you? for calls iter(a), which in turn calls a.__iter__(), to get an iterator. Once it's got, for calls next() on the iterator each time round the loop. Very approximately, that little for-loop translates to: a = [1,2,3,4] i = iter(a) try: while True: x = i.next() print x except StopIteration: pass -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: python needs leaning stuff from other language
On Fri, 03 Apr 2009 02:40:08 +0100, Zac Burns zac...@gmail.com wrote: Is it really worth it to not implement list.clear and answer this question over and over again? For some value of over and over again that allows this to be the first time I've seen it several months of reading the newsgroup. I see no reason that a list shouldn't have a .clear method. This I wouldn't disagree with, though I imagine it will increase the frequency of complaints from people who haven't understood Python's assignment model. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: extract Infobox contents
On Mon, 06 Apr 2009 23:12:14 +0100, Anish Chapagain anishchapag...@gmail.com wrote: Hi, I was trying to extract wikipedia Infobox contents which is in format like given below, from the opened URL page in Python. {{ Infobox Software | name = Bash | logo = [[Image:bash-org.png|165px]] | screenshot = [[Image:Bash demo.png|250px]] | caption= Screenshot of bash and [[Bourne shell|sh]] sessions demonstrating some features | developer = [[Chet Ramey]] | latest release version = 4.0 | latest release date= {{release date|mf=yes|2009|02|20}} | programming language = [[C (programming language)|C]] | operating system = [[Cross-platform]] | platform = [[GNU]] | language = English, multilingual ([[gettext]]) | status = Active | genre = [[Unix shell]] | source model = [[Free software]] | license= [[GNU General Public License]] | website= [http://tiswww.case.edu/php/chet/bash/ bashtop.html Home page] }} //upto this line I need to extract all data between {{ Infobox ...to }} Thank's if anyone can help, am trying with s1='{{ Infobox' s2=len(s1) pos1=data.find({{ Infobox) pos2=data.find(\n,pos2) pat1=data.find(}}) but am ending up getting one line at top only. How are you getting your data? Assuming that you can arrange to get it one line at a time, here's a quick and dirty way to extract the infoboxes on a page. infoboxes = [] infobox = [] reading_infobox = False for line in feed_me_lines_somehow(): if line.startswith({{ Infobox): reading_infobox = True if reading_infobox: infobox.append(line) if line.startswith(}}): reading_infobox = False infoboxes.append(infobox) infobox = [] You end up with 'infoboxes' containing a list of all the infoboxes on the page, each held as a list of the lines of their content. For safety's sake you really should be using regular expressions rather than 'startswith', but I leave that as an exercise for the reader :-) -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: group several methods under a attribute
On Mon, 06 Apr 2009 20:52:50 +0100, jelle jelleferi...@gmail.com wrote: Hi Aaron, Thanks a lot for your suggestions. I wasnt familiar with the __get__ magic, which seems interesting. So, finally it seems that the cleanest pattern is: class ClsA( object ): def __init__( self, other ): self.inst= other def submethA( self, arg ): print( 'submethA %r, instance %r'% ( arg, self.inst ) ) class ClsB( object ): def methA( self, arg ): self.A= ClsA( self ) print( 'methA %r'% arg ) b= ClsB( ) b.methA( 'this' ) b.A.submethA( 'that' ) You'll note that this is, all Aaron's protests to the contrary, splitting your class up into multiple cooperating classes. If you're set on doing it like this, doing it this way avoids polluting your namespace so much: class ClsB(object): class ClsA(object): def do_something(self): print Here's A doing something def __init__(self): self.A = ClsB.ClsA() def do_something(self): print Here's B doing something b = ClsB() b.do_something() b.A.do_something() -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: extract Infobox contents
On Tue, 07 Apr 2009 12:46:18 +0100, J. Clifford Dyer j...@sdf.lonestar.org wrote: On Mon, 2009-04-06 at 23:41 +0100, Rhodri James wrote: On Mon, 06 Apr 2009 23:12:14 +0100, Anish Chapagain anishchapag...@gmail.com wrote: Hi, I was trying to extract wikipedia Infobox contents which is in format like given below, from the opened URL page in Python. {{ Infobox Software | name = Bash [snip] | latest release date= {{release date|mf=yes|2009|02|20}} | programming language = [[C (programming language)|C]] | operating system = [[Cross-platform]] | platform = [[GNU]] | language = English, multilingual ([[gettext]]) | status = Active [snip some more] }} //upto this line I need to extract all data between {{ Infobox ...to }} [snip still more] You end up with 'infoboxes' containing a list of all the infoboxes on the page, each held as a list of the lines of their content. For safety's sake you really should be using regular expressions rather than 'startswith', but I leave that as an exercise for the reader :-) I agree that startswith isn't the right option, but for matching two constant characters, I don't think re is necessary. I'd just do: if '}}' in line: pass Then, as the saying goes, you only have one problem. That would be the problem of matching lines like: | latest release date= {{release date|mf=yes|2009|02|20}} would it? :-) A quick bit of timing suggests that: if line.lstrip().startswith(}}): pass is what we actually want. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: need to start a new project , can python do all that ?
On Wed, 15 Apr 2009 15:54:45 +0100, Deep_Feelings doctore...@gmail.com wrote: thank you so much ,rest assured that the code will me tested very well (in real world situation) before using it. That's not sufficient. It isn't enough that your program works, it also has to satisfy the regulatory authorities otherwise (depending on what country you're in) you could end up on the wrong end of some very expensive law-suits without actually having done anything wrong. Check first. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Re: How to check all elements of a list are same or different
On Wed, 15 Apr 2009 23:56:45 +0100, John Posner jjpos...@snet.net wrote: Chris Rebert wrote: Ah, okay. Then you want: def all_same(lst): return len(set(lst)) == 1 def all_different(lst): return len(set(lst)) == len(lst) Note that these require all the elements of the list to be hashable. This solution relies on the object ID -- no hashability required: # get list of object-IDs ids = map(lambda x: id(x), mylist) # ALL THE SAME? ... test whether average ID matches first ID sum(ids)/len(ids) == ids[0] Oh John! After all the recent discussion of identity versus equality too. my_list = [ 1024 ] my_list.append(1024) # Defeat the interpreter's cunningness ids = map(lambda x: id(x), ml) ids [9864656, 9864704] sum(ids)/len(ids) == ids[0] False -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: reading arguments in python script when passed from URL
On Wed, 15 Apr 2009 07:24:24 +0100, phaneendra s phaneendr...@gmail.com wrote: hi alll.. iam invoking a python script from a standalone client which looks lik this String command=ln -s /usr/lib /tmp/lin; //creating a soft link URL url = new URL(http://server-name/cgi-bin/finalexec1.py?command= +command); but iam not able to read this command in the python script in my script i tried doing for arg in sys.argv; print arg but the command is not being read.. is it the right way of reading arguments in python script? If you fix the indentation, and use a colon instead of a semi-colon, and import sys first, then yes. Your standalone client however makes no sense to me at all. How *exactly* are you invoking your Python script? -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: What IDE support python 3.0.1 ?
On Wed, 15 Apr 2009 23:51:24 +0100, Deep_Feelings doctore...@gmail.com wrote: On Apr 16, 1:45 am, Benjamin Peterson benja...@python.org wrote: Deep_Feelings doctoresam at gmail.com writes: I want to start learning python and not wanna waste my time learning python 2.x ,so i need your advise to what IDE to use for python 3.0.1 Why do you think you're wasting time with 2.x? yes.. should i write 2.x code then after a year or so i have to upgrade to 3.0 :( ? The only difference between 2.x and 3.0 that will trip you up as a beginner is that print is a function rather than a statement. Unless you're a colleague of mine, who started to learn Python a week ago by poking its Unicode handling very hard :-) On IDE's, I'm afraid I'm not going to be much help because I don't use them. I prefer to use a decent editor (Emacs in my case, others have their own preferences) and run my scripts from the command line. That said, IDLE (which comes packaged with Python) is a perfectly decent little IDE. It's surprising how little you really need given the flexibility and immediacy of working with Python. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: binary file compare...
On Thu, 16 Apr 2009 10:44:06 +0100, Adam Olsen rha...@gmail.com wrote: On Apr 16, 3:16 am, Nigel Rantor wig...@wiggly.org wrote: Okay, before I tell you about the empirical, real-world evidence I have could you please accept that hashes collide and that no matter how many samples you use the probability of finding two files that do collide is small but not zero. I'm afraid you will need to back up your claims with real files. So that would be a no then. If the implementation of dicts in Python, say, were to assert as you are that the hashes aren't going to collide, then I'd have to walk away from it. There's no point in using something that guarantees a non-zero chance of corrupting your data. Why are you advocating a solution to the OP's problem that is more computationally expensive than a simple byte-by-byte comparison and doesn't guarantee to give the correct answer? -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Suggestions wanted on Tkinter problem
On Fri, 17 Apr 2009 00:18:03 +0100, norseman norse...@hughes.net wrote: One suggested I change the subject line - OK I also replaced the [TAB]s since I noticed the Emailer seems to get very confused with them. Problem: Using Python 2.5.2 and Tkinter ??? (came with system) List made and for loop in use lst=[ (S, Single), .] for mode, text c = Radiobuton(. c.pack() At this point the program runs, but I cannot control gray-out of a specific Radiobutton. If I: counter=0 for mode, text c[counter] = Radiobuton(specified_frame,.. c[counter].pack() counter += 1 . . blockUseOf= $varSetElsewhere c[blockUseOf].config(state = strSetElsewhere) Program crashes on Radiobutton line. And what, pray, did the traceback say? What was |c| before you started that last loop of Radiobutton creation? -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Don't you just love writing this sort of thing :)
On Sat, 06 Dec 2008 01:20:55 -, Lawrence D'Oliveiro [EMAIL PROTECTED] wrote: Do you find this (open, gzip.GzipFile)[Entry.endswith(.gz)](os.path.join(PatchesDir, Entry), r) complicated or hard to understand? It's made up of very simple pieces, combined according to very simple rules, viz:- Yes, it's very pretty, and you're terribly clever. In six months' time when you come back to make some engineering change and have to sit down and break it back down into those simple pieces to remind yourself what it's doing, pretty and clever will not be the words you are using. Trust me on this one. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: python book for non technical absolute beginner
On Sat, 06 Dec 2008 13:21:45 -, News123 [EMAIL PROTECTED] wrote: No my question does anybody know a nice beginners book (or a learning CD or on line tutorial)? Ideally it shouldn't be too serious and have a lot of small nice mini-examples For just pottering around with, your friend could do worse than the LiveWires Python Course. It doesn't go far into general programming skills, largely because its designed for 12-15 year old kids to get through in about three days of concentrated effort, but it will help to learn the basics of Python and programming in general. Caveat: the worksheets are built around Python 2.x (for small values of x!), tell your friend not to use Python 3.0. This is one of the few cases where it really matters that 'print' is now a function; nothing freaks a beginner like his output not behaving the way he's been told it should. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido's new method definition idea
On Sat, 06 Dec 2008 21:51:51 -, Daniel Fetchinson [EMAIL PROTECTED] wrote: Did you read the blog post? The advantage is having a less confusing situation for newbies (confusing the number of arguments to a method call). Experience suggests that newbies don't find this confusing, or at least not more than momentarily. I'm -0 on this at the moment. Maybe -0.5. I don't really like the potential for hideousness like @staticmethod def spam.alot(isa, silly, place): return silly + spam that's implied by making this a general feature of methods. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Don't you just love writing this sort of thing :)
On Sun, 07 Dec 2008 07:27:51 -, Lawrence D'Oliveiro [EMAIL PROTECTED] wrote: In message [EMAIL PROTECTED], Rhodri James wrote: Yes, it's very pretty, and you're terribly clever. In six months' time when you come back to make some engineering change and have to sit down and break it back down into those simple pieces to remind yourself what it's doing, pretty and clever will not be the words you are using. Trust me on this one. Considering I've been writing and maintaining and debugging code for about 30 years now, I figure I have the hard-earned right to judge what I will be able to understand in six months and what I won't... Huh. I can only claim 25 years, but I would still strongly discourage people from playing that sort of game. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Python for kids?
On Sun, 07 Dec 2008 20:13:37 -, Russ P. [EMAIL PROTECTED] wrote: I have a 12-year-old son who spends too much time playing Xbox live and watching silly YouTube videos. I would like to try to get him interested in programming. Is anyone aware of a good book or website that addresses this concern, preferably (but not necessarily) using Python? I could try to teach him Python myself, but I'm afraid I would just frustrate him and kill his interest in programming. I did a Google search and found a few things, but not a lot. Thanks. -- http://mail.python.org/mailman/listinfo/python-list The LiveWires Python Course, http://www.livewires.org.uk/python/home is aimed at your son's age-group. There are several worksheets that involve building games using a simple veneer over pygame, if you need to entice him with something! -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Rich Comparisons Gotcha
On Mon, 08 Dec 2008 14:24:59 -, Rasmus Fogh [EMAIL PROTECTED] wrote: On the minus side there would be the difference between '__equal__' and '__eq__' to confuse people. This is a very big minus. It would be far better to spell __equal__ in such a way as to make it clear why it wasn't the same as __eq__, otherwise you end up with the confusion that the Perl == and eq operators regularly cause. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: How to pass out the result from iterated function
On Wed, 10 Dec 2008 20:16:56 -, JD [EMAIL PROTECTED] wrote: I got a iterated function like this: def iterSomething(list): has_something = False for cell in list: if something in cell: has_something = True output = something if has_something: iterSomething(output) else: final_out = outupt The problem is how can I read this final_out outside of the function. I tried the global statement, it seems not work. Any idea? Isn't this going to throw an exception anyway if 'something' doesn't appear in 'list'? You try assigning 'output' to 'final_out' with no guarantee that 'output' has ever been assigned to. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question: if var1 == var2:
On Thu, 11 Dec 2008 19:49:23 -, Steve Holden st...@holdenweb.com wrote: Kirk Strauser wrote: At 2008-11-29T04:02:11Z, Mel mwil...@the-wire.com writes: You could try for item in fname: item = item.strip() This is one case where I really miss Perl's chomp function. It removes a trailing newline and nothing else, so you don't have to worry about losing leading or trailing spaces if those are important to you. ... and it's so hard to write item = item[:-1] Tsk. That would be chop. chomp would be if item[-1] == '\n': item = item[:-1] :-) -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie question: if var1 == var2:
On Thu, 11 Dec 2008 23:49:10 -, John Machin sjmac...@lexicon.net wrote: On Dec 12, 10:31 am, Rhodri James rho...@wildebst.demon.co.uk wrote: On Thu, 11 Dec 2008 19:49:23 -, Steve Holden st...@holdenweb.com wrote: ... and it's so hard to write item = item[:-1] Tsk. That would be chop. chomp would be if item[-1] == '\n': item = item[:-1] Better: if item and item[-1] == '\n': return item[:-1] return item If we aren't going for rstrip, yes, but I was trying to stick to Steve's metier. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: sorting for recursive folder rename
On Tue, 16 Dec 2008 18:20:52 -, ianaré ian...@gmail.com wrote: Hello all, I trying to recursively rename folders and files, and am looking for some ideas on the best way of doing this. The problem is that the given list of items can be in order, and one to all items may be renamed. Here is some preliminary code I have, but which does not work very well. self.toRename has the following structure : [ [original_name, new_name, os.path.isdir] .. ] [snip] import os for item in self.toRename: os.renames(item[0], item[1]) That's it. os.renames will take care of all the intermediate directory creation so you don't even need to sort the list. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Why no lexical scoping for a method within a class?
On Wed, 17 Dec 2008 15:19:32 -, walterbyrd walterb...@iname.com wrote: However in the methods are within a class, the scoping seems to work differently. Not really. Hopefully this commentary will show you why. class ab(): def a(self): self.x = 99 print self.x def b(self): print self.x i = ab() This creates |i|, an instance of class |ab|. As yet it is pure and virgin, having nothing but the methods that it gets from |ab|. Soon this will change... i.a() This creates an attribute |x| in |i|, and assigns the number 99 to it. i.b() # this works, why no lexical scoping? This works because you ran |i.a()| first, so |i.x| exists and can be printed out. Lexical scoping is going on here, you're just mistaking what's being scoped; it's the |self| in |b|, which is in scope because it's a parameter. This particular |self| (the |i| you made earlier) happens to have an attribute |x|, so it all works. If however you'd written: j = ab() j.b() then Python would whinge mightily at you, claiming that it knoweth naught of this |x| attribute of which you speak, and can it go home now for this is a silly place. The |self| in |b| is still in lexical scope, though. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: noob trouble with IDLE
On Sun, 21 Dec 2008 21:46:16 -, Ronald Rodriguez ronaldrdg...@gmail.com wrote: Hi, Im new to python and I've just started using Byte of Python, running the samples etc. Im using IDLE on Xp. Ok, here's the thing. A sample script makes a call to the os.system() function in order to zip some files. Everything works fine when running from the command line, but the same code fails when I try Run -- Run module on IDLE. Im using 7z to zip the files. Again, everything is OK when running from the command line. Remember, Im new to python and programming. I've done some google search without results. Maybe its just too simple :-( . Any help would be appreciated. Thanks in advance. When you say the same code fails when run via IDLE, what exactly do you mean? Does it produce huge amounts of traceback and whinging? Does it lock up IDLE entirely? Does it thumb its nose at you and go off to dance the night away in Ibiza? Absent that information, my best guess is that 7z has its own internal event loop (a quick Google suggests that it's a GUI tool) which fights for dominance with IDLE's event loop. This is a fairly common problem, and a good reason for avoiding using IDLE's Run Module for anything but the most straightforward Python code. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: iterating initalizations
On Tue, 23 Dec 2008 03:52:35 -, Aaron Stepp stepp.aa...@gmail.com wrote: Simply put, I just need enough arrays to hold a list of pitches/rhythms. Then I'll have each list member returned to an instrument defined in another module. One array can hold a list of pitches/rhythms. I'm still not terribly clear as to why you need so many. Is each list intended for a different instrument, so you're more looking at: violin_1 = [ ...stuff... ] violin_2 = [ ...other stuff...] viola = [ ...really sweet stuff... ] cello = [ ...really boring stuff... ] -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's popularity
On Tue, 23 Dec 2008 04:35:42 -, Grant Edwards gra...@visi.com wrote: IIRC, Python came pre-installed on my IBM Thinkpad. However, it wasn't anyplace the average user would stumble across it... The suggestively named IBMTOOLS directory, I believe :-) -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: iterating initalizations
On Tue, 23 Dec 2008 15:39:52 -, Aaron Stepp stepp.aa...@gmail.com wrote: import random from rtcmix import * from chimes_source import * # Chime.play() from rhythmblock import * # rhythmBlock.rhythmTwist() and rhythmBlock.printStuff() from pitchblock import * # pitchBlock.pitchTwist() and pitchBlock.printStuff() from lenEval import * #greaterThan.sovler() indexrand = random.Random() indexrand.seed(2) chime = Chime() notes = pitchBlock() rhythm = rhythmBlock() solve = greaterThan() class arrayBlock: def __init__(self, theTempo, start): self.__A = [] self.__B = [] self.__start = start self.__tempo = theTempo def player(self, length, tempo, octave, pan, seed): tempo = (120, self.__tempo) for a in range(length): one = indexrand.randint(0, 3) two = indexrand.randint(0, 7) self.__A = self.__A + notes.pitchTwist(one , two) for b in range(length): one = indexrand.randint(0, 3) two = indexrand.randint(0, 7) self.__B = self.__B + rhythm.rhythmTwist(one , two) lenA = len(self.__A) lenB = len(self.__B) var = solve.solver(lenA, lenB) for c in range(var): print self.__A[c] self.__start = self.__start + tb(self.__B[var]) chime.play(self.__start, self.__A[var], octave, pan, seed) This almost does exactly what I want, and is far cleaner than my previous attempts. The only problem is that now all my arguments are being passed as zeros! Which all your arguments? There are an awful lot there; what *exactly* do you mean? I assume this has to do with WHEN I'm referencing self.__A and self.__B? If you mean __A and __B are full of zeroes, then you should suspect your notes.pitchTwist() and rhythm.rhythmTwist() methods of returning zeroes. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: why cannot assign to function call
On Mon, 05 Jan 2009 22:28:59 -, Steven D'Aprano st...@remove-this-cybersource.com.au wrote: * That only languages substantially taught in undergraduate CS courses matter. As an aside, I use only one of the languages I was taught in my Computer Science course, and that only for poking my EMACS configuration. Every other language I use (yes, including C) I learned afterwards. Moral: times change. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: why cannot assign to function call
On Thu, 08 Jan 2009 00:45:06 -, ru...@yahoo.com wrote: When I started using Python I had no problem with Python's assignment semantics because I had been using references in Perl for years. I did not have a very hard time with Perl's references, after I recognized their similarities to C's pointers. But as I recall, it took a *long* time to wrap my mind around C pointers. I'd suggest that part of the reason for that is C's blurring of the line between arrays and pointers. You can treat them interchangeably enough of the time that when you can't it catches you by surprise. My experience of teaching twelve-year olds Python is that they understand assignment when it's explained in terms of giving names to these objects (numbers, strings, wombats...) that we've already shown them. It's a lot harder to get them to understand the putting an object into a labelled box model when working with other languages. I don't know why this should be, but it is. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: How to store passwords?
On Wed, 07 Jan 2009 21:06:07 -, Oltmans rolf.oltm...@gmail.com wrote: But the thing is that I will ask the user for user name and password only once i.e. when they start the application for the first time. After that, I'm not supposed to ask the user name and password again. So in this scenario, if I store a hash on the disk I cannot retrieve plain-text string back from my hash as I've to send user name and password to the server in plain-text. The words massive security hole spring to mind. Does your server really require you to reauthenticate so often? Can't you invoke some kind of secured protocol instead? -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: why cannot assign to function call
On Sat, 10 Jan 2009 00:21:27 -, ru...@yahoo.com wrote: Joe Strout wrote: ru...@yahoo.com wrote: [snip] Pointers are passed and assigned by value, just as other types (disputedly except arrays) are. One can then use that pointer to manually effect pass-(the-value-pointed-to)-by-reference, or sharing, etc. [snip] In C (you have to explicitly ask for a reference (pointer) to something (other than arrays) if you want to use/pass a reference to something. If you simply use the name, you get by-value semantics. How would anyone develop that expectation if (from a different post in this thread), [Python's] idea of assignment is the same as anyone else's. I can think of two ways: 1. They're new to programming in general, and would have had the same expectation for any other language. OR, IIRC, Someone posted here that his experience was that 12-year old kids (presumably without programming experience) had no problem with Python and references when described as names given to an object. (From memory, can't locate the post right now.) 'Twas I. It was a rebuttal to your point that Python's assignment, parameter passing and data model is somehow inherently more difficult to wrap your brain around than that of other languages. It isn't; if anything it seems to be easier. 2. They already understand some other language, and then they come here and read wild claims that Python's assignment and parameter-passing semantics are different from other languages. Duped by this claim, they conclude that, if it's unlike other languages, then Python must have copy semantics. I have seen no evidence of that. If it were true I would expect at least some posts to refer to reading those wild claims. 3. They conflate assignment, parameter passing and the data model, bring in preconceptions of their own from other languages, and get caught out by them. It's quite easy to do, even within a language. Look at the number of times you had to say except arrays about C above. In Perl it is definitely true that you different syntax: @a = (1,2,3) @b = @a # Copy $b = \...@a # Reference Perl has different syntax for everything. It also has its own peculiarities of assignment and data model that make it a less than glowing example of comprehensibility. List flattening, for instance, is amazingly useful in many common Perl idioms, but really not what you expect during assignment. C is the same way for everything (including pointers) except arrays: Oh look, there's that exception again. It may be one can make a technical case that assignment is the same, but the reason I posted the code and results, was because the behavior of = in them produces clearly different results that = in Python. If you want to then say to someone, ignore those different results, '=' works exactly the same, all I can say is good luck. I will look forward to continuing to see weekly questions on this list. :-) It would help if you were using = on things that were conceptually the same across the languages, instead of things that only looked similar. Which is where the data model comes in, as has already been explained at length, several times now. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Detecting open files and forcing closure
On Sat, 10 Jan 2009 03:06:03 -, Andrew Robert arob...@townisp.com wrote: The usual scenario is that a user will leave a PDF open and then go home for the evening. They are simply viewing and not modifying the file. When the XCOPY executes, it signals a failure and subsequent scheduler job abend. What I need to do is detect if files are open for viewing and force a close before the copy operation is attempted. Sleeping and retrying the copy is not an option because the user will likely leave it open all night. Is there a way to detect the open files and close them out? I can't think of one off the top of my head, but this approach will cause more anguish than you would believe possible in any case. Imagine if the file was open for write; you've either just corrupted it or lost the most recent work if you force it closed. It sounds like you're trying to implement a backup strategy. If you are, I'd suggest your problem is XCOPY -- you really need something more combat capable instead. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: why cannot assign to function call
On Sat, 10 Jan 2009 18:44:37 -, ru...@yahoo.com wrote: What is the observable difference between converting an array to a reference (pointer) to that array and passing the reference by value, and passing the array by reference? This is a red herring, though. From either viewpoint, C arrays are anomalous in comparison with other C data types. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Does Python really follow its philosophy of Readability counts?
On Wed, 14 Jan 2009 02:27:09 -, Paul Rubin http://phr.cx@nospam.invalid wrote: But, if something is done by convention, then departing from the convention is by definition unconventional. If you do something unconventional in a program, it could be on purpose for a reason, or it could be by accident indicating a bug. I wouldn't violently object to having some means of policing class or module privacy, but it does have consequences. When it's a convention, you can break it; when it isn't, you can't, even if you do have good reason. Add that to the obviousness of the leading underscore = private convention, and I just don't see a burning need for it, that's all. -- Rhodri James *-* Wildebeeste Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list