Re: Putting a lock on file.
Harlin Seritt wrote: I have a file that a few different running scripts will need to access. [...] This may seem nice on paper but I hate to run a while for an indeterminate amount of time. Is there anything else that can be done that would be better? On posix systems, there is a fcntl module [1] that can be useful. [1] http://python.org/doc/2.4.1/lib/module-fcntl.html -- http://mail.python.org/mailman/listinfo/python-list
Re: execute commands and return output
billiejoex wrote: Hi all. I'm searching for a portable (working on *nix and win32) function that executes a system command and encapsulate its output into a string. Searching for the web I found this: os.popen('command').read() It is perfect but when che command return an error the funciotn returns an empy string. Does it is possible to return stdout and stderr too? You may want to look at the subprocess [1] module and its Popen class [2]. [1] http://python.org/doc/2.4.1/lib/module-subprocess.html [2] http://python.org/doc/2.4.1/lib/node234.html -- http://mail.python.org/mailman/listinfo/python-list
Re: sys.stdout
Sébastien Boisgérault a écrit : The sys.stdout stream behaves strangely in my Python2.4 shell: import sys sys.stdout.write() sys.stdout.write(\n) sys.stdout.write(\n) sys.stdout.flush() [...nothing...] There are two things competing on your stdout: what you explicitely ask the program to write and the prompt and echo of the interpreter. Try this: import sys, time sys.stdout.write('aaa'); sys.stdout.flush(); time.sleep(2) -- http://mail.python.org/mailman/listinfo/python-list
Re: documentation error
bill wrote: From 3.2 in the Reference Manual The Standard Type Hierarchy: Integers These represent elements from the mathematical set of whole numbers. The generally recognized definition of a 'whole number' is zero and the positive integers. This term is ambiguous as it seems to be used for both natural numbers and signed numbers [1]. That is to say, -1 is not a whole number. The documentation ought to replace whole numbers with integers. Then you get a circular definition, arguably not very useful. Why not simply precise 'signed whole numbers'? However, it can be noted that the first instance of such types provides the range -2147483648, 2147483647 which cannot be mistaken for natural numbers. [1] http://en.wikipedia.org/wiki/Whole_numbers -- http://mail.python.org/mailman/listinfo/python-list
Re: Replacing large number of substrings
Will McGugan wrote: Hi, Is there a simple way of replacing a large number of substrings in a string? I was hoping that str.replace could take a dictionary and use it to replace the occurrences of the keys with the dict values, but that doesnt seem to be the case. You can look at the re.sub [1] and try: d={'a':'x', 'b':'y'} def repl(match): return d.get(match.group(0), '') print re.sub((a|b), repl, a b c) dict_replace( a b c, dict(a=x, b=y) ) x y c Above, I gave the pattern myself but you can try to have it generated from the keys: def dict_replace(s, d): pattern = '(%s)'%'|'.join(d.keys()) def repl(match): return d.get(match.group(0), '') return re.sub(pattern, repl, s) On your example, I get: dict_replace('a b c', {'a': 'x', 'b': 'y'}) 'x y c' [1] http://python.org/doc/2.4.1/lib/node114.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Proposal: add sys to __builtins__
Michael Hoffman wrote: To the contrary, I agree with Larry Wall that laziness is one of the cardinal virtues of a programmer. There's lazy and too lazy. You don't want to be too lazy to even get out of bed to code in Python. Of course, with Perl, that's entirely another mattress^Wmatter. Would you argue that the language is superior because half of its modules must have import sys at the beginning I wouldn't dare arguing about superiority. I was just stating your proposal didn't really solve anything. A good editor/template and .pythonrc already save you the typing of 'import sys' in scripts for the former and shell command for the latter. Sorry, that's incorrect Alright, that was a bit of an overstatement. I should have said your proposal is perceptibly useful in those shell one-liners. The distribution of script and modules is another matter. As for my opinion, you've already guessed I don't perceive 'import sys' as an issue. Therefore, the special case of an implicit import of sys does not appeal to me. -- http://mail.python.org/mailman/listinfo/python-list
Re: Proposal: add sys to __builtins__
Michael Hoffman a écrit : MrJbQ7 wrote: Besides, a better way is to use your ~/.pythonrc file for customizing according to your needs. A simple: echo import sys, os ~./pythonrc will do the job. Until someone else tries to use your script or module. A developper should not be too lazy to add one small line in a complete script/module. Besides your entire justification to this proposal was based on shell one-liners, not script or modules. -- http://mail.python.org/mailman/listinfo/python-list
Re: random seed
[EMAIL PROTECTED] wrote: By default, randomm module uses the timestamp to generate the seed value. Is it possible to know what that seed value is? From a (very) quick glance at the doc [1], I'm not sure you can get it. But if you want to reuse it later (for a deterministic behaviour), you can get and set the internal state of the generator (using getstate and setstate). [1] http://docs.python.org/lib/module-random.html -- http://mail.python.org/mailman/listinfo/python-list
Re: how to append semicolon to a variable
Grant Edwards wrote: On 2005-08-13, yaffa [EMAIL PROTECTED] wrote: i have the following lines of python code: couch = incident.findNextSibling('td') price = couch.findNextSibling('td') sdate = price.findNextSibling('td') city = sdate.findNextSibling('td') strUrl = addr.b.string currently what this ends up doing is creating something like this couch3201/01/2004newyork now what i want to do is add a semicolon after the couch, price, sdate, city so that i get something like this couch;32;01/01/2004;new york Try this: s = ';'.join([couch,price,sdate,city]) print s I'll risk myself with something like: s = ';'.join([tag.string for tag in [couch,price,sdate,city]]) Of course, from the question I wouldn't have any clue. I just like doing some guessing on problems I know nothing about. ;) p.s. i tried couch = couch + ';' and then i tried couch = couch + ; both of those should have worked fine. Not really. It seems to me the OP is using BeautifulSoup (or some other SGML parser). In this case, couch and others are not strings but objects. It may also be that strUrl is their parent (but I wouldn't know, how would I?) Perhaps you ought to read through the tutorial? That's always useful. However, the first thing is to put the minimal context in your question to help the people you want your answers from understanding your issue. I would advise you to read tutorials and documentations on the modules you're using as well as learning to ask meaningful questions[1]. [1] http://www.catb.org/~esr/faqs/smart-questions.html -- http://mail.python.org/mailman/listinfo/python-list
Re: why no arg, abs methods for comlex type?
Daniel Schüle wrote: shrug Okay. Write a patch. Personally, I would prefer that it be a function in cmath rather than a method because then it could be made to work on integers and regular floats, too. Ok, but what semantic should angle/arg have, say for 3 respectively for 3.0? the same as for arg(3+0j)? As a potential user, that's what I would expect. See Dan Bishop's implementation (earlier in this thread). -- http://mail.python.org/mailman/listinfo/python-list
Re: Comparison of functions
Steven D'Aprano wrote: Playing around with comparisons of functions (don't ask), I discovered an interesting bit of unintuitive behaviour: a = lambda y: y b = lambda y: y a function lambda at 0xf70598ec b function lambda at 0xf7059844 a b False So I'm puzzled about how Python compares the two. Seems to me the object addresses are compared in this case. But I'm too lazy to check it in the source. ;) However, the doc [1] warns you about such comparisons: Most other types compare unequal unless they are the same object; the choice whether one object is considered smaller or larger than another one is made arbitrarily but consistently within one execution of a program. [1] http://docs.python.org/ref/comparisons.html -- http://mail.python.org/mailman/listinfo/python-list
Re: showing help(M) when running module M standalone
Chris wrote: hello, I have a small module which only contains some utility functions. when running this standalone I would like to show the module docs and each function docs, as if doing import M help(M) I came up with the following but I reckon there is a much simpler way? if __name__ == '__main__': print __doc__ print \nFUNCTIONS:\n for x in __all__: print x exec print + x + .__doc__ Works but does not seem right using exec for such a task. One way would be to use the locals() [1] to get rid of the exec: if __name__ == '__main__': print __doc__ print \nFUNCTIONS:\n for x in __all__: print x print locals()[x].__doc__ However, if you just want to call help, calling it on '__main__' seems to work: if __name__ == '__main__': help(__name__) [1] http://docs.python.org/lib/built-in-funcs.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Comparison of functions
Steven D'Aprano wrote: It was easy. I never once asked myself whether some complex number was greater or less than another, I just asked which one comes first in a lexicographic sort? The two questions are NOT the same, and it is an ugliness in an otherwise beautiful language that Python treats them as the same. The point is Python does not. The order you proposed above can be implemented using a comparison function you can pass to the sort function of lists [1] or the sorted builtin [2]. If the elements can be compared, Python offers you not to pass the cmp function to sort if you want to use this default order. Python allows you to use the default ordering to sort a list but does not treat both questions in the same manner. However, the fact is ordering a list using the default '' happens pretty often. In the case of complex numbers, no mathematically sound comparison function exists and Python does not impose some default function that would be called a wart. [1] http://docs.python.org/lib/typesseq-mutable.html [2] http://docs.python.org/lib/built-in-funcs.html -- http://mail.python.org/mailman/listinfo/python-list
Re: FAQ?
Michael Hoffman wrote: Keith P. Boruff wrote: Michael Hoffman wrote: Keith P. Boruff wrote: Is there an FAQ available specific to this NG as I'm sure some of the list slicing questions I have have been asked before. Therefore I asked a question on why you want a *newsgroup* FAQ when it sounds like you want a *Python* FAQ, so that I and others could potentially be more helpful in answering your unasked question. Seems to me there is a slight misunderstanding here. Some newsgroups publish a FAQ, based on the questions that are asked in it. These FAQ are often related to the subject of the NG, not specifically the NG and its mechanics. It is advised, when someone wants to post in these kind of NG, to check if their question is not yet answered in the FAQ published by the NG on the subject. Therefore, I think the OP was checking if there was such a FAQ on Python published specifically in c.l.python besides the ones he already found on the web. -- http://mail.python.org/mailman/listinfo/python-list
Re: Printing a variable's name not its value
Simon Dahlbacka wrote: as you have been told, there is no way to get a variable's name Well, if you really want to, you can get all the names bound to a given object: def get_names(obj): g = globals() names = [] for name in g: if g[name] is obj: names.append(name) return names Then you can play around: list1 = [] list2 = [list1] get_names(list2) ['list2'] list3 = list2 get_names(list2) ['list3', 'list2'] get_names(1) [] a = 1 get_names(1) ['a'] b = 1 get_names(1) ['a', 'b'] get_names(a) ['a', 'b'] c = 4/3. d = 4/3. get_names(c) ['c'] get_names(d) ['d'] get_names(4/3.) [] But I wouldn't do it. If I want a name to be attached to some objects, I usually include it as a member/property of my class. -- http://mail.python.org/mailman/listinfo/python-list
Re: Existance of of variable
Josiah Manson wrote: Hello. I am very new to Python, and have been unable to figure out how to check if a variable exists or not. In the following code I have made a kludge that works, but I think that it would be clearer to check if closest exists and not have to initialize it in the first place. How is that check done? Variables are stored in two dictionnaries: globals() (for global variables) and locals() (for the local ones, which are also global on top level). You can therefore write: if 'closest' in locals(): self.sel = [closest.name] On the other hand, if you try to access a variable which doesn't exist, you'll get the NameError exception. Another way is then: try: self.sel = [closest.name] except NameError: pass I also have a few other questions to tack on if you don't mind. I am setting dist to 1e9, because that is a larger value than any of the places in the galaxy will be far away. Is there a better way to initialize dist so that it is impossible for this to fail? For example, would setting dist to infinity work, and how is that done? The float constructed from the string 'inf', float('inf'), may do the trick. I don't know the details, though. 1e100 float('inf') True Extending my existance checking question, how does one check what type a variable has? The '__class__' special attribute [1] will return the class. You can also look at the builtin 'isinstance' [2]. However, type checking is not a common idiom in python since we tend to use 'duck typing': if your object can do what you want with it, don't bother to check if it is exactly of the class you expect. Therefore we often try to use the object then catch the exception rather than check the object then use it. Of course, there may be situations where it's not suitable but type checking seems not to be too common in python. [1] http://docs.python.org/lib/specialattrs.html [2] http://docs.python.org/lib/built-in-funcs.html -- http://mail.python.org/mailman/listinfo/python-list
Re: a question
Xinyue Ye wrote: when I type sys.ps2 after import sys, I got the message like: Traceback (most recent call last): File pyshell#10, line 1, in -toplevel- sys.ps2 AttributeError: 'module' object has no attribute 'ps2' why does it happen? sys.ps2 is defined in an interactive session only as precised in the doc [1]: $ python Python 2.3.5 (#2, May 29 2005, 00:34:43) [GCC 3.3.6 (Debian 1:3.3.6-5)] on linux2 Type help, copyright, credits or license for more information. import sys print sys.ps2 ... compared to: $ cat ps2.py import sys print sys.ps2 $ python ps2.py Traceback (most recent call last): File ps2.py, line 2, in ? print sys.ps2 AttributeError: 'module' object has no attribute 'ps2' $ [1] http://docs.python.org/lib/module-sys.html -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get/set class attributes in Python
Kalle Anke wrote: I'm coming to Python from other programming languages. I like to hide all attributes of a class and to only provide access to them via methods. Some of these languages allows me to write something similar to this int age( ) { return theAge } void age( x : int ) { theAge = x } (I usually do more than this in the methods). You can 'hide' you getsetters using a property attribute[1]: class person(object): ... def __init__(self): ... self.age = 0 ... def set_age(self, age): ... print 'set %d' % age ... self.__age = age ... def get_age(self): ... print 'get' ... return self.__age ... age = property(get_age, set_age) ... joe = person() set 0 joe.age = 20 set 20 print joe.age get 20 [1]http://docs.python.org/lib/built-in-funcs.html -- http://mail.python.org/mailman/listinfo/python-list
Re: If - Or statements
Patrick Down wrote: What about: if True in [thefile.endswith(x) for x in ('mp3','mp4','ogg','aac','wma')]: That will catch (widely used) file names such as 'tmp3' or 'i_cant_spell_frogg'. ;) -- http://mail.python.org/mailman/listinfo/python-list
Re: Dynamic Lists, or...?
Lorn wrote: I'm trying to figure out a way to create dynamic lists or possibly antother solution for the following problem. I have multiple lines in a text file (every line is the same format) that are iterated over and which need to be compared to previous lines in the file in order to perform some simple math. Each line contains 3 fileds: a descriptor and two integers. Here is an example: rose, 1, 500 lilac, 1, 300 lilly, 1, 400 rose, 0, 100 Do you have to maintain a list or just the current value? Also I did not find it clear why you have to compare with previous line? Anyway, I think dictionnary may be useful there: input = rose, 1, 500 ... lilac, 1, 300 ... lilly, 1, 400 ... rose, 0, 100 entries = [l.split(',') for l in input.split('\n')] d = {} for k, op, n in entries: ... if int(op) == 1: ... d[k] = d.get(k, 0) + int(n) ... else: ... d[k] = d.get(k, 0) - int(n) ... print d {'rose': 400, 'lilly': 400, 'lilac': 300} That may not be what you want but there may be some things for you to use. And you can of course keep the full list of operation in d. -- http://mail.python.org/mailman/listinfo/python-list
Re: If - Or statements
Ognjen Bezanov wrote: ext = thefile.split('.') #get the file extension ext[1] = ext[1].lower() #convert to lowercase As a side note, ext[1] will be the first extension: 'foo.bar.ogg'.split('.')[1] 'bar' I'd advise ext[-1], the last element of the splitted list. 'foo.bar.ogg'.split('.')[-1] 'ogg' -- http://mail.python.org/mailman/listinfo/python-list
Re: finding indices in a sequence of parentheses
Peter Otten wrote: tiissa wrote: Disclaimer: not tested further than example above (but confident). Not tested but confident should be an oxymoron for a programmer. Not tested but confident is an oxymoron for mathemtaticians. Programmers know better than that, they leave bugs in their code to have more work to do. ;) OTOH, you're right. Matching parentheses cannot be done without a stack, that should have rung a bell. -- http://mail.python.org/mailman/listinfo/python-list
Re: finding indices in a sequence of parentheses
Peter Otten wrote: I think no amount of testing will give these strange people confidence. Proof is the magic word here. Some would maybe be satisfied if your tests cover the whole set of input. When that's possible, that may be useless. But that's not a matter to bother them with. ;) (And of course, you just don't tell them how you generated their output with the same program.) -- http://mail.python.org/mailman/listinfo/python-list
Re: need help of RE
cheng wrote: im sorry, my engilsh is not vell well, That's alright, you could have been french. ;) the string not only contain '' and '|' and it can be anyting i just want to split out the whole word inside the string Look at the example for split function of re module in the doc [1]. In short: import re s=(word1 (Word2|woRd3)) re.split(\W+,s) ['', 'word1', 'Word2', 'woRd3', ''] [w.lower() for w in re.split(\W+,s) if w != ''] ['word1', 'word2', 'word3'] [1]http://python.org/doc/lib/node114.html -- http://mail.python.org/mailman/listinfo/python-list
Re: finding indices in a sequence of parentheses
Steven Bethard wrote: (2) Does anyone see an easier/clearer/simpler[1] way of doing this? I'd personnally extract the parenthesis then zip the lists of indices. In short: def indices(mylist): ... lopen=reduce(list.__add__, [[i]*s.count('(') for i,s in enumerate(mylist)],[]) ... lclose=reduce(list.__add__, [[i]*s.count(')') for i,s in enumerate(mylist)],[]) ... return zip(lopen,lclose) ... indices(lst) [(2, 2), (4, 7), (6, 7), (8, 9), (8, 10)] Before returning, you can check if the lists have same size and if the '(' has lower or equal index than ')' in each of these couples. If not you can raise the appropriate exception. Disclaimer: not tested further than example above (but confident). -- http://mail.python.org/mailman/listinfo/python-list
Re: Parsing a Python dictionary inside a Python extension
[EMAIL PROTECTED] wrote: I tried something like this and it has not worked. Oh! What did you ask of it, what did you expect and what did you get? if ( (item = PyDict_GetItemString( vdict , atab1)) != NULL ) PyArg_ParseTuple( item , i , atab1 ); This code expects a dictionary in which keys 'atab1' and 'atab2' are singletons of integer. If that's what you want, I'd say it should work. // ndict = Py_BuildValue( create dictionary here ..) return ndict ; } I personnally prefer 'return Py_BuildValue();' than returning NULL pointers (but I don't like to check the doc just to make sure NULL can be interpreted as None). In order to build a dictionary you could try: ... return Py_BuildValue({s:i,s:i}, key1, atab1, key2, atab2); } Or even {s:(i),s:(i)} to have singletons for values. HTH -- http://mail.python.org/mailman/listinfo/python-list
Re: __call__
TK wrote: Sorry but it does not work. It _does_ work. It just don't do what you expect. That's different till you know how to do it. Let's see: class Test(object): ... def __call__(self): ... print 'Hi' ... You first define a class whose members can be called. Test() __main__.Test object at 0x3e6d0 Then you build an instance of these class. Fine. If you want to call this instance you have to tell python: class Test: ... def __init__(self): ... print 'In init.' ... def __call__(self): ... print 'In call.' ... t=Test() In init. t() In call. Test() In init. __main__.Test instance at 0x401e2b6c Test()() In init. In call. -- http://mail.python.org/mailman/listinfo/python-list
Re: Markov chain with extras?
[EMAIL PROTECTED] wrote: I want to use it for music. So given list 1 (melody), list 2 (chords) could be generated by a Markov chain. Also, given the chords the melody could be generated again by a chain. So, at each time step you want: - chord(t) given melody(t-1), chord(t-1) and chord(t-2); - melody(t) given melody(t-1) and chord(t). (or the other way round) Is that correct? If so, one could write: hmm2.py from random import random def decision(p): Return a single value according to a probability distribution. # trivial due to our binary variables return (random()p) and 1 or 0 def ct_given_mt1_ct1_ct2(mt1,ct1,ct2): Chord given past melody and chords. p0=0.5*ct1*ct2+0.25*ct1+0.125*ct2+0.0625 return mt1 and p0 or 1-p0 def mt_given_mt1_ct(mt1,ct): Melody given past melody and present chord. return 0.1+0.5*mt1+0.3*ct def timestep(chord,melody): Chose next chord and melody. chord.append(decision( ct_given_mt1_ct1_ct2(melody[-1],chord[-1],chord[-2]))) melody.append(decision(mt_given_mt1_ct(melody[-1],chord[-1]))) chord=[0,1] melody=[0] for i in range(20): timestep(chord,melody) print Chord:\t%s%''.join(map(str,chord[2:])) print Melody:\t%s%''.join(map(str,melody[1:])) This generates some 0-1 string according to the above conditional distributions. What's needed there is to have proper variables for melody and chord with proper domains (instead of only binary values) and proper probability distributions (and proper decision method also although a draw is fair enough). Usually, specifying your distributions is the hard part (some people actually cheat by having their programs learn these distributions ;)). I haven't had time to play around with your code and as I've only been studying python for about six months I don't quite understand what's going on. This might already do what I want, I just need to think in terms of notes and chords. Doing Bayesian stuff myself, I'd give mathematical expressions to what I want. Then implementation follows. But I wouldn't rush into my favorite editor/python shell before having written some nice equations down. ;) -- http://mail.python.org/mailman/listinfo/python-list
Re: Markov chain with extras?
[EMAIL PROTECTED] wrote: I think is more easy explained as two linked markov chains. So given one list the other can be generated. 'Given one list sounds' like an observation (and this sound like an order 2 hmm). But I'm not sure what exactly you want to do with your markov chain. Do you want the probability distribution at each time step or some value ? In this case, I'd do something like: hmm.py from random import random def St_given_St1_St2_Ot(St1,St2,Ot): p0=0.5*St1*St2+0.25*St1+0.125*St2+0.0625 return Ot and p0 or 1-p0 def decision(p): return (random()p) and 1 or 0 def hmm(LO,LS): for ot in LO[2:]: p=St_given_St1_St2_Ot(LS[-1],LS[-2],ot) LS.append(decision(p)) return LS LO1=(-1,-1,1,0,0,0,1,1) LS1=[1,0] print ''.join(map(str,hmm(LO1,LS1))) LO2=(0,)*50 LS2=[1,1] print ''.join(map(str,hmm(LO2,LS2))) LO3=(1,)*50 LS3=[1,1] print ''.join(map(str,hmm(LO3,LS3))) Which gives hours of fun looking at random numbers: $ python hmm.py 1001 111010 11011011011011011011010110011011011011011010101101 $ python hmm.py 10101011 000111 11011010011010100011010110110011001101101101011010 $ python hmm.py 10100011 11 11011010110011001101011011011101010110101101101011 $ python hmm.py 1001 1110101001 11011001101101011010110111010101010110110110011101 $ python hmm.py 10100011 11 11010110110110110011011010110011010011011011011010 $ Instead of generating the whole sequence, you can wrap it in an iterator. And the observations list can also be an iterator (generated with another chain if you like). HTH -- http://mail.python.org/mailman/listinfo/python-list
Re: function with variable arguments
Xah Lee wrote: on a related topic, I think it would be a improvement for the built-in range() so that step needs not be an integer. There are easy workarounds but I'd find it useful as well. Further, it'd be better to support decreasing range. e.g. Range( 5, 7, 0.3); # returns [5, 5.3, 5.6, 5.9, 6.2, 6.5, 6.8] Range( 5, -4, -2); # returns [5,3,1,-1,-3] The last one already works: range(5,-4,-2) [5, 3, 1, -1, -3] -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting the sender widget's name in function (Tkinter)
Cameron Laird wrote: In article [EMAIL PROTECTED], Eric Brunel [EMAIL PROTECTED] wrote: Unfortunately, making a binding to Button-1 on Button widgets does not have the same behavior as setting their 'command' option. Without unraveling my own confusion about who has said what to whom, does everyone realize that Tkinter bind()ings inherently can access the widgets which generate their events? I don't know about everyone, but I can assume that's definitively the case of infidel (who precisely based the solution you quoted on this) and Eric Brunel. But that may not be the topic at hand. Indeed, the main point is that, according to Eric, bind() and command don't behave in the exact same way. And the OP asked about having a reference on the widget using the command callback (that, contrary to event-binded callbacks, don't get passed any argument). So far, the OP is proposed the choice to either use the event/bind mecanism or use different callbacks for his different buttons (either with the method I proposed or not). -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting the sender widget's name in function (Tkinter)
Cameron Laird wrote: In article [EMAIL PROTECTED], tiissa [EMAIL PROTECTED] wrote: So far, the OP is proposed the choice to either use the event/bind mecanism or use different callbacks for his different buttons (either with the method I proposed or not). Is there general understanding that use different callbacks ... can be implemented as parametrize the same callback with a widget-specific value? Tough questions thou ask! Again I can't answer about general understanding. ;) However, having myself proposed such a solution in this very thread (and hinted about it in the above sentence), I do hope most people (at least those interested in this issue) will be aware of this kind of trick (without any restriction on the actual implementation). :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting the sender widget's name in function (Tkinter)
Harlin Seritt wrote: I have the following script. Two widgets call the same function. How can I tell inside of the called function which button called it?: As far as I know you can't (but I can be proven wrong). You may try to define a class to solve this (not tested): class say_hello: def __init__(self, text): self.text=text def __call__(self) print 'Hello!' print self.text root = Tk() button1 = Button(root, text='Button 1', command=say_hello('Button 1')) button1.pack() button2 = Button(root, text='Button 2', command=say_hello('Button 2')) button2.pack() root.mainloop() -- http://mail.python.org/mailman/listinfo/python-list
Re: a=[ lambda t: t**n for n in range(4) ]
[EMAIL PROTECTED] wrote: i wonder if there is an automatic way to make that without calling a function. You mean without _explicitely_ calling a function. May I inquire why you need to write f instead of f(x)? an automatic way that depends on changing the value of x. as each time x=something used the whole matrix changes automaticly. As pointed out by El Pitonero property can be your friend: class A(object): ... def get_v(self): ... return [1,x] ... v=property(get_v) ... a=A() x=0 a.v [1, 0] x=2 a.v [1, 2] However, you will calculate your matrix each time you will access it (and I find it ugly to use a global variable this way). You can however build it the other way round: class B(object): ... def __init__(self): ... self.v=[1,0] ... self.x=0 ... def calc_v(self): ... self.v[1]=self.__x ... def set_x(self,x): ... self.__x=x ... self.calc_v() ... def get_x(self): ... return self.__x ... x=property(get_x, set_x) ... b=B() b.v [1, 0] b.x=2 b.v [1, 2] This time, calculations only occur when you change the value of x. -- http://mail.python.org/mailman/listinfo/python-list
Re: inner sublist positions ?
Bernard A. wrote: maybe have you some better / faster ideas / implementations ? or even a more pythonic to help me learning that You may want to look at string matches algorithm (a good review: [1]). In particular there are classics like Boyer-Moore and some involving minimal automatons similar to your regular expression ideas. [1] http://www-igm.univ-mlv.fr/~lecroq/string/index.html -- http://mail.python.org/mailman/listinfo/python-list
Re: __del__ and reference count problem
[EMAIL PROTECTED] wrote: Your problem can be simplified : class A: pop = 11 def __del__(self): print A.pop if __name__ == '__main__': objA = A() I got the same error message, and I don't know why ? it looks like the class variable can't be accessed from __del__? It's interesting to note that self.pop instead of A.pop works as expected. But I don't know why A.pop doesn't. -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the difference between these 2 statements?
Reinhold Birkenfeld wrote: ATSkyWalker wrote: What's the difference between these 2 statements? If you have a String s=12345 s[len(s)::-1] = 54321 But s[len(s):0:-1] = 5432 Why? What's the difference? What number then can I use as the end of the slice if I were to supply all 3 parameters? -1. -len(s) or less. -1 will return an empty string. Actually you start from len(s)-1 (len(s) is not an index in s) and you stop when you reach the index specified (or the end). Since -1 is the same index as the starting one (-1~len(s)-1, -2~len(s)-2, -len(s)+1~0), you end up with an empty string. Therefore you have to try to reach indices lower (due to the negative step) than the minimum valid index of your list in order to reverse it fully. -- http://mail.python.org/mailman/listinfo/python-list
Re: pyGTK on Mouse over event ?
[EMAIL PROTECTED] wrote: hello, Is there an event simular to the java event onMouseOver ? I want to get the coordinates of the mouse pointer when it is over an image ( GTKImage widget) I've tried using the EventBox with the motion_notify but that only seems to work when the mouse is pressed ? Why do you use an event box? Image derives from Widget hence can be connected to the motion-notify-event just like EventBox. Did you try directly? -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the difference between these 2 statements?
[EMAIL PROTECTED] wrote: I'm sorry, I'm not really following your logic. Can you supply the statement with the three parameters ? so if I want to reverse it fully using s[len(s)-1:x:-1] what would x be or is it impossible to express it in this way ? Contrary to what I said above x should be _strictly_ less than -len(s). You stop when you reach in the list the given end index (and don't take the item there) or if you leave the index range. But -1 as an index is the same as (len(s)-1). Therefore going from len(s)-1 down to -1 is the same as going from len(s)-1 to len(s)-1 hence an empty list. And -len(s) is the same as 0 (my mistake above) But -len(s)-1 is not in the list thus you won't discard any limit. The example: In [1]: s='12345' In [2]: s[len(s)-1:0:-1] Out[2]: '5432' In [3]: s[len(s)-1:-1:-1] Out[3]: '' In [4]: s[-1],s[len(s)-1] Out[4]: ('5', '5') In [5]: s[len(s)-1:-len(s)-1:-1] Out[5]: '54321' In [6]: s[len(s)-1:-len(s):-1] Out[6]: '5432' -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the difference between these 2 statements?
Peter Otten wrote: [EMAIL PROTECTED] wrote: so if I want to reverse it fully using s[len(s)-1:x:-1] what would x be or is it impossible to express it in this way ? This does not work for integers, because the theoretically correct value x = -1 already has another interpretation as the gap between the last and the last but one character. AFAIK, it is not an issue of integer (what else can an slice index be in python?) but simply of index aliasing. For x=-len(s)-1, you get the whole reversed list: In [5]: s[len(s)-1:-len(s)-1:-1] Out[5]: '54321' -- http://mail.python.org/mailman/listinfo/python-list
Re: pyGTK on Mouse over event ?
[EMAIL PROTECTED] wrote: if i add a motion_notify or even a butten_press event to an image object it does absolutly nothing :s I have tried coding a simple application in pyGTK and I remember I had trouble getting button_press event in a DrawingArea. I was using glade and despite having declared a handler to this event, I had to manually call add_events(gtk.gdk.BUTTON_PRESS_MASK) (the connect was ok but the event mask was not). Have you checked this? -- http://mail.python.org/mailman/listinfo/python-list
Re: What's the difference between these 2 statements?
Peter Otten wrote: Still, for practical purposes you have to test for slicelen = stringlen, so whether you choose None, -len(s)-1, or -sys.maxint as the second slice parameter doesn't matter much. Sure, for practical purposes you don't bother to write extra characters and leave it void. But we knew it from the start of the thread. ;) -- http://mail.python.org/mailman/listinfo/python-list
Re: pyGTK on Mouse over event ?
[EMAIL PROTECTED] wrote: def __init__(self): xml = gtk.glade.XML(/home/domenique/project1.glade) self.window = xml.get_widget(window1) self.img = xml.get_widget(image1) self.img.set_from_file(./test.svg) self.img.show() self.img.add_events(gtk.gdk.BUTTON_MOTION_MASK) xml.signal_autoconnect({ 'on_window1_delete_event': self.on_window1_delete_event, 'on_window1_destroy_event': self.on_window1_destroy_event, 'on_image1_motion_notify_event': self.on_image1_motion_notify_event, 'on_image1_button_press_event': self.img_key_press, }) This is the code so far. i've added the MOTION MASK to the image widget, is that what u ment ? Yes. But I guess by your question it doesn't work better than before. Sorry I didn't help much. :/ -- http://mail.python.org/mailman/listinfo/python-list
Re: pyGTK on Mouse over event ?
[EMAIL PROTECTED] wrote: def __init__(self): xml = gtk.glade.XML(/home/domenique/project1.glade) self.window = xml.get_widget(window1) self.img = xml.get_widget(image1) self.img.set_from_file(./test.svg) self.img.show() self.img.add_events(gtk.gdk.BUTTON_MOTION_MASK) xml.signal_autoconnect({ 'on_window1_delete_event': self.on_window1_delete_event, 'on_window1_destroy_event': self.on_window1_destroy_event, 'on_image1_motion_notify_event': self.on_image1_motion_notify_event, 'on_image1_button_press_event': self.img_key_press, }) This is the code so far. i've added the MOTION MASK to the image widget, is that what u ment ? Actually I read too fast. I meant BUTTON_PRESS_MASK (not motion) for the button_press_event. For motion_notify_event, I guess it would be POINTER_MOTION_MASK (not button). -- http://mail.python.org/mailman/listinfo/python-list
Re: The value of the entry widget doesn't get updated
Clara wrote: SNIP self.loginButton = Button(self, text='Login', command = VerifyProcessor(self.x.get(), self.y.get()) ) SNIP class VerifyProcessor: def __init__(self, thename, thepass): self.username = thename self.password = thepass def __call__(self): print self.username print self.password Your VerifyProcessor object is constructed just before your loginButton, not when you click. Therefore you may want to pass the x and y StringVars to its __init__ function instead of their value at contruction. Therefore your __call__ method can .get() their values each time the button is clicked. -- http://mail.python.org/mailman/listinfo/python-list
Re: Pattern Matching Given # of Characters and no String Input; use RegularExpressions?
Synonymous wrote: tiissa [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED]... tiissa wrote: If you know the number of characters to match can't you just compare slices? If you don't, you can still do it by hand: In [7]: def cmp(s1,s2): : diff_map=[chr(s1[i]!=s2[i]) for i in range(min(len(s1), len(s2)))] : diff_index=''.join(diff_map).find(chr(True)) : if -1==diff_index: : return min(len(s1), len(s2)) : else: : return diff_index : I will look at that, although if i have 300 images i dont want to type all the comparisons (In [9]: cmp('ccc','cccap')) by hand, it would just be easier to sort them then :). I didn't meant you had to type it by hand. I thought about writing a small script (as opposed to using some in the standard tools). It might look like: In [22]: def make_group(L): : root,res='',[] : for i in range(1,len(L)): : if ''==root: : root=L[i][:cmp(L[i-1],L[i])] : if ''==root: : res.append((L[i-1],[L[i-1]])) : else: : res.append((root,[L[i-1],L[i]])) : elif len(root)==cmp(root,L[i]): : res[-1][1].append(L[i]) : else: : root='' : if ''==root: : res.append((L[-1],[L[-1]])) : return res : In [23]: L=['cccat','cccap','cccan','dddfa','dddfg','dddfz'] In [24]: L.sort() In [25]: make_group(L) Out[25]: [('ccca', ['cccan', 'cccap', 'cccat']), ('dddf', ['dddfa', 'dddfg', 'dddfz'])] However I guarantee no optimality in the number of classes (but, hey, that's when you don't specify the size of the prefix). (Actually, I guarantee nothing at all ;p) But in particular, you can have some file singled out: In [26]: make_group(['cccan','cccap','cccat','cccb']) Out[26]: [('ccca', ['cccan', 'cccap', 'cccat']), ('cccb', ['cccb'])] It is a matter of choice: either you want to specify by hand the size of the prefix and you'd rather look at itertools as pointed out by Kent, or you don't and a variation with the above code might do the job. -- http://mail.python.org/mailman/listinfo/python-list
Re: packages
Jaime Wyant wrote: What I *dont* like about the example is the PascalStyleCasing used for the package names. Is their not some *suggested* standard on naming conventions? There is: see PEP 8. http://www.python.org/peps/pep-0008.html However, I understood there was no definitive convention hence various common styles. -- http://mail.python.org/mailman/listinfo/python-list
Re: fpectl
Matt wrote: Sébastien Boisgérault wrote: My platform is Linux (Mandrake 10.x) I'm assuming that means you can't use it on a Windows platform It's harsh to say Mandrake is a Windows platform. ;o) -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter Tkconstants
codecraig wrote: from Tkinter import * you have access to the constants in Tkconstants, since Tkinter imports it automatically. Yes However, in the shell if I do.. from Tkinter import * print Tkinter.HORIZONTAL I get an error..NameError: Tkinter is not defined Sure, you ask for Tkinter.HORIZONTAL. But if you directly ask for HORIZONTAL it should work. indeed your from statement imported the _content_ of the Tkinter module in the global namespace not the module in itself. It's either: from Tkinter import * print HORIZONTAL or: import Tkinter print Tkinter.HORIZONTAL or even: import Tkinter from Tkinter import * print HORIZONTAL,Tkinter.HORIZONTAL any ideas? I usually only use: import OneModule Or sometimes: from OneModule import OneClass, OneConstant But I usually don't import a whole module in my global namespace. I get what i expect. but according to the tutorial i should only need Tkinter. You do. -- http://mail.python.org/mailman/listinfo/python-list
Re: Pattern Matching Given # of Characters and no String Input; use RegularExpressions?
Synonymous wrote: Can regular expressions compare file names to one another. It seems RE can only compare with input i give it, while I want it to compare amongst itself and give me matches if the first x characters are similiar. Do you have to use regular expressions? If you know the number of characters to match can't you just compare slices? In [1]: f1,f2='cccat','cccap' In [2]: f1[:3] Out[2]: 'ccc' In [3]: f1[:3]==f2[:3] Out[3]: True It seems to me you just have to compare each file to the next one (after having sorted your list). -- http://mail.python.org/mailman/listinfo/python-list
Re: Pattern Matching Given # of Characters and no String Input; use RegularExpressions?
tiissa wrote: If you know the number of characters to match can't you just compare slices? If you don't, you can still do it by hand: In [7]: def cmp(s1,s2): : diff_map=[chr(s1[i]!=s2[i]) for i in range(min(len(s1), len(s2)))] : diff_index=''.join(diff_map).find(chr(True)) : if -1==diff_index: : return min(len(s1), len(s2)) : else: : return diff_index : In [8]: cmp('cccat','cccap') Out[8]: 4 In [9]: cmp('ccc','cccap') Out[9]: 3 In [10]: cmp('cccat','dddfa') Out[10]: 0 -- http://mail.python.org/mailman/listinfo/python-list
Re:
[EMAIL PROTECTED] wrote: I have been going through the manuals and not having much luck with the following code. This is basically an issue of giving 'split' multiple patterns to split a string. If it had an ignore case switch, the problem would be solved. Instead, I have to code the following, which works fine for a single byte string. What can I do when I want to look for strings? As far as I know there is no such switch. If you can't convert your string in, say, lowercase, before splitting, you may have to use the re module: In [1]: test = 'A big Fat CAt' In [2]: import re In [3]: A=re.compile('a', re.IGNORECASE) In [4]: A.split(test) Out[4]: ['', ' big F', 't C', 't'] test = 'A big Fat CAt' A = test.split('A') print A ['', ' big Fat C', 't'] a = [] for x in xrange(len(A)): ... tmp = A[x].split('a') ... for y in xrange(len(tmp)): ... a.append(tmp[y]) ... a ['', ' big F', 't C', 't'] As a side note, reduce is great in such situations: In [5]: reduce(list.__add__,[t.split('a') for t in test.split('A')],[]) Out[5]: ['', ' big F', 't C', 't'] -- http://mail.python.org/mailman/listinfo/python-list