title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
Matplotlib coord. sys origin to top left
1,349,230
<p>How can I flip the origin of a matplotlib plot to be in the upper-left corner - as opposed to the default lower-left? I'm using matplotlib.pylab.plot to produce the plot (though if there is another plotting routine that is more flexible, please let me know).</p> <p>I'm looking for the equivalent of the matlab command: axis ij;</p> <p>Also, I've spent a couple hours surfing matplotlib help and google but haven't come up with an answer. Some info on where I could have looked up the answer would be helpful as well.</p>
8
2009-08-28T20:40:31Z
1,350,154
<p>For an image or contour plot, you can use the keyword <code>origin = None | 'lower' | 'upper'</code> and for a line plot, you can set the ylimits high to low.</p> <pre><code>from pylab import * A = arange(25)/25. A = A.reshape((5,5)) figure() imshow(A, interpolation='nearest', origin='lower') figure() imshow(A, interpolation='nearest') d = arange(5) figure() plot(d) ylim(5, 0) show() </code></pre>
8
2009-08-29T01:31:45Z
[ "python", "matplotlib", "axes" ]
Matplotlib coord. sys origin to top left
1,349,230
<p>How can I flip the origin of a matplotlib plot to be in the upper-left corner - as opposed to the default lower-left? I'm using matplotlib.pylab.plot to produce the plot (though if there is another plotting routine that is more flexible, please let me know).</p> <p>I'm looking for the equivalent of the matlab command: axis ij;</p> <p>Also, I've spent a couple hours surfing matplotlib help and google but haven't come up with an answer. Some info on where I could have looked up the answer would be helpful as well.</p>
8
2009-08-28T20:40:31Z
11,653,129
<p>The following is a basic way to achieve this</p> <pre><code>ax=pylab.gca() ax.set_ylim(ax.get_ylim()[::-1]) </code></pre>
4
2012-07-25T15:22:55Z
[ "python", "matplotlib", "axes" ]
Matplotlib coord. sys origin to top left
1,349,230
<p>How can I flip the origin of a matplotlib plot to be in the upper-left corner - as opposed to the default lower-left? I'm using matplotlib.pylab.plot to produce the plot (though if there is another plotting routine that is more flexible, please let me know).</p> <p>I'm looking for the equivalent of the matlab command: axis ij;</p> <p>Also, I've spent a couple hours surfing matplotlib help and google but haven't come up with an answer. Some info on where I could have looked up the answer would be helpful as well.</p>
8
2009-08-28T20:40:31Z
35,917,758
<p>The esisest way is to use:</p> <pre><code>plt.gca().invert_yaxis() </code></pre> <p>Origin works only for imshow.</p>
3
2016-03-10T13:21:33Z
[ "python", "matplotlib", "axes" ]
Matplotlib coord. sys origin to top left
1,349,230
<p>How can I flip the origin of a matplotlib plot to be in the upper-left corner - as opposed to the default lower-left? I'm using matplotlib.pylab.plot to produce the plot (though if there is another plotting routine that is more flexible, please let me know).</p> <p>I'm looking for the equivalent of the matlab command: axis ij;</p> <p>Also, I've spent a couple hours surfing matplotlib help and google but haven't come up with an answer. Some info on where I could have looked up the answer would be helpful as well.</p>
8
2009-08-28T20:40:31Z
39,923,007
<p>This</p> <pre><code>plt.ylim(max(plt.ylim()), min(plt.ylim())) </code></pre> <p>has an advantage over this</p> <pre><code>plt.gca().invert_yaxis() </code></pre> <p>and is that if you are in interactive mode and you repeatedly plot the same plot (maybe with updated data and having a breakpoint after the plot) the y axis won't keep inverting every time. </p>
2
2016-10-07T17:37:27Z
[ "python", "matplotlib", "axes" ]
Python string 'join' is faster (?) than '+', but what's wrong here?
1,349,311
<p>I asked the most efficient method for mass dynamic string concatenation in an earlier post and I was suggested to use the <strong>join</strong> method, the best, simplest and fastest method to do so (as everyone said that). But while I was playing with string concatenations, I found some weird(?) results. I'm sure something is going on but I can't not get it quite. Here is what I did:</p> <p>I defined these functions:</p> <pre><code>import timeit def x(): s=[] for i in range(100): # Other codes here... s.append("abcdefg"[i%7]) return ''.join(s) def y(): s='' for i in range(100): # Other codes here... s+="abcdefg"[i%7] return s def z(): s='' for i in range(100): # Other codes here... s=s+"abcdefg"[i%7] return s def p(): s=[] for i in range(100): # Other codes here... s+="abcdefg"[i%7] return ''.join(s) def q(): s=[] for i in range(100): # Other codes here... s = s + ["abcdefg"[i%7]] return ''.join(s) </code></pre> <p>I have tried to keep other things (except the concatenation) almost same throughout the functions. Then I tested with the following with results in comment (using Python 3.1.1 IDLE on Windows 32 bit machine):</p> <pre><code>timeit.timeit(x) # 31.54912480500002 timeit.timeit(y) # 23.533029429999942 timeit.timeit(z) # 22.116181330000018 timeit.timeit(p) # 37.718607439999914 timeit.timeit(q) # 108.60377576499991 </code></pre> <p>That means it shows that <em>strng = strng + dyn_strng</em> is the fastest. Though the difference in times are not that significant (except the last one), but I wanna know why this is happening. Is that because I am using Python 3.1.1 and that provides '+' as most efficient? Should I use '+' as an alternative to <em>join</em>? Or, have I done something extremely silly? Or what? Please explain clearly.</p>
23
2009-08-28T20:57:29Z
1,349,358
<p>I assume x() is slower because you're first building the array and then joining it. So you're not only measuring the time that join takes, but also the time that you take to build the array.</p> <p>In a scenario where you already have an array and you want to create a string out of its elements, join should be faster than iterating through the array and building the string step by step.</p>
4
2009-08-28T21:05:30Z
[ "python", "string", "performance" ]
Python string 'join' is faster (?) than '+', but what's wrong here?
1,349,311
<p>I asked the most efficient method for mass dynamic string concatenation in an earlier post and I was suggested to use the <strong>join</strong> method, the best, simplest and fastest method to do so (as everyone said that). But while I was playing with string concatenations, I found some weird(?) results. I'm sure something is going on but I can't not get it quite. Here is what I did:</p> <p>I defined these functions:</p> <pre><code>import timeit def x(): s=[] for i in range(100): # Other codes here... s.append("abcdefg"[i%7]) return ''.join(s) def y(): s='' for i in range(100): # Other codes here... s+="abcdefg"[i%7] return s def z(): s='' for i in range(100): # Other codes here... s=s+"abcdefg"[i%7] return s def p(): s=[] for i in range(100): # Other codes here... s+="abcdefg"[i%7] return ''.join(s) def q(): s=[] for i in range(100): # Other codes here... s = s + ["abcdefg"[i%7]] return ''.join(s) </code></pre> <p>I have tried to keep other things (except the concatenation) almost same throughout the functions. Then I tested with the following with results in comment (using Python 3.1.1 IDLE on Windows 32 bit machine):</p> <pre><code>timeit.timeit(x) # 31.54912480500002 timeit.timeit(y) # 23.533029429999942 timeit.timeit(z) # 22.116181330000018 timeit.timeit(p) # 37.718607439999914 timeit.timeit(q) # 108.60377576499991 </code></pre> <p>That means it shows that <em>strng = strng + dyn_strng</em> is the fastest. Though the difference in times are not that significant (except the last one), but I wanna know why this is happening. Is that because I am using Python 3.1.1 and that provides '+' as most efficient? Should I use '+' as an alternative to <em>join</em>? Or, have I done something extremely silly? Or what? Please explain clearly.</p>
23
2009-08-28T20:57:29Z
1,349,526
<p>Interesting: I've done some tests where the size of the string changes, and this is what I found:</p> <pre><code>def x(): x = "a" * 100 s=[] for i in range(100): # Other codes here... s.append(x) return ''.join(s) def z(): x = "a" * 100 s='' for i in xrange(100): # Other codes here... s=s+x return s from timeit import timeit print "x:", timeit(x, number=1000000) print "z:", timeit(z, number=1000000) </code></pre> <p>For strings of length 1 (<code>x = "a" * 1</code>):</p> <pre><code>x: 27.2318270206 z: 14.4046051502 </code></pre> <p>For strings of length 100:</p> <pre><code>x: 30.0796670914 z: 21.5891489983 </code></pre> <p>And for strings of length 1000, running timeit 100,000 times instead of 1,000,000</p> <pre><code>x: 14.1769361496 z: 31.4864079952 </code></pre> <p>Which, if my reading of <code>Objects/stringobject.c</code> is correct, makes sense.</p> <p>It appears, on a first reading, that the String.join algorithm (edge-cases aside) is:</p> <pre><code>def join(sep, sequence): size = 0 for string in sequence: size += len(string) + len(sep) result = malloc(size) for string in sequence: copy string into result copy sep into result return result </code></pre> <p>So this will require more or less <code>O(S)</code> steps (where <code>S</code> is the sum of the lengths of all the strings being joined).</p>
1
2009-08-28T21:40:15Z
[ "python", "string", "performance" ]
Python string 'join' is faster (?) than '+', but what's wrong here?
1,349,311
<p>I asked the most efficient method for mass dynamic string concatenation in an earlier post and I was suggested to use the <strong>join</strong> method, the best, simplest and fastest method to do so (as everyone said that). But while I was playing with string concatenations, I found some weird(?) results. I'm sure something is going on but I can't not get it quite. Here is what I did:</p> <p>I defined these functions:</p> <pre><code>import timeit def x(): s=[] for i in range(100): # Other codes here... s.append("abcdefg"[i%7]) return ''.join(s) def y(): s='' for i in range(100): # Other codes here... s+="abcdefg"[i%7] return s def z(): s='' for i in range(100): # Other codes here... s=s+"abcdefg"[i%7] return s def p(): s=[] for i in range(100): # Other codes here... s+="abcdefg"[i%7] return ''.join(s) def q(): s=[] for i in range(100): # Other codes here... s = s + ["abcdefg"[i%7]] return ''.join(s) </code></pre> <p>I have tried to keep other things (except the concatenation) almost same throughout the functions. Then I tested with the following with results in comment (using Python 3.1.1 IDLE on Windows 32 bit machine):</p> <pre><code>timeit.timeit(x) # 31.54912480500002 timeit.timeit(y) # 23.533029429999942 timeit.timeit(z) # 22.116181330000018 timeit.timeit(p) # 37.718607439999914 timeit.timeit(q) # 108.60377576499991 </code></pre> <p>That means it shows that <em>strng = strng + dyn_strng</em> is the fastest. Though the difference in times are not that significant (except the last one), but I wanna know why this is happening. Is that because I am using Python 3.1.1 and that provides '+' as most efficient? Should I use '+' as an alternative to <em>join</em>? Or, have I done something extremely silly? Or what? Please explain clearly.</p>
23
2009-08-28T20:57:29Z
1,349,532
<p>There's a difference between += and + with strings -- if there's no other references to "x", x+=y can just append to x, rather than having to take a copy of the string to append to -- which is the same benefit you get from using "".join().</p> <p>The main benefit from "".join() over + or += is that join() should always give linear performance, while in many cases +/+= will give quadratic performance (ie, when you double the amount of text, you quadruple the amount of time taken). But this will only matter with a lot of text, not merely 100 bytes, and I <em>think</em> it won't get triggered if you only have one reference to the string you're appending to.</p> <p>In detail:</p> <p>Your best case performance for string concatenation is to look at every character in the final string once. "".join() does that naturally -- it has all the information it needs to right from the start. </p> <p>However a+=b can work in two ways, it can either just add "b" to an existing string, in which case it only needs to look at the characters in "b", or it can have to look at the characters in "a" too.</p> <p>In C, strcat() always looks at all the characters in both strings, so it's works badly always. In Python, however, the string length is stored, so the string can be extended as long as it's not referenced elsewhere -- and you get good performance by only copying the characters in "b". If it is referenced elsewhere, python will make a copy of "a" first, then add "b" to the end, giving you bad performance. If you're appending five strings in this manner, your time taken will be:</p> <pre><code>ab = a+b # Time is a + b abc = ab+c # Time is (a+b) + c abcd = abc+d # Time is (a+b+c) + d abcde = abcd+e # Time is (a+b+c+d) + e </code></pre> <p>which if a,b,c,d,e are all roughly the same size, say, n, is n*(n-1)/2-1 operations, or essentially n-squared.</p> <p>To get the bad behaviour for x+=y, try:</p> <pre><code>def a(n=100): res = "" for k in xrange(n): v=res res += "foobar" return res </code></pre> <p>Even though v isn't actually used, it's enough to trigger the slower path for += and get the bad behaviour that worries people.</p> <p>I believe += wasn't introduced until Python 2.0, so it wasn't possible to append efficiently without using something like "".join() in Python 1.6 and earlier.</p>
2
2009-08-28T21:41:20Z
[ "python", "string", "performance" ]
Python string 'join' is faster (?) than '+', but what's wrong here?
1,349,311
<p>I asked the most efficient method for mass dynamic string concatenation in an earlier post and I was suggested to use the <strong>join</strong> method, the best, simplest and fastest method to do so (as everyone said that). But while I was playing with string concatenations, I found some weird(?) results. I'm sure something is going on but I can't not get it quite. Here is what I did:</p> <p>I defined these functions:</p> <pre><code>import timeit def x(): s=[] for i in range(100): # Other codes here... s.append("abcdefg"[i%7]) return ''.join(s) def y(): s='' for i in range(100): # Other codes here... s+="abcdefg"[i%7] return s def z(): s='' for i in range(100): # Other codes here... s=s+"abcdefg"[i%7] return s def p(): s=[] for i in range(100): # Other codes here... s+="abcdefg"[i%7] return ''.join(s) def q(): s=[] for i in range(100): # Other codes here... s = s + ["abcdefg"[i%7]] return ''.join(s) </code></pre> <p>I have tried to keep other things (except the concatenation) almost same throughout the functions. Then I tested with the following with results in comment (using Python 3.1.1 IDLE on Windows 32 bit machine):</p> <pre><code>timeit.timeit(x) # 31.54912480500002 timeit.timeit(y) # 23.533029429999942 timeit.timeit(z) # 22.116181330000018 timeit.timeit(p) # 37.718607439999914 timeit.timeit(q) # 108.60377576499991 </code></pre> <p>That means it shows that <em>strng = strng + dyn_strng</em> is the fastest. Though the difference in times are not that significant (except the last one), but I wanna know why this is happening. Is that because I am using Python 3.1.1 and that provides '+' as most efficient? Should I use '+' as an alternative to <em>join</em>? Or, have I done something extremely silly? Or what? Please explain clearly.</p>
23
2009-08-28T20:57:29Z
1,349,533
<p>String concatenation was a lot slower before Python 2.5, when it still created a new copy for every string concatenation rather than appending to the original, leading to join() becoming a popular workaround.</p> <p>Here's an old benchmark demonstrating the old problem: <a href="http://www.skymind.com/~ocrow/python%5Fstring/" rel="nofollow">http://www.skymind.com/~ocrow/python%5Fstring/</a></p>
0
2009-08-28T21:41:25Z
[ "python", "string", "performance" ]
Python string 'join' is faster (?) than '+', but what's wrong here?
1,349,311
<p>I asked the most efficient method for mass dynamic string concatenation in an earlier post and I was suggested to use the <strong>join</strong> method, the best, simplest and fastest method to do so (as everyone said that). But while I was playing with string concatenations, I found some weird(?) results. I'm sure something is going on but I can't not get it quite. Here is what I did:</p> <p>I defined these functions:</p> <pre><code>import timeit def x(): s=[] for i in range(100): # Other codes here... s.append("abcdefg"[i%7]) return ''.join(s) def y(): s='' for i in range(100): # Other codes here... s+="abcdefg"[i%7] return s def z(): s='' for i in range(100): # Other codes here... s=s+"abcdefg"[i%7] return s def p(): s=[] for i in range(100): # Other codes here... s+="abcdefg"[i%7] return ''.join(s) def q(): s=[] for i in range(100): # Other codes here... s = s + ["abcdefg"[i%7]] return ''.join(s) </code></pre> <p>I have tried to keep other things (except the concatenation) almost same throughout the functions. Then I tested with the following with results in comment (using Python 3.1.1 IDLE on Windows 32 bit machine):</p> <pre><code>timeit.timeit(x) # 31.54912480500002 timeit.timeit(y) # 23.533029429999942 timeit.timeit(z) # 22.116181330000018 timeit.timeit(p) # 37.718607439999914 timeit.timeit(q) # 108.60377576499991 </code></pre> <p>That means it shows that <em>strng = strng + dyn_strng</em> is the fastest. Though the difference in times are not that significant (except the last one), but I wanna know why this is happening. Is that because I am using Python 3.1.1 and that provides '+' as most efficient? Should I use '+' as an alternative to <em>join</em>? Or, have I done something extremely silly? Or what? Please explain clearly.</p>
23
2009-08-28T20:57:29Z
1,349,538
<p>In addition to what the others said, 100 1-char strings is <em>really small</em>. (I'm kind of surprised you get separation of results at all.) That's the sort of dataset that fits in your processor cache. You're not going to see asymptotic performance on a microbenchmark.</p>
1
2009-08-28T21:42:26Z
[ "python", "string", "performance" ]
Python string 'join' is faster (?) than '+', but what's wrong here?
1,349,311
<p>I asked the most efficient method for mass dynamic string concatenation in an earlier post and I was suggested to use the <strong>join</strong> method, the best, simplest and fastest method to do so (as everyone said that). But while I was playing with string concatenations, I found some weird(?) results. I'm sure something is going on but I can't not get it quite. Here is what I did:</p> <p>I defined these functions:</p> <pre><code>import timeit def x(): s=[] for i in range(100): # Other codes here... s.append("abcdefg"[i%7]) return ''.join(s) def y(): s='' for i in range(100): # Other codes here... s+="abcdefg"[i%7] return s def z(): s='' for i in range(100): # Other codes here... s=s+"abcdefg"[i%7] return s def p(): s=[] for i in range(100): # Other codes here... s+="abcdefg"[i%7] return ''.join(s) def q(): s=[] for i in range(100): # Other codes here... s = s + ["abcdefg"[i%7]] return ''.join(s) </code></pre> <p>I have tried to keep other things (except the concatenation) almost same throughout the functions. Then I tested with the following with results in comment (using Python 3.1.1 IDLE on Windows 32 bit machine):</p> <pre><code>timeit.timeit(x) # 31.54912480500002 timeit.timeit(y) # 23.533029429999942 timeit.timeit(z) # 22.116181330000018 timeit.timeit(p) # 37.718607439999914 timeit.timeit(q) # 108.60377576499991 </code></pre> <p>That means it shows that <em>strng = strng + dyn_strng</em> is the fastest. Though the difference in times are not that significant (except the last one), but I wanna know why this is happening. Is that because I am using Python 3.1.1 and that provides '+' as most efficient? Should I use '+' as an alternative to <em>join</em>? Or, have I done something extremely silly? Or what? Please explain clearly.</p>
23
2009-08-28T20:57:29Z
1,349,598
<p>As to why <code>q</code> is a lot slower: when you say </p> <pre><code>l += "a" </code></pre> <p>you are appending the string <code>"a"</code> to the end of <code>l</code>, but when you say</p> <pre><code>l = l + ["a"] </code></pre> <p>you are creating a new list with the contents of <code>l</code> and <code>["a"]</code> and then reassigning the results back to <code>l</code>. Thus new lists are constantly being generated.</p>
4
2009-08-28T22:00:21Z
[ "python", "string", "performance" ]
Python string 'join' is faster (?) than '+', but what's wrong here?
1,349,311
<p>I asked the most efficient method for mass dynamic string concatenation in an earlier post and I was suggested to use the <strong>join</strong> method, the best, simplest and fastest method to do so (as everyone said that). But while I was playing with string concatenations, I found some weird(?) results. I'm sure something is going on but I can't not get it quite. Here is what I did:</p> <p>I defined these functions:</p> <pre><code>import timeit def x(): s=[] for i in range(100): # Other codes here... s.append("abcdefg"[i%7]) return ''.join(s) def y(): s='' for i in range(100): # Other codes here... s+="abcdefg"[i%7] return s def z(): s='' for i in range(100): # Other codes here... s=s+"abcdefg"[i%7] return s def p(): s=[] for i in range(100): # Other codes here... s+="abcdefg"[i%7] return ''.join(s) def q(): s=[] for i in range(100): # Other codes here... s = s + ["abcdefg"[i%7]] return ''.join(s) </code></pre> <p>I have tried to keep other things (except the concatenation) almost same throughout the functions. Then I tested with the following with results in comment (using Python 3.1.1 IDLE on Windows 32 bit machine):</p> <pre><code>timeit.timeit(x) # 31.54912480500002 timeit.timeit(y) # 23.533029429999942 timeit.timeit(z) # 22.116181330000018 timeit.timeit(p) # 37.718607439999914 timeit.timeit(q) # 108.60377576499991 </code></pre> <p>That means it shows that <em>strng = strng + dyn_strng</em> is the fastest. Though the difference in times are not that significant (except the last one), but I wanna know why this is happening. Is that because I am using Python 3.1.1 and that provides '+' as most efficient? Should I use '+' as an alternative to <em>join</em>? Or, have I done something extremely silly? Or what? Please explain clearly.</p>
23
2009-08-28T20:57:29Z
1,349,629
<p>You are measuring two distinct operations: the creation of an array of strings, and the concatenation of strings.</p> <pre><code> import timeit def x(): s = [] for i in range(100): s.append("abcdefg"[i%7]) return ''.join(s) def y(): s = '' for i in range(100): s += "abcdefgh"[i%7] # timeit.timeit(x) returns about 32s # timeit.timeit(y) returns about 23s </code></pre> <p>From the above it would indeed seem that '+' is a faster operation than join. But consider:</p> <pre><code> src = [] def c(): global src s = [] for i in range(100): s.append("abcdefg"[i%7]) src = s def x2(): return ''.join(src) def y2(): s = '' for i in range(len(src)): s += src[i] return s # timeit.timeit(c) returns about 30s # timeit.timeit(x2) returns about 1.5s # timeit.timeit(y2) returns about 14s </code></pre> <p>In other words, by timing x() vs y(), your result is polluted by the construction of your source array. If you break that out, you find that join is faster.</p> <p>Furthermore, you're working with small arrays, and your timing numbers just happen to coincide. If you increase the size of the array and the length of each string significantly, the differences are more clear:</p> <pre><code> def c2(): global src s = [] for i in range(10000): s.append("abcdefghijklmnopqrstuvwxyz0123456789" src = s # timeit.timeit(x2, number=10000) returns about 1s # timeit.timeit(y2, number=10000) returns about 80s </code></pre>
2
2009-08-28T22:12:17Z
[ "python", "string", "performance" ]
Python string 'join' is faster (?) than '+', but what's wrong here?
1,349,311
<p>I asked the most efficient method for mass dynamic string concatenation in an earlier post and I was suggested to use the <strong>join</strong> method, the best, simplest and fastest method to do so (as everyone said that). But while I was playing with string concatenations, I found some weird(?) results. I'm sure something is going on but I can't not get it quite. Here is what I did:</p> <p>I defined these functions:</p> <pre><code>import timeit def x(): s=[] for i in range(100): # Other codes here... s.append("abcdefg"[i%7]) return ''.join(s) def y(): s='' for i in range(100): # Other codes here... s+="abcdefg"[i%7] return s def z(): s='' for i in range(100): # Other codes here... s=s+"abcdefg"[i%7] return s def p(): s=[] for i in range(100): # Other codes here... s+="abcdefg"[i%7] return ''.join(s) def q(): s=[] for i in range(100): # Other codes here... s = s + ["abcdefg"[i%7]] return ''.join(s) </code></pre> <p>I have tried to keep other things (except the concatenation) almost same throughout the functions. Then I tested with the following with results in comment (using Python 3.1.1 IDLE on Windows 32 bit machine):</p> <pre><code>timeit.timeit(x) # 31.54912480500002 timeit.timeit(y) # 23.533029429999942 timeit.timeit(z) # 22.116181330000018 timeit.timeit(p) # 37.718607439999914 timeit.timeit(q) # 108.60377576499991 </code></pre> <p>That means it shows that <em>strng = strng + dyn_strng</em> is the fastest. Though the difference in times are not that significant (except the last one), but I wanna know why this is happening. Is that because I am using Python 3.1.1 and that provides '+' as most efficient? Should I use '+' as an alternative to <em>join</em>? Or, have I done something extremely silly? Or what? Please explain clearly.</p>
23
2009-08-28T20:57:29Z
1,350,148
<p>This question is really about what things cost. We'll play a bit fast and loose here, subtracting results in similar cases. You can decide for yourself if this is a valid method. Here are some basic test cases:</p> <pre><code>import timeit def append_to_list_with_join(): s=[] for i in xrange(100): s.append("abcdefg"[i%7]) return ''.join(s) def append_to_list_with_join_opt(): s=[] x = s.append for i in xrange(100): x("abcdefg"[i%7]) return ''.join(s) def plus_equals_string(): s='' for i in xrange(100): s+="abcdefg"[i%7] return s def plus_assign_string(): s='' for i in xrange(100): s=s+"abcdefg"[i%7] return s def list_comp_join(): return ''.join(["abcdefg"[i%7] for i in xrange(100)]) def list_comp(): return ["abcdefg"[i%7] for i in xrange(100)] def empty_loop(): for i in xrange(100): pass def loop_mod(): for i in xrange(100): a = "abcdefg"[i%7] def fast_list_join(): return "".join(["0"] * 100) for f in [append_to_list_with_join, append_to_list_with_join_opt, plus_equals_string,plus_assign_string,list_comp_join, list_comp, empty_loop,loop_mod, fast_list_join]: print f.func_name, timeit.timeit(f) </code></pre> <p>And here is what they cost:</p> <pre><code>append_to_list_with_join 25.4540209021 append_to_list_with_join_opt 19.9999782794 plus_equals_string 16.7842428996 plus_assign_string 14.8312124167 list_comp_join 16.329590353 list_comp 14.6934344309 empty_loop 2.3819276612 loop_mod 10.1424356308 fast_list_join 2.58149394686 </code></pre> <p>First off, lots of things have unexpected costs in python. append_to_list_with_join versus append_to_list_with_join_opt shows that even looking up a method on an object has a non-negligible cost. In this case, looking up s.append is one-quarter of the time.</p> <p>Next, list_comp_join versus list_comp shows that join() is pretty fast: It takes about 1.7 or only 10% of list_comp_join's time.</p> <p>loop_mod shows that the greatest part of this test is actually in setting up the data, irrespective of which string construction method is used. By inference, the time taken for "string = string + ", "string += ", and list comprehension are:</p> <pre><code>plus_equals_string = 16.78 - 10.14 = 6.64 plus_assign_string = 14.83 - 10.14 = 4.69 list_comp = 14.69 - 10.14 = 4.55 </code></pre> <p>So as to the OP's question, join() is fast but the time to create the underlying list, whether with list primitives or list comprehension, is comparable to creating the string with string primitives. If you already have a list, convert it to a string with join() -- it will be fast.</p> <p>The timings the OP presents indicate that constructing lists using concatenate operators is slow. In contrast, using list comprehensions is fast. If you have to build a list, use a list comprehension.</p> <p>Finally, let's take three of the OP's closest functions: what is the difference between x, p, and q? Let's simplify a bit:</p> <pre><code>import timeit def x(): s=[] for i in range(100): s.append("c") def p(): s=[] for i in range(100): s += "c" def q(): s=[] for i in range(100): s = s + ["c"] for f in [x,p,q]: print f.func_name, timeit.timeit(f) </code></pre> <p>Here are the results:</p> <pre><code>x 16.0757342064 p 87.1533697719 q 85.0999698984 </code></pre> <p>And here is the <a href="http://docs.python.org/dev/3.0/library/dis.html" rel="nofollow">disassembly</a>:</p> <pre><code>&gt;&gt;&gt; import dis &gt;&gt;&gt; dis.dis(x) 2 0 BUILD_LIST 0 3 STORE_FAST 0 (s) 3 6 SETUP_LOOP 33 (to 42) 9 LOAD_GLOBAL 0 (range) 12 LOAD_CONST 1 (100) 15 CALL_FUNCTION 1 18 GET_ITER &gt;&gt; 19 FOR_ITER 19 (to 41) 22 STORE_FAST 1 (i) 4 25 LOAD_FAST 0 (s) 28 LOAD_ATTR 1 (append) 31 LOAD_CONST 2 ('c') 34 CALL_FUNCTION 1 37 POP_TOP 38 JUMP_ABSOLUTE 19 &gt;&gt; 41 POP_BLOCK &gt;&gt; 42 LOAD_CONST 0 (None) 45 RETURN_VALUE &gt;&gt;&gt; dis.dis(p) 2 0 BUILD_LIST 0 3 STORE_FAST 0 (s) 3 6 SETUP_LOOP 30 (to 39) 9 LOAD_GLOBAL 0 (range) 12 LOAD_CONST 1 (100) 15 CALL_FUNCTION 1 18 GET_ITER &gt;&gt; 19 FOR_ITER 16 (to 38) 22 STORE_FAST 1 (i) 4 25 LOAD_FAST 0 (s) 28 LOAD_CONST 2 ('c') 31 INPLACE_ADD 32 STORE_FAST 0 (s) 35 JUMP_ABSOLUTE 19 &gt;&gt; 38 POP_BLOCK &gt;&gt; 39 LOAD_CONST 0 (None) 42 RETURN_VALUE &gt;&gt;&gt; dis.dis(q) 2 0 BUILD_LIST 0 3 STORE_FAST 0 (s) 3 6 SETUP_LOOP 33 (to 42) 9 LOAD_GLOBAL 0 (range) 12 LOAD_CONST 1 (100) 15 CALL_FUNCTION 1 18 GET_ITER &gt;&gt; 19 FOR_ITER 19 (to 41) 22 STORE_FAST 1 (i) 4 25 LOAD_FAST 0 (s) 28 LOAD_CONST 2 ('c') 31 BUILD_LIST 1 34 BINARY_ADD 35 STORE_FAST 0 (s) 38 JUMP_ABSOLUTE 19 &gt;&gt; 41 POP_BLOCK &gt;&gt; 42 LOAD_CONST 0 (None) 45 RETURN_VALUE </code></pre> <p>The loops are nearly identical. The comparison amounts to CALL_FUNCTION+POP_TOP vs. INPLACE_ADD+STORE_FAST vs. BUILD_LIST+BINARY_ADD+STORE_FAST. However, I can't give a more low-level explanation than that -- I just can't find costs of python bytecodes on the Net. However, you might get some inspiration from looking at Doug Hellmann's Python Module of the Week posting on <a href="http://www.doughellmann.com/PyMOTW/dis/index.html" rel="nofollow">dis</a>.</p>
3
2009-08-29T01:27:37Z
[ "python", "string", "performance" ]
Python string 'join' is faster (?) than '+', but what's wrong here?
1,349,311
<p>I asked the most efficient method for mass dynamic string concatenation in an earlier post and I was suggested to use the <strong>join</strong> method, the best, simplest and fastest method to do so (as everyone said that). But while I was playing with string concatenations, I found some weird(?) results. I'm sure something is going on but I can't not get it quite. Here is what I did:</p> <p>I defined these functions:</p> <pre><code>import timeit def x(): s=[] for i in range(100): # Other codes here... s.append("abcdefg"[i%7]) return ''.join(s) def y(): s='' for i in range(100): # Other codes here... s+="abcdefg"[i%7] return s def z(): s='' for i in range(100): # Other codes here... s=s+"abcdefg"[i%7] return s def p(): s=[] for i in range(100): # Other codes here... s+="abcdefg"[i%7] return ''.join(s) def q(): s=[] for i in range(100): # Other codes here... s = s + ["abcdefg"[i%7]] return ''.join(s) </code></pre> <p>I have tried to keep other things (except the concatenation) almost same throughout the functions. Then I tested with the following with results in comment (using Python 3.1.1 IDLE on Windows 32 bit machine):</p> <pre><code>timeit.timeit(x) # 31.54912480500002 timeit.timeit(y) # 23.533029429999942 timeit.timeit(z) # 22.116181330000018 timeit.timeit(p) # 37.718607439999914 timeit.timeit(q) # 108.60377576499991 </code></pre> <p>That means it shows that <em>strng = strng + dyn_strng</em> is the fastest. Though the difference in times are not that significant (except the last one), but I wanna know why this is happening. Is that because I am using Python 3.1.1 and that provides '+' as most efficient? Should I use '+' as an alternative to <em>join</em>? Or, have I done something extremely silly? Or what? Please explain clearly.</p>
23
2009-08-28T20:57:29Z
1,350,289
<p>Some of us Python committers, I believe mostly Rigo and Hettinger, went out of their way (on the way to 2.5 I believe) to optimize some special cases of the alas-far-too-common <code>s += something</code> <strong>blight</strong>, arguing that it was proven that beginners will never be covinced that <code>''.join</code> is the right way to go and the horrible slowness of the <code>+=</code> might be giving Python a bad name. Others of us weren't that hot, because they just couldn't possibly optimize every occurrence (or even just a majority of them) to decent performance; but we didn't feel hotly enough on the issue to try and actively block them.</p> <p>I believe this thread proves we should have opposed them more sternly. As it is now, they optimized <code>+=</code> in a certain hard-to-predict subset of cases to where it can be maybe 20% faster for particular stupid cases than the proper way (which IS still <code>''.join</code>) -- just a perfect way to trap beginners into pursuing those irrelevant 20% gains by using the wrong idiom... at the cost, once in a while and from their POV out of the blue, of being hit with a performance loss of 200% (or more, since non-linear behavior IS still lurking there just outside of the corners that Hettinger and Rigo prettied up and put flowers in;-) -- one that MATTERS, one that WILL make them miserable. This goes against the grain of Python's "ideally only one obvious way to do it" and it feels to me like we, collectively, have lain a trap for beginners -- the best kind, too... those who don't just accept what they're told by their "betters", but inquisitively go and question and explore.</p> <p>Ah well -- I give up. OP, @mshsayem, go ahead, use += everywhere, enjoy your irrelevant 20% speedups in trivial, tiny, irrelevant cases, and you'd better enjoy them to the hilt -- because one day, when you can't see it coming, on an IMPORTANT, LARGE operation, you'll be hit smack in the midriff by the oncoming trailer truck of a 200% slowdown (unless you get unlucky and it's a 2000% one;-). Just remember: if you ever feel that "Python is horribly slow", REMEMBER, more likely than not it's one of your beloved loops of <code>+=</code> turning around and biting the hand that feeds it.</p> <p>For the rest of us -- those who understand what it means to say <a href="http://shreevatsa.wordpress.com/2008/05/16/premature-optimization-is-the-root-of-all-evil/">We should forget about small efficiencies, say about 97% of the time</a>, I'll keep heartily recommending <code>''.join</code>, so we all can sleep in all tranquility and KNOW we won't be hit with a superlinear slowdown when we least expect and least can afford you. But for you, Armin Rigo, and Raymond Hettinger (the last two, dear personal friends of mine, BTW, not just co-commiters;-) -- may your <code>+=</code> be smooth and your big-O's never worse than N!-)</p> <p>So, for the rest of us, here's a more meaningful and interesting set of measurements:</p> <pre><code>$ python -mtimeit -s'r=[str(x)*99 for x in xrange(100,1000)]' 's="".join(r)' 1000 loops, best of 3: 319 usec per loop </code></pre> <p>900 strings of 300 chars each, joining the list directly is of course fastest, but the OP is terrified about having to do appends before then. But:</p> <pre><code>$ python -mtimeit -s'r=[str(x)*99 for x in xrange(100,1000)]' 's=""' 'for x in r: s+=x' 1000 loops, best of 3: 779 usec per loop $ python -mtimeit -s'r=[str(x)*99 for x in xrange(100,1000)]' 'z=[]' 'for x in r: z.append(x)' '"".join(z)' 1000 loops, best of 3: 538 usec per loop </code></pre> <p>...with a semi-important amount of data (a very few 100's of KB -- taking a measurable fraction of a millisecond every which way), even plain good old <code>.append</code> is alread superior. In addition, it's obviously and trivially easy to optimize:</p> <pre><code>$ python -mtimeit -s'r=[str(x)*99 for x in xrange(100,1000)]' 'z=[]; zap=z.append' 'for x in r: zap(x)' '"".join(z)' 1000 loops, best of 3: 438 usec per loop </code></pre> <p>shaving another tenths of a millisecond over the average looping time. Everybody (at least everybody who's totally obsessed abound performance) obviously knows that HOISTING (taking OUT of the inner loop a repetitive computation that would be otherwise performed over and over) is a crucial technique in optimization -- Python doesn't hoist on your behalf, so you have to do your own hoisting in those rare occasions where every microsecond matters.</p>
42
2009-08-29T02:47:39Z
[ "python", "string", "performance" ]
Python string 'join' is faster (?) than '+', but what's wrong here?
1,349,311
<p>I asked the most efficient method for mass dynamic string concatenation in an earlier post and I was suggested to use the <strong>join</strong> method, the best, simplest and fastest method to do so (as everyone said that). But while I was playing with string concatenations, I found some weird(?) results. I'm sure something is going on but I can't not get it quite. Here is what I did:</p> <p>I defined these functions:</p> <pre><code>import timeit def x(): s=[] for i in range(100): # Other codes here... s.append("abcdefg"[i%7]) return ''.join(s) def y(): s='' for i in range(100): # Other codes here... s+="abcdefg"[i%7] return s def z(): s='' for i in range(100): # Other codes here... s=s+"abcdefg"[i%7] return s def p(): s=[] for i in range(100): # Other codes here... s+="abcdefg"[i%7] return ''.join(s) def q(): s=[] for i in range(100): # Other codes here... s = s + ["abcdefg"[i%7]] return ''.join(s) </code></pre> <p>I have tried to keep other things (except the concatenation) almost same throughout the functions. Then I tested with the following with results in comment (using Python 3.1.1 IDLE on Windows 32 bit machine):</p> <pre><code>timeit.timeit(x) # 31.54912480500002 timeit.timeit(y) # 23.533029429999942 timeit.timeit(z) # 22.116181330000018 timeit.timeit(p) # 37.718607439999914 timeit.timeit(q) # 108.60377576499991 </code></pre> <p>That means it shows that <em>strng = strng + dyn_strng</em> is the fastest. Though the difference in times are not that significant (except the last one), but I wanna know why this is happening. Is that because I am using Python 3.1.1 and that provides '+' as most efficient? Should I use '+' as an alternative to <em>join</em>? Or, have I done something extremely silly? Or what? Please explain clearly.</p>
23
2009-08-28T20:57:29Z
1,390,428
<p>I have figured out the answer from the answers posted here by experts. Python string concatenation (and timing measurements) depends on these (as far as I've seen):</p> <ul> <li>Number of concatenations</li> <li>Average length of strings</li> <li>Number of function callings</li> </ul> <p>I have built a new code that relates these. Thanks to Peter S Magnusson, sepp2k, hughdbrown, David Wolever and others for indicating important points I had missed earlier. Also, in this code I might have missed something. So, I highly appreciate any replies pointing our errors, suggestions, criticisms etc. After all, I am here for learning. Here is my new code:</p> <pre><code>from timeit import timeit noc = 100 tocat = "a" def f_call(): pass def loop_only(): for i in range(noc): pass def concat_method(): s = '' for i in range(noc): s = s + tocat def list_append(): s=[] for i in range(noc): s.append(tocat) ''.join(s) def list_append_opt(): s = [] zap = s.append for i in range(noc): zap(tocat) ''.join(s) def list_comp(): ''.join(tocat for i in range(noc)) def concat_method_buildup(): s='' def list_append_buildup(): s=[] def list_append_opt_buildup(): s=[] zap = s.append def function_time(f): return timeit(f,number=1000)*1000 f_callt = function_time(f_call) def measure(ftuple,n,tc): global noc,tocat noc = n tocat = tc loopt = function_time(loop_only) - f_callt buildup_time = function_time(ftuple[1]) -f_callt if ftuple[1] else 0 total_time = function_time(ftuple[0]) return total_time, total_time - f_callt - buildup_time - loopt*ftuple[2] functions ={'Concat Method\t\t':(concat_method,concat_method_buildup,True), 'List append\t\t\t':(list_append,list_append_buildup,True), 'Optimized list append':(list_append_opt,list_append_opt_buildup,True), 'List comp\t\t\t':(list_comp,0,False)} for i in range(5): print("\n\n%d concatenation\t\t\t\t10'a'\t\t\t\t 100'a'\t\t\t1000'a'"%10**i) print('-'*80) for (f,ft) in functions.items(): print(f,"\t|",end="\t") for j in range(3): t = measure(ft,10**i,'a'*10**j) print("%.3f %.3f |" % t,end="\t") print() </code></pre> <p>And here is what I have got. [In the time column two times (scaled) are shown: first one is the total function execution time, and the second time is the actual(?) concatenation time. I have deducted the function calling time, function buildup time(initialization time), and iteration time. Here I am considering a case where it can't be done without loop (say more statement inside).]</p> <pre><code>1 concatenation 1'a' 10'a' 100'a' ------------------- ---------------------- ------------------- ---------------- List comp | 2.310 2.168 | 2.298 2.156 | 2.304 2.162 Optimized list append | 1.069 0.439 | 1.098 0.456 | 1.071 0.413 Concat Method | 0.552 0.034 | 0.541 0.025 | 0.565 0.048 List append | 1.099 0.557 | 1.099 0.552 | 1.094 0.552 10 concatenations 1'a' 10'a' 100'a' ------------------- ---------------------- ------------------- ---------------- List comp | 3.366 3.224 | 3.473 3.331 | 4.058 3.916 Optimized list append | 2.778 2.003 | 2.956 2.186 | 3.417 2.639 Concat Method | 1.602 0.943 | 1.910 1.259 | 3.381 2.724 List append | 3.290 2.612 | 3.378 2.699 | 3.959 3.282 100 concatenations 1'a' 10'a' 100'a' ------------------- ---------------------- ------------------- ---------------- List comp | 15.900 15.758 | 17.086 16.944 | 20.260 20.118 Optimized list append | 15.178 12.585 | 16.203 13.527 | 19.336 16.703 Concat Method | 10.937 8.482 | 25.731 23.263 | 29.390 26.934 List append | 20.515 18.031 | 21.599 19.115 | 24.487 22.003 1000 concatenations 1'a' 10'a' 100'a' ------------------- ---------------------- ------------------- ---------------- List comp | 134.507 134.365 | 143.913 143.771 | 201.062 200.920 Optimized list append | 112.018 77.525 | 121.487 87.419 | 151.063 117.059 Concat Method | 214.329 180.093 | 290.380 256.515 | 324.572 290.720 List append | 167.625 133.619 | 176.241 142.267 | 205.259 171.313 10000 concatenations 1'a' 10'a' 100'a' ------------------- ---------------------- ------------------- ---------------- List comp | 1309.702 1309.560 | 1404.191 1404.049 | 2912.483 2912.341 Optimized list append | 1042.271 668.696 | 1134.404 761.036 | 2628.882 2255.804 Concat Method | 2310.204 1941.096 | 2923.805 2550.803 | STUCK STUCK List append | 1624.795 1251.589 | 1717.501 1345.137 | 3182.347 2809.233 </code></pre> <p>To sum up all these I have made this decisions for me:</p> <ol> <li>If you have a string list available, string 'join' method is best and fastest.</li> <li>If you can use list comprehension, that's the easiest and fast as well. </li> <li>If you need 1 to 10 concatenation (average) with length 1 to 100, list append, '+' both takes same (almost, note that times are scaled) time.</li> <li>Optimized list append seems very good in most situation.</li> <li>When #concatenation or string length rises, '+' starts to take significantly more and more time. Note that, for 10000 concatenations with 100'a' my PC is stuck!</li> <li>If you use list append and 'join' always, you are safe all time (pointed by Alex Martelli). </li> <li>But in some situation say, where you need to take user input and print 'Hello user's world!', it is simplest to use '+'. I think building a list and join for this case like x = input("Enter user name:") and then x.join(["Hello ","'s world!"]) is uglier than "Hello %s's world!"%x or "Hello " +x+ "'s world"</li> <li>Python 3.1 has improved concatenation performance. But, in some implementation like Jython, '+' is less efficient.</li> <li>Premature optimization is the root of all evil (experts' saying). Most of the time you do not need optimization. So, don't waste time in aspiration for optimization (unless you are writing a big or computational project where every micro/milli second counts.</li> <li>Use these information and write in whatever way you like taking circumstances under consideration.</li> <li>If you really need optimization , use a profiler, find the bottlenecks and try to optimize those.</li> </ol> <p>Finally, I am trying to learn python more deeply. So, it is not unusual that there will be mistakes (error) in my observations. So, comment on this and suggest me if I am taking a wrong route. Thanks to all for participating. </p>
2
2009-09-07T18:07:11Z
[ "python", "string", "performance" ]
Python string 'join' is faster (?) than '+', but what's wrong here?
1,349,311
<p>I asked the most efficient method for mass dynamic string concatenation in an earlier post and I was suggested to use the <strong>join</strong> method, the best, simplest and fastest method to do so (as everyone said that). But while I was playing with string concatenations, I found some weird(?) results. I'm sure something is going on but I can't not get it quite. Here is what I did:</p> <p>I defined these functions:</p> <pre><code>import timeit def x(): s=[] for i in range(100): # Other codes here... s.append("abcdefg"[i%7]) return ''.join(s) def y(): s='' for i in range(100): # Other codes here... s+="abcdefg"[i%7] return s def z(): s='' for i in range(100): # Other codes here... s=s+"abcdefg"[i%7] return s def p(): s=[] for i in range(100): # Other codes here... s+="abcdefg"[i%7] return ''.join(s) def q(): s=[] for i in range(100): # Other codes here... s = s + ["abcdefg"[i%7]] return ''.join(s) </code></pre> <p>I have tried to keep other things (except the concatenation) almost same throughout the functions. Then I tested with the following with results in comment (using Python 3.1.1 IDLE on Windows 32 bit machine):</p> <pre><code>timeit.timeit(x) # 31.54912480500002 timeit.timeit(y) # 23.533029429999942 timeit.timeit(z) # 22.116181330000018 timeit.timeit(p) # 37.718607439999914 timeit.timeit(q) # 108.60377576499991 </code></pre> <p>That means it shows that <em>strng = strng + dyn_strng</em> is the fastest. Though the difference in times are not that significant (except the last one), but I wanna know why this is happening. Is that because I am using Python 3.1.1 and that provides '+' as most efficient? Should I use '+' as an alternative to <em>join</em>? Or, have I done something extremely silly? Or what? Please explain clearly.</p>
23
2009-08-28T20:57:29Z
21,964,653
<p>There are many good summaries already here, but just for more proof.</p> <p>Source: I stared at python source code for an hour and calculated complexities!</p> <p>My findings.</p> <p>For 2 strings. (Assume n is the length of both strings)</p> <pre><code>Concat (+) - O(n) Join - O(n+k) effectively O(n) Format - O(2n+k) effectively O(n) </code></pre> <p>For more than 2 strings. (Assume n is the length of all strings)</p> <pre><code>Concat (+) - O(n^2) Join - O(n+k) effectively O(n) Format - O(2n+k) effectively O(n) </code></pre> <p>RESULT:</p> <p>If you have two strings technically concatenation (+) is better, effectively though it is exactly the same as join and format.</p> <p>If you have more than two strings concat becomes awful and join and format are effectively the same though technically join is a bit better.</p> <p>SUMMARY:</p> <p>If you don't care for efficiency use any of the above. (Though since you asked the question I would assume you care)</p> <p>Therefore - </p> <p>If you have 2 strings use concat (when not in a loop!)</p> <p>If you have more than two strings (all strings) (or in a loop) use join</p> <p>If you have anything not strings use format, because duh.</p> <p>Hope this helps!</p>
2
2014-02-23T05:36:41Z
[ "python", "string", "performance" ]
Python SOAP clients will not work with this WSDL
1,349,325
<p>Thus far I've tried to access this WSDL:</p> <p><a href="https://login.azoogleads.com/affiliate/tool/soap%5Fapi" rel="nofollow">https://login.azoogleads.com/affiliate/tool/soap%5Fapi</a></p> <p>from the two common Python SOAP clients that I'm aware of: SOAPpy and ZSI.client.Binding. SOAPpy raises an exception in PyXML (xml.parsers.expat.ExpatError: not well-formed (invalid token)) and ZSI raises an exception in the urlparse library.</p> <p>What I'm hoping is:</p> <p>1.) I'm using these libraries incorrectly (usage below)</p> <p>or </p> <p>2.) There is another SOAP library I don't know about that will be able to handle this</p> <p>Here's my usage of the libraries:</p> <pre><code>from ZSI.client import Binding b = Binding('https://login.azoogleads.com/affiliate/tool/soap_api/') hash = b.authenticate('should', 'get', 'authenticationfailurefromthis') </code></pre> <p>and</p> <pre><code>import SOAPpy b = SOAPpy.WSDL.Proxy('https://login.azoogleads.com/affiliate/tool/soap_api/') hash = b.authenticate('any', 'info', 'shoulddo') </code></pre>
2
2009-08-28T21:00:06Z
1,353,802
<p>your not actually giving it a valid WSDL endpoint try explicilty giving it the WSDL location rather than the directory it is in. Remember computer are exceptually stupid things!</p>
2
2009-08-30T12:44:32Z
[ "python", "soap", "soappy", "zsi" ]
Python - Passing a function into another function
1,349,332
<p>I am solving a puzzle using python and depending on which puzzle I am solving I will have to use a special set of rules. How can I pass a function into another function in Python?</p> <p>Example</p> <pre><code>def Game(listA, listB, rules): if rules == True: do... else: do... def Rule1(v): if "variable_name1" in v: return False elif "variable_name2" in v: return False else: return True def Rule2(v): if "variable_name3" and "variable_name4" in v: return False elif "variable_name4" and variable_name1 in v: return False else: return True </code></pre> <p>This is just a pseudo code and therefore not specific but I get the code to compile but I need to know how to call the function <code>Game</code> and whether it's correctly defined since rules will be switched for either <code>Rule1(v)</code> or <code>Rule2(v)</code>.</p>
37
2009-08-28T21:01:19Z
1,349,350
<p>Just pass it in like any other parameter:</p> <pre><code>def a(x): return "a(%s)" % (x,) def b(f,x): return f(x) print b(a,10) </code></pre>
72
2009-08-28T21:04:04Z
[ "python", "function", "first-class-functions" ]
Python - Passing a function into another function
1,349,332
<p>I am solving a puzzle using python and depending on which puzzle I am solving I will have to use a special set of rules. How can I pass a function into another function in Python?</p> <p>Example</p> <pre><code>def Game(listA, listB, rules): if rules == True: do... else: do... def Rule1(v): if "variable_name1" in v: return False elif "variable_name2" in v: return False else: return True def Rule2(v): if "variable_name3" and "variable_name4" in v: return False elif "variable_name4" and variable_name1 in v: return False else: return True </code></pre> <p>This is just a pseudo code and therefore not specific but I get the code to compile but I need to know how to call the function <code>Game</code> and whether it's correctly defined since rules will be switched for either <code>Rule1(v)</code> or <code>Rule2(v)</code>.</p>
37
2009-08-28T21:01:19Z
1,349,359
<p>Treat function as variable in your program so you can just pass them to other functions easily:</p> <pre><code>def test (): print "test was invoked" def invoker(func): func() invoker(test) # prints test was invoked </code></pre>
10
2009-08-28T21:06:28Z
[ "python", "function", "first-class-functions" ]
Python - Passing a function into another function
1,349,332
<p>I am solving a puzzle using python and depending on which puzzle I am solving I will have to use a special set of rules. How can I pass a function into another function in Python?</p> <p>Example</p> <pre><code>def Game(listA, listB, rules): if rules == True: do... else: do... def Rule1(v): if "variable_name1" in v: return False elif "variable_name2" in v: return False else: return True def Rule2(v): if "variable_name3" and "variable_name4" in v: return False elif "variable_name4" and variable_name1 in v: return False else: return True </code></pre> <p>This is just a pseudo code and therefore not specific but I get the code to compile but I need to know how to call the function <code>Game</code> and whether it's correctly defined since rules will be switched for either <code>Rule1(v)</code> or <code>Rule2(v)</code>.</p>
37
2009-08-28T21:01:19Z
1,349,395
<p>Just pass it in, like this:</p> <pre><code>Game(list_a, list_b, Rule1) </code></pre> <p>and then your Game function could look something like this (still pseudocode):</p> <pre><code>def Game(listA, listB, rules=None): if rules: # do something useful # ... result = rules(variable) # this is how you can call your rule else: # do something useful without rules </code></pre>
6
2009-08-28T21:12:57Z
[ "python", "function", "first-class-functions" ]
Python - Passing a function into another function
1,349,332
<p>I am solving a puzzle using python and depending on which puzzle I am solving I will have to use a special set of rules. How can I pass a function into another function in Python?</p> <p>Example</p> <pre><code>def Game(listA, listB, rules): if rules == True: do... else: do... def Rule1(v): if "variable_name1" in v: return False elif "variable_name2" in v: return False else: return True def Rule2(v): if "variable_name3" and "variable_name4" in v: return False elif "variable_name4" and variable_name1 in v: return False else: return True </code></pre> <p>This is just a pseudo code and therefore not specific but I get the code to compile but I need to know how to call the function <code>Game</code> and whether it's correctly defined since rules will be switched for either <code>Rule1(v)</code> or <code>Rule2(v)</code>.</p>
37
2009-08-28T21:01:19Z
13,382,678
<p>A function name can become a variable name (and thus be passed as an argument) by dropping the parentheses. A variable name can become a function name by adding the parentheses.</p> <p>In your example, equate the variable <code>rules</code> to one of your functions, leaving off the parentheses and the mention of the argument. Then in your <code>game()</code> function, invoke <code>rules( v )</code> with the parentheses and the <code>v</code> parameter.</p> <pre><code>if puzzle == type1: rules = Rule1 else: rules = Rule2 def Game(listA, listB, rules): if rules( v ) == True: do... else: do... </code></pre>
6
2012-11-14T16:15:48Z
[ "python", "function", "first-class-functions" ]
Python - Passing a function into another function
1,349,332
<p>I am solving a puzzle using python and depending on which puzzle I am solving I will have to use a special set of rules. How can I pass a function into another function in Python?</p> <p>Example</p> <pre><code>def Game(listA, listB, rules): if rules == True: do... else: do... def Rule1(v): if "variable_name1" in v: return False elif "variable_name2" in v: return False else: return True def Rule2(v): if "variable_name3" and "variable_name4" in v: return False elif "variable_name4" and variable_name1 in v: return False else: return True </code></pre> <p>This is just a pseudo code and therefore not specific but I get the code to compile but I need to know how to call the function <code>Game</code> and whether it's correctly defined since rules will be switched for either <code>Rule1(v)</code> or <code>Rule2(v)</code>.</p>
37
2009-08-28T21:01:19Z
35,467,124
<p><strong>A generalized approach</strong></p> <p>For passing both a function, and the parameters to the function (e.g. using the same iteration routine for different functions) consider the following (<code>python2.x</code>) example:</p> <pre><code>def test(a, b): '''The function to pass''' print a+b def looper(func, **kwargs): '''A basic iteration function''' for i in range(5): # Our passed function with passed parameters func(*tuple(value for _, value in kwargs.iteritems())) if __name__ == '__main__': # This will print `3` five times looper(test, a=1, b=2) </code></pre> <p><strong>Some explanation</strong></p> <ul> <li><code>tuple( i for i in (1, 2, 3))</code> is a tuple generator, creating a tuple from the items in a list, set, tuple... in our case, the values from <code>**kwargs</code></li> <li>the <code>*</code> in front of the <code>tuple()</code> will unpack its contents, effectively passing them as parameters to the passed function</li> <li><code>_</code> in the generator is just a place holder for the <code>key</code>, since we aren't using that</li> </ul> <p><strong>For <code>python3.x</code>:</strong></p> <ul> <li><code>print(a+b)</code> instead of <code>print a+b</code></li> <li><code>kwargs.items()</code> instead of <code>kwargs.iteritems()</code></li> </ul>
2
2016-02-17T20:31:58Z
[ "python", "function", "first-class-functions" ]
Parse an HTTP request Authorization header with Python
1,349,367
<p>I need to take a header like this:</p> <pre><code> Authorization: Digest qop="chap", realm="testrealm@host.com", username="Foobear", response="6629fae49393a05397450978507c4ef1", cnonce="5ccc069c403ebaf9f0171e9517f40e41" </code></pre> <p>And parse it into this using Python:</p> <pre><code>{'protocol':'Digest', 'qop':'chap', 'realm':'testrealm@host.com', 'username':'Foobear', 'response':'6629fae49393a05397450978507c4ef1', 'cnonce':'5ccc069c403ebaf9f0171e9517f40e41'} </code></pre> <p>Is there a library to do this, or something I could look at for inspiration?</p> <p>I'm doing this on Google App Engine, and I'm not sure if the Pyparsing library is available, but maybe I could include it with my app if it is the best solution.</p> <p>Currently I'm creating my own MyHeaderParser object and using it with reduce() on the header string. It's working, but very fragile.</p> <p>Brilliant solution by nadia below:</p> <pre><code>import re reg = re.compile('(\w+)[=] ?"?(\w+)"?') s = """Digest realm="stackoverflow.com", username="kixx" """ print str(dict(reg.findall(s))) </code></pre>
9
2009-08-28T21:07:56Z
1,349,506
<p>If those components will always be there, then a regex will do the trick:</p> <pre><code>test = '''Authorization: Digest qop="chap", realm="testrealm@host.com", username="Foobear", response="6629fae49393a05397450978507c4ef1", cnonce="5ccc069c403ebaf9f0171e9517f40e41"''' import re re_auth = re.compile(r""" Authorization:\s*(?P&lt;protocol&gt;[^ ]+)\s+ qop="(?P&lt;qop&gt;[^"]+)",\s+ realm="(?P&lt;realm&gt;[^"]+)",\s+ username="(?P&lt;username&gt;[^"]+)",\s+ response="(?P&lt;response&gt;[^"]+)",\s+ cnonce="(?P&lt;cnonce&gt;[^"]+)" """, re.VERBOSE) m = re_auth.match(test) print m.groupdict() </code></pre> <p>produces:</p> <pre><code>{ 'username': 'Foobear', 'protocol': 'Digest', 'qop': 'chap', 'cnonce': '5ccc069c403ebaf9f0171e9517f40e41', 'realm': 'testrealm@host.com', 'response': '6629fae49393a05397450978507c4ef1' } </code></pre>
1
2009-08-28T21:36:41Z
[ "python", "http", "google-app-engine", "parsing", "http-headers" ]
Parse an HTTP request Authorization header with Python
1,349,367
<p>I need to take a header like this:</p> <pre><code> Authorization: Digest qop="chap", realm="testrealm@host.com", username="Foobear", response="6629fae49393a05397450978507c4ef1", cnonce="5ccc069c403ebaf9f0171e9517f40e41" </code></pre> <p>And parse it into this using Python:</p> <pre><code>{'protocol':'Digest', 'qop':'chap', 'realm':'testrealm@host.com', 'username':'Foobear', 'response':'6629fae49393a05397450978507c4ef1', 'cnonce':'5ccc069c403ebaf9f0171e9517f40e41'} </code></pre> <p>Is there a library to do this, or something I could look at for inspiration?</p> <p>I'm doing this on Google App Engine, and I'm not sure if the Pyparsing library is available, but maybe I could include it with my app if it is the best solution.</p> <p>Currently I'm creating my own MyHeaderParser object and using it with reduce() on the header string. It's working, but very fragile.</p> <p>Brilliant solution by nadia below:</p> <pre><code>import re reg = re.compile('(\w+)[=] ?"?(\w+)"?') s = """Digest realm="stackoverflow.com", username="kixx" """ print str(dict(reg.findall(s))) </code></pre>
9
2009-08-28T21:07:56Z
1,349,512
<p>I would recommend finding a correct library for parsing http headers unfortunately I can't reacall any. :(</p> <p>For a while check the snippet below (it should mostly work):</p> <pre><code>input= """ Authorization: Digest qop="chap", realm="testrealm@host.com", username="Foob,ear", response="6629fae49393a05397450978507c4ef1", cnonce="5ccc069c403ebaf9f0171e9517f40e41" """ field, sep, value = input.partition(":") if field.endswith('Authorization'): protocol, sep, opts_str = value.strip().partition(" ") opts = {} for opt in opts_str.split(",\n"): key, value = opt.strip().split('=') key = key.strip(" ") value = value.strip(' "') opts[key] = value opts['protocol'] = protocol print opts </code></pre>
1
2009-08-28T21:38:11Z
[ "python", "http", "google-app-engine", "parsing", "http-headers" ]
Parse an HTTP request Authorization header with Python
1,349,367
<p>I need to take a header like this:</p> <pre><code> Authorization: Digest qop="chap", realm="testrealm@host.com", username="Foobear", response="6629fae49393a05397450978507c4ef1", cnonce="5ccc069c403ebaf9f0171e9517f40e41" </code></pre> <p>And parse it into this using Python:</p> <pre><code>{'protocol':'Digest', 'qop':'chap', 'realm':'testrealm@host.com', 'username':'Foobear', 'response':'6629fae49393a05397450978507c4ef1', 'cnonce':'5ccc069c403ebaf9f0171e9517f40e41'} </code></pre> <p>Is there a library to do this, or something I could look at for inspiration?</p> <p>I'm doing this on Google App Engine, and I'm not sure if the Pyparsing library is available, but maybe I could include it with my app if it is the best solution.</p> <p>Currently I'm creating my own MyHeaderParser object and using it with reduce() on the header string. It's working, but very fragile.</p> <p>Brilliant solution by nadia below:</p> <pre><code>import re reg = re.compile('(\w+)[=] ?"?(\w+)"?') s = """Digest realm="stackoverflow.com", username="kixx" """ print str(dict(reg.findall(s))) </code></pre>
9
2009-08-28T21:07:56Z
1,349,517
<p>If your response comes in a single string that that <strong>never varies and has as many lines as there are expressions to match</strong>, you can split it into an array on the newlines called <code> authentication_array</code> and use regexps:</p> <pre><code>pattern_array = ['qop', 'realm', 'username', 'response', 'cnonce'] i = 0 parsed_dict = {} for line in authentication_array: pattern = "(" + pattern_array[i] + ")" + "=(\".*\")" # build a matching pattern match = re.search(re.compile(pattern), line) # make the match if match: parsed_dict[match.group(1)] = match.group(2) i += 1 </code></pre>
0
2009-08-28T21:38:47Z
[ "python", "http", "google-app-engine", "parsing", "http-headers" ]
Parse an HTTP request Authorization header with Python
1,349,367
<p>I need to take a header like this:</p> <pre><code> Authorization: Digest qop="chap", realm="testrealm@host.com", username="Foobear", response="6629fae49393a05397450978507c4ef1", cnonce="5ccc069c403ebaf9f0171e9517f40e41" </code></pre> <p>And parse it into this using Python:</p> <pre><code>{'protocol':'Digest', 'qop':'chap', 'realm':'testrealm@host.com', 'username':'Foobear', 'response':'6629fae49393a05397450978507c4ef1', 'cnonce':'5ccc069c403ebaf9f0171e9517f40e41'} </code></pre> <p>Is there a library to do this, or something I could look at for inspiration?</p> <p>I'm doing this on Google App Engine, and I'm not sure if the Pyparsing library is available, but maybe I could include it with my app if it is the best solution.</p> <p>Currently I'm creating my own MyHeaderParser object and using it with reduce() on the header string. It's working, but very fragile.</p> <p>Brilliant solution by nadia below:</p> <pre><code>import re reg = re.compile('(\w+)[=] ?"?(\w+)"?') s = """Digest realm="stackoverflow.com", username="kixx" """ print str(dict(reg.findall(s))) </code></pre>
9
2009-08-28T21:07:56Z
1,349,528
<p>A little regex:</p> <pre><code>import re reg=re.compile('(\w+)[:=] ?"?(\w+)"?') &gt;&gt;&gt;dict(reg.findall(headers)) {'username': 'Foobear', 'realm': 'testrealm', 'qop': 'chap', 'cnonce': '5ccc069c403ebaf9f0171e9517f40e41', 'response': '6629fae49393a05397450978507c4ef1', 'Authorization': 'Digest'} </code></pre>
11
2009-08-28T21:40:19Z
[ "python", "http", "google-app-engine", "parsing", "http-headers" ]
Parse an HTTP request Authorization header with Python
1,349,367
<p>I need to take a header like this:</p> <pre><code> Authorization: Digest qop="chap", realm="testrealm@host.com", username="Foobear", response="6629fae49393a05397450978507c4ef1", cnonce="5ccc069c403ebaf9f0171e9517f40e41" </code></pre> <p>And parse it into this using Python:</p> <pre><code>{'protocol':'Digest', 'qop':'chap', 'realm':'testrealm@host.com', 'username':'Foobear', 'response':'6629fae49393a05397450978507c4ef1', 'cnonce':'5ccc069c403ebaf9f0171e9517f40e41'} </code></pre> <p>Is there a library to do this, or something I could look at for inspiration?</p> <p>I'm doing this on Google App Engine, and I'm not sure if the Pyparsing library is available, but maybe I could include it with my app if it is the best solution.</p> <p>Currently I'm creating my own MyHeaderParser object and using it with reduce() on the header string. It's working, but very fragile.</p> <p>Brilliant solution by nadia below:</p> <pre><code>import re reg = re.compile('(\w+)[=] ?"?(\w+)"?') s = """Digest realm="stackoverflow.com", username="kixx" """ print str(dict(reg.findall(s))) </code></pre>
9
2009-08-28T21:07:56Z
1,349,539
<p>Your original concept of using PyParsing would be the best approach. What you've implicitly asked for is something that requires a grammar... that is, a regular expression or simple parsing routine is always going to be brittle, and that sounds like it's something you're trying to avoid.</p> <p>It appears that getting pyparsing on google app engine is easy: <a href="http://stackoverflow.com/questions/1341137/how-do-i-get-pyparsing-set-up-on-the-google-app-engine">http://stackoverflow.com/questions/1341137/how-do-i-get-pyparsing-set-up-on-the-google-app-engine</a></p> <p>So I'd go with that, and then implement the full HTTP authentication/authorization header support from rfc2617.</p>
0
2009-08-28T21:42:40Z
[ "python", "http", "google-app-engine", "parsing", "http-headers" ]
Parse an HTTP request Authorization header with Python
1,349,367
<p>I need to take a header like this:</p> <pre><code> Authorization: Digest qop="chap", realm="testrealm@host.com", username="Foobear", response="6629fae49393a05397450978507c4ef1", cnonce="5ccc069c403ebaf9f0171e9517f40e41" </code></pre> <p>And parse it into this using Python:</p> <pre><code>{'protocol':'Digest', 'qop':'chap', 'realm':'testrealm@host.com', 'username':'Foobear', 'response':'6629fae49393a05397450978507c4ef1', 'cnonce':'5ccc069c403ebaf9f0171e9517f40e41'} </code></pre> <p>Is there a library to do this, or something I could look at for inspiration?</p> <p>I'm doing this on Google App Engine, and I'm not sure if the Pyparsing library is available, but maybe I could include it with my app if it is the best solution.</p> <p>Currently I'm creating my own MyHeaderParser object and using it with reduce() on the header string. It's working, but very fragile.</p> <p>Brilliant solution by nadia below:</p> <pre><code>import re reg = re.compile('(\w+)[=] ?"?(\w+)"?') s = """Digest realm="stackoverflow.com", username="kixx" """ print str(dict(reg.findall(s))) </code></pre>
9
2009-08-28T21:07:56Z
1,349,626
<p>You can also use urllib2 as <a href="http://www.google.com/codesearch/p?hl=en&amp;sa=N&amp;cd=9&amp;ct=rc#OQvO9n2mc04/CherryPy-3.0.1/cherrypy/lib/httpauth.py&amp;q=Authorization%20Digest%20http%20lang%3Apython">CheryPy</a> does.</p> <p>here is the snippet:</p> <pre><code>input= """ Authorization: Digest qop="chap", realm="testrealm@host.com", username="Foobear", response="6629fae49393a05397450978507c4ef1", cnonce="5ccc069c403ebaf9f0171e9517f40e41" """ import urllib2 field, sep, value = input.partition("Authorization: Digest ") if value: items = urllib2.parse_http_list(value) opts = urllib2.parse_keqv_list(items) opts['protocol'] = 'Digest' print opts </code></pre> <p>it outputs:</p> <pre><code>{'username': 'Foobear', 'protocol': 'Digest', 'qop': 'chap', 'cnonce': '5ccc069c403ebaf9f0171e9517f40e41', 'realm': 'testrealm@host.com', 'response': '6629fae49393a05397450978507c4ef1'} </code></pre>
8
2009-08-28T22:11:31Z
[ "python", "http", "google-app-engine", "parsing", "http-headers" ]
Parse an HTTP request Authorization header with Python
1,349,367
<p>I need to take a header like this:</p> <pre><code> Authorization: Digest qop="chap", realm="testrealm@host.com", username="Foobear", response="6629fae49393a05397450978507c4ef1", cnonce="5ccc069c403ebaf9f0171e9517f40e41" </code></pre> <p>And parse it into this using Python:</p> <pre><code>{'protocol':'Digest', 'qop':'chap', 'realm':'testrealm@host.com', 'username':'Foobear', 'response':'6629fae49393a05397450978507c4ef1', 'cnonce':'5ccc069c403ebaf9f0171e9517f40e41'} </code></pre> <p>Is there a library to do this, or something I could look at for inspiration?</p> <p>I'm doing this on Google App Engine, and I'm not sure if the Pyparsing library is available, but maybe I could include it with my app if it is the best solution.</p> <p>Currently I'm creating my own MyHeaderParser object and using it with reduce() on the header string. It's working, but very fragile.</p> <p>Brilliant solution by nadia below:</p> <pre><code>import re reg = re.compile('(\w+)[=] ?"?(\w+)"?') s = """Digest realm="stackoverflow.com", username="kixx" """ print str(dict(reg.findall(s))) </code></pre>
9
2009-08-28T21:07:56Z
1,378,208
<p>Here's my pyparsing attempt:</p> <pre><code>text = """Authorization: Digest qop="chap", realm="testrealm@host.com", username="Foobear", response="6629fae49393a05397450978507c4ef1", cnonce="5ccc069c403ebaf9f0171e9517f40e41" """ from pyparsing import * AUTH = Keyword("Authorization") ident = Word(alphas,alphanums) EQ = Suppress("=") quotedString.setParseAction(removeQuotes) valueDict = Dict(delimitedList(Group(ident + EQ + quotedString))) authentry = AUTH + ":" + ident("protocol") + valueDict print authentry.parseString(text).dump() </code></pre> <p>which prints:</p> <pre><code>['Authorization', ':', 'Digest', ['qop', 'chap'], ['realm', 'testrealm@host.com'], ['username', 'Foobear'], ['response', '6629fae49393a05397450978507c4ef1'], ['cnonce', '5ccc069c403ebaf9f0171e9517f40e41']] - cnonce: 5ccc069c403ebaf9f0171e9517f40e41 - protocol: Digest - qop: chap - realm: testrealm@host.com - response: 6629fae49393a05397450978507c4ef1 - username: Foobear </code></pre> <p>I'm not familiar with the RFC, but I hope this gets you rolling.</p>
2
2009-09-04T09:40:06Z
[ "python", "http", "google-app-engine", "parsing", "http-headers" ]
Parse an HTTP request Authorization header with Python
1,349,367
<p>I need to take a header like this:</p> <pre><code> Authorization: Digest qop="chap", realm="testrealm@host.com", username="Foobear", response="6629fae49393a05397450978507c4ef1", cnonce="5ccc069c403ebaf9f0171e9517f40e41" </code></pre> <p>And parse it into this using Python:</p> <pre><code>{'protocol':'Digest', 'qop':'chap', 'realm':'testrealm@host.com', 'username':'Foobear', 'response':'6629fae49393a05397450978507c4ef1', 'cnonce':'5ccc069c403ebaf9f0171e9517f40e41'} </code></pre> <p>Is there a library to do this, or something I could look at for inspiration?</p> <p>I'm doing this on Google App Engine, and I'm not sure if the Pyparsing library is available, but maybe I could include it with my app if it is the best solution.</p> <p>Currently I'm creating my own MyHeaderParser object and using it with reduce() on the header string. It's working, but very fragile.</p> <p>Brilliant solution by nadia below:</p> <pre><code>import re reg = re.compile('(\w+)[=] ?"?(\w+)"?') s = """Digest realm="stackoverflow.com", username="kixx" """ print str(dict(reg.findall(s))) </code></pre>
9
2009-08-28T21:07:56Z
2,831,097
<p>The http digest Authorization header field is a bit of an odd beast. Its format is similar to that of <a href="http://tools.ietf.org/html/rfc2616" rel="nofollow">rfc 2616</a>'s Cache-Control and Content-Type header fields, but just different enough to be incompatible. If you're still looking for a library that's a little smarter and more readable than the regex, you might try removing the Authorization: Digest part with <a href="http://docs.python.org/library/stdtypes.html#str.split" rel="nofollow">str.split()</a> and parsing the rest with <a href="http://werkzeug.pocoo.org/documentation/dev/http.html#werkzeug.parse_dict_header" rel="nofollow">parse_dict_header()</a> from <a href="http://werkzeug.pocoo.org/" rel="nofollow">Werkzeug</a>'s http module. (Werkzeug can be installed on App Engine.)</p>
1
2010-05-14T00:13:46Z
[ "python", "http", "google-app-engine", "parsing", "http-headers" ]
Parse an HTTP request Authorization header with Python
1,349,367
<p>I need to take a header like this:</p> <pre><code> Authorization: Digest qop="chap", realm="testrealm@host.com", username="Foobear", response="6629fae49393a05397450978507c4ef1", cnonce="5ccc069c403ebaf9f0171e9517f40e41" </code></pre> <p>And parse it into this using Python:</p> <pre><code>{'protocol':'Digest', 'qop':'chap', 'realm':'testrealm@host.com', 'username':'Foobear', 'response':'6629fae49393a05397450978507c4ef1', 'cnonce':'5ccc069c403ebaf9f0171e9517f40e41'} </code></pre> <p>Is there a library to do this, or something I could look at for inspiration?</p> <p>I'm doing this on Google App Engine, and I'm not sure if the Pyparsing library is available, but maybe I could include it with my app if it is the best solution.</p> <p>Currently I'm creating my own MyHeaderParser object and using it with reduce() on the header string. It's working, but very fragile.</p> <p>Brilliant solution by nadia below:</p> <pre><code>import re reg = re.compile('(\w+)[=] ?"?(\w+)"?') s = """Digest realm="stackoverflow.com", username="kixx" """ print str(dict(reg.findall(s))) </code></pre>
9
2009-08-28T21:07:56Z
7,404,187
<p>Nadia's regex only matches alphanumeric characters for the value of a parameter. That means it fails to parse at least two fields. Namely, the uri and qop. According to RFC 2617, the uri field is a duplicate of the string in the request line (i.e. the first line of the HTTP request). And qop fails to parse correctly if the value is "auth-int" due to the non-alphanumeric '-'.</p> <p>This modified regex allows the URI (or any other value) to contain anything but ' ' (space), '"' (qoute), or ',' (comma). That's probably more permissive than it needs to be, but shouldn't cause any problems with <em>correctly</em> formed HTTP requests.</p> <pre><code>reg re.compile('(\w+)[:=] ?"?([^" ,]+)"?') </code></pre> <p>Bonus tip: From there, it's fairly straight forward to convert the example code in RFC-2617 to python. Using python's md5 API, "MD5Init()" becomes "m = md5.new()", "MD5Update()" becomes "m.update()" and "MD5Final()" becomes "m.digest()".</p>
1
2011-09-13T15:09:58Z
[ "python", "http", "google-app-engine", "parsing", "http-headers" ]
Python change screen resolution virtual machine
1,349,544
<p>In virtualbox, the screen resolution can be anything - even something strange like 993x451, etc. I tried changing it using pywin32 but I failed::</p> <pre><code>&gt;&gt;&gt; dm = win32api.EnumDisplaySettings(None, 0) &gt;&gt;&gt; dm.PelsHeight = 451 &gt;&gt;&gt; dm.PelsWidth = 950 &gt;&gt;&gt; win32api.ChangeDisplaySettings(dm, 0) -2L </code></pre> <p>which ends up being:</p> <pre><code>DISP_CHANGE_BADMODE </code></pre> <p>any help?</p>
3
2009-08-28T21:44:14Z
1,349,559
<p>Do you have VirtualBox set to automatically set the client window? that could cause some issues.</p>
0
2009-08-28T21:48:16Z
[ "python", "winapi", "virtualization", "resolution", "pywin32" ]
Python change screen resolution virtual machine
1,349,544
<p>In virtualbox, the screen resolution can be anything - even something strange like 993x451, etc. I tried changing it using pywin32 but I failed::</p> <pre><code>&gt;&gt;&gt; dm = win32api.EnumDisplaySettings(None, 0) &gt;&gt;&gt; dm.PelsHeight = 451 &gt;&gt;&gt; dm.PelsWidth = 950 &gt;&gt;&gt; win32api.ChangeDisplaySettings(dm, 0) -2L </code></pre> <p>which ends up being:</p> <pre><code>DISP_CHANGE_BADMODE </code></pre> <p>any help?</p>
3
2009-08-28T21:44:14Z
1,411,168
<p>Have you configured the virtual machine to actually advertise this mode to the OS?</p> <p>edit: VirtualBox automatically sets new resolutions if you change the size of the window. You can set video mode hints from the host OS I believe (look for it in the documentation), but you need guest additions installed. You can also add VESA modes when using the fallback VESA driver. Either way, it seems this all needs to happen from the host OS for the guest OS to be able to make use of it. And it doesn't look like there's an easy (non cmdline possibly not persistent) way to configure it, though YMMV.</p> <p>I haven't tested it but the command should be: VBoxManage controlvm </p> <p>You can also set the maximum guest OS screen size, found this while looking into it a bit deeper: VBoxManage setextradata global GUI/MaxGuestResolution xres,yres</p> <p>HTH</p>
1
2009-09-11T14:20:04Z
[ "python", "winapi", "virtualization", "resolution", "pywin32" ]
Python change screen resolution virtual machine
1,349,544
<p>In virtualbox, the screen resolution can be anything - even something strange like 993x451, etc. I tried changing it using pywin32 but I failed::</p> <pre><code>&gt;&gt;&gt; dm = win32api.EnumDisplaySettings(None, 0) &gt;&gt;&gt; dm.PelsHeight = 451 &gt;&gt;&gt; dm.PelsWidth = 950 &gt;&gt;&gt; win32api.ChangeDisplaySettings(dm, 0) -2L </code></pre> <p>which ends up being:</p> <pre><code>DISP_CHANGE_BADMODE </code></pre> <p>any help?</p>
3
2009-08-28T21:44:14Z
1,981,856
<p>The way I found to do this is to enable the automatic client resizing from the Guest OS. Then, in the host OS, programatically resize the VM window. This will cause the resolution to change.</p>
0
2009-12-30T19:06:43Z
[ "python", "winapi", "virtualization", "resolution", "pywin32" ]
Strategy for maintaining complex filter states?
1,349,840
<p>I need to maintain a list of filtered and sorted objects, preferably in a generic manner, that can be used in multiple views. This is necessary so I can generate next, prev links, along with some other very useful things for the user.</p> <p>Examples of filters:</p> <pre><code>field__isnull=True field__exact="so" field__field__isnull=False </code></pre> <p>Additionally, after the filtered query set is built, ordering may be applied by any of the fields.</p> <p>My current solution is to use a FilterSpec class containing a collection of filters, along with an initial query set. This class is then serialized and passed to a view.</p> <p>Consider a view with 25 dynamically filtered items. Each item in the view has a link to get a detailed view of the item. To each of these links, the serialized FilterSpec object of the current list is appended. So you end up with huge urls. Worse, the same huge filter is appended to all 25 links! </p> <p>Another option is to store the FilterSpec in the session, but then you run into problems of when to delete the FilterSpec. Next you find all your views getting cluttered with code trying to determine if the filter should be deleted in preparation for a new list of objects.</p> <p>I'm sure this problem has been solved before, so I'd love to hear other solutions that you guys have come up with. </p>
0
2009-08-28T23:19:04Z
1,350,064
<p>Depending on what you want to do, you'll want to either <a href="http://docs.djangoproject.com/en/dev/topics/db/managers/#modifying-initial-manager-querysets" rel="nofollow">create a custom manager</a> or add a <a href="http://docs.djangoproject.com/en/dev/topics/db/managers/#adding-extra-manager-methods" rel="nofollow">new manager method</a>.</p> <p>In this example, you add a new manager that selects blog posts that are marked as published with a date after the current <code>datetime</code>.</p> <pre><code>from django.db import models from datetime import datetime class PublishedPostManager(models.Manager): def get_query_set(self): return super(PublishedPostManager, self).get_query_set().filter(published=True, time__lt=datetime.now()) class Post(models.Model): title = models.CharField(max_length=128) body = models.TextField() published = models.BooleanField(default=False) time = models.DateTimeField() objects = models.Manager() # Needed to ensure that the default manager is still available published = PublishedPostManager() </code></pre> <p>Then, instead of <code>Post.objects.all()</code>, you can use <code>Post.published.all()</code> to fetch all records. The normal QuerySet methods are available as well:</p> <pre><code>Post.published.count() Post.published.select_related().filter(spam__iexact='eggs') # etc </code></pre> <p>And of course, you can still use the default manager:</p> <pre><code>Post.objects.all() </code></pre>
1
2009-08-29T00:48:42Z
[ "python", "django", "http" ]
Strategy for maintaining complex filter states?
1,349,840
<p>I need to maintain a list of filtered and sorted objects, preferably in a generic manner, that can be used in multiple views. This is necessary so I can generate next, prev links, along with some other very useful things for the user.</p> <p>Examples of filters:</p> <pre><code>field__isnull=True field__exact="so" field__field__isnull=False </code></pre> <p>Additionally, after the filtered query set is built, ordering may be applied by any of the fields.</p> <p>My current solution is to use a FilterSpec class containing a collection of filters, along with an initial query set. This class is then serialized and passed to a view.</p> <p>Consider a view with 25 dynamically filtered items. Each item in the view has a link to get a detailed view of the item. To each of these links, the serialized FilterSpec object of the current list is appended. So you end up with huge urls. Worse, the same huge filter is appended to all 25 links! </p> <p>Another option is to store the FilterSpec in the session, but then you run into problems of when to delete the FilterSpec. Next you find all your views getting cluttered with code trying to determine if the filter should be deleted in preparation for a new list of objects.</p> <p>I'm sure this problem has been solved before, so I'd love to hear other solutions that you guys have come up with. </p>
0
2009-08-28T23:19:04Z
1,351,611
<p>You've identified the two options for maintaining user-specific state in a web application: store it in cookies/session, or pass it around on URLs. I don't believe there's a third "silver bullet" waiting in the wings to solve your problem.</p> <p>The URL query-string option has the advantage that a particular view state can be bookmarked, sent as an emailed URL, &amp;c. It also may keep your view code a bit simpler, but at the cost of some extra template code to ensure the proper query-string always gets passed along on links.</p> <p>In part your preferred solution may depend on the behavior you want. For instance, if a user bookmarks (or emails to a friend) the URL for a detail view of an item, do you want that URL to simply refer to the item itself, or to always carry along information about what list that item came out of? If the former, use session data. If the latter, use URLs with query strings.</p> <p>In either case, I'm confident that the code that you find "cluttering all your views" can be refactored to be elegant, DRY, and as invisible as you want it to be. Decorators and/or class-based views might help.</p>
2
2009-08-29T14:46:31Z
[ "python", "django", "http" ]
Novice needs advice for script that gets data and returns it in a usable format
1,349,932
<p>I have a large number of images that I am putting into web pages. Rather than painstakingly enter all of the image attributes, I thought I could write a script that would do the work for me. I just need a little push in the right direction. </p> <p>I want the script to get the width and height of each image, then format this into an img tag that would include the url I'm using. I'm thinking that first I would loop through the files in the directory and output the results that I'm looking for to a file. Then I can copy and paste. </p> <p>Ideally, it should eventually have a GUI where you can choose each file, save the result to the clipboard, then paste it directly into the document. But I believe this is beyond me at this point. </p> <p>I have a basic understanding of coding and have done a smattering of scripts in Python and PHP. </p> <p>Where do I start? Can I use Python? Or PHP? Or a different language? PHP has the getimagesize() function that returns the data I need. Does Python have a similar function? </p> <p>Sorry to be long winded. And thanks for any input.</p>
0
2009-08-28T23:49:50Z
1,349,982
<p>Maybe the better solution would be not to create a script that generates a list of all the image elements for you to put in your document but rather generate the image elements on the fly in the desired document. This could be done like this:</p> <pre><code>if ($handle = opendir('/path/to/images')) { while (false !== ($file = readdir($handle))) { ?&gt; &lt;img src="http://you.server.com/path/to/images/&lt;?php echo $file ?&gt;" alt="&lt;?php echo $file ?&gt;" /&gt; &lt;?php } closedir($handle); } </code></pre> <p>Furthermore I don't understand why you would want to include image height and width in the img elements as there is no need to specify those. The height and the width are only used to modify the image dimensions as the browser automatically display's the actual size.</p> <p>But to include the image size the getimagesize() function would work:</p> <pre><code>if ($handle = opendir('/path/to/images')) { while (false !== ($file = readdir($handle))) { $size=getimagesize('/path/to/images/'.$file); ?&gt; &lt;img &lt;?php echo $size[3] ?&gt; src="http://you.server.com/path/to/images/&lt;?php echo $file ?&gt;" alt="&lt;?php echo $file ?&gt;" /&gt; &lt;?php } closedir($handle); } </code></pre> <p>more info: <a href="http://nl2.php.net/function.getimagesize" rel="nofollow">http://nl2.php.net/function.getimagesize</a></p>
1
2009-08-29T00:08:07Z
[ "php", "python", "scripting", "image-processing", "website" ]
Novice needs advice for script that gets data and returns it in a usable format
1,349,932
<p>I have a large number of images that I am putting into web pages. Rather than painstakingly enter all of the image attributes, I thought I could write a script that would do the work for me. I just need a little push in the right direction. </p> <p>I want the script to get the width and height of each image, then format this into an img tag that would include the url I'm using. I'm thinking that first I would loop through the files in the directory and output the results that I'm looking for to a file. Then I can copy and paste. </p> <p>Ideally, it should eventually have a GUI where you can choose each file, save the result to the clipboard, then paste it directly into the document. But I believe this is beyond me at this point. </p> <p>I have a basic understanding of coding and have done a smattering of scripts in Python and PHP. </p> <p>Where do I start? Can I use Python? Or PHP? Or a different language? PHP has the getimagesize() function that returns the data I need. Does Python have a similar function? </p> <p>Sorry to be long winded. And thanks for any input.</p>
0
2009-08-28T23:49:50Z
1,349,986
<p>Check out the <a href="http://www.pythonware.com/products/pil/" rel="nofollow">PIL</a>:</p> <pre><code>from PIL import Image im = Image.open("yourfile.jpg") print im.size </code></pre> <p>For looping through files see <a href="http://love-python.blogspot.com/2008/05/list-of-files-directories-in-python.html" rel="nofollow">this tutorial</a>.</p>
3
2009-08-29T00:09:32Z
[ "php", "python", "scripting", "image-processing", "website" ]
Novice needs advice for script that gets data and returns it in a usable format
1,349,932
<p>I have a large number of images that I am putting into web pages. Rather than painstakingly enter all of the image attributes, I thought I could write a script that would do the work for me. I just need a little push in the right direction. </p> <p>I want the script to get the width and height of each image, then format this into an img tag that would include the url I'm using. I'm thinking that first I would loop through the files in the directory and output the results that I'm looking for to a file. Then I can copy and paste. </p> <p>Ideally, it should eventually have a GUI where you can choose each file, save the result to the clipboard, then paste it directly into the document. But I believe this is beyond me at this point. </p> <p>I have a basic understanding of coding and have done a smattering of scripts in Python and PHP. </p> <p>Where do I start? Can I use Python? Or PHP? Or a different language? PHP has the getimagesize() function that returns the data I need. Does Python have a similar function? </p> <p>Sorry to be long winded. And thanks for any input.</p>
0
2009-08-28T23:49:50Z
1,350,015
<p>You can also use shell <a href="http://www.imagemagick.org/script/identify.php" rel="nofollow">identify</a> command from <a href="http://www.imagemagick.org/script/index.php" rel="nofollow">Imagemagick</a>:</p> <pre><code>for file in dir/*; do identify -format "Width: %w, Height: %h" $file done </code></pre>
0
2009-08-29T00:26:34Z
[ "php", "python", "scripting", "image-processing", "website" ]
Novice needs advice for script that gets data and returns it in a usable format
1,349,932
<p>I have a large number of images that I am putting into web pages. Rather than painstakingly enter all of the image attributes, I thought I could write a script that would do the work for me. I just need a little push in the right direction. </p> <p>I want the script to get the width and height of each image, then format this into an img tag that would include the url I'm using. I'm thinking that first I would loop through the files in the directory and output the results that I'm looking for to a file. Then I can copy and paste. </p> <p>Ideally, it should eventually have a GUI where you can choose each file, save the result to the clipboard, then paste it directly into the document. But I believe this is beyond me at this point. </p> <p>I have a basic understanding of coding and have done a smattering of scripts in Python and PHP. </p> <p>Where do I start? Can I use Python? Or PHP? Or a different language? PHP has the getimagesize() function that returns the data I need. Does Python have a similar function? </p> <p>Sorry to be long winded. And thanks for any input.</p>
0
2009-08-28T23:49:50Z
1,350,082
<p>I think this should do what you want. But it's not necessarily the best way (it's late, I'm tired, etc...):</p> <pre><code>&lt;?php $directory = "img"; // The path in which your images are located. if ($directory) { $files = scandir($directory); // $files becomes an array of files in the relevant directory. } foreach($files as $k =&gt; $v) { if ($v == "." || $v == "..") { // because I'm not good enough to think of a better way unset($k); } else { $size = getimagesize($directory . "/" . $v); $images[] = array('img' =&gt; $v, 'w' =&gt; $size[0], 'h' =&gt; $size[1]); // $size[0] is width, $size[1] is height, both in px. } } unset($files); // I just like to clear as I go. I make more than enough mess as it is without keeping it around. if ($images) { foreach($images as $key =&gt; $value) { echo "\n\t\t&lt;img src=\"$directory/" . $value[img] . "\" width=\"" . $value[w] . "px\" height=\"" . $value[h] . "px\" alt=\"" . $value[img] . "\" /&gt;"; } } ?&gt; </code></pre>
0
2009-08-29T00:57:57Z
[ "php", "python", "scripting", "image-processing", "website" ]
Can Selenium RC tests written in Python be integrated into PHPUnit?
1,350,114
<p>I'm working on large project in PHP and I'm running phpundercontrol with PHPUnit for my unit tests. I would like to use Selenium RC for running acceptance tests. Unfortunately the only person I have left to write tests only knows Python. Can Selenium tests written in Python be integrated into PHPUnit?</p> <p>Thanks!</p>
1
2009-08-29T01:15:11Z
1,360,647
<p>The only thing that comes to my mind is running them through the shell. It would be:</p> <pre><code>&lt;?php $output = shell_exec('python testScript.py'); echo $output; ?&gt; </code></pre> <p>It's not too integrated with phpunit, but once you get the output in a variable ($output), you can then parse the text inside it to see if you have "E" or "." ("E" states for errors in pyunit and "." states for pass).</p> <p>This is the best thing I could think of, hope it helps.</p>
1
2009-09-01T05:17:19Z
[ "python", "selenium", "phpunit" ]
sqlalchemy create a foreign key?
1,350,121
<p>I have a composite PK in table Strings (integer id, varchar(2) lang)</p> <p>I want to create a FK to ONLY the id half of the PK from other tables. This means I'd have potentially many rows in Strings table (translations) matching the FK. I just need to store the id, and have referential integrity maintained by the DB.</p> <p>Is this possible? If so, how?</p>
1
2009-08-29T01:17:07Z
1,351,222
<p>This is from <a href="http://en.wikipedia.org/wiki/Foreign%5Fkey" rel="nofollow">wiki</a></p> <blockquote> <p>The columns in the referencing table must be the primary key or other candidate key in the referenced table. The values in one row of the referencing columns must occur in a single row in the referenced table.</p> </blockquote> <p>Let's say you have this:</p> <pre><code>id | var 1 | 10 1 | 11 2 | 10 </code></pre> <p>The foreign key must reference <strong>exactly one row</strong> from the referenced table. This is why usually it references the primary key. </p> <p>In your case you need to make another Table1(id) where you stored the ids and make the column unique/primary key. The id column in your current table is not unique - you can't use it in your situation... so you make a Table1(id - primary key) <strong>and make the id in your current table a foreign key to the Table1</strong>. Now you can create foreign keys to id in Table1 and the primary key in your current table is ok. </p>
3
2009-08-29T11:36:52Z
[ "python", "sql", "sqlalchemy" ]
What does matrix**2 mean in python/numpy?
1,350,174
<p>I have a python ndarray temp in some code I'm reading that suffers this:</p> <pre><code>x = temp**2 </code></pre> <p>Is this the dot square (ie, equivalent to m.*m) or the matrix square (ie m must be a square matrix)? In particular, I'd like to know whether I can get rid of the transpose in this code:</p> <pre><code>temp = num.transpose(whatever) num.sum(temp**2,axis=1)) </code></pre> <p>and turn it into this:</p> <pre><code>num.sum(whatever**2,axis=0) </code></pre> <p>That will save me at least 0.1ms, and is clearly worth my time.<br /> Thanks! The ** operator is ungooglable and I know nothing! a</p>
9
2009-08-29T01:40:52Z
1,350,199
<p>It's just the square of each element.</p> <pre><code>from numpy import * a = arange(4).reshape((2,2)) print a**2 </code></pre> <p>prints</p> <pre><code>[[0 1] [4 9]] </code></pre>
12
2009-08-29T01:54:48Z
[ "python", "numpy" ]
What does matrix**2 mean in python/numpy?
1,350,174
<p>I have a python ndarray temp in some code I'm reading that suffers this:</p> <pre><code>x = temp**2 </code></pre> <p>Is this the dot square (ie, equivalent to m.*m) or the matrix square (ie m must be a square matrix)? In particular, I'd like to know whether I can get rid of the transpose in this code:</p> <pre><code>temp = num.transpose(whatever) num.sum(temp**2,axis=1)) </code></pre> <p>and turn it into this:</p> <pre><code>num.sum(whatever**2,axis=0) </code></pre> <p>That will save me at least 0.1ms, and is clearly worth my time.<br /> Thanks! The ** operator is ungooglable and I know nothing! a</p>
9
2009-08-29T01:40:52Z
1,350,212
<p><code>**</code> is the raise-to-power operator in Python, so <code>x**2</code> means "x squared" in Python -- including numpy. Such operations in numpy always apply element by element, so <code>x**2</code> squares each element of array <code>x</code> (whatever number of dimensions) just like, say, <code>x*2</code> would double each element, or <code>x+2</code> would increment each element by two (in each case, <code>x</code> proper is unaffected -- the result is a new temporary array of the same shape as <code>x</code>!).</p> <p><strong>Edit</strong>: as @kaizer.ze points out, while what I wrote holds for <code>numpy.array</code> objects, it doesn't apply to <code>numpy.matrix</code> objects, where multiplication means matrix multiplication rather than element by element operation like for <code>array</code> (and similarly for raising to power) -- indeed, that's the key difference between the two types. As the <a href="http://www.scipy.org/SciPy%5FTutorial" rel="nofollow">Scipy tutorial</a> puts it, for example:</p> <blockquote> <p>When we use numpy.array or numpy.matrix there is a difference. A*x will be in the latter case matrix product, not elementwise product as with array.</p> </blockquote> <p>i.e., as the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.matrix.html" rel="nofollow">numpy reference</a> puts it:</p> <blockquote> <p>A matrix is a specialized 2-d array that retains its 2-d nature through operations. It has certain special operators, such as <code>*</code> (matrix multiplication) and <code>**</code> (matrix power).</p> </blockquote>
5
2009-08-29T02:04:01Z
[ "python", "numpy" ]
What does matrix**2 mean in python/numpy?
1,350,174
<p>I have a python ndarray temp in some code I'm reading that suffers this:</p> <pre><code>x = temp**2 </code></pre> <p>Is this the dot square (ie, equivalent to m.*m) or the matrix square (ie m must be a square matrix)? In particular, I'd like to know whether I can get rid of the transpose in this code:</p> <pre><code>temp = num.transpose(whatever) num.sum(temp**2,axis=1)) </code></pre> <p>and turn it into this:</p> <pre><code>num.sum(whatever**2,axis=0) </code></pre> <p>That will save me at least 0.1ms, and is clearly worth my time.<br /> Thanks! The ** operator is ungooglable and I know nothing! a</p>
9
2009-08-29T01:40:52Z
1,351,683
<p>You should read <a href="http://www.scipy.org/NumPy%5Ffor%5FMatlab%5FUsers" rel="nofollow">NumPy for Matlab Users</a>. The elementwise power operation is mentioned there, and you can also see that in numpy, some operators apply differently to <code>array</code> and <code>matrix</code>.</p> <pre><code>&gt;&gt;&gt; from numpy import * &gt;&gt;&gt; a = arange(4).reshape((2,2)) &gt;&gt;&gt; print a**2 [[0 1] [4 9]] &gt;&gt;&gt; print matrix(a)**2 [[ 2 3] [ 6 11]] </code></pre>
5
2009-08-29T15:17:41Z
[ "python", "numpy" ]
Check whether debug is enabled in a Pylons application
1,350,227
<p>I'm working on a fairly simple Pylons 0.9.7 application. How do I tell, in code, whether or not debugging is enabled? That is, I'm interested in the value of the <strong>debug</strong> setting under <strong>[app:main]</strong> in my INI file. More generally, how do I access the other values from there in my code?</p>
1
2009-08-29T02:11:19Z
1,350,240
<pre><code># tmp.py print __debug__ $ python tmp.py True $ python -O tmp.py False </code></pre> <p>I'm not sure if this holds in Pylons, as I've never used that -- but in "normal" command line Python, debug is enabled if optimizations are <em>not</em> enabled. The <code>-O</code> flag indicates to Python to turn on optimizations.</p> <p>Actually, there's this snippet from <a href="http://pylonsbook.com/en/1.0/pylons-internal-architecture.html#the-pylons-middleware-stack" rel="nofollow">Pylons documentation</a>:</p> <pre><code> # Display error documents for 401, 403, 404 status codes (and # 500 when debug is disabled) if asbool(config['debug']): app = StatusCodeRedirect(app) else: app = StatusCodeRedirect(app, [400, 401, 403, 404, 500]) </code></pre> <p>Looks like <code>config['debug']</code> is what you want.</p>
3
2009-08-29T02:18:32Z
[ "python", "configuration", "pylons" ]
Java equivalent of Python repr()?
1,350,397
<p>Is there a Java method that works like Python's repr? For example, assuming the function were named repr,</p> <pre><code>"foo\n\tbar".repr() </code></pre> <p>would return</p> <pre>"foo\n\tbar"</pre> <p>not</p> <pre>foo bar</pre> <p>as toString does.</p>
20
2009-08-29T03:52:13Z
1,350,443
<p>If you're only going to be using this on strings, in a pinch you could just write a method that goes through the string and replaces special characters (for whatever definition of "special" you want) with their escape codes. That's what I would do. (I did a quick search and nothing came up on Google, so it might be faster to just write the method than to hunt for an existing implementation)</p>
0
2009-08-29T04:23:06Z
[ "java", "python", "repr" ]
Java equivalent of Python repr()?
1,350,397
<p>Is there a Java method that works like Python's repr? For example, assuming the function were named repr,</p> <pre><code>"foo\n\tbar".repr() </code></pre> <p>would return</p> <pre>"foo\n\tbar"</pre> <p>not</p> <pre>foo bar</pre> <p>as toString does.</p>
20
2009-08-29T03:52:13Z
1,350,529
<p>This will do it, but it's a bit of a hack, it uses <a href="http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/StringUtils.html" rel="nofollow">StringUtils</a> and <strong>replaceEach</strong> from Common Lang to achieve a simple replace:</p> <pre><code>String hello = "hello\n\tworld\n\n\t"; String replaced = StringUtils.replaceEach(hello, new String[] {"\n", "\t", "\r", "\f"}, new String[] {"\\n", "\\t", "\\r", "\\f"}); System.out.println("Replaced " + replaced); </code></pre>
0
2009-08-29T05:10:53Z
[ "java", "python", "repr" ]
Java equivalent of Python repr()?
1,350,397
<p>Is there a Java method that works like Python's repr? For example, assuming the function were named repr,</p> <pre><code>"foo\n\tbar".repr() </code></pre> <p>would return</p> <pre>"foo\n\tbar"</pre> <p>not</p> <pre>foo bar</pre> <p>as toString does.</p>
20
2009-08-29T03:52:13Z
1,350,820
<p>If there were such a method, it would make writing quines in Java really easy, because it would solve the problem of escaping the quotes. Seeing as the simplest quines in Java all require manually inserting the quote character manually with its character code, it is unlikely that such a method exists.</p>
0
2009-08-29T08:06:50Z
[ "java", "python", "repr" ]
Java equivalent of Python repr()?
1,350,397
<p>Is there a Java method that works like Python's repr? For example, assuming the function were named repr,</p> <pre><code>"foo\n\tbar".repr() </code></pre> <p>would return</p> <pre>"foo\n\tbar"</pre> <p>not</p> <pre>foo bar</pre> <p>as toString does.</p>
20
2009-08-29T03:52:13Z
1,351,230
<p>don't think there's a specific method -- but this'll solve it without commons lang:</p> <pre><code>public class test { public test() throws Exception { byte[] hello = "hello\n\tworld\n\n\t".getBytes(); System.out.println(new String(hexToByte(stringToHex(hello).replaceAll("0a", "5c6e") .replaceAll("09", "5c74")))); } public static void main(String[] args) throws Exception { new test(); } public static String stringToHex(byte[] b) throws Exception { String result = ""; for (int i = 0; i &lt; b.length; i++) { result += Integer.toString((b[i] &amp; 0xff) + 0x100, 16).substring(1); } return result; } public static byte[] hexToByte(String s) { int len = s.length(); byte[] data = new byte[len / 2]; for (int i = 0; i &lt; len; i += 2) { data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) &lt;&lt; 4) + Character.digit(s.charAt(i + 1), 16)); } return data; } </code></pre> <p>}</p>
1
2009-08-29T11:41:40Z
[ "java", "python", "repr" ]
Java equivalent of Python repr()?
1,350,397
<p>Is there a Java method that works like Python's repr? For example, assuming the function were named repr,</p> <pre><code>"foo\n\tbar".repr() </code></pre> <p>would return</p> <pre>"foo\n\tbar"</pre> <p>not</p> <pre>foo bar</pre> <p>as toString does.</p>
20
2009-08-29T03:52:13Z
1,351,973
<p>In some projects, I use the following helper function to accomplish something akin to Python's <em>repr</em> for strings:</p> <pre><code>private static final char CONTROL_LIMIT = ' '; private static final char PRINTABLE_LIMIT = '\u007e'; private static final char[] HEX_DIGITS = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; public static String toPrintableRepresentation(String source) { if( source == null ) return null; else { final StringBuilder sb = new StringBuilder(); final int limit = source.length(); char[] hexbuf = null; int pointer = 0; sb.append('"'); while( pointer &lt; limit ) { int ch = source.charAt(pointer++); switch( ch ) { case '\0': sb.append("\\0"); break; case '\t': sb.append("\\t"); break; case '\n': sb.append("\\n"); break; case '\r': sb.append("\\r"); break; case '\"': sb.append("\\\""); break; case '\\': sb.append("\\\\"); break; default: if( CONTROL_LIMIT &lt;= ch &amp;&amp; ch &lt;= PRINTABLE_LIMIT ) sb.append((char)ch); else { sb.append("\\u"); if( hexbuf == null ) hexbuf = new char[4]; for( int offs = 4; offs &gt; 0; ) { hexbuf[--offs] = HEX_DIGITS[ch &amp; 0xf]; ch &gt;&gt;&gt;= 4; } sb.append(hexbuf, 0, 4); } } } return sb.append('"').toString(); } } </code></pre> <p>Its main advantage over many of the other solutions given here is, that it does not filter only a limited set of non-printable characters (like those <em>replace</em>-based solutions), but simply all non-printable ASCII characters. Some of it could have been written slightly nicer, but it actually does its job...</p> <p>Note, that like the Python function, this one will surround the string with quotes. If you do not want that, you will have to eliminate the <em>append('"')</em> calls before and after the <em>while</em> loop.</p>
8
2009-08-29T17:49:30Z
[ "java", "python", "repr" ]
Java equivalent of Python repr()?
1,350,397
<p>Is there a Java method that works like Python's repr? For example, assuming the function were named repr,</p> <pre><code>"foo\n\tbar".repr() </code></pre> <p>would return</p> <pre>"foo\n\tbar"</pre> <p>not</p> <pre>foo bar</pre> <p>as toString does.</p>
20
2009-08-29T03:52:13Z
1,352,380
<p>It appears that Jython already does this. You could, in theory, include the Jython jar, startup an interpreter, and actually run repr(object) on the object in question. Probably more overhead than you want, but does exactly what you describe.</p> <p>If you want to embed the Jython interpreter in your application, consider <a href="http://wiki.python.org/jython/JythonFaq/EmbeddingJython" rel="nofollow">http://wiki.python.org/jython/JythonFaq/EmbeddingJython</a> .</p>
0
2009-08-29T21:08:56Z
[ "java", "python", "repr" ]
Java equivalent of Python repr()?
1,350,397
<p>Is there a Java method that works like Python's repr? For example, assuming the function were named repr,</p> <pre><code>"foo\n\tbar".repr() </code></pre> <p>would return</p> <pre>"foo\n\tbar"</pre> <p>not</p> <pre>foo bar</pre> <p>as toString does.</p>
20
2009-08-29T03:52:13Z
18,722,866
<p>Java has no repr-Function, but <a href="http://repr.sf.net" rel="nofollow">repr</a> has got you covered (Full disclosure: I am the author of repr).</p>
2
2013-09-10T15:21:57Z
[ "java", "python", "repr" ]
Java equivalent of Python repr()?
1,350,397
<p>Is there a Java method that works like Python's repr? For example, assuming the function were named repr,</p> <pre><code>"foo\n\tbar".repr() </code></pre> <p>would return</p> <pre>"foo\n\tbar"</pre> <p>not</p> <pre>foo bar</pre> <p>as toString does.</p>
20
2009-08-29T03:52:13Z
23,957,629
<p>Use the static method <code>escapeJava</code> from Commons Lang <code>StringEscapeUtils</code> class.</p> <pre><code>String repr = "\"" + StringEscapeUtils.escapeJava(myString) + "\""; </code></pre>
1
2014-05-30T15:00:31Z
[ "java", "python", "repr" ]
Java equivalent of Python repr()?
1,350,397
<p>Is there a Java method that works like Python's repr? For example, assuming the function were named repr,</p> <pre><code>"foo\n\tbar".repr() </code></pre> <p>would return</p> <pre>"foo\n\tbar"</pre> <p>not</p> <pre>foo bar</pre> <p>as toString does.</p>
20
2009-08-29T03:52:13Z
32,284,299
<p>In case you are using <strong>Groovy</strong>, it provides a similar <a href="http://docs.groovy-lang.org/latest/html/api/groovy/json/StringEscapeUtils.html#escapeJava(java.lang.String)" rel="nofollow"><code>StringEscapeUtils</code> class</a> as Apache Commons Lang:</p> <pre><code>StringEscapeUtils.escapeJava("foo\n\tbar") </code></pre>
0
2015-08-29T08:52:44Z
[ "java", "python", "repr" ]
Preventing Python code from importing certain modules?
1,350,466
<p>I'm writing an application where users can enter a python script and execute it in a sandbox. I need a way to prevent the exec'ed code from importing certain modules, so malicious code won't be as much of a problem. Is there a way to do this in Python?</p>
7
2009-08-29T04:39:33Z
1,350,472
<p>You can overload the import mechanism. We used this to have a licensing system for plugins, you can easily have a whitelist / blacklist of module names.</p>
1
2009-08-29T04:43:36Z
[ "python", "module", "sandbox" ]
Preventing Python code from importing certain modules?
1,350,466
<p>I'm writing an application where users can enter a python script and execute it in a sandbox. I need a way to prevent the exec'ed code from importing certain modules, so malicious code won't be as much of a problem. Is there a way to do this in Python?</p>
7
2009-08-29T04:39:33Z
1,350,473
<p>Unfortunately, I think that what you're trying to do is fundamentally impossible. If users can execute arbitrary code in your application then they can do whatever they want. Even if you were able to prevent them from importing certain modules there would be nothing stopping them from writing equivalent functionality themselves (from scratch or using some of the modules that are available).</p> <p>I don't really know the specifics of implementing a sandbox in Python, but I would imagine it's something that needs to be done at the interpreter level and is far from easy!</p>
0
2009-08-29T04:43:49Z
[ "python", "module", "sandbox" ]
Preventing Python code from importing certain modules?
1,350,466
<p>I'm writing an application where users can enter a python script and execute it in a sandbox. I need a way to prevent the exec'ed code from importing certain modules, so malicious code won't be as much of a problem. Is there a way to do this in Python?</p>
7
2009-08-29T04:39:33Z
1,350,476
<p>Have you checked the python.org <a href="http://wiki.python.org/moin/SandboxedPython">article on SandboxedPython</a>, and the <a href="http://wiki.python.org/moin/How%20can%20I%20run%20an%20untrusted%20Python%20script%20safely%20%28i.e.%20Sandbox%29">linked article</a>?</p> <p>Both of those pages have links to other resources.</p> <p>Specifically, PyPi's <a href="http://pypi.python.org/pypi/RestrictedPython/">RestrictedPython</a> lets you define exactly what is available, and has a few 'safe' defaults to choose from.</p>
11
2009-08-29T04:44:34Z
[ "python", "module", "sandbox" ]
Preventing Python code from importing certain modules?
1,350,466
<p>I'm writing an application where users can enter a python script and execute it in a sandbox. I need a way to prevent the exec'ed code from importing certain modules, so malicious code won't be as much of a problem. Is there a way to do this in Python?</p>
7
2009-08-29T04:39:33Z
1,350,505
<p>Google App Engine's open source <a href="http://code.google.com/appengine/downloads.html">SDK</a> has a detailed and solid implementation of mechanics to stop the importing of unwanted modules (to help detect code trying to import modules that aren't made available in the production instances of App Engine), though even that could be subverted if the user code was evil rather than just mistaken (production instances obviously have more layers of defense, such as simply not having those modules around at all;-).</p> <p>So it all depends on how in-depth your defense needs to be. At one extreme you just stash the builtin <code>__import__</code> somewhere else and replace it with your function that does all the checks you want before delegating to the <code>__builtin__</code>; that's maybe 20 lines of code, 30 minutes to implement and test thoroughly... but it might not protect you for long if somebody credibly offered <em>me</em> a million bucks to break into your system (and, hypothetically, I wasn't the goody-two-shoes kind of guy I actually AM, of course;-). At the other extreme you deploy an in-depth series of layers of defense that might take thousands of lines and weeks of implementation and testing work -- given that kind of resource budget I could surely implement something <em>I</em> would be unable to penetrate (but there's always the risk that somebody ELSE is smarter and more Python-savvy than I am, of course!).</p> <p>So, how deep do you want to go, or rather, how deep can you AFFORD to go...?</p>
5
2009-08-29T04:59:50Z
[ "python", "module", "sandbox" ]
Preventing Python code from importing certain modules?
1,350,466
<p>I'm writing an application where users can enter a python script and execute it in a sandbox. I need a way to prevent the exec'ed code from importing certain modules, so malicious code won't be as much of a problem. Is there a way to do this in Python?</p>
7
2009-08-29T04:39:33Z
1,350,574
<p>If you put None in sys.modules for a module name, in won't be importable...</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; import os &gt;&gt;&gt; del os &gt;&gt;&gt; sys.modules['os']=None &gt;&gt;&gt; import os Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named os &gt;&gt;&gt; </code></pre>
13
2009-08-29T05:35:31Z
[ "python", "module", "sandbox" ]
"Inner exception" (with traceback) in Python?
1,350,671
<p>My background is in C# and I've just recently started programming in Python. When an exception is thrown I typically want to wrap it in another exception that adds more information, while still showing the full stack trace. It's quite easy in C#, but how do I do it in Python?</p> <p>Eg. in C# I would do something like this:</p> <pre><code>try { ProcessFile(filePath); } catch (Exception ex) { throw new ApplicationException("Failed to process file " + filePath, ex); } </code></pre> <p>In Python I can do something similar:</p> <pre><code>try: ProcessFile(filePath) except Exception as e: raise Exception('Failed to process file ' + filePath, e) </code></pre> <p>...but this loses the traceback of the inner exception!</p> <p><strong>Edit:</strong> I'd like to see both exception messages and both stack traces and correlate the two. That is, I want to see in the output that exception X occurred here and then exception Y there - same as I would in C#. Is this possible in Python 2.6? Looks like the best I can do so far (based on Glenn Maynard's answer) is:</p> <pre><code>try: ProcessFile(filePath) except Exception as e: raise Exception('Failed to process file' + filePath, e), None, sys.exc_info()[2] </code></pre> <p>This includes both the messages and both the tracebacks, but it doesn't show which exception occurred where in the traceback.</p>
86
2009-08-29T06:35:17Z
1,350,692
<p>I don't think you can do this in Python 2.x, but something similar to this functionality is part of Python 3. From <a href="http://www.python.org/dev/peps/pep-3134/" rel="nofollow">PEP 3134</a>:</p> <blockquote> <p>In today's Python implementation, exceptions are composed of three parts: the type, the value, and the traceback. The 'sys' module, exposes the current exception in three parallel variables, exc_type, exc_value, and exc_traceback, the sys.exc_info() function returns a tuple of these three parts, and the 'raise' statement has a three-argument form accepting these three parts. Manipulating exceptions often requires passing these three things in parallel, which can be tedious and error-prone. Additionally, the 'except' statement can only provide access to the value, not the traceback. Adding the '<strong>traceback</strong>' attribute to exception values makes all the exception information accessible from a single place.</p> </blockquote> <p>Comparison to C#:</p> <blockquote> <p>Exceptions in C# contain a read-only 'InnerException' property that may point to another exception. Its documentation [10] says that "When an exception X is thrown as a direct result of a previous exception Y, the InnerException property of X should contain a reference to Y." This property is not set by the VM automatically; rather, all exception constructors take an optional 'innerException' argument to set it explicitly. The '<strong>cause</strong>' attribute fulfills the same purpose as InnerException, but this PEP proposes a new form of 'raise' rather than extending the constructors of all exceptions. C# also provides a GetBaseException method that jumps directly to the end of the InnerException chain; this PEP proposes no analog.</p> </blockquote> <p>Note also that Java, Ruby and Perl 5 don't support this type of thing either. Quoting again:</p> <blockquote> <p>As for other languages, Java and Ruby both discard the original exception when another exception occurs in a 'catch'/'rescue' or 'finally'/'ensure' clause. Perl 5 lacks built-in structured exception handling. For Perl 6, RFC number 88 [9] proposes an exception mechanism that implicitly retains chained exceptions in an array named @@.</p> </blockquote>
4
2009-08-29T06:49:47Z
[ "python", "exception", "error-handling" ]
"Inner exception" (with traceback) in Python?
1,350,671
<p>My background is in C# and I've just recently started programming in Python. When an exception is thrown I typically want to wrap it in another exception that adds more information, while still showing the full stack trace. It's quite easy in C#, but how do I do it in Python?</p> <p>Eg. in C# I would do something like this:</p> <pre><code>try { ProcessFile(filePath); } catch (Exception ex) { throw new ApplicationException("Failed to process file " + filePath, ex); } </code></pre> <p>In Python I can do something similar:</p> <pre><code>try: ProcessFile(filePath) except Exception as e: raise Exception('Failed to process file ' + filePath, e) </code></pre> <p>...but this loses the traceback of the inner exception!</p> <p><strong>Edit:</strong> I'd like to see both exception messages and both stack traces and correlate the two. That is, I want to see in the output that exception X occurred here and then exception Y there - same as I would in C#. Is this possible in Python 2.6? Looks like the best I can do so far (based on Glenn Maynard's answer) is:</p> <pre><code>try: ProcessFile(filePath) except Exception as e: raise Exception('Failed to process file' + filePath, e), None, sys.exc_info()[2] </code></pre> <p>This includes both the messages and both the tracebacks, but it doesn't show which exception occurred where in the traceback.</p>
86
2009-08-29T06:35:17Z
1,350,885
<p>Maybe you could grab the relevant information and pass it up? I'm thinking something like:</p> <pre><code>import traceback import sys import StringIO class ApplicationError: def __init__(self, value, e): s = StringIO.StringIO() traceback.print_exc(file=s) self.value = (value, s.getvalue()) def __str__(self): return repr(self.value) try: try: a = 1/0 except Exception, e: raise ApplicationError("Failed to process file", e) except Exception, e: print e </code></pre>
3
2009-08-29T08:51:09Z
[ "python", "exception", "error-handling" ]
"Inner exception" (with traceback) in Python?
1,350,671
<p>My background is in C# and I've just recently started programming in Python. When an exception is thrown I typically want to wrap it in another exception that adds more information, while still showing the full stack trace. It's quite easy in C#, but how do I do it in Python?</p> <p>Eg. in C# I would do something like this:</p> <pre><code>try { ProcessFile(filePath); } catch (Exception ex) { throw new ApplicationException("Failed to process file " + filePath, ex); } </code></pre> <p>In Python I can do something similar:</p> <pre><code>try: ProcessFile(filePath) except Exception as e: raise Exception('Failed to process file ' + filePath, e) </code></pre> <p>...but this loses the traceback of the inner exception!</p> <p><strong>Edit:</strong> I'd like to see both exception messages and both stack traces and correlate the two. That is, I want to see in the output that exception X occurred here and then exception Y there - same as I would in C#. Is this possible in Python 2.6? Looks like the best I can do so far (based on Glenn Maynard's answer) is:</p> <pre><code>try: ProcessFile(filePath) except Exception as e: raise Exception('Failed to process file' + filePath, e), None, sys.exc_info()[2] </code></pre> <p>This includes both the messages and both the tracebacks, but it doesn't show which exception occurred where in the traceback.</p>
86
2009-08-29T06:35:17Z
1,350,972
<p>In <strong>Python 3.x</strong>:</p> <pre><code>raise Exception('Failed to process file ' + filePath).with_traceback(e.__traceback__) </code></pre> <p><strong>or</strong> simply </p> <pre><code>except Exception: raise MyException() </code></pre> <p>which will propagate <code>MyException</code> but print <strong>both</strong> exceptions if it will not be handled.</p> <p>In <strong>Python 2.x</strong>:</p> <pre><code>raise Exception, 'Failed to process file ' + filePath, e </code></pre> <p><hr /></p> <p>You can prevent printing both exceptions by killing the <code>__context__</code> attribute. Here I write a context manager using that to catch and change your exception on the fly: (see <a href="http://docs.python.org/3.1/library/stdtypes.html">http://docs.python.org/3.1/library/stdtypes.html</a> for expanation of how they work) </p> <pre><code>try: # Wrap the whole program into the block that will kill __context__. class Catcher(Exception): '''This context manager reraises an exception under a different name.''' def __init__(self, name): super().__init__('Failed to process code in {!r}'.format(name)) def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): if exc_type is not None: self.__traceback__ = exc_tb raise self ... with Catcher('class definition'): class a: def spam(self): # not really pass, but you get the idea pass lut = [1, 3, 17, [12,34], 5, _spam] assert a().lut[-1] == a.spam ... except Catcher as e: e.__context__ = None raise </code></pre>
6
2009-08-29T09:36:19Z
[ "python", "exception", "error-handling" ]
"Inner exception" (with traceback) in Python?
1,350,671
<p>My background is in C# and I've just recently started programming in Python. When an exception is thrown I typically want to wrap it in another exception that adds more information, while still showing the full stack trace. It's quite easy in C#, but how do I do it in Python?</p> <p>Eg. in C# I would do something like this:</p> <pre><code>try { ProcessFile(filePath); } catch (Exception ex) { throw new ApplicationException("Failed to process file " + filePath, ex); } </code></pre> <p>In Python I can do something similar:</p> <pre><code>try: ProcessFile(filePath) except Exception as e: raise Exception('Failed to process file ' + filePath, e) </code></pre> <p>...but this loses the traceback of the inner exception!</p> <p><strong>Edit:</strong> I'd like to see both exception messages and both stack traces and correlate the two. That is, I want to see in the output that exception X occurred here and then exception Y there - same as I would in C#. Is this possible in Python 2.6? Looks like the best I can do so far (based on Glenn Maynard's answer) is:</p> <pre><code>try: ProcessFile(filePath) except Exception as e: raise Exception('Failed to process file' + filePath, e), None, sys.exc_info()[2] </code></pre> <p>This includes both the messages and both the tracebacks, but it doesn't show which exception occurred where in the traceback.</p>
86
2009-08-29T06:35:17Z
1,350,981
<p>It's simple; pass the traceback as the third argument to raise.</p> <pre><code>import sys class MyException(Exception): pass try: raise TypeError("test") except TypeError, e: raise MyException(), None, sys.exc_info()[2] </code></pre> <p>Always do this when catching one exception and re-raising another.</p>
97
2009-08-29T09:41:33Z
[ "python", "exception", "error-handling" ]
"Inner exception" (with traceback) in Python?
1,350,671
<p>My background is in C# and I've just recently started programming in Python. When an exception is thrown I typically want to wrap it in another exception that adds more information, while still showing the full stack trace. It's quite easy in C#, but how do I do it in Python?</p> <p>Eg. in C# I would do something like this:</p> <pre><code>try { ProcessFile(filePath); } catch (Exception ex) { throw new ApplicationException("Failed to process file " + filePath, ex); } </code></pre> <p>In Python I can do something similar:</p> <pre><code>try: ProcessFile(filePath) except Exception as e: raise Exception('Failed to process file ' + filePath, e) </code></pre> <p>...but this loses the traceback of the inner exception!</p> <p><strong>Edit:</strong> I'd like to see both exception messages and both stack traces and correlate the two. That is, I want to see in the output that exception X occurred here and then exception Y there - same as I would in C#. Is this possible in Python 2.6? Looks like the best I can do so far (based on Glenn Maynard's answer) is:</p> <pre><code>try: ProcessFile(filePath) except Exception as e: raise Exception('Failed to process file' + filePath, e), None, sys.exc_info()[2] </code></pre> <p>This includes both the messages and both the tracebacks, but it doesn't show which exception occurred where in the traceback.</p>
86
2009-08-29T06:35:17Z
6,246,394
<p>In python 3 you can do the following:</p> <pre><code>try: raise MyExceptionToBeWrapped("I have twisted my ankle") except MyExceptionToBeWrapped as e: raise MyWrapperException("I'm not in a good shape") from e </code></pre> <p>This will produce something like this:</p> <pre><code>Traceback (most recent call last): ... MyExceptionToBeWrapped: ("I have twisted my ankle") The above exception was the direct cause of the following exception: Traceback (most recent call last): ... MyWrapperException: ("I'm not in a good shape") </code></pre>
105
2011-06-05T22:42:06Z
[ "python", "exception", "error-handling" ]
"Inner exception" (with traceback) in Python?
1,350,671
<p>My background is in C# and I've just recently started programming in Python. When an exception is thrown I typically want to wrap it in another exception that adds more information, while still showing the full stack trace. It's quite easy in C#, but how do I do it in Python?</p> <p>Eg. in C# I would do something like this:</p> <pre><code>try { ProcessFile(filePath); } catch (Exception ex) { throw new ApplicationException("Failed to process file " + filePath, ex); } </code></pre> <p>In Python I can do something similar:</p> <pre><code>try: ProcessFile(filePath) except Exception as e: raise Exception('Failed to process file ' + filePath, e) </code></pre> <p>...but this loses the traceback of the inner exception!</p> <p><strong>Edit:</strong> I'd like to see both exception messages and both stack traces and correlate the two. That is, I want to see in the output that exception X occurred here and then exception Y there - same as I would in C#. Is this possible in Python 2.6? Looks like the best I can do so far (based on Glenn Maynard's answer) is:</p> <pre><code>try: ProcessFile(filePath) except Exception as e: raise Exception('Failed to process file' + filePath, e), None, sys.exc_info()[2] </code></pre> <p>This includes both the messages and both the tracebacks, but it doesn't show which exception occurred where in the traceback.</p>
86
2009-08-29T06:35:17Z
11,669,125
<p>Here is an answer straight from the docs: <a href="http://docs.python.org/tutorial/errors.html" rel="nofollow">http://docs.python.org/tutorial/errors.html</a></p> <p>Look at the the second code sample in the Raising Exceptions section(copied below):</p> <pre><code>try: raise NameError('HiThere') except NameError: print 'An exception flew by!' raise </code></pre> <p>The output:</p> <pre><code>An exception flew by! Traceback (most recent call last): File "&lt;stdin&gt;", line 2, in ? NameError: HiThere </code></pre> <p>It looks like the key piece is the simplified 'raise' keyword that stands alone. That will re-raise the Exception in the except block.</p>
0
2012-07-26T12:17:54Z
[ "python", "exception", "error-handling" ]
"Inner exception" (with traceback) in Python?
1,350,671
<p>My background is in C# and I've just recently started programming in Python. When an exception is thrown I typically want to wrap it in another exception that adds more information, while still showing the full stack trace. It's quite easy in C#, but how do I do it in Python?</p> <p>Eg. in C# I would do something like this:</p> <pre><code>try { ProcessFile(filePath); } catch (Exception ex) { throw new ApplicationException("Failed to process file " + filePath, ex); } </code></pre> <p>In Python I can do something similar:</p> <pre><code>try: ProcessFile(filePath) except Exception as e: raise Exception('Failed to process file ' + filePath, e) </code></pre> <p>...but this loses the traceback of the inner exception!</p> <p><strong>Edit:</strong> I'd like to see both exception messages and both stack traces and correlate the two. That is, I want to see in the output that exception X occurred here and then exception Y there - same as I would in C#. Is this possible in Python 2.6? Looks like the best I can do so far (based on Glenn Maynard's answer) is:</p> <pre><code>try: ProcessFile(filePath) except Exception as e: raise Exception('Failed to process file' + filePath, e), None, sys.exc_info()[2] </code></pre> <p>This includes both the messages and both the tracebacks, but it doesn't show which exception occurred where in the traceback.</p>
86
2009-08-29T06:35:17Z
12,279,514
<p>You could use my <a href="http://code.activestate.com/recipes/578252-python-exception-chains-or-trees/?in=user-4182236" rel="nofollow">CausedException class</a> to chain exceptions in Python 2.x (and even in Python 3 it can be useful in case you want to give more than one caught exception as cause to a newly raised exception). Maybe it can help you.</p>
3
2012-09-05T10:35:23Z
[ "python", "exception", "error-handling" ]
"Inner exception" (with traceback) in Python?
1,350,671
<p>My background is in C# and I've just recently started programming in Python. When an exception is thrown I typically want to wrap it in another exception that adds more information, while still showing the full stack trace. It's quite easy in C#, but how do I do it in Python?</p> <p>Eg. in C# I would do something like this:</p> <pre><code>try { ProcessFile(filePath); } catch (Exception ex) { throw new ApplicationException("Failed to process file " + filePath, ex); } </code></pre> <p>In Python I can do something similar:</p> <pre><code>try: ProcessFile(filePath) except Exception as e: raise Exception('Failed to process file ' + filePath, e) </code></pre> <p>...but this loses the traceback of the inner exception!</p> <p><strong>Edit:</strong> I'd like to see both exception messages and both stack traces and correlate the two. That is, I want to see in the output that exception X occurred here and then exception Y there - same as I would in C#. Is this possible in Python 2.6? Looks like the best I can do so far (based on Glenn Maynard's answer) is:</p> <pre><code>try: ProcessFile(filePath) except Exception as e: raise Exception('Failed to process file' + filePath, e), None, sys.exc_info()[2] </code></pre> <p>This includes both the messages and both the tracebacks, but it doesn't show which exception occurred where in the traceback.</p>
86
2009-08-29T06:35:17Z
13,018,468
<p>Python 3 has the <a href="https://docs.python.org/3/reference/simple_stmts.html#raise" rel="nofollow"><code>raise</code> ... <code>from</code> clause</a> to chain exceptions. <a href="http://stackoverflow.com/a/1350981/4794">Glenn's answer</a> is great for Python 2.7, but it only uses the original exception's traceback and throws away the error message and other details. Here are some examples in Python 2.7 that add context information from the current scope into the original exception's error message, but keep other details intact.</p> <h2>Known Exception Type</h2> <pre><code>try: sock_common = xmlrpclib.ServerProxy(rpc_url+'/common') self.user_id = sock_common.login(self.dbname, username, self.pwd) except IOError: _, ex, traceback = sys.exc_info() message = "Connecting to '%s': %s." % (config['connection'], ex.strerror) raise IOError, (ex.errno, message), traceback </code></pre> <p>That flavour of <a href="http://docs.python.org/reference/simple_stmts.html#the-raise-statement" rel="nofollow"><code>raise</code> statement</a> takes the exception type as the first expression, the exception class constructor arguments in a tuple as the second expression, and the traceback as the third expression. If you're running earlier than Python 2.2, see the warnings on <a href="http://docs.python.org/library/sys.html#sys.exc_info" rel="nofollow"><code>sys.exc_info()</code></a>.</p> <h2>Any Exception Type</h2> <p>Here's another example that's more general purpose if you don't know what kind of exceptions your code might have to catch. The downside is that it loses the exception type and just raises a RuntimeError. You have to import the <code>traceback</code> module.</p> <pre><code>except Exception: extype, ex, tb = sys.exc_info() formatted = traceback.format_exception_only(extype, ex)[-1] message = "Importing row %d, %s" % (rownum, formatted) raise RuntimeError, message, tb </code></pre> <h2>Modify the Message</h2> <p>Here's another option if the exception type will let you add context to it. You can modify the exception's message and then reraise it.</p> <pre><code>import subprocess try: final_args = ['lsx', '/home'] s = subprocess.check_output(final_args) except OSError as ex: ex.strerror += ' for command {}'.format(final_args) raise </code></pre> <p>That generates the following stack trace:</p> <pre><code>Traceback (most recent call last): File "/mnt/data/don/workspace/scratch/scratch.py", line 5, in &lt;module&gt; s = subprocess.check_output(final_args) File "/usr/lib/python2.7/subprocess.py", line 566, in check_output process = Popen(stdout=PIPE, *popenargs, **kwargs) File "/usr/lib/python2.7/subprocess.py", line 710, in __init__ errread, errwrite) File "/usr/lib/python2.7/subprocess.py", line 1327, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory for command ['lsx', '/home'] </code></pre> <p>You can see that it shows the line where <code>check_output()</code> was called, but the exception message now includes the command line.</p>
8
2012-10-22T19:33:05Z
[ "python", "exception", "error-handling" ]
Tool for analysing and stepping through code?
1,350,864
<p>Recently I came across a tool which could analyse running python code and produced a visual representation similar to a code editor to allow one to step through the different parts of the code, seeing how many times each part was called, execution time, etc.</p> <p>I can't find the reference to it again. Would anyone know what it might be? </p>
2
2009-08-29T08:37:59Z
1,350,869
<p><a href="http://www.netbeans.org/features/python/index.html" rel="nofollow">NetBeans</a> with python plug-in?</p>
0
2009-08-29T08:42:34Z
[ "python", "code-analysis", "profiling" ]
Tool for analysing and stepping through code?
1,350,864
<p>Recently I came across a tool which could analyse running python code and produced a visual representation similar to a code editor to allow one to step through the different parts of the code, seeing how many times each part was called, execution time, etc.</p> <p>I can't find the reference to it again. Would anyone know what it might be? </p>
2
2009-08-29T08:37:59Z
1,350,872
<p><a href="http://pydoc.org/2.5.1/cProfile.html" rel="nofollow">cProfile</a> or <a href="http://docs.python.org/library/hotshot.html" rel="nofollow">Hotshot</a>.</p>
2
2009-08-29T08:44:08Z
[ "python", "code-analysis", "profiling" ]
Tool for analysing and stepping through code?
1,350,864
<p>Recently I came across a tool which could analyse running python code and produced a visual representation similar to a code editor to allow one to step through the different parts of the code, seeing how many times each part was called, execution time, etc.</p> <p>I can't find the reference to it again. Would anyone know what it might be? </p>
2
2009-08-29T08:37:59Z
1,350,889
<p><a href="http://www.vrplumber.com/programming/runsnakerun/" rel="nofollow"><strong>RunSnakeRun</strong></a> is user interface for cProfile/Hotshot (see <a href="http://stackoverflow.com/questions/1350864/tool-for-analysing-and-stepping-through-code/1350872#1350872">James' answer</a>), which also provides a visualization of the profiling data.</p> <p>Another useful link might be the link to the <strong>PyCon2009 Talk <a href="http://us.pycon.org/2009/conference/schedule/event/15/" rel="nofollow">Introduction to Python Profiling (#65)</a></strong></p>
1
2009-08-29T08:53:20Z
[ "python", "code-analysis", "profiling" ]
Tool for analysing and stepping through code?
1,350,864
<p>Recently I came across a tool which could analyse running python code and produced a visual representation similar to a code editor to allow one to step through the different parts of the code, seeing how many times each part was called, execution time, etc.</p> <p>I can't find the reference to it again. Would anyone know what it might be? </p>
2
2009-08-29T08:37:59Z
1,351,373
<p>Maybe <a href="http://pycallgraph.slowchop.com/" rel="nofollow">Python Call Graph</a>?</p>
0
2009-08-29T12:55:05Z
[ "python", "code-analysis", "profiling" ]
Tool for analysing and stepping through code?
1,350,864
<p>Recently I came across a tool which could analyse running python code and produced a visual representation similar to a code editor to allow one to step through the different parts of the code, seeing how many times each part was called, execution time, etc.</p> <p>I can't find the reference to it again. Would anyone know what it might be? </p>
2
2009-08-29T08:37:59Z
1,352,647
<p>Found what I was looking for: <a href="http://codeinvestigator.googlepages.com/main" rel="nofollow">Code Investigator</a></p> <blockquote> <p>CodeInvestigator is a tracing tool for Python programs. All run time information is recorded. Read your code together with its run time details in a Firefox browser. See what your program did when it ran.</p> </blockquote>
1
2009-08-29T23:37:54Z
[ "python", "code-analysis", "profiling" ]
Python: Is there a place when I can put default imports for all my modules?
1,350,887
<p>Is there a place when I can put default imports for all my modules?</p>
1
2009-08-29T08:52:21Z
1,350,906
<p>Yes, just create a separate module and import it into yours.</p> <p>Example:</p> <pre><code># my_imports.py '''Here go all of my imports''' import sys import functools from contextlib import contextmanager # This is a long name, no chance to confuse it. .... # something1.py '''One of my project files.''' from my_imports import * .... # something2.py '''Another project file.''' from my_imports import * .... </code></pre> <p>Note that according to standard guidelines, <strong><code>from module import *</code> should be avoided</strong>. If you're managing a small project with several files that need common imports, I think you'll be fine with <code>from module import *</code>, but it still would be <strong>a better idea to refactor your code</strong> so that different files need different imports.</p> <p>So do it like this:</p> <pre><code># something1.py '''One of my project files. Takes care of main cycle.''' import sys .... # something2.py '''Another project file. Main program logic.''' import functools from contextlib import contextmanager # This is a long name, no chance to confuse it. .... </code></pre>
3
2009-08-29T09:03:05Z
[ "python" ]
Python: Is there a place when I can put default imports for all my modules?
1,350,887
<p>Is there a place when I can put default imports for all my modules?</p>
1
2009-08-29T08:52:21Z
33,278,074
<p>If you want default imports when using the python shell you can also set the <code>PYTHONSTARTUP</code> environmental variable to point to a python file that will be executed whenever you start the shell. Put all your default imports in this file.</p>
2
2015-10-22T09:47:25Z
[ "python" ]
How to import XSD schema with Python Suds (version 0.3.6) SOAP library : TypeNotFound exception?
1,351,125
<p>I'm trying to use SABRE travel web services with Python Suds, but one XSD seems not well-formed (maybe namespace is missing in this schema).</p> <pre><code> from suds.client import Client wsdl = 'http://webservices.sabre.com/wsdl/sabreXML1.0.00/tpf/OTA_AirPriceLLSRQ.wsdl' client = Client(wsdl, cache=None) </code></pre> <p>Debug trace returns :</p> <pre><code> .DEBUG:suds.wsdl:reading wsdl at: http://webservices.sabre.com/wsdl/sabreXML1.0.00/tpf/OTA_AirPriceLLSRQ.wsdl ... DEBUG:suds.transport.http:opening (http://webservices.sabre.com/wsdl/sabreXML1.0.00/tpf/OTA_AirPriceLLSRQ.wsdl) DEBUG:suds.metrics:sax (http://webservices.sabre.com/wsdl/sabreXML1.0.00/tpf/OTA_AirPriceLLSRQ.wsdl) duration: 406 (ms) DEBUG:suds.xsd.sxbasic:Import:0x7f90196fd5f0, importing ns="http://webservices.sabre.com/sabreXML/2003/07", location="OTA_AirPriceLLSRQRS.xsd" DEBUG:suds.transport.http:opening (http://webservices.sabre.com/wsdl/sabreXML1.0.00/tpf/OTA_AirPriceLLSRQRS.xsd) DEBUG:suds.metrics:sax (http://webservices.sabre.com/wsdl/sabreXML1.0.00/tpf/OTA_AirPriceLLSRQRS.xsd) duration: 504 (ms) DEBUG:suds.xsd.sxbasic:Include:0x7f90196fdf80, importing ns="None", location="OTA_AirPriceLLSRQ.xsd" DEBUG:suds.transport.http:opening (http://webservices.sabre.com/wsdl/sabreXML1.0.00/tpf/OTA_AirPriceLLSRQ.xsd) DEBUG:suds.metrics:sax (http://webservices.sabre.com/wsdl/sabreXML1.0.00/tpf/OTA_AirPriceLLSRQ.xsd) duration: 1.363 (seconds) DEBUG:suds.xsd.schema:built: Schema:0x7f9019708e60 (...) DEBUG:suds.xsd.query:(u'MessageHeader', http://www.ebxml.org/namespaces/messageHeader), found as: DEBUG:suds.xsd.query:(u'Security', http://schemas.xmlsoap.org/ws/2002/12/secext), found as: DEBUG:suds.xsd.query:(u'OTA_AirPriceRQ', http://webservices.sabre.com/sabreXML/2003/07), not-found . ---------------------------------------------------------------------- Ran 2 tests in 11.669s Type not found: '(OTA_AirPriceRQ, http://webservices.sabre.com/sabreXML/2003/07, )' </code></pre> <p>It's logic : Python Suds loads OTA_AirPriceRQ in a "None" namespace. I read "fix broken schema" Python Suds documentation (<a href="https://fedorahosted.org/suds/wiki/Documentation#FIXINGBROKENSCHEMAs">https://fedorahosted.org/suds/wiki/Documentation#FIXINGBROKENSCHEMAs</a>):</p> <pre><code> from suds.client import Client from suds.xsd.doctor import ImportDoctor, Import wsdl = 'http://webservices.sabre.com/wsdl/sabreXML1.0.00/tpf/OTA_AirPriceLLSRQ.wsdl' imp = Import('http://webservices.sabre.com/sabreXML/2003/07/OTA_AirPriceLLSRQ', 'http://webservices.sabre.com/wsdl/sabreXML1.0.00/tpf/OTA_AirPriceLLSRQ.xsd') d = ImportDoctor(imp) client = Client(wsdl, cache=None, doctor=d) </code></pre> <p>But script return another exception :</p> <pre><code> .DEBUG:suds.wsdl:reading wsdl at: http://webservices.sabre.com/wsdl/sabreXML1.0.00/tpf/OTA_AirPriceLLSRQ.wsdl ... DEBUG:suds.transport.http:opening (http://webservices.sabre.com/wsdl/sabreXML1.0.00/tpf/OTA_AirPriceLLSRQ.wsdl) DEBUG:suds.metrics:sax (http://webservices.sabre.com/wsdl/sabreXML1.0.00/tpf/OTA_AirPriceLLSRQ.wsdl) duration: 617 (ms) DEBUG:suds.xsd.doctor:inserting: DEBUG:suds.xsd.sxbasic:Import:0xe6cf80, importing ns="http://webservices.sabre.com/sabreXML/2003/07/OTA_AirPriceLLSRQ", location="http://webservices.sabre.com/wsdl/sabreXML1.0.00/tpf/OTA_AirPriceLLSRQ.xsd" DEBUG:suds.transport.http:opening (http://webservices.sabre.com/wsdl/sabreXML1.0.00/tpf/OTA_AirPriceLLSRQ.xsd) DEBUG:suds.metrics:sax (http://webservices.sabre.com/wsdl/sabreXML1.0.00/tpf/OTA_AirPriceLLSRQ.xsd) duration: 1.375 (seconds) DEBUG:suds.xsd.doctor:inserting: (...) Error maximum recursion depth exceeded while calling a Python object </code></pre> <p>I don't understand how to use "doctor" functions. Somebody can help me, please ? Thank you.</p>
9
2009-08-29T10:47:41Z
3,282,657
<p>This looks like <a href="https://fedorahosted.org/suds/ticket/239" rel="nofollow">https://fedorahosted.org/suds/ticket/239</a> . I added your example to the ticket.</p>
1
2010-07-19T15:48:17Z
[ "python", "soap", "wsdl", "suds" ]
How to import XSD schema with Python Suds (version 0.3.6) SOAP library : TypeNotFound exception?
1,351,125
<p>I'm trying to use SABRE travel web services with Python Suds, but one XSD seems not well-formed (maybe namespace is missing in this schema).</p> <pre><code> from suds.client import Client wsdl = 'http://webservices.sabre.com/wsdl/sabreXML1.0.00/tpf/OTA_AirPriceLLSRQ.wsdl' client = Client(wsdl, cache=None) </code></pre> <p>Debug trace returns :</p> <pre><code> .DEBUG:suds.wsdl:reading wsdl at: http://webservices.sabre.com/wsdl/sabreXML1.0.00/tpf/OTA_AirPriceLLSRQ.wsdl ... DEBUG:suds.transport.http:opening (http://webservices.sabre.com/wsdl/sabreXML1.0.00/tpf/OTA_AirPriceLLSRQ.wsdl) DEBUG:suds.metrics:sax (http://webservices.sabre.com/wsdl/sabreXML1.0.00/tpf/OTA_AirPriceLLSRQ.wsdl) duration: 406 (ms) DEBUG:suds.xsd.sxbasic:Import:0x7f90196fd5f0, importing ns="http://webservices.sabre.com/sabreXML/2003/07", location="OTA_AirPriceLLSRQRS.xsd" DEBUG:suds.transport.http:opening (http://webservices.sabre.com/wsdl/sabreXML1.0.00/tpf/OTA_AirPriceLLSRQRS.xsd) DEBUG:suds.metrics:sax (http://webservices.sabre.com/wsdl/sabreXML1.0.00/tpf/OTA_AirPriceLLSRQRS.xsd) duration: 504 (ms) DEBUG:suds.xsd.sxbasic:Include:0x7f90196fdf80, importing ns="None", location="OTA_AirPriceLLSRQ.xsd" DEBUG:suds.transport.http:opening (http://webservices.sabre.com/wsdl/sabreXML1.0.00/tpf/OTA_AirPriceLLSRQ.xsd) DEBUG:suds.metrics:sax (http://webservices.sabre.com/wsdl/sabreXML1.0.00/tpf/OTA_AirPriceLLSRQ.xsd) duration: 1.363 (seconds) DEBUG:suds.xsd.schema:built: Schema:0x7f9019708e60 (...) DEBUG:suds.xsd.query:(u'MessageHeader', http://www.ebxml.org/namespaces/messageHeader), found as: DEBUG:suds.xsd.query:(u'Security', http://schemas.xmlsoap.org/ws/2002/12/secext), found as: DEBUG:suds.xsd.query:(u'OTA_AirPriceRQ', http://webservices.sabre.com/sabreXML/2003/07), not-found . ---------------------------------------------------------------------- Ran 2 tests in 11.669s Type not found: '(OTA_AirPriceRQ, http://webservices.sabre.com/sabreXML/2003/07, )' </code></pre> <p>It's logic : Python Suds loads OTA_AirPriceRQ in a "None" namespace. I read "fix broken schema" Python Suds documentation (<a href="https://fedorahosted.org/suds/wiki/Documentation#FIXINGBROKENSCHEMAs">https://fedorahosted.org/suds/wiki/Documentation#FIXINGBROKENSCHEMAs</a>):</p> <pre><code> from suds.client import Client from suds.xsd.doctor import ImportDoctor, Import wsdl = 'http://webservices.sabre.com/wsdl/sabreXML1.0.00/tpf/OTA_AirPriceLLSRQ.wsdl' imp = Import('http://webservices.sabre.com/sabreXML/2003/07/OTA_AirPriceLLSRQ', 'http://webservices.sabre.com/wsdl/sabreXML1.0.00/tpf/OTA_AirPriceLLSRQ.xsd') d = ImportDoctor(imp) client = Client(wsdl, cache=None, doctor=d) </code></pre> <p>But script return another exception :</p> <pre><code> .DEBUG:suds.wsdl:reading wsdl at: http://webservices.sabre.com/wsdl/sabreXML1.0.00/tpf/OTA_AirPriceLLSRQ.wsdl ... DEBUG:suds.transport.http:opening (http://webservices.sabre.com/wsdl/sabreXML1.0.00/tpf/OTA_AirPriceLLSRQ.wsdl) DEBUG:suds.metrics:sax (http://webservices.sabre.com/wsdl/sabreXML1.0.00/tpf/OTA_AirPriceLLSRQ.wsdl) duration: 617 (ms) DEBUG:suds.xsd.doctor:inserting: DEBUG:suds.xsd.sxbasic:Import:0xe6cf80, importing ns="http://webservices.sabre.com/sabreXML/2003/07/OTA_AirPriceLLSRQ", location="http://webservices.sabre.com/wsdl/sabreXML1.0.00/tpf/OTA_AirPriceLLSRQ.xsd" DEBUG:suds.transport.http:opening (http://webservices.sabre.com/wsdl/sabreXML1.0.00/tpf/OTA_AirPriceLLSRQ.xsd) DEBUG:suds.metrics:sax (http://webservices.sabre.com/wsdl/sabreXML1.0.00/tpf/OTA_AirPriceLLSRQ.xsd) duration: 1.375 (seconds) DEBUG:suds.xsd.doctor:inserting: (...) Error maximum recursion depth exceeded while calling a Python object </code></pre> <p>I don't understand how to use "doctor" functions. Somebody can help me, please ? Thank you.</p>
9
2009-08-29T10:47:41Z
4,395,481
<p>I just posted a workaround to that Suds ticket. You may want to check it out: <a href="https://fedorahosted.org/suds/ticket/239#comment:19" rel="nofollow">https://fedorahosted.org/suds/ticket/239#comment:19</a></p> <p>Briefly, here's the workaround code:</p> <pre><code>from suds.client import Client import sys sys.setrecursionlimit(10000) c = Client('http://url.to/endpoint?wsdl', cache=None) </code></pre>
3
2010-12-09T06:26:35Z
[ "python", "soap", "wsdl", "suds" ]
Compiling a py2app working build for both Leopard and Snow Leopard?
1,351,209
<p>I currently am making my PyObjC application work for Snow Leopard and I successfully compiled a standalone app. My question would be, how do I make the build to be also Leopard-compatible, given these errors?</p> <pre><code>dyld: lazy symbol binding failed: Symbol not found: _fopen$UNIX2003 Referenced from: /Applications/MyApp.app/Contents/MacOS/MyApp Expected in: /usr/lib/libSystem.B.dylib dyld: Symbol not found: _fopen$UNIX2003 Referenced from: /Applications/MyApp.app/Contents/MacOS/MyApp Expected in: /usr/lib/libSystem.B.dylib </code></pre> <p>This is a Snow Leopard-compiled py2app application. Also, when I compile on Leopard, on the other hand, this error occurs:</p> <pre><code>Traceback (most recent call last): File "/Users/jofell/client/dist/MyApp.app/Contents/Resources/__boot__.py", line 31, in &lt;module&gt; _run('main.py') File "/Users/jofell/client/dist/MyApp.app/Contents/Resources/__boot__.py", line 28, in _run execfile(path, globals(), globals()) File "/Users/jofell/client/dist/MyApp.app/Contents/Resources/main.py", line 17, in &lt;module&gt; from AppKit import * File "AppKit/__init__.pyc", line 10, in &lt;module&gt; File "Foundation/__init__.pyc", line 10, in &lt;module&gt; File "CoreFoundation/__init__.pyc", line 17, in &lt;module&gt; File "objc/_bridgesupport.pyc", line 129, in initFrameworkWrapper File "objc/_bridgesupport.pyc", line 53, in _parseBridgeSupport ValueError: Unknown typestr 2009-08-29 19:30:14.530 MyApp[445:903] MyApp Error 2009-08-29 19:30:14.534 MyApp[445:903] MyApp Error An unexpected error has occurred during execution of the main script </code></pre> <p>Any help would be appreciated. Thanks in advance.</p>
6
2009-08-29T11:31:25Z
1,541,364
<p>Since both are on distinct architecture (respectively 32 bits and 64 bits) I think you have to create 2 distinct compilations.</p>
0
2009-10-09T01:08:17Z
[ "python", "osx-snow-leopard", "osx-leopard", "py2app" ]
Compiling a py2app working build for both Leopard and Snow Leopard?
1,351,209
<p>I currently am making my PyObjC application work for Snow Leopard and I successfully compiled a standalone app. My question would be, how do I make the build to be also Leopard-compatible, given these errors?</p> <pre><code>dyld: lazy symbol binding failed: Symbol not found: _fopen$UNIX2003 Referenced from: /Applications/MyApp.app/Contents/MacOS/MyApp Expected in: /usr/lib/libSystem.B.dylib dyld: Symbol not found: _fopen$UNIX2003 Referenced from: /Applications/MyApp.app/Contents/MacOS/MyApp Expected in: /usr/lib/libSystem.B.dylib </code></pre> <p>This is a Snow Leopard-compiled py2app application. Also, when I compile on Leopard, on the other hand, this error occurs:</p> <pre><code>Traceback (most recent call last): File "/Users/jofell/client/dist/MyApp.app/Contents/Resources/__boot__.py", line 31, in &lt;module&gt; _run('main.py') File "/Users/jofell/client/dist/MyApp.app/Contents/Resources/__boot__.py", line 28, in _run execfile(path, globals(), globals()) File "/Users/jofell/client/dist/MyApp.app/Contents/Resources/main.py", line 17, in &lt;module&gt; from AppKit import * File "AppKit/__init__.pyc", line 10, in &lt;module&gt; File "Foundation/__init__.pyc", line 10, in &lt;module&gt; File "CoreFoundation/__init__.pyc", line 17, in &lt;module&gt; File "objc/_bridgesupport.pyc", line 129, in initFrameworkWrapper File "objc/_bridgesupport.pyc", line 53, in _parseBridgeSupport ValueError: Unknown typestr 2009-08-29 19:30:14.530 MyApp[445:903] MyApp Error 2009-08-29 19:30:14.534 MyApp[445:903] MyApp Error An unexpected error has occurred during execution of the main script </code></pre> <p>Any help would be appreciated. Thanks in advance.</p>
6
2009-08-29T11:31:25Z
1,758,020
<p>Try the following:</p> <p><a href="http://groups.google.com/group/wxpython-users/browse%5Fthread/thread/916fa0569bfa3efd/9d16f540a89cc4c3?lnk=gst&amp;q=py2app#9d16f540a89cc4c3" rel="nofollow">http://groups.google.com/group/wxpython-users/browse%5Fthread/thread/916fa0569bfa3efd/9d16f540a89cc4c3?lnk=gst&amp;q=py2app#9d16f540a89cc4c3</a></p>
0
2009-11-18T18:18:59Z
[ "python", "osx-snow-leopard", "osx-leopard", "py2app" ]
Compiling a py2app working build for both Leopard and Snow Leopard?
1,351,209
<p>I currently am making my PyObjC application work for Snow Leopard and I successfully compiled a standalone app. My question would be, how do I make the build to be also Leopard-compatible, given these errors?</p> <pre><code>dyld: lazy symbol binding failed: Symbol not found: _fopen$UNIX2003 Referenced from: /Applications/MyApp.app/Contents/MacOS/MyApp Expected in: /usr/lib/libSystem.B.dylib dyld: Symbol not found: _fopen$UNIX2003 Referenced from: /Applications/MyApp.app/Contents/MacOS/MyApp Expected in: /usr/lib/libSystem.B.dylib </code></pre> <p>This is a Snow Leopard-compiled py2app application. Also, when I compile on Leopard, on the other hand, this error occurs:</p> <pre><code>Traceback (most recent call last): File "/Users/jofell/client/dist/MyApp.app/Contents/Resources/__boot__.py", line 31, in &lt;module&gt; _run('main.py') File "/Users/jofell/client/dist/MyApp.app/Contents/Resources/__boot__.py", line 28, in _run execfile(path, globals(), globals()) File "/Users/jofell/client/dist/MyApp.app/Contents/Resources/main.py", line 17, in &lt;module&gt; from AppKit import * File "AppKit/__init__.pyc", line 10, in &lt;module&gt; File "Foundation/__init__.pyc", line 10, in &lt;module&gt; File "CoreFoundation/__init__.pyc", line 17, in &lt;module&gt; File "objc/_bridgesupport.pyc", line 129, in initFrameworkWrapper File "objc/_bridgesupport.pyc", line 53, in _parseBridgeSupport ValueError: Unknown typestr 2009-08-29 19:30:14.530 MyApp[445:903] MyApp Error 2009-08-29 19:30:14.534 MyApp[445:903] MyApp Error An unexpected error has occurred during execution of the main script </code></pre> <p>Any help would be appreciated. Thanks in advance.</p>
6
2009-08-29T11:31:25Z
2,043,657
<p>I've done this recently and the trick was to build a <strong>standalone</strong> version on a <strong>Leopard</strong> installation.</p> <p>By default, unless you have an open source version of Python installed, py2app creates a <strong>semi-standalone</strong> application that has symlinks to the OS files.</p> <p>If instead, you create a standalone version of the application, then the interpreter and supporting files are embedded within your application and are therefore consistent on all machines running your application. Instructions on creating a fully standalone application are available <a href="http://aralbalkan.com/1675" rel="nofollow">here</a>, but pay attention to the blog's comments as some things did change after the blog post was written.</p> <p>If you have specific libs that you need you can reference them in the setup.py file or alternatively you can always add them manually to the dylib directory (which was easier for me as I needed to change the startup scripts and didn't want to regenerate), but make sure you use the 32-bit libs (which it will be on Leopard).</p>
3
2010-01-11T17:42:56Z
[ "python", "osx-snow-leopard", "osx-leopard", "py2app" ]
What are some of the core conceptual differences between C# and Python?
1,351,227
<p>I'm new to Python, coming from a C# background and I'm trying to get up to speed. <strike>I understand that Python is dynamically typed, whereas C# is strongly-typed.</strike> -> see comments. What conceptual obstacles should I watch out for when attempting to learn Python? Are there concepts for which no analog exists in Python? How important is object-oriented analysis? </p> <p>I believe answers to these and any other questions you might be able to think of would speed up my understanding Python besides the Nike mentality ("just do it")?</p> <p>A little more context: My company is moving from ASP.NET C# Web Forms to Django. I've gone through the Django tutorial and it was truly great. I need to get up to speed in about 2 weeks time (ridiculous maybe? LOL)</p> <p>Thank you all for your time and efforts to respond to a realllly broad question(s).</p>
3
2009-08-29T11:39:35Z
1,351,287
<p>There are a lot of differences between C# and Python; rather than dwell on the individual differences, it's probably better just to look at how Python works using a guide such as <a href="http://www.diveintopython.org/" rel="nofollow">Dive Into Python</a>. And remember, while Python allows you to do OOP very well, it doesn't constrain you to OOP. There are times when just plain functions are good enough (Django views being a good example).</p> <p>There are also numerous conceptual differences between WebForms and Django. Django is more in tune with HTTP - there's no muddling of what happens client-side and what happens server-side. With a typical WebForms application, client side events often trigger server-side code using postbacks. Even with the ASP.NET Ajax framework, it's an environment which offers less control than you sometimes need. In Django, you achieve the same effect using client-side libraries using e.g. YUI or jQuery and make Ajax calls yourself. Even though that kind of approach doesn't hold your hand as much as say the ASP.NET approach, you should be more productive with Django and Python to make the latter an overall net positive. ASP.NET aims to make things more familiar for developers accustomed to WinForms and other desktop development environments; while this is a perfectly reasonable approach for Microsoft to have taken (and they're not the only ones - for example, Java has JSF), it's not really in tune with HTTP and REST to the same extent. For an example of this, just take a look at how constraining ASP.NET URLs are (pre ASP.NET MVC) as compared to Django URLs.</p> <p>Just my 2 cents' worth :-)</p>
3
2009-08-29T12:06:08Z
[ "c#", "asp.net", "python", "django", "programming-languages" ]
What are some of the core conceptual differences between C# and Python?
1,351,227
<p>I'm new to Python, coming from a C# background and I'm trying to get up to speed. <strike>I understand that Python is dynamically typed, whereas C# is strongly-typed.</strike> -> see comments. What conceptual obstacles should I watch out for when attempting to learn Python? Are there concepts for which no analog exists in Python? How important is object-oriented analysis? </p> <p>I believe answers to these and any other questions you might be able to think of would speed up my understanding Python besides the Nike mentality ("just do it")?</p> <p>A little more context: My company is moving from ASP.NET C# Web Forms to Django. I've gone through the Django tutorial and it was truly great. I need to get up to speed in about 2 weeks time (ridiculous maybe? LOL)</p> <p>Thank you all for your time and efforts to respond to a realllly broad question(s).</p>
3
2009-08-29T11:39:35Z
1,351,334
<p>The conceptual differences are important, but mostly in how they result in different attitudes. </p> <p>Most important of those are "duck typing". Ie, forget what type things are, you don't need to care. You only need to care about what attributes and methods objects have. "If it looks like a duck and walks like a duck, it's a duck". Usually, these attitude changes come naturally after a while.</p> <p>The biggest conceptual hurdles seems to be</p> <ol> <li><p>The significant indenting. But the only ones who hate it are people who have, or are forced to work with, people who change their editors tab expansion from something other than the default 8.</p></li> <li><p>No compiler, and hence no type testing at the compile stage. Many people coming from statically typed languages believe that the type checking during compilation finds many bugs. It doesn't, in my experience. </p></li> </ol>
1
2009-08-29T12:33:40Z
[ "c#", "asp.net", "python", "django", "programming-languages" ]
What are some of the core conceptual differences between C# and Python?
1,351,227
<p>I'm new to Python, coming from a C# background and I'm trying to get up to speed. <strike>I understand that Python is dynamically typed, whereas C# is strongly-typed.</strike> -> see comments. What conceptual obstacles should I watch out for when attempting to learn Python? Are there concepts for which no analog exists in Python? How important is object-oriented analysis? </p> <p>I believe answers to these and any other questions you might be able to think of would speed up my understanding Python besides the Nike mentality ("just do it")?</p> <p>A little more context: My company is moving from ASP.NET C# Web Forms to Django. I've gone through the Django tutorial and it was truly great. I need to get up to speed in about 2 weeks time (ridiculous maybe? LOL)</p> <p>Thank you all for your time and efforts to respond to a realllly broad question(s).</p>
3
2009-08-29T11:39:35Z
1,351,338
<h2>duck typing</h2> <p>I think the main thing that sets c#/java from python is that there is often no need for interfaces. This is because python has <a href="http://en.wikipedia.org/wiki/Duck%5Ftyping" rel="nofollow">ducktyping</a>. </p> <pre><code>class Duck(object): def quack(self): print "quack" class Cat(object): """Cat that specializes in hunting ducks""" def quack(self): print "quack" duck = Duck() cat = Cat() def quacker(something_that_quacks): something_that_quacks.quack() quacker(cat) #quack quacker(duck) #quack </code></pre> <p>As long as an object has the method quack its OK to use it to call quacker. Duck typing also makes design patterns more easy to implement. Because you don't need to write interfaces and make sure objects are of the same type.</p>
4
2009-08-29T12:34:31Z
[ "c#", "asp.net", "python", "django", "programming-languages" ]
What are some of the core conceptual differences between C# and Python?
1,351,227
<p>I'm new to Python, coming from a C# background and I'm trying to get up to speed. <strike>I understand that Python is dynamically typed, whereas C# is strongly-typed.</strike> -> see comments. What conceptual obstacles should I watch out for when attempting to learn Python? Are there concepts for which no analog exists in Python? How important is object-oriented analysis? </p> <p>I believe answers to these and any other questions you might be able to think of would speed up my understanding Python besides the Nike mentality ("just do it")?</p> <p>A little more context: My company is moving from ASP.NET C# Web Forms to Django. I've gone through the Django tutorial and it was truly great. I need to get up to speed in about 2 weeks time (ridiculous maybe? LOL)</p> <p>Thank you all for your time and efforts to respond to a realllly broad question(s).</p>
3
2009-08-29T11:39:35Z
1,351,664
<p>You said that Python is dynamically typed and C# is strongly typed but this isn't true. Strong vs. weak typing and static vs. dynamic typing are orthagonal. Strong typing means str + int doesn't coerce one of the opperands, so in this regard both Python and C# are strongly typed (whereas PHP or C is weakly typed). Python is dynamically typed which means names don't have a defined type at compile time, whereas in C# they do.</p>
2
2009-08-29T15:10:48Z
[ "c#", "asp.net", "python", "django", "programming-languages" ]
What are some of the core conceptual differences between C# and Python?
1,351,227
<p>I'm new to Python, coming from a C# background and I'm trying to get up to speed. <strike>I understand that Python is dynamically typed, whereas C# is strongly-typed.</strike> -> see comments. What conceptual obstacles should I watch out for when attempting to learn Python? Are there concepts for which no analog exists in Python? How important is object-oriented analysis? </p> <p>I believe answers to these and any other questions you might be able to think of would speed up my understanding Python besides the Nike mentality ("just do it")?</p> <p>A little more context: My company is moving from ASP.NET C# Web Forms to Django. I've gone through the Django tutorial and it was truly great. I need to get up to speed in about 2 weeks time (ridiculous maybe? LOL)</p> <p>Thank you all for your time and efforts to respond to a realllly broad question(s).</p>
3
2009-08-29T11:39:35Z
1,351,670
<p>" I understand that Python is dynamically typed, whereas C# is strongly-typed. "</p> <p>This is weirdly wrong.</p> <ol> <li><p>Python is strongly typed. A list or integer or dictionary is always of the given type. The object's type cannot be changed.</p></li> <li><p>Python variables are not strongly typed. Indeed, Python variables are just labels on objects. Variables are not declared; hence the description of Python as "dynamic". </p></li> <li><p>C# is statically typed. The variables are declared to the compiler to be of a specific type. The code is generated based on certain knowledge about the variables use at run-time.</p></li> </ol> <p>Python is "interpreted" -- things are done at run-time -- little is assumed. [Technically, the Python source is compiled into byte code and the byte code is interpreted. Some folks think this is an important distinction.]</p> <p>C# is compiled -- the compiler generates code based on the declared assumptions.</p> <p><hr /></p> <p><strong>What conceptual obstacles should I watch out for when attempting to learn Python?</strong></p> <p>None. If you insist that Python <em>should</em> be like something else; or you insist that something else is <em>more intuitive</em> then you've polluted your own thinking with inappropriate concepts.</p> <p>No programming language has obstacles. We bring our own obstacles when we impose things on the language.</p> <p><strong>Are there concepts for which no analog exists in Python?</strong></p> <p>Since Python has object-oriented, procedural and functional elements, you'd be hard-pressed to find something missing from Python.</p> <p><strong>How important is object-oriented analysis?</strong></p> <p>OO analysis helps all phases of software development -- even if you aren't doing an OO implementation. This is unrelated to Python and should be a separate question.</p> <p><strong>I need to get up to speed in about 2 weeks time (ridiculous maybe?)</strong></p> <p>Perhaps not. If you start with a fresh, open mind, then Python can be learned in a week or so of diligent work.</p> <p>If, on the other hand, you compare and contrast Python with C#, it can take you years to get past your C# bias and learn Python. Don't translate C# to Python. Don't translate Python to C#. </p> <p>Don't go to the well with a full bucket.</p>
9
2009-08-29T15:11:48Z
[ "c#", "asp.net", "python", "django", "programming-languages" ]
Object store for objects in Django between requests
1,351,323
<p>I had the following idea: Say we have a webapp written using django which models some kind of bulletin board. This board has many threads but a few of them get the most posts/views per hour. The thread pages look a little different for each user, so you can't cache the rendered page as whole and caching only some parts of the rendered page is also not an option.</p> <p>My idea was: I create an object structure of the thread in memory (with every post and other data that is needed to display it). If a new message is posted the structure is updated and every X posts (or every Y minutes, whatever comes first) the new messages are written back to the database. If the app crashes, some posts are lost, but this is definitely okay (for users and admins).</p> <p>The question: Can I create such a persistent in memory storage <strong>without serialization</strong> (so no serialize->memcached)? As I understand it, WSGI applications (like Django) run in a continuous process without shutting down between requests, so it should be possible in theory. Is there any API I could use? If not: any point to look?</p> <p>/edit1: I know that "persistent" usually has a different meaning, but in this case I strictly mean "in between request".</p>
5
2009-08-29T12:24:56Z
1,351,459
<p>An in memory storage is not persistent, so no. </p> <p>I think you mean that you only want to write to the database ever X new posts of objects. I guess this is for speedup reasons. But since you need to serialize them sooner or later anyway, you don't actually save any time that way. However, you will save time by not flushing the new objects to disk, but most databases already support that.</p> <p>But you also talk about caching the rendered page, which is read caching. There you can't cache the finished result you say, but you can cache the result of the database query. That means that new message will not be immediately updated, but take a minute or so to show up, but I think most people will see this as acceptable.</p> <p>Update: In this case not, then. But you should still easily be able to cache the query results, but invalidate that cache when new responses are added. That should help.</p>
0
2009-08-29T13:37:27Z
[ "python", "django" ]
Object store for objects in Django between requests
1,351,323
<p>I had the following idea: Say we have a webapp written using django which models some kind of bulletin board. This board has many threads but a few of them get the most posts/views per hour. The thread pages look a little different for each user, so you can't cache the rendered page as whole and caching only some parts of the rendered page is also not an option.</p> <p>My idea was: I create an object structure of the thread in memory (with every post and other data that is needed to display it). If a new message is posted the structure is updated and every X posts (or every Y minutes, whatever comes first) the new messages are written back to the database. If the app crashes, some posts are lost, but this is definitely okay (for users and admins).</p> <p>The question: Can I create such a persistent in memory storage <strong>without serialization</strong> (so no serialize->memcached)? As I understand it, WSGI applications (like Django) run in a continuous process without shutting down between requests, so it should be possible in theory. Is there any API I could use? If not: any point to look?</p> <p>/edit1: I know that "persistent" usually has a different meaning, but in this case I strictly mean "in between request".</p>
5
2009-08-29T12:24:56Z
1,352,415
<p>In a production WSGI environment, you would probably have multiple worker processes serving requests at the same time. These worker processes would be recycled from time to time, meaning local memory objects would be lost.</p> <p>But if you really need this (and make sure you do), I suggest you look into Django's <a href="http://docs.djangoproject.com/en/dev/topics/cache/" rel="nofollow">caching framework</a>, check out local-memory caching. Also, have a look at <a href="http://docs.djangoproject.com/en/dev/topics/http/sessions/" rel="nofollow">sessions</a>.</p> <p>But even the local-memory caching uses serialization (with <code>pickle</code>). It is easy to implement local-memory cache without serialization by implementing a custom cache back-end (see <a href="http://docs.djangoproject.com/en/dev/topics/cache/#using-a-custom-cache-backend" rel="nofollow">the docs</a>). You could use the code in <code>locmem.py</code> as a starting point to create a cache without serialization.</p> <p>But I suspect you are doing a bit of premature optimization here?</p>
5
2009-08-29T21:24:11Z
[ "python", "django" ]
How to make custom buttons in wx?
1,351,448
<p>I'd like to make a custom button in wxPython. Where should I start, how should I do it?</p>
4
2009-08-29T13:31:52Z
1,351,475
<p>You can extend the default button class, like this for example:</p> <pre><code>class RedButton(wx.Button): def __init__(self, *a, **k): wx.Button.__init__(self, *a, **k) self.SetBackgroundColour('RED') # more customization here </code></pre> <p>Every time you put a <code>RedButton</code> into your layout, it should appear red (haven't tested it though). </p>
3
2009-08-29T13:43:46Z
[ "python", "button", "wxpython" ]
How to make custom buttons in wx?
1,351,448
<p>I'd like to make a custom button in wxPython. Where should I start, how should I do it?</p>
4
2009-08-29T13:31:52Z
1,351,690
<p>Try using a <a href="http://www.wxpython.org/docs/api/wx.lib.buttons-module.html" rel="nofollow">Generic Button</a> or a <a href="http://www.wxpython.org/docs/api/wx.BitmapButton-class.html" rel="nofollow">Bitmap Button</a>.</p>
2
2009-08-29T15:19:49Z
[ "python", "button", "wxpython" ]
How to make custom buttons in wx?
1,351,448
<p>I'd like to make a custom button in wxPython. Where should I start, how should I do it?</p>
4
2009-08-29T13:31:52Z
1,351,727
<p>When I wanted to learn how to make custom widgets (buttons included) I referenced <a href="http://wiki.wxpython.org/CreatingCustomControls">Andrea Gavana's page</a> (full working example there) on the wxPyWiki and Cody Precord's platebutton (the source is in wx.lib.platebtn, also <a href="http://svn.wxwidgets.org/viewvc/wx/wxPython/trunk/wx/lib/platebtn.py?view=markup">here</a> in svn). Look at both of those and you should be able to build most any custom widget you would like.</p>
5
2009-08-29T15:36:54Z
[ "python", "button", "wxpython" ]
How to make custom buttons in wx?
1,351,448
<p>I'd like to make a custom button in wxPython. Where should I start, how should I do it?</p>
4
2009-08-29T13:31:52Z
1,361,336
<p>Here is a skeleton which you can use to draw totally custom button, its up to your imagination how it looks or behaves</p> <pre><code>class MyButton(wx.PyControl): def __init__(self, parent, id, bmp, text, **kwargs): wx.PyControl.__init__(self,parent, id, **kwargs) self.Bind(wx.EVT_LEFT_DOWN, self._onMouseDown) self.Bind(wx.EVT_LEFT_UP, self._onMouseUp) self.Bind(wx.EVT_LEAVE_WINDOW, self._onMouseLeave) self.Bind(wx.EVT_ENTER_WINDOW, self._onMouseEnter) self.Bind(wx.EVT_ERASE_BACKGROUND,self._onEraseBackground) self.Bind(wx.EVT_PAINT,self._onPaint) self._mouseIn = self._mouseDown = False def _onMouseEnter(self, event): self._mouseIn = True def _onMouseLeave(self, event): self._mouseIn = False def _onMouseDown(self, event): self._mouseDown = True def _onMouseUp(self, event): self._mouseDown = False self.sendButtonEvent() def sendButtonEvent(self): event = wx.CommandEvent(wx.wxEVT_COMMAND_BUTTON_CLICKED, self.GetId()) event.SetInt(0) event.SetEventObject(self) self.GetEventHandler().ProcessEvent(event) def _onEraseBackground(self,event): # reduce flicker pass def _onPaint(self, event): dc = wx.BufferedPaintDC(self) dc.SetFont(self.GetFont()) dc.SetBackground(wx.Brush(self.GetBackgroundColour())) dc.Clear() # draw whatever you want to draw # draw glossy bitmaps e.g. dc.DrawBitmap if self._mouseIn: pass# on mouserover may be draw different bitmap if self._mouseDown: pass # draw different image text </code></pre>
7
2009-09-01T08:55:55Z
[ "python", "button", "wxpython" ]
IBOutlet in Python
1,351,480
<p>Is there a way to use a Cocoa IBOutlet in Python? Or do I need to do this in ObjC? Thanks in advance.</p>
0
2009-08-29T13:45:08Z
1,351,594
<p><a href="http://lethain.com/entry/2008/aug/22/an-epic-introduction-to-pyobjc-and-cocoa/" rel="nofollow">This article</a> (found by searching Google for <a href="http://www.google.com/search?ie=utf-8&amp;oe=utf-8&amp;num=20&amp;q=pyobjc+iboutlet" rel="nofollow">“pyobjc iboutlet”</a>) has an example. Basically, you create <code>objc.IBOutlet</code> objects and set them as the values of class variables.</p>
1
2009-08-29T14:35:27Z
[ "python", "objective-c", "cocoa" ]
How do you make a PDF searchable with text in the sidebar?
1,351,510
<p>I'm looking to create some PDF's from Python.</p> <p>I've noticed that some pdf's have sidebar text that allows you to see the context of occurrences of search terms.</p> <p>e.g. search for "dictionary"</p> <p>View in Sidebar:</p> <p>Page 10 Assigning a value to an existing <strong>dictionary</strong> key simply replaces the old value with a new one. </p> <p>How is that done?</p> <p>Is there anyway to convert existing PDFs to render this sidebar text?</p>
2
2009-08-29T13:59:52Z
1,352,775
<p>I believe what you're referring to are bookmarks. The <a href="http://www.ehow.com/how%5F10082%5Fcreate-bookmarks-pdf.html" rel="nofollow">first hit on Google</a> indicates that you can put them in by hand with Acrobat Pro.</p> <p>The <a href="http://docbook.sourceforge.net/" rel="nofollow">DocBook XSL</a> templates when used with <a href="http://xmlgraphics.apache.org/fop/" rel="nofollow">Apache FOP</a></p>
0
2009-08-30T01:07:33Z
[ "python", "pdf" ]
How do you make a PDF searchable with text in the sidebar?
1,351,510
<p>I'm looking to create some PDF's from Python.</p> <p>I've noticed that some pdf's have sidebar text that allows you to see the context of occurrences of search terms.</p> <p>e.g. search for "dictionary"</p> <p>View in Sidebar:</p> <p>Page 10 Assigning a value to an existing <strong>dictionary</strong> key simply replaces the old value with a new one. </p> <p>How is that done?</p> <p>Is there anyway to convert existing PDFs to render this sidebar text?</p>
2
2009-08-29T13:59:52Z
1,405,464
<p>If you use <a href="http://www.reportlab.org/" rel="nofollow">Reportlab</a> to generate your pdfs, then there are facilities in the library to bookmark as you want. Checkout the <code>bookmarkPage</code> method on page 54 of the documentation.</p>
1
2009-09-10T14:00:40Z
[ "python", "pdf" ]
How do you make a PDF searchable with text in the sidebar?
1,351,510
<p>I'm looking to create some PDF's from Python.</p> <p>I've noticed that some pdf's have sidebar text that allows you to see the context of occurrences of search terms.</p> <p>e.g. search for "dictionary"</p> <p>View in Sidebar:</p> <p>Page 10 Assigning a value to an existing <strong>dictionary</strong> key simply replaces the old value with a new one. </p> <p>How is that done?</p> <p>Is there anyway to convert existing PDFs to render this sidebar text?</p>
2
2009-08-29T13:59:52Z
1,428,147
<p>The <a href="http://www.riverbankcomputing.com" rel="nofollow">PyQt gui toolkit</a> has support for creating PDF's. See for example: <a href="http://doc.trolltech.com/4.5/richtext-common-tasks.html" rel="nofollow">Printing Rich Text with Qt</a></p>
0
2009-09-15T16:14:50Z
[ "python", "pdf" ]
referencing class methods in class lists in Python
1,351,669
<p>I am writing a class in Python 2.6.2 that contains a lookup table. Most cases are simple enough that the table contains data. Some of the cases are more complex and I want to be able call a function. However, I'm running into some trouble referencing the function.</p> <p>Here's some sample code:</p> <pre><code>class a: lut = [1, 3, 17, [12,34], 5] </code></pre> <p>Where <code>lut</code> is static, and is expected to be constant as well.</p> <p>and now I wan to do the following:</p> <pre><code>class a: def spam0(self): return (some_calculation_based_on_self) def spam1(self): return (a_different_calculation_based_on_self) lut = [1, 3, 17, [12,34], 5, self.spam0 self.spam1] </code></pre> <p>This doesn't compile because <code>self.spam0</code> and <code>self.spam1</code> are undefined. I tried using <code>a.spam</code> but that is also undefined. How can I set <code>lut[5]</code> to return a reference to <code>self.spam</code>?</p> <p><strong>Edit:</strong> This is what I plan to do:</p> <p>(continuing the definition of <code>class a</code>): import inspect</p> <pre><code># continue to somewhere in the definition of class a def __init__(self, param): self.param = param def eggs(self): tmp = lut[param] if (insect.isfunction(tmp)): # if tmp is self.spam() return tmp() # should call it here return tmp </code></pre> <p>So I want to either return a simple value or run some extra code, depending on the parameter.</p> <p><strong>Edit:</strong> <code>lut</code> doesn't have to be a class property, but the methods <code>spam0</code> and <code>spam1</code> do need to access the class members, so they have to belong to the class.</p> <p>I'm not sure that this is the best way to do this. I'm still in the process of working this out.</p>
1
2009-08-29T15:11:45Z
1,351,688
<p>You're going to need to move the definition of <code>a.lut</code> outside of the definition of <code>a</code>. </p> <pre><code>class a(): def spam():pass a.lut = [1,2,3,a.spam] </code></pre> <p>If you think about it, this makes perfect sense. Using self wouldn't work because <code>self</code> is actually only defined for class methods for which you use the parameter "<code>self</code>". <code>self</code> has no special meaning in Python and is not a reserved word; it is simply the conventional argument passed to bound class methods, but could also be <code>this</code>, or <code>foo</code>, or whatever you want.</p> <p>Referring to <code>a.lut</code> doesn't work because the definition of <code>a</code> isn't complete yet. How should Python know, at that point in the code, what a is? In the scope of <code>a</code>'s class definition, <code>a</code> itself is still undefined.</p>
-1
2009-08-29T15:18:48Z
[ "python", "class", "reference" ]
referencing class methods in class lists in Python
1,351,669
<p>I am writing a class in Python 2.6.2 that contains a lookup table. Most cases are simple enough that the table contains data. Some of the cases are more complex and I want to be able call a function. However, I'm running into some trouble referencing the function.</p> <p>Here's some sample code:</p> <pre><code>class a: lut = [1, 3, 17, [12,34], 5] </code></pre> <p>Where <code>lut</code> is static, and is expected to be constant as well.</p> <p>and now I wan to do the following:</p> <pre><code>class a: def spam0(self): return (some_calculation_based_on_self) def spam1(self): return (a_different_calculation_based_on_self) lut = [1, 3, 17, [12,34], 5, self.spam0 self.spam1] </code></pre> <p>This doesn't compile because <code>self.spam0</code> and <code>self.spam1</code> are undefined. I tried using <code>a.spam</code> but that is also undefined. How can I set <code>lut[5]</code> to return a reference to <code>self.spam</code>?</p> <p><strong>Edit:</strong> This is what I plan to do:</p> <p>(continuing the definition of <code>class a</code>): import inspect</p> <pre><code># continue to somewhere in the definition of class a def __init__(self, param): self.param = param def eggs(self): tmp = lut[param] if (insect.isfunction(tmp)): # if tmp is self.spam() return tmp() # should call it here return tmp </code></pre> <p>So I want to either return a simple value or run some extra code, depending on the parameter.</p> <p><strong>Edit:</strong> <code>lut</code> doesn't have to be a class property, but the methods <code>spam0</code> and <code>spam1</code> do need to access the class members, so they have to belong to the class.</p> <p>I'm not sure that this is the best way to do this. I'm still in the process of working this out.</p>
1
2009-08-29T15:11:45Z
1,351,693
<p>In the clas body, you're creating the class; there is no <code>self</code>, so you obviously cannot yet refer to <code>self.anything</code>. But also within that body there is as yet no <code>a</code>: name <code>a</code> gets bound AFTER the class body is done. So, although that's a tad less obvious, in the body of class <code>a</code> you cannot refer to <code>a.anything</code> either, yet.</p> <p>What you CAN refer to are bare names of class attributes that have already been bound: for example, you could simply use <code>5, spam]</code> at the end of your list <code>lut</code>. <code>spam</code> will be there as a function, as you say at one point that you want; not as a method, and most definitely NOT as a class method (I don't see <code>classmethod</code> ANYWHERE in your code, why do you think a class method would magically spring into existence unless you explicitly wrap a function in the <code>classmethod</code> builtin, directly or by decorator?) -- I suspect your use of "class method" does not actually refer to the class-method type (though it's certainly confusing;-).</p> <p>So, if you later need to call that function on some instance <code>x</code> of <code>a</code>, you'll be calling e.g. <code>a.lut[-1](x)</code>, with the argument explicitly there.</p> <p>If you need to do something subtler it may be possible to get a bound or unbound method of some sort at various points during processing (after the class creation is done, or, if you want a bound instance method, only after a specific instance is instantiated). But you don't explain clearly and completely enough what exactly it is that you want to do, for us to offer very detailed help on this later-stage alternatives.</p>
4
2009-08-29T15:20:34Z
[ "python", "class", "reference" ]
referencing class methods in class lists in Python
1,351,669
<p>I am writing a class in Python 2.6.2 that contains a lookup table. Most cases are simple enough that the table contains data. Some of the cases are more complex and I want to be able call a function. However, I'm running into some trouble referencing the function.</p> <p>Here's some sample code:</p> <pre><code>class a: lut = [1, 3, 17, [12,34], 5] </code></pre> <p>Where <code>lut</code> is static, and is expected to be constant as well.</p> <p>and now I wan to do the following:</p> <pre><code>class a: def spam0(self): return (some_calculation_based_on_self) def spam1(self): return (a_different_calculation_based_on_self) lut = [1, 3, 17, [12,34], 5, self.spam0 self.spam1] </code></pre> <p>This doesn't compile because <code>self.spam0</code> and <code>self.spam1</code> are undefined. I tried using <code>a.spam</code> but that is also undefined. How can I set <code>lut[5]</code> to return a reference to <code>self.spam</code>?</p> <p><strong>Edit:</strong> This is what I plan to do:</p> <p>(continuing the definition of <code>class a</code>): import inspect</p> <pre><code># continue to somewhere in the definition of class a def __init__(self, param): self.param = param def eggs(self): tmp = lut[param] if (insect.isfunction(tmp)): # if tmp is self.spam() return tmp() # should call it here return tmp </code></pre> <p>So I want to either return a simple value or run some extra code, depending on the parameter.</p> <p><strong>Edit:</strong> <code>lut</code> doesn't have to be a class property, but the methods <code>spam0</code> and <code>spam1</code> do need to access the class members, so they have to belong to the class.</p> <p>I'm not sure that this is the best way to do this. I'm still in the process of working this out.</p>
1
2009-08-29T15:11:45Z
1,351,694
<p>While you are in the scope of the class, you can just write</p> <pre><code>class A: def spam(self): pass lut = [1, 2, 3, spam] a = A() print a.lut </code></pre> <p>gives</p> <pre><code>[1, 2, 3, &lt;function spam at 0xb7bb764c&gt;] </code></pre> <p>Don't forget that this is a <em>function</em> in your lookup table, not a number as you probably intended. You probably want to solve another problem.</p>
2
2009-08-29T15:20:35Z
[ "python", "class", "reference" ]
referencing class methods in class lists in Python
1,351,669
<p>I am writing a class in Python 2.6.2 that contains a lookup table. Most cases are simple enough that the table contains data. Some of the cases are more complex and I want to be able call a function. However, I'm running into some trouble referencing the function.</p> <p>Here's some sample code:</p> <pre><code>class a: lut = [1, 3, 17, [12,34], 5] </code></pre> <p>Where <code>lut</code> is static, and is expected to be constant as well.</p> <p>and now I wan to do the following:</p> <pre><code>class a: def spam0(self): return (some_calculation_based_on_self) def spam1(self): return (a_different_calculation_based_on_self) lut = [1, 3, 17, [12,34], 5, self.spam0 self.spam1] </code></pre> <p>This doesn't compile because <code>self.spam0</code> and <code>self.spam1</code> are undefined. I tried using <code>a.spam</code> but that is also undefined. How can I set <code>lut[5]</code> to return a reference to <code>self.spam</code>?</p> <p><strong>Edit:</strong> This is what I plan to do:</p> <p>(continuing the definition of <code>class a</code>): import inspect</p> <pre><code># continue to somewhere in the definition of class a def __init__(self, param): self.param = param def eggs(self): tmp = lut[param] if (insect.isfunction(tmp)): # if tmp is self.spam() return tmp() # should call it here return tmp </code></pre> <p>So I want to either return a simple value or run some extra code, depending on the parameter.</p> <p><strong>Edit:</strong> <code>lut</code> doesn't have to be a class property, but the methods <code>spam0</code> and <code>spam1</code> do need to access the class members, so they have to belong to the class.</p> <p>I'm not sure that this is the best way to do this. I'm still in the process of working this out.</p>
1
2009-08-29T15:11:45Z
1,351,716
<p>I'm not sure I understand the question. Is this what you mean?</p> <pre><code>class a: lut = [1, 3, 17, [12,34], 5] def __init__(self): self.lut.append(self.spam) def spam(self, a): print "this is %s" % a b = a() b.lut[-1](4) </code></pre> <p>this will output: "this is 4".</p>
0
2009-08-29T15:31:35Z
[ "python", "class", "reference" ]
referencing class methods in class lists in Python
1,351,669
<p>I am writing a class in Python 2.6.2 that contains a lookup table. Most cases are simple enough that the table contains data. Some of the cases are more complex and I want to be able call a function. However, I'm running into some trouble referencing the function.</p> <p>Here's some sample code:</p> <pre><code>class a: lut = [1, 3, 17, [12,34], 5] </code></pre> <p>Where <code>lut</code> is static, and is expected to be constant as well.</p> <p>and now I wan to do the following:</p> <pre><code>class a: def spam0(self): return (some_calculation_based_on_self) def spam1(self): return (a_different_calculation_based_on_self) lut = [1, 3, 17, [12,34], 5, self.spam0 self.spam1] </code></pre> <p>This doesn't compile because <code>self.spam0</code> and <code>self.spam1</code> are undefined. I tried using <code>a.spam</code> but that is also undefined. How can I set <code>lut[5]</code> to return a reference to <code>self.spam</code>?</p> <p><strong>Edit:</strong> This is what I plan to do:</p> <p>(continuing the definition of <code>class a</code>): import inspect</p> <pre><code># continue to somewhere in the definition of class a def __init__(self, param): self.param = param def eggs(self): tmp = lut[param] if (insect.isfunction(tmp)): # if tmp is self.spam() return tmp() # should call it here return tmp </code></pre> <p>So I want to either return a simple value or run some extra code, depending on the parameter.</p> <p><strong>Edit:</strong> <code>lut</code> doesn't have to be a class property, but the methods <code>spam0</code> and <code>spam1</code> do need to access the class members, so they have to belong to the class.</p> <p>I'm not sure that this is the best way to do this. I'm still in the process of working this out.</p>
1
2009-08-29T15:11:45Z
1,352,027
<p>Trivial:</p> <pre><code>class a: @classmethod def spam(cls): # not really pass, but you get the idea pass lut = [1, 3, 17, [12,34], 5, spam] assert a().lut[-1] == a.spam assert a.spam() is None </code></pre>
0
2009-08-29T18:14:54Z
[ "python", "class", "reference" ]
referencing class methods in class lists in Python
1,351,669
<p>I am writing a class in Python 2.6.2 that contains a lookup table. Most cases are simple enough that the table contains data. Some of the cases are more complex and I want to be able call a function. However, I'm running into some trouble referencing the function.</p> <p>Here's some sample code:</p> <pre><code>class a: lut = [1, 3, 17, [12,34], 5] </code></pre> <p>Where <code>lut</code> is static, and is expected to be constant as well.</p> <p>and now I wan to do the following:</p> <pre><code>class a: def spam0(self): return (some_calculation_based_on_self) def spam1(self): return (a_different_calculation_based_on_self) lut = [1, 3, 17, [12,34], 5, self.spam0 self.spam1] </code></pre> <p>This doesn't compile because <code>self.spam0</code> and <code>self.spam1</code> are undefined. I tried using <code>a.spam</code> but that is also undefined. How can I set <code>lut[5]</code> to return a reference to <code>self.spam</code>?</p> <p><strong>Edit:</strong> This is what I plan to do:</p> <p>(continuing the definition of <code>class a</code>): import inspect</p> <pre><code># continue to somewhere in the definition of class a def __init__(self, param): self.param = param def eggs(self): tmp = lut[param] if (insect.isfunction(tmp)): # if tmp is self.spam() return tmp() # should call it here return tmp </code></pre> <p>So I want to either return a simple value or run some extra code, depending on the parameter.</p> <p><strong>Edit:</strong> <code>lut</code> doesn't have to be a class property, but the methods <code>spam0</code> and <code>spam1</code> do need to access the class members, so they have to belong to the class.</p> <p>I'm not sure that this is the best way to do this. I'm still in the process of working this out.</p>
1
2009-08-29T15:11:45Z
1,352,190
<p>You want the function to be bound to the class. None of the answers seem to address this.</p> <p>This won't be done automatically; when you do this:</p> <pre><code>class a: def spam(self): print self lut = [1, spam] </code></pre> <p><code>lut[1]</code> is spam itself, not a bound method to an object, so you can't simply call <code>lut[1]()</code>; you'd have to call <code>lut[1](self)</code>.</p> <p>If you specifically want to be able to include functions in the list that can be called directly, you need to arrange for the functions to be bound, which means referencing them from an instance and not the class. To do this, you'd probably want to initialize this list from <code>__init__</code>:</p> <pre><code>class a: def spam(self): print self def __init__(self): self.lut = [1, self.spam] </code></pre> <p>and now <code>self.lut[1]()</code> is correct, since it's a bound method.</p> <p>This all has the advantage that other functions can be placed in the list for other purposes, possibly bound to other objects or otherwise not expecting a parameter.</p> <p>It has the disadvantage that you aren't reusing the list between instances; this may or may not matter to you.</p>
0
2009-08-29T19:27:34Z
[ "python", "class", "reference" ]