Re: newbie problem with str.replace
On Aug 4, 9:10 am, BobAalsma bob.aal...@aalsmacons.nl wrote: # bestandsnaam_nieuw = bestandsnaam bestandsnaam_nieuw.replace(KLANTNAAM_OUT,KLANTNAAM_IN) The replace method does not modify the string (strings are immutable). You need to use the retun value of the method in an assignment, like so: bestandsnaam_nieuw = bestandsnaam.replace(KLANTNAAM_OUT,KLANTNAAM_IN) This will not change the value of bestandsnaam -- http://mail.python.org/mailman/listinfo/python-list
Re: Need debugging knowhow for my creeping Unicodephobia
On Feb 10, 2:09 pm, kj no.em...@please.post wrote: Some people have mathphobia. I'm developing a wicked case of Unicodephobia. [snip] Some general advice (Looks like I am reiterating what MRAB said -- I type slower :): 1. If possible, use unicode strings for everything. That is, don't use both str and unicode within the same project. 2. If that isn't possible, convert strings to unicode as early as possible, work with them that way, then convert them back as late as possible. 3. Know what type of string you are working with! If a function returns or accepts a string value, verify whether the expected type is unicode or str. 4. Consider switching to Python 3.x, since there is only one string type (unicode). -- -- http://mail.python.org/mailman/listinfo/python-list
Re: A silly question on file opening
On Feb 10, 3:42 pm, joy99 subhakolkata1...@gmail.com wrote: Dear Group, [snip] I tried to change the location to D:\file and as I saw in Python Docs the file reading option is now r+ so I changed the statement to file_open=open(D:\file,r+) but it is still giving error. Only use r+ if you need to also write to the file. r is still good for opening for reading. Without seeing a traceback, I can only assume the error is caused by using a backslash in the path without escaping it. Try either the following: file_open=open(D:\\file,r+) file_open=open(rD:\file,r+) For an explanation, see the Python documentation: http://docs.python.org/reference/lexical_analysis.html#string-literals -- http://mail.python.org/mailman/listinfo/python-list
Re: interaction of mode 'r+', file.write(), and file.tell(): a bug or undefined behavior?
On Jan 28, 7:12 am, Lie Ryan lie.1...@gmail.com wrote: In the code: f = open('input.txt', 'r+') for line in f: s = line.replace('python', 'PYTHON') # f.tell() f.write(s) [snip] My guess is that there are a few possible problems: 1) In this case, writing to file opened with 'r+' without an explicit f.seek is probably not a good idea. The file iterator (for line in f) uses a readahead buffer, which means you can't guarantee what the current file position will be. 2) It may be necessary to do an explicit f.flush or f.close when writing to an 'r+' file. In your case, the close should automatically happen when the f object falls out of scope, which tells me that were still looking at some other problem, like not using f.seek 3) It is possible that f.tell implicitly flushes buffers used by the file object. That would explain why uncommenting the f.tell causes the writes to show up. What are you trying to accomplish? Overwrite the original file, or append to it? If you want to overwrite the file, it may be better to generate a new file, delete the old one, then rename the new one. If you want to append, then it would be better to open the file with append mode ('a') -- http://mail.python.org/mailman/listinfo/python-list
Re: Python OOP Problem
On Dec 28, 7:29 am, Martin v. Loewis mar...@v.loewis.de wrote: In this case (you just started to learn Python), I recommend to take an explicit approach. Create a dictionary that maps class names to classes: name2class = { MyObject : MyObject, MyOtherObject : MyOtherObject, Etc : Etc } Then, when you receive the string class_name, you do o = name2class[class_name] o.myfunction() HTH, Martin The class needs to be instantiated, so the one line should be as follows: o = name2class[class_name]() -- -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows file paths, again
On Oct 21, 3:20 pm, Dan Guido dgu...@gmail.com wrote: Hi Diez, The source of the string literals is ConfigParser, so I can't just mark them with an 'r'. config = ConfigParser.RawConfigParser() config.read(filename) crazyfilepath = config.get(name, ImagePath) normalfilepath = normalize_path(crazyfilepath) The ultimate origin of the strings is the _winreg function. Here I also can't mark them with an 'r'. regkey = OpenKey(HKEY_LOCAL_MACHINE, SYSTEM\\CurrentControlSet\\Services\\ + name) crazyimagepath = QueryValueEx(regkey, ImagePath)[0] CloseKey(key) -- Dan Guido I just did a quick test using Python 2.5.1 with the following script on Windows: # start of test.py import ConfigParser config = ConfigParser.RawConfigParser() config.read(cfg.ini) x = config.get(foo, bar) print x print repr(x) from _winreg import * regkey = OpenKey(HKEY_LOCAL_MACHINE, rSYSTEM\CurrentControlSet\Services\IPSec) x = QueryValueEx(regkey, ImagePath)[0] CloseKey(regkey) print x print repr(x) # end of test.py Here is the contesnts of cfg.ini: [foo] bar=c:\dir\file.txt Here is the output of the script: c:\dir\file.txt 'c:\\dir\\file.txt' system32\DRIVERS\ipsec.sys u'system32\\DRIVERS\\ipsec.sys' In either case, I don't see the functions returning strings that requires special handling. The backslashes are properly escaped in the repr of both strings. Something else must be going on if the strings are getting messed up along the way. -- http://mail.python.org/mailman/listinfo/python-list
Re: set using alternative hash function?
On Oct 16, 12:24 pm, Ethan Furman et...@stoneleaf.us wrote: [snip] As for what you want: No, it's not currently possible. If it's so big a deal that the various methods presented don't meet with your approval, break out the C and write your own. Then you could give that back to the community instead of your snide remarks. ~Ethan~ I didn't get the impression that Austin was being snide. Instead, I get the impression that they are someone from a different programming background (C++/STL) who has not had sufficient exposure to the Python way of doing things. I believe Austin is genuinely curious as to why Python may not implement features found in another programming environment. Coming from a C/C++ background myself, it took me a while to un-learn certain idioms. I still find myself thinking in C on occasion, only to find a more elegant way to accomplish the task. -- http://mail.python.org/mailman/listinfo/python-list
Re: set using alternative hash function?
On Oct 15, 7:24 am, Austin Bingham austin.bing...@gmail.com wrote: [snip] I'd like to create a set of these objects where the hashing is done on these names. [snip] Why not use a dict? The key would be the object name. Pretty much the same behavior as a set (via the key), and you can still easily iterate over the objects. -- http://mail.python.org/mailman/listinfo/python-list
Re: set using alternative hash function?
On Oct 15, 10:42 am, Austin Bingham austin.bing...@gmail.com wrote: On Thu, Oct 15, 2009 at 4:06 PM, Anthony Tolle To reiterate, dict only gets me part of what I want. Whereas a set with uniqueness defined over 'obj.name' would guarantee no name collisions, dict only sorta helps me keep things straight; it doesn't actually enforce that my values have unique names. I don't understand how a set would help you enforce that your values ave unique names. If you have two objects, both named foo, and added them to the set, no errors would occur. Please provide an example of how a set provides functionality that a dict (which enforces unique keys) doesn't. -- http://mail.python.org/mailman/listinfo/python-list
Re: set using alternative hash function?
On Oct 15, 12:11 pm, Austin Bingham austin.bing...@gmail.com wrote: To put it in code, I want this: s = set(hash_func = lambda obj: hash(obj.name), eq_func = ...) ... x.name = 'foo' y.name = 'foo' s.add(x) s.add(y) # no-op because of uniqueness criteria assert len(s) == 1 I wrote a quick subclass of set that does something similar, but uses just one function for the object uniqueness: class MySet(set): def __init__(self, iterable = (), idfunc = lambda x: x): self.idfunc = idfunc self.ids = set() for item in iterable: self.add(item) def add(self, item): id = self.idfunc(item) if id not in self.ids: self.ids.add(id) set.add(self, item) class Foo(object): ... def __init__(self, name): ... self.name = name ... x = Foo('foo') y = Foo('foo') s = MySet(idfunc = lambda x: x.name) s.add(x) s MySet([__main__.Foo object at 0x00A89F90]) s.add(y) s MySet([__main__.Foo object at 0x00A89F90]) Is this what you are looking for? -- http://mail.python.org/mailman/listinfo/python-list
Re: set using alternative hash function?
On Oct 15, 1:49 pm, Ethan Furman et...@stoneleaf.us wrote: I'm still not sure I understand your concern about the values in a set, though. Sets keep the first object of a given key, dicts keep the last object of a given key; in both cases, all other objects with the same key are lost. So is that the behavior you're wanting, keeping the first object and discarding all others? Or is there something else I'm still missing? I think that without a practical example of what this would be used for, we're all going to be a little lost on this one. So far, we've not seen the original problem, only the author's preferred method for solving it. My guess is there are other, more pythonic ways to solve the original problem. -- http://mail.python.org/mailman/listinfo/python-list
Re: Move dictionary from instance to class level
To take things one step further, I would recommend using decorators to allow symbolic association of functions with the message identifiers, as follows: == (MESSAGE_ONE ,MESSAGE_TWO ,MESSAGE_THREE ) = xrange(3) class MyClass(object): method_dict = {} # create helper decorator register_method = lambda msg, method_dict=method_dict: lambda function: method_dict.setdefault(msg, function) @register_method(MESSAGE_ONE) def handle_one(self): print 'handling MESSAGE_ONE' @register_method(MESSAGE_TWO) def handle_two(self): print 'handling MESSAGE_TWO' @register_method(MESSAGE_THREE) def handle_three(self): print 'handling MESSAGE_THREE' # no longer need helper decorator del register_method # function to dispatch messages def on_message_received(self, msg): MyClass.method_dict[msg](self) x = MyClass() x.on_message_received(MESSAGE_ONE) x.on_message_received(MESSAGE_TWO) x.on_message_received(MESSAGE_THREE) == Note: the line containing the lambda definition is all one line. -- http://mail.python.org/mailman/listinfo/python-list
Re: Help understanding the decisions *behind* python?
On Jul 20, 12:27 pm, Phillip B Oldham phillip.old...@gmail.com wrote: ... Specifically the differences between lists and tuples have us confused and have caused many discussions in the office. We understand that lists are mutable and tuples are not, but we're a little lost as to why the two were kept separate from the start. They both perform a very similar job as far as we can tell. ... There's no hard-set rules, but tuples are typically used to hold collections of heterogeneous data, e.g. (10, spam, 3.21). As has been mentioned, such a tuple can be used as a dictionary key, whereas a list cannot be used as a dictionary key, because it is mutable. Lists, on the other hand, typically hold collections of homogeneous data, e.g. [1, 2, 5] or [spam, eggs, sausage]. Of course, you'll also see plenty of examples of tuples containing homogeneous data and lists containing heterogeneous data :) -- http://mail.python.org/mailman/listinfo/python-list
Re: missing 'xor' Boolean operator
On Jul 15, 8:32 pm, Paul Rubin http://phr...@nospam.invalid wrote: Among other things, that uses quadratic time! Why do you want to keep popping items from that list instead of iterating through it anyway? Anyway, I think you wrote something close to this: ... Very true! I didn't think about the problems with pop(). I was using it as a shortcut for pulling off the first operand. I forgot that if you start with an initial operand of False, the result will be the same (0 xor X = X) While I'm not sure how useful it would be, here's a version of the first function that returns one of the operands (ala AND and OR), except in the case where there is an even number of True elements, where it returns False: def xor(*operands): r, rprime = False, False for x in operands: xprime = bool(x) if rprime: if xprime: r, rprime = False, False else: r, rprime = x, xprime return r xor(0, 0) 0 xor(0, 1) 1 xor(1, 0) 1 xor(1, 1) False xor(0, 1, 2) False xor(0, 1, 2, 3) 3 xor(None, []) [] -- http://mail.python.org/mailman/listinfo/python-list
Re: missing 'xor' Boolean operator
On Jul 14, 2:25 pm, Dr. Phillip M. Feldman pfeld...@verizon.net wrote: Current Boolean operators are 'and', 'or', and 'not'. It would be nice to have an 'xor' operator as well. My $0.02 on this discussion: There would be nothing gained by having non-bitwise XOR operator. You can't short-circuit XOR, because you must evaluate all operands to produce a result. Consequently, returning the true item also doesn't make much sense. XOR is closer to the the logical NOT operator than it is to AND or OR. Here's my own take on a function that can handle any number of arguments (it should probably raise an exception for 0 or 1 arguments, but I'm lazy): def xor(*operands): if operands: operands = list(operands) a = bool(operands.pop(0)) while operands: b = bool(operands.pop(0)) if a: if b: a = False elif b: a = True return a return False -- http://mail.python.org/mailman/listinfo/python-list
Re: why cannot assign to function call
On Dec 29, 1:01 am, scsoce scs...@gmail.com wrote: I have a function return a reference, and want to assign to the reference, simply like this: def f(a) return a b = 0 * f( b ) = 1* but the last line will be refused as can't assign to function call. In my thought , the assignment is very nature, but why the interpreter refused to do that ? thks Probably the closest thing you are going to get in Python would be the following: class C: ... pass ... def f(a): ... return a ... b = C() b.value = 0 b.value 0 f(b).value = 1 b.value 1 But as others have pointed out, Python is not C/C++, and shouldn't be treated as such. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to read stdout from subprocess as it is being produced
On Dec 19, 9:34 am, Alex alex.pul...@gmail.com wrote: Hi, I have a Pyhon GUI application that launches subprocess. I would like to read the subprocess' stdout as it is being produced (show it in GUI), without hanging the GUI. I guess threading will solve the no-hanging issue, but as far as I searched for now, I've only seen how to read the stdout after subprocess is finished. Thanks! If I'm interpreting your needs correctly, then you may find this module helpful: http://code.activestate.com/recipes/440554/ I've used it successfully in the past when I wanted to use native python code (no C extensions necessary) for asynchronous reading from a child process. I'm not sure if later versions of Python (2.6, 3.0) support this in the standard library. I haven't researched it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido's new method definition idea
On Dec 6, 4:15 pm, Carl Banks [EMAIL PROTECTED] wrote: On Dec 6, 12:47 am, Patrick Mullen [EMAIL PROTECTED] wrote: Could I do something like this: def a.add(b): return a+b Outside of a class? Of course then that makes you think you could do 5.add(6) or something crzy like that. (I mean, you can do (5).__add__(6) but that's something else entirely) I'd be inclined to think that this defines an instancemethod on an existing object a. In other word, I'd read the following two lines as more or less equivalent. def a.add(b): return a+b a.add = lambda b: a+b Just as the following are equivalent: def foo(): return bar foo = lambda: bar I had been -0 on this, but now I think I'm -1. This brings up another question, what would one use when referencing method names inside the class definition?: class C: def self.method(arg): self.value = arg def self.othermethod(arg): self.value = arg # do this? funcs = (self.method, self.othermethod) # or this? funcs = (method, othermethod) On another related note, I would be interested in seeing this syntax adopted for a different purpose... Normally, if I'm defining a nested function that needs to be stored as an object attribute, I have to use a dummy name, like the following: class C: def createfunc(self, arg): def _dummy(arg): return arg + 1 self.func = _dummy It would be nice to be able to do the following instead: class C: def createfunc(self): def self.func(arg): return arg + 1 Or, after the class definition is done, to extend it dynamically: def C.method(self, arg): self.value = arg ...which would be the equivalent of the following: def method(self, arg): self.value = arg C.method = method Since functions are first-class objects, it seems perfectly reasonable to me. -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido's new method definition idea
On Dec 6, 4:15 pm, Carl Banks [EMAIL PROTECTED] wrote: On Dec 6, 12:47 am, Patrick Mullen [EMAIL PROTECTED] wrote: Could I do something like this: def a.add(b): return a+b Outside of a class? Of course then that makes you think you could do 5.add(6) or something crzy like that. (I mean, you can do (5).__add__(6) but that's something else entirely) I'd be inclined to think that this defines an instancemethod on an existing object a. In other word, I'd read the following two lines as more or less equivalent. def a.add(b): return a+b a.add = lambda b: a+b Just as the following are equivalent: def foo(): return bar foo = lambda: bar I had been -0 on this, but now I think I'm -1. This brings up another question, what would one use when referencing method names inside the class definition?: class C: def self.method(arg): self.value = arg def self.othermethod(arg): self.value = arg # do this? funcs = (self.method, self.othermethod) # or this? funcs = (method, othermethod) On another related note, I would be interested in seeing this syntax adopted for the very purpose Carl hinted at... Normally, if I'm defining a nested function that needs to be stored as an object attribute, I have to use a dummy name, like the following: class C: def createfunc(self, arg): def _dummy(arg): return arg + 1 self.func = _dummy It would be nice to be able to do the following instead: class C: def createfunc(self): def self.func(arg): return arg + 1 Or, after the class definition is done, to extend it dynamically: def C.method(self, arg): self.value = arg ...which would be the equivalent of the following: def method(self, arg): self.value = arg C.method = method Since functions are first-class objects, it seems perfectly reasonable to me. -- http://mail.python.org/mailman/listinfo/python-list
Re: Guido's new method definition idea
On Dec 8, 12:01 pm, [EMAIL PROTECTED] wrote: It would be nice to be able to do the following instead: class C: def createfunc(self): def self.func(arg): return arg + 1 The above example should have read as follows: class C: def createfunc(self, arg): def self.func(arg): return arg + 1 - Anthony Tolle -- http://mail.python.org/mailman/listinfo/python-list