shelve non-transparency
class x: pass z = x() z.a = 'a' d = {'a': z} for i in range(5): print id(d['a']) prints the same id 5 times as you'd expect. d = shelve('filename') d['a'] = z for i in range(5): print id(d['a']) prints five different id's. So, for example, y = d['a'] y.x = 'x' fails to update the shelve. The reason is sort of understandable but I hadn't guessed it ahead of time (I'd actually forgotten that d wasn't a normal dict, which you're supposed to be able to do if abstraction works properly), and it caused a bug in my program that took a little while to figure out. I wonder if some fix is possible. -- http://mail.python.org/mailman/listinfo/python-list
Re: Jargons of Info Tech industry
l v [EMAIL PROTECTED] wrote: Mike Schilling wrote: A formatting-only subset of HTML would be useful for both e-mail and Usenet posts. I would *agree* (your news reader may bold that last word) It had bloody better not. You're cross-posting this to a C newsgroup, where *ptr* 4 is a legal (albeit inadvisably spaced) expression. Richard -- http://mail.python.org/mailman/listinfo/python-list
Externally-defined properties?
Frankly, I was surprised this worked at all, but I tried creating a property outside of a class (i.e. at the module level), and it seems to behave as a property: def get_x(ob): ... global x ... return str(x) ... def set_x(ob, value): ... global x ... x = int(value) ... def del_x(ob): ... global x ... del x ... def x_access(): ... return property(get_x, set_x, del_x, X defined externally?) ... class Accessor(object): ... s_x = x_access() ... def __str__(self): ... print Accessor has x = %s % self.s_X ... a = Accessor() a.s_x = 3 a.s_x '3' dir() ['Accessor', '__builtins__', '__doc__', '__name__', 'a', 'del_x', 'get_x', 'p', 'set_x', 'x', 'x_access'] x 3 (of course in the real example, x will probably be in an entirely different module, used as a library -- the client code just calls a function to get a property that is automatically managed for it). So far, the only problem I see is that it only works if the property is assigned to a new-type class attribute (otherwise, the first assignment simply replaces the property). I'm thinking of using this to tie a property of a class to an external data source (a joystick axis, in fact -- or at least its last-polled value). There is a more convential way to do this, of course -- I could just use a get_value function, but there is something attractive about have a variable that is simply bound to the external data source like this. It seems like a good way to encapsulate functionality that I don't really want the high level class to have to think about. I mention it here, because I've never seen a property used this way. So I'm either being very clever, or very dumb, and I would be interested in opinions on which applies. ;-) Am I about to shoot myself in the foot? Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com -- http://mail.python.org/mailman/listinfo/python-list
Re: where does __class__ come from?
You might find the chapter 3.3 (in my python 2.3.4, it's Special Method names) in the reference manual useful, it is the only place I have found sofar that describes most of these special methods. It does however not contain __class__. I don't know where in the reference manual to find it's description, probaly in some Special attribute names chapter I can't find. Diez B. Roggisch [EMAIL PROTECTED] 08/23/05 11:26 pm Where does __class__ come from, what does it mean and what else is being hidden? I am used to using dir(...) to figure out what I can play with. Clearly that does not always work... :-( Your question has benn answered - let me just add this from the dir()-docs: Note: Because dir() is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. from http://docs.python.org/lib/built-in-funcs.html Regards, Diez -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
FileIO problem
i'm havin a problem with this simple program. i need the output of this loop to be written to a file but i dont know how to do it!! this is what i have right now: gclas = raw_input(What is the class:) count = 0 while count != 1000: count = count + 1 print Admin forceclass , count , gclas i know the IO script. i tried calling it a function, but i got an error that says i cant call funtions for writing: gclas = raw_input(What is the class:) def Princlas(): count = 0 while count != 1000: count = count + 1 print Admin forceclass , count , gclas #asks for file name a = raw_input(What is new file name:) out_file = open(a,w) #this is the input of text out_file.write(Princlas) out_file.close() i know i need to get it to a string but i dont know how?Any solution or help i s more that welcome -- http://mail.python.org/mailman/listinfo/python-list
Re: Logging all activity on a tty/pty?
I only do this on Linux, and it will probably not work on all versions of Unix, not even to mention Windows, but I basically have used the code of Pexpect and removed the part that does the expecting. ;-) The author of the Pexpect module also has clearly documented potential pitfalls in his FAQ. I think you can find it on pexpect.sourceforge.org See also the documentation of the pty module. Dan Stromberg [EMAIL PROTECTED] 08/24/05 1:54 am Is there a way, using python, to (voluntarily) log all activity in a given shell, in a way that should work on pretty much all *ix's with a port of python? Thanks! -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: FileIO problem
Layin'_Low enlightened us with: count = 0 while count != 1000: count = count + 1 print Admin forceclass , count , gclas I think you want: output = file('out', 'w') gclas = raw_input(What is the class:) for count in range(1000): output.write(Admin forceclass %4i %s\n % (count , gclas)) output.close() Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa -- http://mail.python.org/mailman/listinfo/python-list
Re: shelve non-transparency
The option writeback=True seems to work: # put something in the shelve import shelve class C(object): pass s = shelve.open(x.shelve) s[x] = C() s.close() # read it s = shelve.open(x.shelve, writeback=True) c = s[x] c.attr = 1 print s[x].attr # = 1 s.close() Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: FileIO problem
Try this: gclas = raw_input(What is the class:) def Princlas(): count = 0 while count != 1000: count = count + 1 return Admin forceclass %s %s % ( count , gclas ) #asks for file name a = raw_input(What is new file name:) out_file = open(a,w) #this is the input of text out_file.write(Princlas()) out_file.close() i know i need to get it to a string but i dont know how? Your functions should RETURN a string, with the return statement. Another issue: you cannot write the function itself, only its result: out_file.write(Princlas()) instead of out_file.write(Princlas) -- http://mail.python.org/mailman/listinfo/python-list
Re: list insertion
Randy Bush enlightened us with: hold = self.next self.next = DaClass(value) self.next.next = hold shouldn't that last line be this? self.next.prev = hold but i suspect (from print statement insertions) that the result is not as i expect. What did you expect, and what did you ovserve? Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa -- http://mail.python.org/mailman/listinfo/python-list
Re: Inline::Python, pyperl, etc.
Eli Stevens (WG.c) enlightened us with: I've bumped into some snags with pyperl (can't import perl2.so? But it's right there in site-packages/ !), and I'm wondering if it's bitrot or a config error on my end. If the .so file is as old as you described, it's probably linked to an old version of python. Try recompiling it. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa -- http://mail.python.org/mailman/listinfo/python-list
What's the matter with this code section?
Here is the source: #! /bin/python [EMAIL PROTECTED] This is a xunit test framework for python, see TDD for more details class TestCase: def setUp(self): print setUp in TestCase pass def __init__(self, name): print __init__ in TestCase self.name = name def run(self): print run in TestCase self.setUp() method = getattr(self, self.name) method() class WasRun(TestCase): def __init__(self, name): print __init__ in WasRun self.wasRun = None TestCase.__init__(self, name) def testMethod(self): print testMethod in WasRun self.wasRun = 1 def run(self): print run in WasRun method = getattr(self, self.name) method() def setUp(self): print in setUp of WasRun self.wasSetUp = 1 class TestCaseTest(TestCase): def testRunning(self): print testRunning in TestCaseTest test = WasRun(testMethod) assert(not test.wasRun) test.run() assert(test.wasRun) def testSetUp(self): print testSetUp in TestCaseTest test = WasRun(testMethod) test.run() assert(test.wasSetUp) # the program starts here print starts TestCaseTest(\testRunning\).run() TestCaseTest(testRunning).run() print starts TestCaseTest(\testSetUp\).run() TestCaseTest(testSetUp).run() And here is the result running under cygwin: $ ./xunit.py starts TestCaseTest(testRunning).run() __init__ in TestCase run in TestCase setUp in TestCase testRunning in TestCaseTest __init__ in WasRun __init__ in TestCase run in WasRun testMethod in WasRun starts TestCaseTest(testSetUp).run() __init__ in TestCase run in TestCase setUp in TestCase testSetUp in TestCaseTest __init__ in WasRun __init__ in TestCase run in WasRun testMethod in WasRun Traceback (most recent call last): File ./xunit.py, line 51, in ? TestCaseTest(testSetUp).run() File ./xunit.py, line 16, in run method() File ./xunit.py, line 45, in testSetUp assert(test.wasSetUp) AttributeError: WasRun instance has no attribute 'wasSetUp' -- http://mail.python.org/mailman/listinfo/python-list
Re: how to deal with space between numbers
Mohammed Altaj enlightened us with: I managed to do all these things , but i did it in the way that i am reading my data as strings ( no space between numbers) Keep the spaces, and use thestring.split() Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa -- http://mail.python.org/mailman/listinfo/python-list
Re: how to deal with space between numbers
Mohammed Altaj enlightened us with: Thanks a lot for your valuable answer, i like the way you code , but i would like to use my own, You don't learn to code properly if you always stick to your own stuff... so if it is possible for you and if you have time, please could you fix my code, so that i can do what i want. Learn from the answers you've been given. Read the documentation. Then you can incorporate them into your own program. You won't learn anything of you don't challenge yourself! Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa -- http://mail.python.org/mailman/listinfo/python-list
Re: pipes like perl
max(01)* enlightened us with: but i need to check the success/failure of the external command *before* closing the file! You can't, unless you have a more intimite knowledge of the command involved. If you know, for instance, that any output on stderr means an error, you can check for just that. Without knowledge of the command and it's output, the only thing you can check on is the exit code. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa -- http://mail.python.org/mailman/listinfo/python-list
Re: FileIO problem
thnx guys it was late and had just come from a bar and didnt reread the lines. thnx again for the help -- http://mail.python.org/mailman/listinfo/python-list
Re: python asp page keeps state across queries !?!?
nicolas_riesch enlightened us with: I notice that variables outside functions keep their value across queries. I don't know if it is normal. I think it's normal. To be sure, I tried a similar asp script written in VB script, and I can see that in VBscript, variables at this same level ARE NOT kept across different queries !!! So? Someone has an explanation ? Speed. No need to reload the module for each query. Just don't use any uninitialized module-scope variables. It's bad style anyway. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa -- http://mail.python.org/mailman/listinfo/python-list
Re: py-serial + CSV
McBooCzech enlightened us with: This (according to your suggestions) is my code which works for me import serial s = serial.Serial(port=0,baudrate=4800, timeout=20) while 1: line = s.readline() words = line.split(',') if words[0]==$GPRMC: print words[1], words[3], words[5] I just wonder if there is some beter (or as you are saying more pythonic:) aproach how to write such a piece of code. You could use regular expressions instead. And to make it even more pythonic, replace the while and the line = s.readline() with for line in s: Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa -- http://mail.python.org/mailman/listinfo/python-list
Re: Doubt C and Python
--- James [EMAIL PROTECTED] wrote: Some people with C background use Python instead of programming in C.why? Becuase it is much more efficient. -James What why it is more efficient. Kindly let me know with some details. regards Prabahar Send a rakhi to your brother, buy gifts and win attractive prizes. Log on to http://in.promos.yahoo.com/rakhi/index.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Network performance
[Roland] The client sends a number of lines (each ending with \n) and ends one set of lines with a empty line. [...] I was surprised to find that the performance was [poor]. Are you sending all the lines in a single packet: sock.send('\n'.join(lines)) or sending them one at a time: for line in lines: sock.send(line + '\n') ? If the latter, you are probably experiencing Nagle delays. Google will furnish you with any number of explanations of what that means, but in summary, one end of a TCP/IP connection should never send two consecutive small packets without receiving a packet from the other end. ('Small' typically means less than about 1400 bytes.) Each time you do that, you'll suffer an artificial delay introduced by TCP/IP itself. -- Richie Hindle [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
reg packages examples
Dear All, I want to know about Modules and packages. I can understand about Modules but I cannot understand about Packages. Kindly let me know about Packages with small example. I can understand conceptually but I don't know how to write programmatically. regards Prabahar Send a rakhi to your brother, buy gifts and win attractive prizes. Log on to http://in.promos.yahoo.com/rakhi/index.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Anyone recognize this numeric storage format - similar to float, but not quite
This appears to be a repost, perhaps not by the op but due to a glitch somewhere, of a question posted about a month ago and answered. [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] We are working on a project to decipher a record structure of an old accounting system that originates from the late80's mid-90's. We have come across a number format that appears to be a float but doesn't match any of the more standard implementations. so we are hoping this is a recognizable number storage format with an identifiable name AND pre-built conversion method similiar to the struct modules available in python. Here is what we have determined so far. Example Number: 1234567890 This get stored on disk as 8 bytes, resulting in the following HEX characters; 00 00 00 A4 05 2c 13 9f If we changed the order so that it is little Endian we get; 9F 13 2c 05 A4 00 00 00 If the HEX is converted to binary it looks like; 1001 00010011 00101100 0101 10100100 0 If the example number 1234567890 is converted to binary it looks like; 10010011 00101100 0101 1010010 To extract the example number, you need to do the following; 1) take the decimal value of the first byte and subtract 128 2) This tells you how many of the following bits to are significant and must be read 3) Once the remaining bits are read, reverse the first bit of that group (ie if it is a 0 make it a 1) 4) convert the result to decimal ... and presto, the example number ! Using a fixed width font it is easy to see the match at the bit level; 1001 0001001100101100010110100100 100100110010110001011010010 If you are interested, the following are three other examples; Orig Hex: 00 00 00 60 92 96 72 A0 Actual Value: 4069954144 Orig Hex: 00 00 80 22 A3 26 3C A1 Actual Value: 6313297477 So ... does anyone recognize this ?? Is there a built-in conversion method in Python ?? Thanks in advance. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Reg Python Modules/Packages
Dear All, I know how to use modules. But I want to know how to create package. Can any one let me know how to write package through small specimen code. regards PRabahar Send a rakhi to your brother, buy gifts and win attractive prizes. Log on to http://in.promos.yahoo.com/rakhi/index.html -- http://mail.python.org/mailman/listinfo/python-list
execfile in global scope
I need to execfile() from a function in order to set value for a global variable from inside the executed file. I know there are globals and locals optional arguments for execfile, but I just can't figure out how to use them correctly. Here is an example: Change.py = x = 555 Main.py === def changevar(): execfile(change.py) x = 111 # global var changevar() print x # returns 111 instead of 555 -- http://mail.python.org/mailman/listinfo/python-list
Re: while c = f.read(1)
Op 2005-08-24, Magnus Lycka schreef [EMAIL PROTECTED]: Antoon Pardon wrote: Such a PEP would have no chance of being accepted, since it would break to much existing code. What's the point of this thread then? I only hope to impress people that the way python treats 'nothing' in a condional context is not so obvious as seems to be accepted here. But how can you do this when somewhere else '' is used as an indication for an EOF. If that's your problem, I guess that's what you should attack, not that Python considers nothing to be nothing even it might some time become something. IMO the two are linked. People use '' as an EOF because the call they are working with returns strings and they need a way to end a loop. Since if var: is considered beautifull they search for a nothing value and since they were working with strings, '' gets chosen. Network programming with Python works pretty well though, so it seems this is a non-issue too. I think the typical comment is to replace if s != '': with if s: in contexts where s is always a string, And it is IMO this kind of comments that lead to '' being used as an EOF. Huh? Aren't the Python APIs just mirroring the behaviour of the underlying C APIs? That may depend on how strict the meaning of mirroring is, you are using. I would say no. Even if the answer is yes I would say that chosing such values on that basis was a bad design choice. or to replace if expr != False: with if expr: in cases where expr is an expression that returns True or False etc. In some cases, obvious bugs, such as if (a and b) == True: where the programmer should have written if (a and b): are pointed out. This is not such an obvious bug. Because python allows non boolean operands with and the two don't behave the same. How do you know which behaviour the other person wants? I think you misread my text. If the programmer should have written if (a and b):, adding ==True will cause different behaviour unless True (or 1) is the only non-False value that b can have. This would not be obvious for someone who expects that the results of logical operations will return boolean values. So? How do you know what the writer of the code expects. You originaly wrote it was an obvious bug, how do you come to that conclusion. I have yet to see a mathematical work where 0, or any kind of empty sequence is treated as false. In mathematics accuracy is considered vitaly important and won't be sacrified to remove redundancy. Boolean expression are always written out fully. Dear Antoon. The if statement interprets the result of an expression to determine whether or not to execute a block of code. If x is an expression that returns True or False, then x==True is an equivalent expression. It's just not written in its minimal form. But we were talking about interpreting 0, '', (), [], and {} directly in a conditional context. No mathematical text will just contain a line like a = b 10 when what is meant is: a != 0 = b 10 It's like writing a / b * 100 % instead of just a / b in a mathematical equation. The first version contains some kind of noise that just looks ugly for people who know that 100%==1. Why multiply with 1? At least in my home town, the MBA students write stuff like that, but mathematicians and engineers would just think it was ugly. But you can't transfer this situation to python, because python allows non Boolean values to be interpreted in a conditional context. I have code somewhere that looks like this: if var is True: and that is exactly how it should be. The if branch should not be taken if var would be 5. I even have code that looks like: if var is not False: And although in a logical context those two would be equivallent to each other and to just if var:, they are not equivallent in a python context. Yet I see a lot of suggestions here to change logical expressions in python code, seemingly based on the fact that they would be equivallent in a logical context. But you don't know if the logic expression are redundant. The suggestions made are usually not equivallent. I think I know. Please point out if I made some mistake. It's pretty common that people fail to reduce logical expressions. I've seen C++ code checking for overlapping periods looking roughly like this: if ((start1=start2 and stop1=start2 and stop1=stop2) or (start1=start2 and stop1=stop2) or (start1=start2 and stop1=stop2) or (start1=start2 and start1=stop2 and stop1stop2)) For that person, his code might actually have been clearer than the less cluttered version I changed it to: if (start1=stop2 and start2=stop1) At least he spent a few minutes staring at it before he could accept that they were equivalent. (Maybe he just gave up.) I think he did, because both expression are not equivallent unless some implicite constraints make them so. Values where both expressions differ are: start1=67, stop1=9,
Re: list insertion
On Tue, 23 Aug 2005 20:58:11 -0700, Randy Bush wrote: i am trying to insert into a singly linked list hold = self.next self.next = DaClass(value) self.next.next = hold but i suspect (from print statement insertions) that the result is not as i expect. as the concept and code should be very common, as i am too old for pride, i thought i would ask. mahalo, randy The example above looks like it would work, as long as other stuff you _don't_ show is fine. Specifically, how do you handle the case when the list is empty? Better to show a more complete example with output and how that is not what you expect. Ross -- http://mail.python.org/mailman/listinfo/python-list
slip beta code released
Hi All Just released the code from my little excusion in socket coding with Python. I still need many pointers esp wrt. the way I hacked wx into the code. Comments welcomed. Quick start --- start up the service: slip.py -s all hosts running slip will be discovered, to see who else is around: slip.py -l debug view: slip.py -la to send files: slip.py c:\mp3\alphavi* bob to send a message slip.py -m bob catch this if you use windows you can add an explorer extention by creating a link to: slip.exe -sendto and adding it to your sendto directory. if you use explorer you can now sendto and a wx window will popup asking you which peer to send it to. http://prdownloads.sourceforge.net/slip-p2p/slip_beta_0.3.zip?download Regards Marinus comments ? [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Line Removal strategy
On 23 Aug 2005 14:07:15 -0700, PyPK [EMAIL PROTECTED] wrote: Hi I am looking for a simple algorithm for removing straight lines in a given Image using something like an PIL or simpler. The simplest is if you are in control of drawing in the first place and don't draw the lines ;-) Otherwise, you need to define your requirements a little more precisely. E.g., replacing horizontal and vertical runs of identical pixels of a given color with another given background color could be one definition. Removing an arbitrarily diagonal anti-aliased line of some undprcified width running through a speckled background is a different problem ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the matter with this code section?
On 24 Aug 2005 00:18:00 -0700, Johnny Lee [EMAIL PROTECTED] wrote: AttributeError: WasRun instance has no attribute 'wasSetUp' It means exactly what it says. The last line of your TestCaseTest classes testSetUp method refers to test.wasSetUp. So far as I can see, test is an instance of your WasRun class, and I don't see a wasSetUp attribute being set anywhere. -- Cheers, Simon B, [EMAIL PROTECTED], http://www.brunningonline.net/simon/blog/ -- http://mail.python.org/mailman/listinfo/python-list
Re: loop in python
Terry Hancock wrote: On Tuesday 23 August 2005 05:35 am, bruno modulix wrote: (snip) ot If you hope to be taken seriously, please abandon the sms-talk style here. /ot I think it's reasonably clear that neither poster hoped to be taken seriously. :-D Err... I guess that to be taken seriously (in french: être pris au sérieux) has some other meaning in english :-/ -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: Anyone recognize this numeric storage format - similar to float, but not quite
On 23 Aug 2005 19:04:45 -0700, [EMAIL PROTECTED] wrote: We are working on a project to decipher a record structure of an old accounting system that originates from the late80's mid-90's. We have come across a number format that appears to be a float but doesn't match any of the more standard implementations. so we are hoping this is a recognizable number storage format with an identifiable name AND pre-built conversion method similiar to the struct modules available in python. Here is what we have determined so far. Example Number: 1234567890 This get stored on disk as 8 bytes, resulting in the following HEX characters; 00 00 00 A4 05 2c 13 9f If we changed the order so that it is little Endian we get; 9F 13 2c 05 A4 00 00 00 If the HEX is converted to binary it looks like; 1001 00010011 00101100 0101 10100100 0 If the example number 1234567890 is converted to binary it looks like; 10010011 00101100 0101 1010010 To extract the example number, you need to do the following; 1) take the decimal value of the first byte and subtract 128 2) This tells you how many of the following bits to are significant and must be read 3) Once the remaining bits are read, reverse the first bit of that group (ie if it is a 0 make it a 1) 4) convert the result to decimal ... and presto, the example number ! Using a fixed width font it is easy to see the match at the bit level; 1001 0001001100101100010110100100 100100110010110001011010010 If you are interested, the following are three other examples; Orig Hex: 00 00 00 60 92 96 72 A0 Actual Value: 4069954144 Orig Hex: 00 00 80 22 A3 26 3C A1 Actual Value: 6313297477 So ... does anyone recognize this ?? Is there a built-in conversion method in Python ?? Thanks in advance. Not looking too closely, but I recall something similar (although I suspect that the bit you are reversing is a sign bit that shadows a known constant MSB 1 for non-zero numbers, and shouldn't just be reversed): http://groups.google.com/group/comp.lang.python/browse_thread/thread/42150ccc20a1d8d5/4aadc71be8aeddbe#4aadc71be8aeddbe Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list
Re: Externally-defined properties?
On Wed, 24 Aug 2005 01:15:03 -0500, Terry Hancock [EMAIL PROTECTED] wrote: Frankly, I was surprised this worked at all, but I tried creating a property outside of a class (i.e. at the module level), and it seems to behave as a property: def get_x(ob): ... global x ... return str(x) ... def set_x(ob, value): ... global x ... x = int(value) ... def del_x(ob): ... global x ... del x ... def x_access(): ... return property(get_x, set_x, del_x, X defined externally?) ... class Accessor(object): ... s_x = x_access() ... def __str__(self): ... print Accessor has x = %s % self.s_X ... a = Accessor() a.s_x = 3 a.s_x '3' dir() ['Accessor', '__builtins__', '__doc__', '__name__', 'a', 'del_x', 'get_x', 'p', 'set_x', 'x', 'x_access'] x 3 (of course in the real example, x will probably be in an entirely different module, used as a library -- the client code just calls a function to get a property that is automatically managed for it). So far, the only problem I see is that it only works if the property is assigned to a new-type class attribute (otherwise, the first assignment simply replaces the property). I'm thinking of using this to tie a property of a class to an external data source (a joystick axis, in fact -- or at least its last-polled value). There is a more convential way to do this, of course -- I could just use a get_value function, but there is something attractive about have a variable that is simply bound to the external data source like this. It seems like a good way to encapsulate functionality that I don't really want the high level class to have to think about. I mention it here, because I've never seen a property used this way. So I'm either being very clever, or very dumb, and I would be interested in opinions on which applies. ;-) Am I about to shoot myself in the foot? ISTM you are basically exploiting your freedom to define the getter/setter/deleter functions of a property any way you please. Another way, if you just want a proxy object whose property attributes access designated other objects' attributes, you could use a custom descriptor class, e.g., class Indirect(object): ... def __init__(self, tgtattr, tgtobj): ... self.tgtattr = tgtattr ... self.tgtobj = tgtobj ... def __get__(self, inst, cls=None): ... if inst is None: return self ... return getattr(self.tgtobj, self.tgtattr) ... def __set__(self, inst, value): ... setattr(self.tgtobj, self.tgtattr, value) ... def __delete__(self, inst): ... delattr(self.tgtobj, self.tgtattr) ... A place to put properties: class Accessor(object): pass ... An example object to access indirectly class Obj(object): pass ... obj = Obj() Making Accessor instance attribute 'xobj' access 'obj' attribute of Obj instance obj Accessor.xobj = Indirect('obj', obj) An Accessor instance to use for the property attribute magic a = Accessor() Set obj.obj = 123 indirectly a.xobj = 123 Check vars(obj) {'obj': 123} Set up access to an object attribute in a different module import sys Accessor.sin = Indirect('stdin', sys) a.sin open file 'stdin', mode 'r' at 0x02E8E020 Accessor.pi = Indirect('pi', __import__('math')) a.pi 3.1415926535897931 a.pi = 3 a.pi 3 import math math.pi 3 I'd say there's possibilities for shooting yourself in the foot. Maybe passing a code to Indirect to enable get/set/del selectively would help. Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list
Inheritance problem ?
Hello all, I'm trying to implement a common behavior for some object that can be read from a DB or (when out of network) from an XML extract of this DB. I've then wrote 2 classes, one reading from XML the other from the DB, both inheritating from a common one where I want to implement several common methods. Doing this, I've come to some behaviour I can't explain to myself, which I've reproduced in the example bellow : - class myfather: def __repr__(self): return \t a=+self.a+\n\t b=+self.b class mychilda(myfather): def __init__(self,a): self.a= a def __getattr__(self,name): return Undefined for mychilda class mychildb(myfather): def __init__(self,b): self.b= b def __getattr__(self,name): return Undefined for mychildb a= mychilda(a) b= mychildb(b) print a:\n+str(a) print b:\n+str(b) - I was expecting to get : a: a= a b= Undefined for mychilda b: a= Undefined for mychildb b= b but I get the following error : File /home/thierry/mytest.py, line 20, in ? print a:\n+str(a) TypeError: 'str' object is not callable Could someone explain me what I missed ? Thanks in advance ! -- http://mail.python.org/mailman/listinfo/python-list
Re: Anyone recognize this numeric storage format - similar to float, but not quite
On Wed, 24 Aug 2005 04:10:07 -0400, Terry Reedy [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] We are working on a project to decipher a record structure of an old accounting system that originates from the late80's mid-90's. We have come across a number format that appears to be a float but doesn't match any of the more standard implementations. so we are hoping this is a recognizable number storage format with an identifiable name AND pre-built conversion method similiar to the struct modules available in python. [...] moved from top-posted position This appears to be a repost, perhaps not by the op but due to a glitch somewhere, of a question posted about a month ago and answered. /moved UIAM the more or less recent original you are thinking of turned out to be straight IEEE double format, and I think this is not, though I think it looks like one that was answered (by me ;-) quite a while ago (Dec 1 2003). Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list
Re: Binary Trees in Python
[diegueus9] == [diegueus9] Diego Andrés Sanabria diegueus9 writes: [diegueus9] Hello!!! I want know if python have binary trees and [diegueus9] more? The latest boost, 1.33, says it has a python wrapper for the boost graph library. Boost explicitely states that it's experimental, but my emerge was successful. See http://boost.org -Chris -- http://mail.python.org/mailman/listinfo/python-list
Eric3 for Windows not firing up.
Hi, I downloaded Python 2.4.1 for Windows and PyQtGPL10.exe and Eric3snapshot2005-04-10.exe from http://pythonqt.vanrietpaap.nl/ They seemed to install fine. Python 2.4.1 works. I tried Linguist and Designer, but there was some entrypoint error in qt-mt3.dll. I copied this file into the c:\windows directory, and then QT at least fired up, with Linguist and Designer now working. Then I tried Eric3, but I get the following: The procedure entry point [EMAIL PROTECTED]@@MAEXPAVQWheelEvent@@@Z could not be located in the dynamic link library qt-mt3.dll. Any clues how to fix this one? thanks Michael -- http://mail.python.org/mailman/listinfo/python-list
jython debugger
Hi, I am looking for an ide debugger for jython: is there someone with some suggestions ? Thanks, Adriano -- http://mail.python.org/mailman/listinfo/python-list
Re: execfile in global scope
What about : globdict= globals() def changevar(): global globdict execfile(changevar.py,globdict) x = 111 # global var changevar() print x # returns 111 instead of 555 -- http://mail.python.org/mailman/listinfo/python-list
Re: execfile in global scope
What about : globdict= globals() def changevar(): global globdict execfile(changevar.py,globdict) x = 111 # global var changevar() print x # returns 111 instead of 555 -- http://mail.python.org/mailman/listinfo/python-list
Variables in REs
Anyway to set variables in REs. Meaning: I have the RE re.compile(r'/[^/]*') for example and I want to use it on both Win32 machines and Unix machnes. Meaning tha tI need to be able to control the '/' before compiling. I want to create and if and decide what the system is and then put the right char in a variable and compile the RE using that varialbe. I am quite a noob, so I know the question might sound stupid, but any help will be appreciated. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: list insertion
hold = self.next self.next = DaClass(value) self.next.next = hold shouldn't that last line be this? self.next.prev = hold single threaded list What did you expect, and what did you ovserve? i will try to distill a case randy -- http://mail.python.org/mailman/listinfo/python-list
Re: slip beta code released
I forgot to say that this is my little P2P pet project. Need to send files quickly between systems without having to set up shares or start ftp servers. The idea is to make it easy to slip files between parties esp if they are on different OS's. -- http://mail.python.org/mailman/listinfo/python-list
Re: Variables in REs
Use os.sep to get / or \ or whatever character used to build pathes on the os you're working on -- http://mail.python.org/mailman/listinfo/python-list
Re: The ONLY thing that prevents me from using Python
[Chris] Not to be a shill, but I'd be interested in testimonials on http://linode.org/ I wonder if virtualization is the next killer app. Certainly blows the WTF my ISP? question away... I can't speak for linode.org, but I have a Xen VPS from rimuhosting.com and it's early days but so far I've been very impressed. It's $19/mo (normally $20 but they kindly gave me a 5% Open Source Developer discount) which is not that much more than a decent shared hosting account. You need to be comfortable with administering your own Linux box, but these days that's not difficult. (NB. entrian.com is not running on it yet.) -- Richie Hindle [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Warning when doubly linked list is defined gloablly
Hi., In my api.py file 'g_opt_list' is defined globally g_opt_list =[[],[],[],[],[],[],[]] I am using this global list in the fucntion def function (): gloabl g_opt_list when I run the py file, I am getting the Following Error SyntaxWarning: name 'g_opt_list' is used prior to global declaration Please let me know how to remove this error --BestRegars., --Chandra -- http://mail.python.org/mailman/listinfo/python-list
Re: where does __class__ come from?
Adriaan Renting wrote: You might find the chapter 3.3 (in my python 2.3.4, it's Special Method names) in the reference manual useful, it is the only place I have found sofar that describes most of these special methods. It does however not contain __class__. I don't know where in the reference manual to find it's description, probaly in some Special attribute names chapter I can't find. Some of these are in the library reference, but lot's of them are also in the language reference - which has bitten me quite a few times, but by now I know where to look... Regards, Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Warning when doubly linked list is defined gloablly
chand wrote: In my api.py file 'g_opt_list' is defined globally g_opt_list =[[],[],[],[],[],[],[]] I am using this global list in the fucntion def function (): gloabl g_opt_list This is obviously wrong and not the code you wrote, global being written horribly wrong - which should teach you an important lesson: post actual code that exposes the problem, not something you think that is working. Then we might be able to help you. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Warning when doubly linked list is defined gloablly
chand wrote: Hi., In my api.py file 'g_opt_list' is defined globally g_opt_list =[[],[],[],[],[],[],[]] I am using this global list in the fucntion def function (): gloabl g_opt_list global? when I run the py file, I am getting the Following Error SyntaxWarning: name 'g_opt_list' is used prior to global declaration Please let me know how to remove this error This happens in cases like a = 1 def c(): ... a ... global a Does your source only consist of the three lines above? (These would trigger a SyntaxError because of the typo...) You should provide a more complete example, so we can tell you where the problem is. Try to build a minimal file that reproduces the problem. Often you will find the line causing the error yourself - and the fix might be obvious to you -, if your strip stuff away. -- Benjamin Niemann Email: pink at odahoda dot de WWW: http://www.odahoda.de/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Inheritance problem ?
On Wed, 24 Aug 2005 03:34:36 -0700, tooper wrote: Hello all, I'm trying to implement a common behavior for some object that can be read from a DB or (when out of network) from an XML extract of this DB. I've then wrote 2 classes, one reading from XML the other from the DB, both inheritating from a common one where I want to implement several common methods. Doing this, I've come to some behaviour I can't explain to myself, which I've reproduced in the example bellow : - class myfather: def __repr__(self): return \t a=+self.a+\n\t b=+self.b class mychilda(myfather): def __init__(self,a): self.a= a def __getattr__(self,name): return Undefined for mychilda class mychildb(myfather): def __init__(self,b): self.b= b def __getattr__(self,name): return Undefined for mychildb a= mychilda(a) b= mychildb(b) print a:\n+str(a) print b:\n+str(b) - I was expecting to get : a: a= a b= Undefined for mychilda b: a= Undefined for mychildb b= b but I get the following error : File /home/thierry/mytest.py, line 20, in ? print a:\n+str(a) TypeError: 'str' object is not callable Could someone explain me what I missed ? Thanks in advance ! try new style classes. class myfather(object): see http://users.rcn.com/python/download/Descriptor.htm HTH Arjen -- http://mail.python.org/mailman/listinfo/python-list
Re: Inheritance problem ?
tooper wrote: Hello all, I'm trying to implement a common behavior for some object that can be read from a DB or (when out of network) from an XML extract of this DB. I've then wrote 2 classes, one reading from XML the other from the DB, both inheritating from a common one where I want to implement several common methods. Doing this, I've come to some behaviour I can't explain to myself, which I've reproduced in the example bellow : - class myfather: def __repr__(self): return \t a=+self.a+\n\t b=+self.b class mychilda(myfather): def __init__(self,a): self.a= a def __getattr__(self,name): return Undefined for mychilda class mychildb(myfather): def __init__(self,b): self.b= b def __getattr__(self,name): return Undefined for mychildb a= mychilda(a) b= mychildb(b) print a:\n+str(a) print b:\n+str(b) - I was expecting to get : a: a= a b= Undefined for mychilda b: a= Undefined for mychildb b= b but I get the following error : File /home/thierry/mytest.py, line 20, in ? print a:\n+str(a) TypeError: 'str' object is not callable Could someone explain me what I missed ? Thanks in advance ! hi I am got python 2.4 and changed class myfather to new style classes class myfather(object) it worked. here is the output : a: a=a b=Undefined for mychilda b: a=Undefined for mychildb b=b But i myself still need explaination ;) regards jitu -- http://mail.python.org/mailman/listinfo/python-list
Re: Anyone recognize this numeric storage format - similar to float, but not quite
Thanks Bengt for directing me to your previous post. I think I agree with you on the reversing bit and the constant MSB. In reworking my examples I was always changing the 0 to 1. -- http://mail.python.org/mailman/listinfo/python-list
Re: reg packages examples
praba kar wrote: Dear All, I want to know about Modules and packages. I can understand about Modules but I cannot understand about Packages. Kindly let me know about Packages with small example. I can understand conceptually but I don't know how to write programmatically. regards Prabahar Prabahar: In your headers I see In-Reply-To: [EMAIL PROTECTED]. This means that people will see your message as part of another thread. It's better not to do that if you want your message to be read in the proper context. A package is simply a directory containing an __init__.py file, which is executed when the package is imported. Sub-packages are subdirectories of the package main directory containing __init__.py files, which will be executed when the sub-package is imported. Packages can also contains modules, which are regular Python files that are executed when the module is imported. So, in brief, packages are just a way to let you organize your code in to a set of mutually dependent modules and sub-packages, making source maintenance easier and allowing selective import of parts of the implemented functionality. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Logging all activity on a tty/pty?
Dan Stromberg wrote: Is there a way, using python, to (voluntarily) log all activity in a given shell, in a way that should work on pretty much all *ix's with a port of python? If it's just a simple transcript you're wanting see man script. -- Benji York -- http://mail.python.org/mailman/listinfo/python-list
Re: Inheritance problem ?
Thanks, at least makes it running ! I'll have to teach myself to move to this new style classes by default anyway... -- http://mail.python.org/mailman/listinfo/python-list
wanna stop by my homemade glory hole?
my husband is installing an extra bathroom poolside. there is a perfect size hole (unless you have a huge cock) to stick your dick through into the adjoing room. come around the side of my house(perfect if you look like a repair man) enter into the unfisnished bathroom and I'll service you from the other side. you can leave when your done, no talking or small talk. i want to do this before the hole gets patched up. its been a huge fantasy of mine ever since I've seen a glory hole online. you can email me for a time convienient for you. im home all-day most days so my schedule is open. do you prefer a certain color of lipstick? check out my pic and email here under kallegirl26 www.no-strings-fun.net/kallegirl26 ready and waiting, me ;o) -- http://mail.python.org/mailman/listinfo/python-list
Re: jython debugger
wait one more week... until there, pydev (http://pydev.sf.net) should already have debugger support for jython. Cheers, Fabio [EMAIL PROTECTED] wrote: Hi, I am looking for an ide debugger for jython: is there someone with some suggestions ? Thanks, Adriano -- Fabio Zadrozny -- Software Developer ESSS - Engineering Simulation and Scientific Software www.esss.com.br PyDev - Python Development Enviroment for Eclipse pydev.sf.net pydev.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: where does __class__ come from?
I did mean the Language reference. chapter Special method names. It contains a lot of the funky stuff like __dict__ and __getattr__. There is a little info in chapter 3.2 about __class__ : __class__ is the instance's class. Adriaan Renting| Email: [EMAIL PROTECTED] ASTRON | Phone: +31 521 595 217 P.O. Box 2 | GSM: +31 6 24 25 17 28 NL-7990 AA Dwingeloo | FAX: +31 521 597 332 The Netherlands| Web: http://www.astron.nl/~renting/ Diez B. Roggisch [EMAIL PROTECTED] 08/24/05 1:13 pm Adriaan Renting wrote: You might find the chapter 3.3 (in my python 2.3.4, it's Special Method names) in the reference manual useful, it is the only place I have found sofar that describes most of these special methods. It does however not contain __class__. I don't know where in the reference manual to find it's description, probaly in some Special attribute names chapter I can't find. Some of these are in the library reference, but lot's of them are also in the language reference - which has bitten me quite a few times, but by now I know where to look... Regards, Diez -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Should I move to Amsterdam?
http://www.slate.com/id/2124561/entry/2124562/ Nice little series by Seth Stevenson for Americans daydreaming about emigration. Somewhere, anywhere ... maybe Amsterdam? I've never been to the Netherlands myself, but it sounds very civilized. Extra Python connection, besides the obvious one: Is gezellig related to the Zen of Python? ( http://wordcraft.infopop.cc/eve/ubb.x/a/tpc/f/6351024471/m/2041067571/r/3901049571 ) -- Wade Leftwich Ithaca, NY -- http://mail.python.org/mailman/listinfo/python-list
Re: jython debugger
The PyDev environment (http://pydev.sourceforge.net/) for Eclipse appears to have Jython debug support, though I just tried it now and it did not work for me. The release notes http://pydev.sourceforge.net/features.html seem to suggest it should, so perhaps I just haven't configured something properly. PyDev currently only works with Java 1.5; Java 1.4 is expected, but not available yet. If you try it, let us know if you can get it to work. Frank. [EMAIL PROTECTED] wrote: Hi, I am looking for an ide debugger for jython: is there someone with some suggestions ? Thanks, Adriano -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the matter with this code section?
Johnny Lee wrote: Here is the source: (snip) class TestCaseTest(TestCase): def testRunning(self): print testRunning in TestCaseTest test = WasRun(testMethod) assert(not test.wasRun) test.run() assert(test.wasRun) def testSetUp(self): print testSetUp in TestCaseTest test = WasRun(testMethod) test.run() Shouldn't it be test.setUp() instead ? Unless the problem is here: ### TestCase.run() calls self.setUp() class TestCase: (snip) def run(self): print run in TestCase self.setUp() method = getattr(self, self.name) method() ### WasRun.run() doesn't call self.setUp() class WasRun(TestCase): (snip) def run(self): print run in WasRun method = getattr(self, self.name) method() def setUp(self): print in setUp of WasRun self.wasSetUp = 1 BTW, if the only reason for overloading WasRun.run() is to print run in WasRun, you can also modify parent's class run() method so it display the effective class name, not an hard-coded one: class TestCase: (snip) def run(self): print run in %s % self.__class__.__name__ self.setUp() method = getattr(self, self.name) method() and then remove run() from WasRun. There should be a simple solution to 'aspect' the debug/trace stuff with a decorator, like: def traced(func): def _wrapper(self, *args, **kwargs): print %s method in %s class % (func.func_name, self.__class__.__name) return func(self, *args, **kwargs) return _wrapper(func) class TestCase: @traced def run(self): self.setUp() method = getattr(self, self.name) method() (not tested, and I don't have much experience with decorators...) -- bruno desthuilliers ruby -e print '[EMAIL PROTECTED]'.split('@').collect{|p| p.split('.').collect{|w| w.reverse}.join('.')}.join('@') python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: how to deal with space between numbers
Mohammed Altaj wrote: Thanks a lot for your valuable answer, i like the way you code , Thanks. but i would like to use my own, so if it is possible for you and if you have time, please could you fix my code, so that i can do what i want. Because i am using the this out put to another one , and i have the same problem. I will really appreciate it !!! No problem, it's 500 euro a day. Please give me your snailmail and the whole code and spec, so I can send you back a contract. I'll start as soon as I'll receive the contract signed and the first check. best regards, -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: Should I move to Amsterdam?
Well, I'm not sure if Amsterdam is nice, but the Netherlands is o.k., except for the weather. I'd like to descripbe it as 49 weeks of autumn, 1 week of spring, 1 week of summer, 1 week of winter. Currently my employer only has an opening for a Microwave Antenna designer though, sorry no Python coders. http://www.astron.nl/astron/jobs/index.htm Seems like a nice column, I'll read it completely some other time. Wade [EMAIL PROTECTED] 08/24/05 2:31 pm http://www.slate.com/id/2124561/entry/2124562/ Nice little series by Seth Stevenson for Americans daydreaming about emigration. Somewhere, anywhere ... maybe Amsterdam? I've never been to the Netherlands myself, but it sounds very civilized. Extra Python connection, besides the obvious one: Is gezellig related to the Zen of Python? ( http://wordcraft.infopop.cc/eve/ubb.x/a/tpc/f/6351024471/m/2041067571/r/3901049571 ) -- Wade Leftwich Ithaca, NY -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Inheritance problem ?
The stuff on Descriptor.htm was really good . Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Variables in REs
Such a sweet and simple way. Thanks. tooper wrote: Use os.sep to get / or \ or whatever character used to build pathes on the os you're working on -- http://mail.python.org/mailman/listinfo/python-list
Getting rid of close failed: [Errno 0] No Error on Win32
I am using os.popen3 to call a console process and get its output and stderr. However on Win32 (and not OS X) I also get the Errno message. It's printed to the screen, which I wish to keep clean. How can disable this notification? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: global interpreter lock
Mike Meyer wrote: Bryan Olson writes: Mike Meyer wrote: The rule I follow in choosing my tools is Use the least complex tool that will get the job done. Even if a more complex tool could do the job better? In that case, the simpler model isn't necessarily getting the job done. I purposely didn't refine the word job just so this would be the case. I didn't ask about any particular case. You stated a general rule you follow, and I think that rule is nuts. Now I've gotten off-topic. Threads are winning, and the industry is going to multiple processors even for PC-class machines. Might as well learn to use that power. I own too many orphans to ever confuse popularity with technical superiority. The issue here is whether to confuse reality with what one might wish reality to be. I've learned how to use threads, and done some non-trivial thread proramming, and hope to never repeat that experience. It was the second most difficult programming task I've ever attempted(*). Great -- lets see it! Can you point out what parts were so hard? How would you have solved the same problems without threads? As I said above, the real problem isn't threads per se, it's that the model for programming them in popular languages is still primitive. So far, to achieve the non-repitition goal, I've used async I/O, restricted my use of real threads in popular languages to trivial cases, and started using servers so someone else gets tod eal with these issues. Then maybe we should listen to those other people. Is there a successful single-line-of-execution async-I/O based server that provides a service as sophisticated as the modern relational- database engines? Why do you think that is? -- --Bryan -- http://mail.python.org/mailman/listinfo/python-list
Re: Inheritance problem ?
Not always easy to follow but great ! Using __str__ instead of __repr__ makes it work also with old style (thanks to Simon Brunning for suggesting it, and with your link I even now understand why !) -- http://mail.python.org/mailman/listinfo/python-list
Re: Proposed PEP: New style indexing, was Re: Bug in slice type
Paul Rubin wrote: Bryan Olson writes: seq[3 : -4] we write: seq[3 ; $ - 4] +1 I think you're wrong about the +1. I defined '$' to stand for the length of the sequence (not the address of the last element). When square-brackets appear within other square-brackets, the inner-most bracket-pair determines which sequence '$' describes. (Perhaps '$$' should be the length of the next containing bracket pair, and '$$$' the next-out and...?) Not sure. $1, $2, etc. might be better, or $tag like in regexps, etc. Sounds reasonable. [...] Hmm, tuples are hashable and are already valid indices to mapping objects like dictionaries. Having slices means an object can implement both the mapping and sequence interfaces. Whether that's worth caring about, I don't know. Yeah, I thought that alternative might break peoples code, and it turns out it does. -- --Bryan -- http://mail.python.org/mailman/listinfo/python-list
Re: Proposed PEP: New style indexing, was Re: Bug in slice type
Kay Schluehr wrote: Bryan Olson wrote: Steven Bethard wrote: Well, I couldn't find where the general semantics of a negative stride index are defined, but for sequences at least[1]: The slice of s from i to j with step k is defined as the sequence of items with index x = i + n*k such that 0 = n (j-i)/k. This seems to contradict list behavior though. [...] The conclusion is inescapable: Python's handling of negative subscripts is a wart. Indexing from the high end is too useful to give up, but it should be specified by the slicing/indexing operation, not by the value of the index expression. It is a Python gotcha, but the identity X[-1] == X[len(X)-1] holds and is very usefull IMO. No question index-from-the-far-end is useful, but I think special-casing some otherwise-out-of-bounds indexes is a mistake. Are there any cases in popular Python code where my proposal would not allow as elegant a solution? If you want to slice to the bottom, take 0 as bottom value. The docs have to be extended in this respect. I'm not sure what you mean. Slicing with a negative step and a stop value of zero will not reach the bottom (unless the sequence is empty). In general, Python uses inclusive beginning bounds and exclusive ending bounds. (The rule is frequently stated incorrectly as inclusive lower bounds and exclusive upper bounds, which fails to consider negative increments.) -- --Bryan -- http://mail.python.org/mailman/listinfo/python-list
Unix diff command under Window.
Hello, Does any one have using Python to write a Unix diff command for Window? Tony Ha. -- http://mail.python.org/mailman/listinfo/python-list
[no subject]
-- http://mail.python.org/mailman/listinfo/python-list
tkraise oddity
I'm seeing some new and unexpected behaviour with tkinter + python2.4, in a gnome+linux environment. The code below used to work (and continues to work under windows). The intended behaviour is that a window is created the the first time the button is pushed, and then de-iconified and brought to the top whenever the button is pushed again. The behaviour I'm seeing is that the window is de-iconified (if iconified) correctly, but if already present on the screen, it is not raised. Does this code look ok? Any suggestions as to what the problem could be? Thanks for any pointers. -- from Tkinter import * t = None def cmd(): global t if t: t.tkraise() t.deiconify() else: t = Toplevel() l = Label( t, text= some text goes here ... ) l.pack() b = Button(text=Raise,command=cmd) b.pack() b.mainloop() -- http://mail.python.org/mailman/listinfo/python-list
Re: Jargons of Info Tech industry
[EMAIL PROTECTED] (Richard Bos) writes: l v [EMAIL PROTECTED] wrote: Mike Schilling wrote: A formatting-only subset of HTML would be useful for both e-mail and Usenet posts. I would *agree* (your news reader may bold that last word) It had bloody better not. You're cross-posting this to a C newsgroup, where *ptr* 4 is a legal (albeit inadvisably spaced) expression. Or _ptr_ for that matter (does it underline for you?) Well, at least on my newsreader (gnus), I can toggle the behaviour. Ditto for smileys: (setq gnus-treat-display-smileys nil) Dragan -- Dragan Cvetkovic, To be or not to be is true. G. Boole No it isn't. L. E. J. Brouwer !!! Sender/From address is bogus. Use reply-to one !!! -- http://mail.python.org/mailman/listinfo/python-list
Re: Unix diff command under Window.
There probably is some free version somewhere, maybe even as part of CygWin. I've used Araxis Merge on Windows. It used to be shareware. It's nice enough that I bought it. TonyHa [EMAIL PROTECTED] 08/24/05 3:50 pm Hello, Does any one have using Python to write a Unix diff command for Window? Tony Ha. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: The ONLY thing that prevents me from using Python
On Wed, Aug 24, 2005 at 09:49:01AM +0100, Richie Hindle wrote: [Chris] Not to be a shill, but I'd be interested in testimonials on http://linode.org/ I wonder if virtualization is the next killer app. Certainly blows the WTF my ISP? question away... I can't speak for linode.org, but I have a Xen VPS from rimuhosting.com and it's early days but so far I've been very impressed. It's $19/mo (normally $20 but they kindly gave me a 5% Open Source Developer discount) which is not that much more than a decent shared hosting account. You need to be comfortable with administering your own Linux box, but these days that's not difficult. (NB. entrian.com is not running on it yet.) I cannot comment on linode as I'm not a customer. The info on the website seems ok. But the prices are somehow laughable: I'm currently paying EUR39 for a dedicated host (with at least 200GB traffic, I'd had to look it up 60GB storage, 256MB RAM and a 2.4GHz P4 CPU all alone to me). That makes the 79.95 dollars for Linode 256 somehow a bit expensive. OTOH perhaps dedicated servers are really cheap in Germany ;) Whatever, Andreas -- http://mail.python.org/mailman/listinfo/python-list
Re: Should I move to Amsterdam?
Nice little series by Seth Stevenson for Americans daydreaming about emigration. Somewhere, anywhere ... maybe Amsterdam? I've never been to the Netherlands myself, but it sounds very civilized. It used to be, until some lunatic (alledged to be a left-winger) killed an (alledged right-wing) politician, and another (alledged muslim-extremist) lunatic killed an (alledged right- or left-wing, depends on who you ask) cineast. We used to be a place where everything happens a few years later, but we are catching up! :( But I fondly remember the classes I had at the Delft university by Lambert Meertens about the ABC language, which is the forerunner of Python. :) Wouter van Ooijen -- http://www.voti.nl Webshop for PICs and other electronics http://www.voti.nl/hvu Teacher electronics and informatics -- http://mail.python.org/mailman/listinfo/python-list
Re: Should I move to Amsterdam?
Adriaan Renting wrote: Well, I'm not sure if Amsterdam is nice, but the Netherlands is o.k., except for the weather. I'd like to descripbe it as 49 weeks of autumn, 1 week of spring, 1 week of summer, 1 week of winter. Currently my employer only has an opening for a Microwave Antenna designer though, sorry no Python coders. http://www.astron.nl/astron/jobs/index.htm Seems like a nice column, I'll read it completely some other time. Wade [EMAIL PROTECTED] 08/24/05 2:31 pm http://www.slate.com/id/2124561/entry/2124562/ Nice little series by Seth Stevenson for Americans daydreaming about emigration. Somewhere, anywhere ... maybe Amsterdam? I've never been to the Netherlands myself, but it sounds very civilized. What a joke ... Amsterdam is 'civilized' since several hundreds of years :) --Armin Extra Python connection, besides the obvious one: Is gezellig related to the Zen of Python? ( http://wordcraft.infopop.cc/eve/ubb.x/a/tpc/f/6351024471/m/2041067571/r/3901049571 ) -- Wade Leftwich Ithaca, NY -- http://mail.python.org/mailman/listinfo/python-list
Re: Doubt C and Python
On 2005-08-23, praba kar [EMAIL PROTECTED] wrote: Some people with C background use Python instead of programming in C.why? Becuase it is much more efficient. -James What why it is more efficient. Kindly let me know with some details. Have you read _any_ of the thread? A number of people have already explained in detail why programming in Pything is more efficient. Please read the responses you've already gotten. -- Grant Edwards grante Yow! My DIGITAL WATCH at has an automatic SNOOZE visi.comFEATURE!! -- http://mail.python.org/mailman/listinfo/python-list
Re: yapsnmp port issues
Solved the problem all by myself. Patch (and rationale) available on sourceforge. -- http://mail.python.org/mailman/listinfo/python-list
Re: py-serial + CSV
On 2005-08-24, Sybren Stuvel [EMAIL PROTECTED] wrote: import serial s = serial.Serial(port=0,baudrate=4800, timeout=20) while 1: line = s.readline() words = line.split(',') if words[0]==$GPRMC: print words[1], words[3], words[5] I just wonder if there is some beter (or as you are saying more pythonic:) aproach how to write such a piece of code. You could use regular expressions instead. There is a programmer who has a problem to solve. He decides to use regular expressions. Now he has two problems. And to make it even more pythonic, replace the while and the line = s.readline() with for line in s: Serial port objects aren't iterable. -- Grant Edwards grante Yow! I was making donuts at and now I'm on a bus! visi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Unix diff command under Window.
TonyHa wrote: Does any one have using Python to write a Unix diff command for Window? No, but you can get the *actual* diff command for Windows: http://unxutils.sourceforge.net/ -- Benji York -- http://mail.python.org/mailman/listinfo/python-list
Email client in Pyhton
Hi grp, I new to this grp and python too. i have started writing few python scripts myself. now i am planning to write a bear minimum email client in pyhton. i found the smtp module of python could serve my pupose. I can send message using mails using the smtp lib. Now i'm looking for some modules which can help me in fetching the mails from the mailserver and managing folders. I also look for some existing mail client, written in python which wud serve my cause. i searched google for no avail. -- K Naren,MeTel Team. http://www.midascomm.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Unix diff command under Window.
TonyHa [EMAIL PROTECTED] writes: Hello, Does any one have using Python to write a Unix diff command for Window? Tony Ha. Yes. There's a script in your Python distribution: Tools/scripts/diff.py See also the docs for the 'difflib' standard library module. I do not know whether the Tools directory is installed by default or not. Thomas -- http://mail.python.org/mailman/listinfo/python-list
Re: Bug in slice type
Kay Schluehr wrote: Steven Bethard wrote: The slice of s from i to j with step k is defined as the sequence of items with index x = i + n*k such that 0 = n (j-i)/k. This seems to contradict list behavior though. range(10)[9:-1:-2] == [] No, both is correct. But we don't have to interpret the second slice argument m as the limit j of the above definition. Even if we don't have to, it sure reads like we should. For positive values of m the identity m==j holds. For negative values of m we have j = max(0,i+m). First, the definition from the doc is still ambiguous: Is the division in 0 = n (j-i)/k real division, or is it Python integer (truncating) division? It matters. Second, the rule Kay Schluehr states is wrong for either type of division. Look at: range(5)[4 : -6 : -2] Since Python is so programmer-friendly, I wrote some code to make the look at task easy: slice_definition = The slice of s from i to j with step k is defined as the sequence of items with index x = i + n*k such that 0 = n (j-i)/k. Kay_Schluehr_rule = For positive values of m the identity m==j holds. For negative values of m we have j = max(0,i+m). def m_to_j(i, m): Compute slice_definition's 'j' according to Kay_Schluehr_rule when the slice of sequence is specified as, sequence[i : m : k]. if m 0: j = m else: j = max(0, i + m) return j def extract_slice(sequence, i, m, k, div_type='i'): Apply the slice definition with Kay Schluehr's rule to find what the slice should be. Pass div_type of 'i' to use integer division, or 'f' for float (~real) division, in the slice_definition expression, (j-i)/k. j = m_to_j(i, m) result = [] n = 0 if div_type == 'i': end_bound = (j - i) / k else: assert div_type == 'f', div_type must be 'i' or 'f'. end_bound = float(j - i) / k while n end_bound: result.append(sequence[i + n * k]) n += 1 return result def show(sequence, i, m, k): Print what happens, both actually and according to stated rules. print Checking: %s[%d : %d : %d] % (sequence, i, m, k) print actual :, sequence[i : m : k] print Kay's rule, int division :, extract_slice(sequence, i, m, k) print Kay's rule, real division:, extract_slice(sequence, i, m, k, 'f') print show(range(5), 4, -6, -2) -- --Bryan -- http://mail.python.org/mailman/listinfo/python-list
use SciPy with Python 2.4.1?
Is SciPy usable with Python 2.4.1? At http://www.scipy.org/download/ it says that 2.3.3 is recommended, and I don't see a binary for 2.4.1. -- http://mail.python.org/mailman/listinfo/python-list
Re: Email client in Pyhton
On Wed, 24 Aug 2005 20:15:01 +0530 (IST) [EMAIL PROTECTED] wrote: now i am planning to write a bear minimum email client in pyhton. i found the smtp module of python could serve my pupose. I can send message using mails using the smtp lib. Now i'm looking for some modules which can help me in fetching the mails from the mailserver and managing folders. Check out the POP and IMAP modules (poplib and imaplib), the email package, and the mailbox and mhlib modules (all in the standard library). I seem to recall seeing a maildir module somewhere, but can't find it now. IIRC, many of the mailbox modules (such as mailbox and mhlib) are read-only, but they should provide a good starting point. I also look for some existing mail client, written in python which wud serve my cause. Mahogany Mail isn't written in Python, but it uses wxWidgets and has an embedded Python interpreter. A quick Google for python email client (sans quotes) revealed the following useful links: http://sourceforge.net/projects/usablemail/ http://mail.python.org/pipermail/python-list/2003-August/177139.html -Michael -- http://mail.python.org/mailman/listinfo/python-list
a question about tkinter StringVars()
Working with tkinter, I have a createWidgets() method in a class. Within createWidgets() I create several StringVars() and assign them to the textvariable option of several widgets. Effectively my code structure is: def createWidgets(self): ... var = StringVar() Entry(master,textvariable=var) ... ... Though 'var' would normally go out of scope when createWidgets completes, since the Entry and its reference do not go out of scope, only the name 'var' goes out of scope, not the StringVar object, Right? Thanks, Bill -- http://mail.python.org/mailman/listinfo/python-list
Re: Email client in Pyhton
[EMAIL PROTECTED] wrote: Hi grp, I new to this grp and python too. i have started writing few python scripts myself. now i am planning to write a bear minimum email client in pyhton. i found the smtp module of python could serve my pupose. I can send message using mails using the smtp lib. Now i'm looking for some modules which can help me in fetching the mails from the mailserver and managing folders. I also look for some existing mail client, written in python which wud serve my cause. i searched google for no avail. Maybe start by reading some email related rfc's -- http://mail.python.org/mailman/listinfo/python-list
Re: gtkmozembed in fedora core 3
Jonas Geiregat [EMAIL PROTECTED] wrote: If you can't find any rpm's there aren't any available. You need to compile mozilla with (I think) support for gtkmozembed but I guess that's done by default when you compile mozilla with ac_add_options --enable-default-toolkit=gtk2 in your mozconfig file. Check /usr/lib/mozilla for libgtkembedmoz.so if it's not there you'll have to rebuild your mozilla/firefox rpm , again I think, these are just some random tips .. Good luck! Thanks, I'll give it a whirl! martin -- http://mail.python.org/mailman/listinfo/python-list
Re: py-serial + CSV
McBooCzech wrote: This (according to your suggestions) is my code which works for me import serial s = serial.Serial(port=0,baudrate=4800, timeout=20) while 1: line = s.readline() words = line.split(',') if words[0]==$GPRMC: print words[1], words[3], words[5] I just wonder if there is some beter (or as you are saying more pythonic:) aproach how to write such a piece of code. import csv from serial import Serial port = Serial(port=0, baudrate=4800, timeout=20) for row in csv.reader(iter(port.readline, None)): if row[0] == $GPMRC: print row[1], row[3], row[5] -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Email client in Pyhton
Mark Lutz in Programming Python, 2nd ed from O'Reilly covers the subject in chapter 11 using only the standards modules for mails and Tkinter. hth [EMAIL PROTECTED] wrote: Hi grp, I new to this grp and python too. i have started writing few python scripts myself. now i am planning to write a bear minimum email client in pyhton. i found the smtp module of python could serve my pupose. I can send message using mails using the smtp lib. Now i'm looking for some modules which can help me in fetching the mails from the mailserver and managing folders. I also look for some existing mail client, written in python which wud serve my cause. i searched google for no avail. -- rafi Imagination is more important than knowledge. (Albert Einstein) -- http://mail.python.org/mailman/listinfo/python-list
Re: Proposed PEP: New style indexing, was Re: Bug in slice type
Steven Bethard wrote: Bryan Olson wrote: Steven Bethard wrote: Well, I couldn't find where the general semantics of a negative stride index are defined, but for sequences at least[1]: The slice of s from i to j with step k is defined as the sequence of items with index x = i + n*k such that 0 = n (j-i)/k. This seems to contradict list behavior though. [...] The conclusion is inescapable: Python's handling of negative subscripts is a wart. I'm not sure I'd go that far. Note that my confusion above was the order of combination of points (3) and (5) on the page quoted above[1]. I think the problem is not the subscript handling so much as the documentation thereof. Any bug can be pseudo-fixed by changing the documentation to conform to the behavior. Here, the doc clearly went wrong by expecting Python's behavior to follow from a few consistent rules. The special-case handling of negative indexes looks handy, but raises more difficulties than people realized. I believe my PPEP avoids the proliferation of special cases. The one additional issue I've discovered is that user-defined types that are to support __getitem__ and/or __setitem__ *must* also implement __len__. Sensible sequence types already do, so I don't think it's much of an issue. This is already valid syntax, and is used heavily by the numarray/numeric folks. Yeah, I thought that variant might break some code. I didn't know it would be that much. Forget that variant. -- --Bryan -- http://mail.python.org/mailman/listinfo/python-list
Re: Unix diff command under Window.
TonyHa said the following on 24.08.2005 15:50: Hello, Does any one have using Python to write a Unix diff command for Window? http://gnuwin32.sourceforge.net/ http://gnuwin32.sourceforge.net/packages.html Under Diffutils -- Dejan Rodiger - PGP ID 0xAC8722DC Delete wirus from e-mail address -- http://mail.python.org/mailman/listinfo/python-list
Re: Email client in Python
[EMAIL PROTECTED] wrote: Hi grp, I new to this grp and python too. i have started writing few python scripts myself. now i am planning to write a bear minimum email client in pyhton. i found the smtp module of python could serve my pupose. I can send message using mails using the smtp lib. Now i'm looking for some modules which can help me in fetching the mails from the mailserver and managing folders. I also look for some existing mail client, written in python which wud serve my cause. i searched google for no avail. I'd recommend the poplib library. There is also imaplib, but that is much more difficult to use. Examples of use: http://docs.python.org/lib/pop3-example.html http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/82233 http://effbot.org/zone/librarybook/network-protocols.pdf regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Unix diff command under Window.
Either it didn't exist at the time, or I didn't know about the diff.py that Thomas Heller mentioned in another response, so I wrote 'pyunidiff' http://unpy.net/~jepler/pyunidiff.py ah, I guess unix 'diff'-style output was added to difflib.py in 2003, while my pyunidiff dates to 2002. Jeff pgp9OPAVfz7se.pgp Description: PGP signature -- http://mail.python.org/mailman/listinfo/python-list
Re: a question about tkinter StringVars()
On Wed, 24 Aug 2005 15:07:27 GMT, William Gill [EMAIL PROTECTED] wrote: Working with tkinter, I have a createWidgets() method in a class. Within createWidgets() I create several StringVars() and assign them to the textvariable option of several widgets. Effectively my code structure is: def createWidgets(self): ... var = StringVar() Entry(master,textvariable=var) ... ... Though 'var' would normally go out of scope when createWidgets completes, since the Entry and its reference do not go out of scope, only the name 'var' goes out of scope, not the StringVar object, Right? Well, apparently not: from Tkinter import * class MyStringVar(StringVar): def __del__(self): print I'm dying! root = Tk() def cw(): var = MyStringVar() Entry(root, textvariable=var).pack() cw() root.mainloop() Running this script actually prints I'm dying!, so there is obviously no reference from the Entry widget to the variable object. The reference is actually kept at tcl level between an entry and the *tcl* variable, which knows nothing about the *Python* variable. BTW, the whole purpose of StringVar's is to be kept so that the text for the entry can be retrieved or modified by another part of the program. So what can be the purpose of creating variables in a function or method and not keeping them anywhere else than a local variable? -- python -c print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-']) -- http://mail.python.org/mailman/listinfo/python-list
Default function arguments behaving badly
Hi I'm having some trouble with a function I've written in Python: def myFunction(l1,l2,result=[]): index=0 for i in l1: result.append([]) if type(i)==list: myFunction(i,l2,result[index]) else: for j in l2: result[index].append(i*j) index+=1 return result l1 and l2 are lists and the function multiplies every element of l1 with every element of l2. l1 is (possibly) multi-dimensional, and the recursive bit is in there to cope with that. For example, if l1=[[1,2],[3,4]] and l2=[5,6] the result is [[[5,6],[10,12]],[[15,18],[20,40]]]. The problem is that it works if I run it once, but then on repeated runs the value for 'result' doesn't seem to set itself to my default of [], but instead uses the state it was in last time the function was run. I've had a problem like this in the past and ended up rewriting the function as a class and using something like self.result, but I don't really like this solution as the code becomes considerabley more difficult to read (and I suspect less efficient). Also, I suppose I could feed in an empty array every time but that doesn't provide a very intuitive interface to the function. Does anyone know what is going on here? Is there an easy solution? Thanks for your help! -- http://mail.python.org/mailman/listinfo/python-list
Re: Default function arguments behaving badly
[EMAIL PROTECTED] wrote: Hi hi I'm having some trouble with a function I've written in Python: def myFunction(l1,l2,result=[]): index=0 for i in l1: result.append([]) if type(i)==list: myFunction(i,l2,result[index]) else: for j in l2: result[index].append(i*j) index+=1 return result The problem is that it works if I run it once, but then on repeated runs the value for 'result' doesn't seem to set itself to my default of [], but instead uses the state it was in last time the function was run. Does anyone know what is going on here? Is there an easy solution? the list you provide as default parameter is evaluated once (at loading time of the function). so each time you call the function, it uses the same list that has been filled before... you do not have the problem with say and int or a string as they are non mutable objects. however lists are mutable objects so... modify your function as follow: def myFunction(l1,l2,result=None): if result is None: result = [] hth -- rafi Imagination is more important than knowledge. (Albert Einstein) -- http://mail.python.org/mailman/listinfo/python-list
Re: tkraise oddity
On 24 Aug 2005 06:57:07 -0700, twd [EMAIL PROTECTED] wrote: I'm seeing some new and unexpected behaviour with tkinter + python2.4, in a gnome+linux environment. The code below used to work (and continues to work under windows). The intended behaviour is that a window is created the the first time the button is pushed, and then de-iconified and brought to the top whenever the button is pushed again. The behaviour I'm seeing is that the window is de-iconified (if iconified) correctly, but if already present on the screen, it is not raised. What exactly do you expect? Do you want to raise the window above all other windows *in your application*, or above *all* other windows? I doubt tk can guarantee the latter, and this seems to be confirmed by the manuel for tk's raise command; cf. http://www.tcl.tk/man/tcl8.4/TkCmd/raise.htm If you put the window with the button in front of the window with the label, and if pressing the button doesn't bring the window with the lable above the other, then it may be a bug. If it works, I guess it's just a matter of how the window managers interpret what raising a window means... But I'm no specialist here, so maybe someone else will confirm that. [snip] from Tkinter import * t = None def cmd(): global t if t: t.tkraise() t.deiconify() else: t = Toplevel() l = Label( t, text= some text goes here ... ) l.pack() b = Button(text=Raise,command=cmd) b.pack() b.mainloop() (BTW, did you try to put the deiconify before the tkraise?) HTH -- python -c print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-']) -- http://mail.python.org/mailman/listinfo/python-list
Re: Default function arguments behaving badly
[EMAIL PROTECTED] wrote: I'm having some trouble with a function I've written in Python: def myFunction(l1,l2,result=[]): [snipped rest of function and explanation of what it does] Does anyone know what is going on here? Is there an easy solution? It shined out like a supernova. It has to do with mutability of certain Python objects (e.g. dicts and lists) and the fact that Python binds the default arguments only once. So, when your function is defined, python binds the name result to the value []. Then, your function runs the first time using that original binding. The second time, it still uses the original binding which, because lists are mutable, still contains the prior list. Etcetera. The solution is to never assign mutable objects to default arguments. Instead, assign to None, like: def myFunction(l1, l2, result=None): if result is None: result = [] Others will certainly post links to the python docs that explain this. -- Paul McNett http://paulmcnett.com -- http://mail.python.org/mailman/listinfo/python-list