replace mothod for only one object but not for a class
Hi, I have multiple objects all belonging to the same class (which I didn't implement and whose code I don't want to modify) Now I'd like to change one method for one object only (after it has been created) without adding any overhead to the call of the other object's methods. Is this possible? Example # This is NOT what I'd like to do # as it overwrites the method for all objects of this class o1 = aclass() o2 = aclass() # call original method o1.method() o2.method() # overwrite the method for the entire class aclass.method = mymethod o1.method() # now new method o2.method() # now new method ### What doesn't work, but what I'd like to do o1 = aclass() o2 = aclass() # call original method o1.method() o2.method() # overwrite the method for the entire class o1.method = mymethod o1.method() # now new method o2.method() # still old method thanks for any pointers. P.S. I guess, that there is a computer science term for what I try to achieve. If anybody knew it I would be interested to learn it as well. -- http://mail.python.org/mailman/listinfo/python-list
Re: replace mothod for only one object but not for a class
On Oct 14, 7:50 pm, hofer <[EMAIL PROTECTED]> wrote: > Hi, > > I have multiple objects all belonging to the same class > (which I didn't implement and whose code I don't want to modify) > > Now I'd like to change one method for one object only (after it has > been created) without adding any overhead > to the call of the other object's methods. > > Is this possible? > > Example > # This is NOT what I'd like to do > # as it overwrites the method for all objects of this class > o1 = aclass() > o2 = aclass() > # call original method > o1.method() > o2.method() > # overwrite the method for the entire class > aclass.method = mymethod > o1.method() # now new method > o2.method() # now new method > > ### What doesn't work, but what I'd like to do > o1 = aclass() > o2 = aclass() > # call original method > o1.method() > o2.method() > # overwrite the method for the entire class > o1.method = mymethod > o1.method() # now new method > o2.method() # still old method > > thanks for any pointers. > > P.S. I guess, that there is a computer science term for what I try to > achieve. > If anybody knew it I would be interested to learn it as well. Thanks a lot this works. Though I must admint, that even after reading the doc I don't really understand why. -- http://mail.python.org/mailman/listinfo/python-list
Re: replace mothod for only one object but not for a class
Hi > > hofer a écrit : > >> I have multiple objects all belonging to the same class > >> (which I didn't implement and whose code I don't want to modify) > > >> Now I'd like to change one method for one object only (after it has > >> been created) without adding any overhead > >> to the call of the other object's methods. Thanks for all of your answers: Here an example with three of the suggested solutions: (I didn't succeed in implementing Jason's solution with my example) import threading # some objects a = threading.Event() b = threading.Event() c = threading.Event() d = threading.Event() def run_dly(o): # a test function print o,"start", o.wait(1) print "stop" # unmodified test run_dly(a) run_dly(b) run_dly(c) run_dly(d) # The new Method def verbose_wait(self,dly): print "VERBOSE", threading._Event.wait(self,dly) ### Implemented with partial from functools import partial b.wait = partial(verbose_wait,b) ### with __get__ for new classes c.wait = verbose_wait.__get__(c,type(c)) ## with new for old classes import new d.wait = new.instancemethod(verbose_wait,d,type(d)) run_dly(a) run_dly(b) run_dly(c) run_dly(d) # end thanks again Hofer -- http://mail.python.org/mailman/listinfo/python-list
converting a sed / grep / awk / . . . bash pipe line into python
Hi, Something I have to do very often is filtering / transforming line based file contents and storing the result in an array or a dictionary. Very often the functionallity exists already in form of a shell script with sed / awk / grep , . . . and I would like to have the same implementation in my script What's a compact, efficient (no intermediate arrays generated / regexps compiled only once) way in python for such kind of 'pipe line' Example 1 (in bash): (annotated with comment (thus not working) if copied / pasted #--- cat file \ ### read from file | sed 's/\.\..*//' \### remove '//' comments | sed 's/#.*//' \ ### remove '#' comments | grep -v '^\s*$' \### get rid of empty lines | awk '{ print $1 + $2 " " $2 }' \ ### knowing, that all remaining lines contain always at least \ ### two integers calculate sum and 'keep' second number | grep '^42 ' ### keep lines for which sum is 42 | awk '{ print $2 }' ### print number Same example in perl: # I guess (but didn't try), taht the perl example will create more intermediate # data structures than necessary. # Ideally the python implementation shouldn't do this, but just 'chain' iterators. #--- my $filename= "file"; open(my $fh,$filename) or die "failed opening file $filename"; # order of 'pipeline' is syntactically reversed (if compared to shell script) my @numbers = map { $_->[1] } # extract num 2 grep { $_->[0] == 42 } # keep lines with result 42 map { [ $_->[0]+$_->[1],$_->[1] ] } # calculate sum of first two nums and keep second num map { [ split(' ',$_,3) ] } # split by white space grep { ! ($_ =~ /^\s*$/) }# remove empty lines map { $_ =~ s/#.*//; $_} # strip '#' comments map { $_ =~ s/\/\/.*// ; $_} # strip '//' comments <$fh>; print "Numbers are:\n",join("\n",@numbers),"\n"; thanks in advance for any suggestions of how to code this (keeping the comments) H -- http://mail.python.org/mailman/listinfo/python-list
dict slice in python (translating perl to python)
Hi, Let's take following perl code snippet: %myhash=( one => 1, two => 2, three => 3 ); ($v1,$v2,$v3) = @myhash{qw(one two two)}; # <-- line of interest print "$v1\n$v2\n$v2\n"; How do I translate the second line in a similiar compact way to python? Below is what I tried. I'm just interested in something more compact. mydict={ 'one' : 1, 'two' : 2, 'three' : 3 } # first idea, but still a little too much to type [v1,v2,v3] = [ mydict[k] for k in ['one','two','two']] # for long lists lazier typing,but more computational intensive # as split will probably be performed at runtime and not compilation time [v1,v2,v3] = [ mydict[k] for k in 'one two two'.split()] print "%s\n%s\n%s" %(v1,v2,v3) thanks for any ideas -- http://mail.python.org/mailman/listinfo/python-list
Re: dict slice in python (translating perl to python)
Thanks a lot for all your answers. There's quite some things I learnt :-) [v1,v2,v3] = ... can be typed as v1,v2,v3 = . . . I also wasn't used to map(myhash.get, ['one', 'two', 'two']) itemgetter('one', 'one', 'two')(x) I also didn't know print "%(one)s\n%(two)s\n%(two)s" % mydict The reason I'd like to have a short statement for above is, that this is for me basically just some code, to name and use certain fields of a hash in i given code section. The real example would be more like: name,age,country = itemgetter('name age country'.split())(x) # or any of my above versions # a lot of code using name / age / country thanks a gain and bye H On Sep 10, 5:28 pm, hofer <[EMAIL PROTECTED]> wrote: > Let's take following perl code snippet: > > %myhash=( one => 1 , two => 2 , three => 3 ); > ($v1,$v2,$v3) = @myhash{qw(one two two)}; # <-- line of interest > print "$v1\n$v2\n$v2\n"; > > How do I translate the second line in a similiar compact way to > python? > > Below is what I tried. I'm just interested in something more compact. > > mydict={ 'one' : 1 , 'two' : 2 , 'three' : 3 } > # first idea, but still a little too much to type > [v1,v2,v3] = [ mydict[k] for k in ['one','two','two']] > > # for long lists lazier typing,but more computational intensive > # as split will probably be performed at runtime and not compilation > time > [v1,v2,v3] = [ mydict[k] for k in 'one two two'.split()] > > print "%s\n%s\n%s" %(v1,v2,v3) -- http://mail.python.org/mailman/listinfo/python-list
Re: dict slice in python (translating perl to python)
On Sep 11, 10:36 am, Nick Craig-Wood <[EMAIL PROTECTED]> wrote: >I'd type the explicit > > v1,v2,v3 = mydict['one'], mydict['two'], mydict['two'] # 54 chars > Either > is only a couple more > characters to type. It is completely > explicit and comprehensible to everyone, in comparison to > > v1,v2,v3 = [ mydict[k] for k in ['one','two','two']] # 52 chars > v1,v2,v3 = [ mydict[k] for k in 'one two two'.split()] # 54 chars > > Unlike perl, it will also blow up if mydict doesn't contain 'one' > which may or may not be what you want. > Is your above solution robust against undefined keys. In my example it would'nt be a problem. The dict would be fully populated, but I'm just curious. -- http://mail.python.org/mailman/listinfo/python-list
Understanding (and getting rid) of optparse.py:668: FutureWarning: %u/%o/%x/%X of negative int will return a
Hi, I get following warning with a python script: optparse.py:668: FutureWarning: %u/%o/%x/%X of negative int will return a signed string in Python 2.4 and up my code: from optparse import OptionParser if __name__ == '__main__': parser = OptionParser() parser.add_option('-G','--green',action= 'store_const', const= '#00FF00' , dest='color', default='#808080', help='life is so green') parser.add_option('-R','--red',action= 'store_const', const = '#FF' , dest='color', help='I just see red') # add more elaborated command line parsing and help text here (options,argv) = parser.parse_args() print 'options',options I assume python wants to tell me that newer version will behave differently for numeric arguments What I wonder is: Why do I get the warning if my code doesn't try to parse any numbers? Is there any way to get rid of the warning without having to change the python version? (I noticed, the warning disappears if I remove the line printing options) thanks for any explanations. suggestions H -- http://mail.python.org/mailman/listinfo/python-list
Re: Understanding (and getting rid) of optparse.py:668: FutureWarning: %u/%o/%x/%X of negative int will return a
On Sep 26, 6:21 pm, Peter Otten <[EMAIL PROTECTED]> wrote: > hofer wrote: > > Hi, > > > I get following warning with a python script: > > > optparse.py:668: FutureWarning: %u/%o/%x/%X of negative int will > > return a signed string in Python 2.4 and up > > You can print options.__dict__ instead of options with little loss of > information, or turn the warning off > > python -Wignore::FutureWarning myscript.py > > Peter Thanks a lot Peter, Any trick to disable warnings just for a given range of code? bye H -- http://mail.python.org/mailman/listinfo/python-list