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
Shorter, more pythonic way of writing an if statement
1,319,214
<p>I have this</p> <pre><code>bc = 'off' if c.page == 'blog': bc = 'on' print bc </code></pre> <p>Is there a more pythonic (and/or shorter) way of writing this in python?</p>
38
2009-08-23T18:33:08Z
1,319,219
<p>Shortest one should be:</p> <pre><code>bc = 'on' if c.page=='blog' else 'off' </code></pre> <p>Generally this might look a bit confusing, so you should only use it when it is clear what it means. Don't use it for big boolean clauses, since it begins to look ugly fast.</p>
80
2009-08-23T18:34:47Z
[ "python", "if-statement" ]
Shorter, more pythonic way of writing an if statement
1,319,214
<p>I have this</p> <pre><code>bc = 'off' if c.page == 'blog': bc = 'on' print bc </code></pre> <p>Is there a more pythonic (and/or shorter) way of writing this in python?</p>
38
2009-08-23T18:33:08Z
1,319,223
<p>Or you could use an inline if statement:</p> <pre><code>&gt;&gt;&gt; cpage = 'blog' &gt;&gt;&gt; bc = 'on' if cpage == 'blog' else 'off' &gt;&gt;&gt; bc 'on' &gt;&gt;&gt; cpage = 'asdf' &gt;&gt;&gt; bc = 'on' if cpage == 'blog' else 'off' &gt;&gt;&gt; bc 'off' </code></pre> <p>There's a bit of a writeup on that feature at <a href="http://www.siafoo.net/article/52#id34" rel="nofollow">this blog</a>, and the relevant PEP is <a href="http://www.python.org/doc/2.5/whatsnew/pep-308.html" rel="nofollow">PEP308</a>. The inline if statement was introduced in Python 2.5.</p> <p>This one might be a little less pythonic, but you can use and/or in this fashion:</p> <pre><code>&gt;&gt;&gt; cpage = 'asdf' &gt;&gt;&gt; bc = (cpage == 'blog') and 'on' or 'off' &gt;&gt;&gt; bc 'off' &gt;&gt;&gt; cpage = 'blog' &gt;&gt;&gt; bc = (cpage == 'blog') and 'on' or 'off' &gt;&gt;&gt; bc 'on' </code></pre> <p>This one is used more often in lambda statements than on a line by itself, but the form</p> <pre><code> A and B or C </code></pre> <p>is similar to</p> <pre><code> if A: return B else: return C </code></pre> <p>I was going to write out a little bit longer explanation, but they covered it better <a href="http://www.diveintopython.net/power_of_introspection/and_or.html" rel="nofollow">at Dive into Python</a>. They also noted a couple caveats that you probably need to know.</p>
13
2009-08-23T18:35:56Z
[ "python", "if-statement" ]
Shorter, more pythonic way of writing an if statement
1,319,214
<p>I have this</p> <pre><code>bc = 'off' if c.page == 'blog': bc = 'on' print bc </code></pre> <p>Is there a more pythonic (and/or shorter) way of writing this in python?</p>
38
2009-08-23T18:33:08Z
1,319,289
<p>Well, not being a python guy please take this with a huge grain of salt, but having written (and, with more difficulty, <em>read</em>) a lot of clever code over the years, I find myself with a strong preference now for readable code. I got the gist of what your original code was doing even though I'm a nobody as a Python guy. To be sure, you could hide it and maybe impress a Python wonk or two, but why?</p>
25
2009-08-23T19:03:25Z
[ "python", "if-statement" ]
Shorter, more pythonic way of writing an if statement
1,319,214
<p>I have this</p> <pre><code>bc = 'off' if c.page == 'blog': bc = 'on' print bc </code></pre> <p>Is there a more pythonic (and/or shorter) way of writing this in python?</p>
38
2009-08-23T18:33:08Z
1,319,479
<p>This is:</p> <ol> <li>definitely shorter</li> <li>arguably Pythonic (pre-Python 2.5, which introduced the controversial <code>X if Z else Y</code> syntax)</li> <li><p>questionably readable. With those caveats in mind, here it goes:</p> <pre><code>bc = ("off","on")[c.page=="blog"] </code></pre></li> </ol> <p>EDIT: As per request, the generalized form is:</p> <pre><code> result = (on_false, on_true)[condition] </code></pre> <p>Explanation: <code>condition</code> can be anything that evaluates to a Boolean. It is then treated as an integer since it is used to index the tuple: <code>False == 0</code>, <code>True == 1</code>, which then selects the right item from the tuple.</p>
58
2009-08-23T20:33:02Z
[ "python", "if-statement" ]
Shorter, more pythonic way of writing an if statement
1,319,214
<p>I have this</p> <pre><code>bc = 'off' if c.page == 'blog': bc = 'on' print bc </code></pre> <p>Is there a more pythonic (and/or shorter) way of writing this in python?</p>
38
2009-08-23T18:33:08Z
1,319,687
<p>You can use,</p> <pre><code>a = b if c else d </code></pre> <p>but if you are using a python version prior to 2.5,</p> <pre><code>bc = c.page == "blog" and "on" or "off" </code></pre> <p>can do the trick also.</p>
2
2009-08-23T22:05:59Z
[ "python", "if-statement" ]
Shorter, more pythonic way of writing an if statement
1,319,214
<p>I have this</p> <pre><code>bc = 'off' if c.page == 'blog': bc = 'on' print bc </code></pre> <p>Is there a more pythonic (and/or shorter) way of writing this in python?</p>
38
2009-08-23T18:33:08Z
1,320,324
<p>Another possibility is to use a dict if you can compute the values outside of the function that accesses them (i.e. the values are static, which also addresses the evaluation issue in scrible's answer's comments).</p> <pre><code>want_bc = {True: "on", False: "off"} # ... bc = want_bc[c.page == "blog"] </code></pre> <p>I prefer this and/or the tuple indexing solutions under the general rubric of preferring computation to testing.</p>
3
2009-08-24T03:10:48Z
[ "python", "if-statement" ]
What is the most efficient way to add an element to a list only if isn't there yet?
1,319,254
<p>I have the following code in Python:</p> <pre><code>def point_to_index(point): if point not in points: points.append(point) return points.index(point) </code></pre> <p>This code is awfully inefficient, especially since I expect <code>points</code> to grow to hold a few million elements.</p> <p>If the point isn't in the list, I traverse the list 3 times:</p> <ol> <li>look for it and decide it isn't there</li> <li>go to the end of the list and add a new element</li> <li>go to the end of the list until I find the index</li> </ol> <p>If it <em>is</em> in the list, I traverse it twice: 1. look for it and decide it is there 2. go almost to the end of the list until I find the index</p> <p>Is there any more efficient way to do this? For instance, I know that:</p> <ul> <li>I'm more likely to call this function with a point that isn't in the list.</li> <li>If the point is in the list, it's likelier to be near the end than in the beginning.</li> </ul> <p>So if I could have the line:</p> <pre><code>if point not in points: </code></pre> <p>search the list from the end to the beginning it would improve performance when the point is already in the list.</p> <p>However, I don't want to do:</p> <pre><code>if point not in reversed(points): </code></pre> <p>because I imagine that <code>reversed(points)</code> itself will come at a huge cost.</p> <p>Nor do I want to add new points to the beginning of the list (assuming I knew how to do that in Python) because that would change the indices, which must remain constant for the algorithm to work.</p> <p>The only improvement I can think of is to implement the function with only one pass, if possible from the end to the beginning. The bottom line is:</p> <ul> <li>Is there a good way to do this?</li> <li>Is there a better way to optimize the function?</li> </ul> <p><strong>Edit:</strong> I've gotten suggestions for implementing this with only one pass. Is there any way for <code>index()</code> to go from the end to the beginning?</p> <p><strong>Edit:</strong> People have asked why the index is critical. I'm trying to describe a 3D surface using the <a href="http://shape.cs.princeton.edu/benchmark/documentation/off%5Fformat.html" rel="nofollow">OFF file format</a>. This format describes a surface using its vertices and faces. First the vertices are listed, and the faces are described using a list of indices of vertices. That's why once I add a vortex to the list, its index must not change.</p> <p><strong>Edit:</strong> There have been some suggestions (such as <a href="http://stackoverflow.com/questions/1319254/what-is-the-most-efficient-way-to-add-an-element-to-a-list-only-if-isnt-there-ye/1319470#1319470">igor's</a>) to use a dict. This is a good solution for <em>scanning</em> the list. However, when I'm done I need to print out the list in the same order it was created. If I use a dict, I need to print out its keys sorted by value. Is there a good way to do that?</p> <p><strong>Edit:</strong> I implemented <a href="http://stackoverflow.com/users/55225/www-brool-com">www.brool.com</a>'s <a href="http://stackoverflow.com/questions/1319254/what-is-the-most-efficient-way-to-add-an-element-to-a-list-only-if-isnt-there-ye/1321039#1321039">suggestion</a>. This was the simplest and fastest. It is essentially an ordered Dict, but without the overhead. The performance is great!</p>
7
2009-08-23T18:50:41Z
1,319,270
<pre><code>def point_to_index(point): try: return points.index(point) except: points.append(point) return len(points)-1 </code></pre> <p><strong>Update:</strong> Added in Nathan's exception code.</p>
2
2009-08-23T18:54:33Z
[ "python", "list", "optimization" ]
What is the most efficient way to add an element to a list only if isn't there yet?
1,319,254
<p>I have the following code in Python:</p> <pre><code>def point_to_index(point): if point not in points: points.append(point) return points.index(point) </code></pre> <p>This code is awfully inefficient, especially since I expect <code>points</code> to grow to hold a few million elements.</p> <p>If the point isn't in the list, I traverse the list 3 times:</p> <ol> <li>look for it and decide it isn't there</li> <li>go to the end of the list and add a new element</li> <li>go to the end of the list until I find the index</li> </ol> <p>If it <em>is</em> in the list, I traverse it twice: 1. look for it and decide it is there 2. go almost to the end of the list until I find the index</p> <p>Is there any more efficient way to do this? For instance, I know that:</p> <ul> <li>I'm more likely to call this function with a point that isn't in the list.</li> <li>If the point is in the list, it's likelier to be near the end than in the beginning.</li> </ul> <p>So if I could have the line:</p> <pre><code>if point not in points: </code></pre> <p>search the list from the end to the beginning it would improve performance when the point is already in the list.</p> <p>However, I don't want to do:</p> <pre><code>if point not in reversed(points): </code></pre> <p>because I imagine that <code>reversed(points)</code> itself will come at a huge cost.</p> <p>Nor do I want to add new points to the beginning of the list (assuming I knew how to do that in Python) because that would change the indices, which must remain constant for the algorithm to work.</p> <p>The only improvement I can think of is to implement the function with only one pass, if possible from the end to the beginning. The bottom line is:</p> <ul> <li>Is there a good way to do this?</li> <li>Is there a better way to optimize the function?</li> </ul> <p><strong>Edit:</strong> I've gotten suggestions for implementing this with only one pass. Is there any way for <code>index()</code> to go from the end to the beginning?</p> <p><strong>Edit:</strong> People have asked why the index is critical. I'm trying to describe a 3D surface using the <a href="http://shape.cs.princeton.edu/benchmark/documentation/off%5Fformat.html" rel="nofollow">OFF file format</a>. This format describes a surface using its vertices and faces. First the vertices are listed, and the faces are described using a list of indices of vertices. That's why once I add a vortex to the list, its index must not change.</p> <p><strong>Edit:</strong> There have been some suggestions (such as <a href="http://stackoverflow.com/questions/1319254/what-is-the-most-efficient-way-to-add-an-element-to-a-list-only-if-isnt-there-ye/1319470#1319470">igor's</a>) to use a dict. This is a good solution for <em>scanning</em> the list. However, when I'm done I need to print out the list in the same order it was created. If I use a dict, I need to print out its keys sorted by value. Is there a good way to do that?</p> <p><strong>Edit:</strong> I implemented <a href="http://stackoverflow.com/users/55225/www-brool-com">www.brool.com</a>'s <a href="http://stackoverflow.com/questions/1319254/what-is-the-most-efficient-way-to-add-an-element-to-a-list-only-if-isnt-there-ye/1321039#1321039">suggestion</a>. This was the simplest and fastest. It is essentially an ordered Dict, but without the overhead. The performance is great!</p>
7
2009-08-23T18:50:41Z
1,319,272
<p>You want to use a <a href="http://docs.python.org/library/stdtypes.html#set">set</a>:</p> <pre><code>&gt;&gt;&gt; x = set() &gt;&gt;&gt; x set([]) &gt;&gt;&gt; x.add(1) &gt;&gt;&gt; x set([1]) &gt;&gt;&gt; x.add(1) &gt;&gt;&gt; x set([1]) </code></pre> <p>A set contains only one instance of any item you add, and it will be a lot more efficient than iterating a list manually.</p> <p><a href="http://en.wikibooks.org/wiki/Python%5FProgramming/Sets">This wikibooks page</a> looks like a good primer if you haven't used sets in Python before.</p>
8
2009-08-23T18:55:27Z
[ "python", "list", "optimization" ]
What is the most efficient way to add an element to a list only if isn't there yet?
1,319,254
<p>I have the following code in Python:</p> <pre><code>def point_to_index(point): if point not in points: points.append(point) return points.index(point) </code></pre> <p>This code is awfully inefficient, especially since I expect <code>points</code> to grow to hold a few million elements.</p> <p>If the point isn't in the list, I traverse the list 3 times:</p> <ol> <li>look for it and decide it isn't there</li> <li>go to the end of the list and add a new element</li> <li>go to the end of the list until I find the index</li> </ol> <p>If it <em>is</em> in the list, I traverse it twice: 1. look for it and decide it is there 2. go almost to the end of the list until I find the index</p> <p>Is there any more efficient way to do this? For instance, I know that:</p> <ul> <li>I'm more likely to call this function with a point that isn't in the list.</li> <li>If the point is in the list, it's likelier to be near the end than in the beginning.</li> </ul> <p>So if I could have the line:</p> <pre><code>if point not in points: </code></pre> <p>search the list from the end to the beginning it would improve performance when the point is already in the list.</p> <p>However, I don't want to do:</p> <pre><code>if point not in reversed(points): </code></pre> <p>because I imagine that <code>reversed(points)</code> itself will come at a huge cost.</p> <p>Nor do I want to add new points to the beginning of the list (assuming I knew how to do that in Python) because that would change the indices, which must remain constant for the algorithm to work.</p> <p>The only improvement I can think of is to implement the function with only one pass, if possible from the end to the beginning. The bottom line is:</p> <ul> <li>Is there a good way to do this?</li> <li>Is there a better way to optimize the function?</li> </ul> <p><strong>Edit:</strong> I've gotten suggestions for implementing this with only one pass. Is there any way for <code>index()</code> to go from the end to the beginning?</p> <p><strong>Edit:</strong> People have asked why the index is critical. I'm trying to describe a 3D surface using the <a href="http://shape.cs.princeton.edu/benchmark/documentation/off%5Fformat.html" rel="nofollow">OFF file format</a>. This format describes a surface using its vertices and faces. First the vertices are listed, and the faces are described using a list of indices of vertices. That's why once I add a vortex to the list, its index must not change.</p> <p><strong>Edit:</strong> There have been some suggestions (such as <a href="http://stackoverflow.com/questions/1319254/what-is-the-most-efficient-way-to-add-an-element-to-a-list-only-if-isnt-there-ye/1319470#1319470">igor's</a>) to use a dict. This is a good solution for <em>scanning</em> the list. However, when I'm done I need to print out the list in the same order it was created. If I use a dict, I need to print out its keys sorted by value. Is there a good way to do that?</p> <p><strong>Edit:</strong> I implemented <a href="http://stackoverflow.com/users/55225/www-brool-com">www.brool.com</a>'s <a href="http://stackoverflow.com/questions/1319254/what-is-the-most-efficient-way-to-add-an-element-to-a-list-only-if-isnt-there-ye/1321039#1321039">suggestion</a>. This was the simplest and fastest. It is essentially an ordered Dict, but without the overhead. The performance is great!</p>
7
2009-08-23T18:50:41Z
1,319,287
<p>This will traverse at most once:</p> <pre><code>def point_to_index(point): try: return points.index(point) except ValueError: points.append(point) return len(points)-1 </code></pre> <p>You may also want to try this version, which takes into account that matches are likely to be near the end of the list. Note that <code>reversed()</code> has almost no cost even on very large lists - it does not create a copy and does not traverse the list more than once.</p> <pre><code>def point_to_index(point): for index, this_point in enumerate(reversed(points)): if point == this_point: return len(points) - (index+1) else: points.append(point) return len(points)-1 </code></pre> <p>You might also consider keeping a parallel <code>dict</code> or <code>set</code> of points to check for membership, since both of those types can do membership tests in O(1). There would be, of course, a substantial memory cost.</p> <p>Obviously, if the points were ordered somehow, you would have many other options for speeding this code up, notably using a binary search for membership tests.</p>
10
2009-08-23T19:02:13Z
[ "python", "list", "optimization" ]
What is the most efficient way to add an element to a list only if isn't there yet?
1,319,254
<p>I have the following code in Python:</p> <pre><code>def point_to_index(point): if point not in points: points.append(point) return points.index(point) </code></pre> <p>This code is awfully inefficient, especially since I expect <code>points</code> to grow to hold a few million elements.</p> <p>If the point isn't in the list, I traverse the list 3 times:</p> <ol> <li>look for it and decide it isn't there</li> <li>go to the end of the list and add a new element</li> <li>go to the end of the list until I find the index</li> </ol> <p>If it <em>is</em> in the list, I traverse it twice: 1. look for it and decide it is there 2. go almost to the end of the list until I find the index</p> <p>Is there any more efficient way to do this? For instance, I know that:</p> <ul> <li>I'm more likely to call this function with a point that isn't in the list.</li> <li>If the point is in the list, it's likelier to be near the end than in the beginning.</li> </ul> <p>So if I could have the line:</p> <pre><code>if point not in points: </code></pre> <p>search the list from the end to the beginning it would improve performance when the point is already in the list.</p> <p>However, I don't want to do:</p> <pre><code>if point not in reversed(points): </code></pre> <p>because I imagine that <code>reversed(points)</code> itself will come at a huge cost.</p> <p>Nor do I want to add new points to the beginning of the list (assuming I knew how to do that in Python) because that would change the indices, which must remain constant for the algorithm to work.</p> <p>The only improvement I can think of is to implement the function with only one pass, if possible from the end to the beginning. The bottom line is:</p> <ul> <li>Is there a good way to do this?</li> <li>Is there a better way to optimize the function?</li> </ul> <p><strong>Edit:</strong> I've gotten suggestions for implementing this with only one pass. Is there any way for <code>index()</code> to go from the end to the beginning?</p> <p><strong>Edit:</strong> People have asked why the index is critical. I'm trying to describe a 3D surface using the <a href="http://shape.cs.princeton.edu/benchmark/documentation/off%5Fformat.html" rel="nofollow">OFF file format</a>. This format describes a surface using its vertices and faces. First the vertices are listed, and the faces are described using a list of indices of vertices. That's why once I add a vortex to the list, its index must not change.</p> <p><strong>Edit:</strong> There have been some suggestions (such as <a href="http://stackoverflow.com/questions/1319254/what-is-the-most-efficient-way-to-add-an-element-to-a-list-only-if-isnt-there-ye/1319470#1319470">igor's</a>) to use a dict. This is a good solution for <em>scanning</em> the list. However, when I'm done I need to print out the list in the same order it was created. If I use a dict, I need to print out its keys sorted by value. Is there a good way to do that?</p> <p><strong>Edit:</strong> I implemented <a href="http://stackoverflow.com/users/55225/www-brool-com">www.brool.com</a>'s <a href="http://stackoverflow.com/questions/1319254/what-is-the-most-efficient-way-to-add-an-element-to-a-list-only-if-isnt-there-ye/1321039#1321039">suggestion</a>. This was the simplest and fastest. It is essentially an ordered Dict, but without the overhead. The performance is great!</p>
7
2009-08-23T18:50:41Z
1,319,470
<p>As others said, consider using set or dict. You don't explain why you need the indices. If they are needed only to assign unique ids to the points (and I can't easily come up with another reason for using them), then dict will indeed work much better, e.g.,</p> <pre><code>points = {} def point_to_index(point): if point in points: return points[point] else: points[point] = len(points) return len(points) - 1 </code></pre>
1
2009-08-23T20:27:37Z
[ "python", "list", "optimization" ]
What is the most efficient way to add an element to a list only if isn't there yet?
1,319,254
<p>I have the following code in Python:</p> <pre><code>def point_to_index(point): if point not in points: points.append(point) return points.index(point) </code></pre> <p>This code is awfully inefficient, especially since I expect <code>points</code> to grow to hold a few million elements.</p> <p>If the point isn't in the list, I traverse the list 3 times:</p> <ol> <li>look for it and decide it isn't there</li> <li>go to the end of the list and add a new element</li> <li>go to the end of the list until I find the index</li> </ol> <p>If it <em>is</em> in the list, I traverse it twice: 1. look for it and decide it is there 2. go almost to the end of the list until I find the index</p> <p>Is there any more efficient way to do this? For instance, I know that:</p> <ul> <li>I'm more likely to call this function with a point that isn't in the list.</li> <li>If the point is in the list, it's likelier to be near the end than in the beginning.</li> </ul> <p>So if I could have the line:</p> <pre><code>if point not in points: </code></pre> <p>search the list from the end to the beginning it would improve performance when the point is already in the list.</p> <p>However, I don't want to do:</p> <pre><code>if point not in reversed(points): </code></pre> <p>because I imagine that <code>reversed(points)</code> itself will come at a huge cost.</p> <p>Nor do I want to add new points to the beginning of the list (assuming I knew how to do that in Python) because that would change the indices, which must remain constant for the algorithm to work.</p> <p>The only improvement I can think of is to implement the function with only one pass, if possible from the end to the beginning. The bottom line is:</p> <ul> <li>Is there a good way to do this?</li> <li>Is there a better way to optimize the function?</li> </ul> <p><strong>Edit:</strong> I've gotten suggestions for implementing this with only one pass. Is there any way for <code>index()</code> to go from the end to the beginning?</p> <p><strong>Edit:</strong> People have asked why the index is critical. I'm trying to describe a 3D surface using the <a href="http://shape.cs.princeton.edu/benchmark/documentation/off%5Fformat.html" rel="nofollow">OFF file format</a>. This format describes a surface using its vertices and faces. First the vertices are listed, and the faces are described using a list of indices of vertices. That's why once I add a vortex to the list, its index must not change.</p> <p><strong>Edit:</strong> There have been some suggestions (such as <a href="http://stackoverflow.com/questions/1319254/what-is-the-most-efficient-way-to-add-an-element-to-a-list-only-if-isnt-there-ye/1319470#1319470">igor's</a>) to use a dict. This is a good solution for <em>scanning</em> the list. However, when I'm done I need to print out the list in the same order it was created. If I use a dict, I need to print out its keys sorted by value. Is there a good way to do that?</p> <p><strong>Edit:</strong> I implemented <a href="http://stackoverflow.com/users/55225/www-brool-com">www.brool.com</a>'s <a href="http://stackoverflow.com/questions/1319254/what-is-the-most-efficient-way-to-add-an-element-to-a-list-only-if-isnt-there-ye/1321039#1321039">suggestion</a>. This was the simplest and fastest. It is essentially an ordered Dict, but without the overhead. The performance is great!</p>
7
2009-08-23T18:50:41Z
1,321,039
<p>If you're worried about memory usage, but want to optimize the common case, keep a dictionary with the last n points and their indexes. points_dict = dictionary, max_cache = size of the cache.</p> <pre><code>def point_to_index(point): try: return points_dict.get(point, points.index(point)) except: if len(points) &gt;= max_cache: del points_dict[points[len(points)-max_cache]] points.append(point) points_dict[points] = len(points)-1 return len(points)-1 </code></pre>
5
2009-08-24T08:06:53Z
[ "python", "list", "optimization" ]
What is the most efficient way to add an element to a list only if isn't there yet?
1,319,254
<p>I have the following code in Python:</p> <pre><code>def point_to_index(point): if point not in points: points.append(point) return points.index(point) </code></pre> <p>This code is awfully inefficient, especially since I expect <code>points</code> to grow to hold a few million elements.</p> <p>If the point isn't in the list, I traverse the list 3 times:</p> <ol> <li>look for it and decide it isn't there</li> <li>go to the end of the list and add a new element</li> <li>go to the end of the list until I find the index</li> </ol> <p>If it <em>is</em> in the list, I traverse it twice: 1. look for it and decide it is there 2. go almost to the end of the list until I find the index</p> <p>Is there any more efficient way to do this? For instance, I know that:</p> <ul> <li>I'm more likely to call this function with a point that isn't in the list.</li> <li>If the point is in the list, it's likelier to be near the end than in the beginning.</li> </ul> <p>So if I could have the line:</p> <pre><code>if point not in points: </code></pre> <p>search the list from the end to the beginning it would improve performance when the point is already in the list.</p> <p>However, I don't want to do:</p> <pre><code>if point not in reversed(points): </code></pre> <p>because I imagine that <code>reversed(points)</code> itself will come at a huge cost.</p> <p>Nor do I want to add new points to the beginning of the list (assuming I knew how to do that in Python) because that would change the indices, which must remain constant for the algorithm to work.</p> <p>The only improvement I can think of is to implement the function with only one pass, if possible from the end to the beginning. The bottom line is:</p> <ul> <li>Is there a good way to do this?</li> <li>Is there a better way to optimize the function?</li> </ul> <p><strong>Edit:</strong> I've gotten suggestions for implementing this with only one pass. Is there any way for <code>index()</code> to go from the end to the beginning?</p> <p><strong>Edit:</strong> People have asked why the index is critical. I'm trying to describe a 3D surface using the <a href="http://shape.cs.princeton.edu/benchmark/documentation/off%5Fformat.html" rel="nofollow">OFF file format</a>. This format describes a surface using its vertices and faces. First the vertices are listed, and the faces are described using a list of indices of vertices. That's why once I add a vortex to the list, its index must not change.</p> <p><strong>Edit:</strong> There have been some suggestions (such as <a href="http://stackoverflow.com/questions/1319254/what-is-the-most-efficient-way-to-add-an-element-to-a-list-only-if-isnt-there-ye/1319470#1319470">igor's</a>) to use a dict. This is a good solution for <em>scanning</em> the list. However, when I'm done I need to print out the list in the same order it was created. If I use a dict, I need to print out its keys sorted by value. Is there a good way to do that?</p> <p><strong>Edit:</strong> I implemented <a href="http://stackoverflow.com/users/55225/www-brool-com">www.brool.com</a>'s <a href="http://stackoverflow.com/questions/1319254/what-is-the-most-efficient-way-to-add-an-element-to-a-list-only-if-isnt-there-ye/1321039#1321039">suggestion</a>. This was the simplest and fastest. It is essentially an ordered Dict, but without the overhead. The performance is great!</p>
7
2009-08-23T18:50:41Z
1,321,086
<p>What you really want is an ordered dict (key insertion determines the order):</p> <ul> <li>Recipe: <a href="http://code.activestate.com/recipes/107747/" rel="nofollow">http://code.activestate.com/recipes/107747/</a></li> <li>PEP: <a href="http://www.python.org/dev/peps/pep-0372/" rel="nofollow">http://www.python.org/dev/peps/pep-0372/</a></li> </ul>
1
2009-08-24T08:20:32Z
[ "python", "list", "optimization" ]
Combining two lists and removing duplicates, without removing duplicates in original list
1,319,338
<p>I have two lists that i need to combine where the second list has any duplicates of the first list ignored. .. A bit hard to explain, so let me show an example of what the code looks like, and what i want as a result.</p> <pre><code>first_list = [1, 2, 2, 5] second_list = [2, 5, 7, 9] # The result of combining the two lists should result in this list: resulting_list = [1, 2, 2, 5, 7, 9] </code></pre> <p>You'll notice that the result has the first list, <em>including</em> its two "2" values, but the fact that second_list also has an additional 2 and 5 value is not added to the first list.</p> <p>Normally for something like this i would use sets, but a set on first_list would purge the duplicate values it already has. So i'm simply wondering what the best/fastest way to achieve this desired combination.</p> <p>Thanks.</p>
31
2009-08-23T19:27:58Z
1,319,353
<p>You need to append to the first list those elements of the second list that aren't in the first - sets are the easiest way of determining which elements they are, like this:</p> <pre><code>first_list = [1, 2, 2, 5] second_list = [2, 5, 7, 9] in_first = set(first_list) in_second = set(second_list) in_second_but_not_in_first = in_second - in_first result = first_list + list(in_second_but_not_in_first) print result # Prints [1, 2, 2, 5, 9, 7] </code></pre> <p>Or if you prefer one-liners 8-)</p> <pre><code>print first_list + list(set(second_list) - set(first_list)) </code></pre>
59
2009-08-23T19:32:09Z
[ "python", "list" ]
Combining two lists and removing duplicates, without removing duplicates in original list
1,319,338
<p>I have two lists that i need to combine where the second list has any duplicates of the first list ignored. .. A bit hard to explain, so let me show an example of what the code looks like, and what i want as a result.</p> <pre><code>first_list = [1, 2, 2, 5] second_list = [2, 5, 7, 9] # The result of combining the two lists should result in this list: resulting_list = [1, 2, 2, 5, 7, 9] </code></pre> <p>You'll notice that the result has the first list, <em>including</em> its two "2" values, but the fact that second_list also has an additional 2 and 5 value is not added to the first list.</p> <p>Normally for something like this i would use sets, but a set on first_list would purge the duplicate values it already has. So i'm simply wondering what the best/fastest way to achieve this desired combination.</p> <p>Thanks.</p>
31
2009-08-23T19:27:58Z
1,319,354
<pre><code>resulting_list = first_list + [i for i in second_list if i not in first_list] </code></pre>
1
2009-08-23T19:32:18Z
[ "python", "list" ]
Combining two lists and removing duplicates, without removing duplicates in original list
1,319,338
<p>I have two lists that i need to combine where the second list has any duplicates of the first list ignored. .. A bit hard to explain, so let me show an example of what the code looks like, and what i want as a result.</p> <pre><code>first_list = [1, 2, 2, 5] second_list = [2, 5, 7, 9] # The result of combining the two lists should result in this list: resulting_list = [1, 2, 2, 5, 7, 9] </code></pre> <p>You'll notice that the result has the first list, <em>including</em> its two "2" values, but the fact that second_list also has an additional 2 and 5 value is not added to the first list.</p> <p>Normally for something like this i would use sets, but a set on first_list would purge the duplicate values it already has. So i'm simply wondering what the best/fastest way to achieve this desired combination.</p> <p>Thanks.</p>
31
2009-08-23T19:27:58Z
1,319,355
<pre><code>resulting_list = list(first_list) resulting_list.extend(x for x in second_list if x not in resulting_list) </code></pre>
19
2009-08-23T19:32:42Z
[ "python", "list" ]
Combining two lists and removing duplicates, without removing duplicates in original list
1,319,338
<p>I have two lists that i need to combine where the second list has any duplicates of the first list ignored. .. A bit hard to explain, so let me show an example of what the code looks like, and what i want as a result.</p> <pre><code>first_list = [1, 2, 2, 5] second_list = [2, 5, 7, 9] # The result of combining the two lists should result in this list: resulting_list = [1, 2, 2, 5, 7, 9] </code></pre> <p>You'll notice that the result has the first list, <em>including</em> its two "2" values, but the fact that second_list also has an additional 2 and 5 value is not added to the first list.</p> <p>Normally for something like this i would use sets, but a set on first_list would purge the duplicate values it already has. So i'm simply wondering what the best/fastest way to achieve this desired combination.</p> <p>Thanks.</p>
31
2009-08-23T19:27:58Z
12,389,407
<p>This might help </p> <pre><code>def union(a,b): for e in b: if e not in a: a.append(e) </code></pre> <p>The union function merges the second list into first, with out duplicating an element of a, if it's already in a. Similar to set union operator. This function does not change b. If a=[1,2,3] b=[2,3,4]. After union(a,b) makes a=[1,2,3,4] and b=[2,3,4]</p>
0
2012-09-12T13:34:53Z
[ "python", "list" ]
Combining two lists and removing duplicates, without removing duplicates in original list
1,319,338
<p>I have two lists that i need to combine where the second list has any duplicates of the first list ignored. .. A bit hard to explain, so let me show an example of what the code looks like, and what i want as a result.</p> <pre><code>first_list = [1, 2, 2, 5] second_list = [2, 5, 7, 9] # The result of combining the two lists should result in this list: resulting_list = [1, 2, 2, 5, 7, 9] </code></pre> <p>You'll notice that the result has the first list, <em>including</em> its two "2" values, but the fact that second_list also has an additional 2 and 5 value is not added to the first list.</p> <p>Normally for something like this i would use sets, but a set on first_list would purge the duplicate values it already has. So i'm simply wondering what the best/fastest way to achieve this desired combination.</p> <p>Thanks.</p>
31
2009-08-23T19:27:58Z
14,832,994
<p>You can use sets:</p> <pre><code>first_list = [1, 2, 2, 5] second_list = [2, 5, 7, 9] resultList= List(set(first_list)|set(second_list)) resultList=[1,2,5,7,9] </code></pre>
4
2013-02-12T12:51:00Z
[ "python", "list" ]
Combining two lists and removing duplicates, without removing duplicates in original list
1,319,338
<p>I have two lists that i need to combine where the second list has any duplicates of the first list ignored. .. A bit hard to explain, so let me show an example of what the code looks like, and what i want as a result.</p> <pre><code>first_list = [1, 2, 2, 5] second_list = [2, 5, 7, 9] # The result of combining the two lists should result in this list: resulting_list = [1, 2, 2, 5, 7, 9] </code></pre> <p>You'll notice that the result has the first list, <em>including</em> its two "2" values, but the fact that second_list also has an additional 2 and 5 value is not added to the first list.</p> <p>Normally for something like this i would use sets, but a set on first_list would purge the duplicate values it already has. So i'm simply wondering what the best/fastest way to achieve this desired combination.</p> <p>Thanks.</p>
31
2009-08-23T19:27:58Z
29,943,019
<pre><code> first_list = [1, 2, 2, 5] second_list = [2, 5, 7, 9] newList=[] for i in first_list: newList.append(i) for z in second_list: if z not in newList: newList.append(z) newList.sort() print newList </code></pre> <p>[1, 2, 2, 5, 7, 9]</p>
0
2015-04-29T11:56:40Z
[ "python", "list" ]
Combining two lists and removing duplicates, without removing duplicates in original list
1,319,338
<p>I have two lists that i need to combine where the second list has any duplicates of the first list ignored. .. A bit hard to explain, so let me show an example of what the code looks like, and what i want as a result.</p> <pre><code>first_list = [1, 2, 2, 5] second_list = [2, 5, 7, 9] # The result of combining the two lists should result in this list: resulting_list = [1, 2, 2, 5, 7, 9] </code></pre> <p>You'll notice that the result has the first list, <em>including</em> its two "2" values, but the fact that second_list also has an additional 2 and 5 value is not added to the first list.</p> <p>Normally for something like this i would use sets, but a set on first_list would purge the duplicate values it already has. So i'm simply wondering what the best/fastest way to achieve this desired combination.</p> <p>Thanks.</p>
31
2009-08-23T19:27:58Z
33,792,245
<p>You can also combine RichieHindle's and Ned Batchelder's responses for an <em><a href="http://stackoverflow.com/a/3906036/320036">average-case</a> O(m+n)</em> algorithm that preserves order:</p> <pre><code>first_list = [1, 2, 2, 5] second_list = [2, 5, 7, 9] fs = set(first_list) resulting_list = first_list + [x for x in second_list if x not in fs] assert(resulting_list == [1, 2, 2, 5, 7, 9]) </code></pre> <p>Note that <a href="https://wiki.python.org/moin/TimeComplexity#set" rel="nofollow"><code>x in s</code> has a worst-case complexity of <em>O(m)</em></a>, so the <em>worst-case</em> complexity of this code is still <em>O(m*n)</em>.</p>
0
2015-11-18T23:07:03Z
[ "python", "list" ]
Need Help using XPath in ElementTree
1,319,385
<p>I am having a heck of a time using ElementTree 1.3 in Python. Essentially, ElementTree does absolutely nothing.</p> <p>My XML file looks like the following:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;ItemSearchResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2008-08-19"&gt; &lt;Items&gt; &lt;Item&gt; &lt;ItemAttributes&gt; &lt;ListPrice&gt; &lt;Amount&gt;2260&lt;/Amount&gt; &lt;/ListPrice&gt; &lt;/ItemAttributes&gt; &lt;Offers&gt; &lt;Offer&gt; &lt;OfferListing&gt; &lt;Price&gt; &lt;Amount&gt;1853&lt;/Amount&gt; &lt;/Price&gt; &lt;/OfferListing&gt; &lt;/Offer&gt; &lt;/Offers&gt; &lt;/Item&gt; &lt;/Items&gt; &lt;/ItemSearchResponse&gt; </code></pre> <p>All I want to do is extract the ListPrice.</p> <p>This is the code I am using...</p> <pre><code>&gt;&gt; from elementtree import ElementTree as ET &gt;&gt; fp = open("output.xml","r") &gt;&gt; element = ET.parse(fp).getroot() &gt;&gt; e = element.findall('ItemSearchResponse/Items/Item/ItemAttributes/ListPrice/Amount') &gt;&gt; for i in e: &gt;&gt; print i.text &gt;&gt; &gt;&gt; e &gt;&gt; </code></pre> <p>Absolutely no output. I also tried</p> <pre><code>&gt;&gt; e = element.findall('Items/Item/ItemAttributes/ListPrice/Amount') </code></pre> <p>No difference.</p> <p>What am I doing wrong?</p>
26
2009-08-23T19:48:21Z
1,319,417
<p>There are 2 problems that you have.</p> <p>1) <code>element</code> contains only the root element, not recursively the whole document. It is of type Element not ElementTree.</p> <p>2) Your search string needs to use namespaces if you keep the namespace in the XML.</p> <p><strong>To fix problem #1:</strong> </p> <p>You need to change:</p> <pre><code>element = ET.parse(fp).getroot() </code></pre> <p>to:</p> <pre><code>element = ET.parse(fp) </code></pre> <p><strong>To fix problem #2:</strong></p> <p>You can take off the xmlns from the XML document so it looks like this: </p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;ItemSearchResponse&gt; &lt;Items&gt; &lt;Item&gt; &lt;ItemAttributes&gt; &lt;ListPrice&gt; &lt;Amount&gt;2260&lt;/Amount&gt; &lt;/ListPrice&gt; &lt;/ItemAttributes&gt; &lt;Offers&gt; &lt;Offer&gt; &lt;OfferListing&gt; &lt;Price&gt; &lt;Amount&gt;1853&lt;/Amount&gt; &lt;/Price&gt; &lt;/OfferListing&gt; &lt;/Offer&gt; &lt;/Offers&gt; &lt;/Item&gt; &lt;/Items&gt; &lt;/ItemSearchResponse&gt; </code></pre> <p>With this document you can use the following search string:</p> <pre><code>e = element.findall('Items/Item/ItemAttributes/ListPrice/Amount') </code></pre> <p>The full code:</p> <pre><code>from elementtree import ElementTree as ET fp = open("output.xml","r") element = ET.parse(fp) e = element.findall('Items/Item/ItemAttributes/ListPrice/Amount') for i in e: print i.text </code></pre> <p><strong>Alternate fix to problem #2:</strong> </p> <p>Otherwise you need to specify the xmlns inside the srearch string for each element.</p> <p>The full code:</p> <pre><code>from elementtree import ElementTree as ET fp = open("output.xml","r") element = ET.parse(fp) namespace = "{http://webservices.amazon.com/AWSECommerceService/2008-08-19}" e = element.findall('{0}Items/{0}Item/{0}ItemAttributes/{0}ListPrice/{0}Amount'.format(namespace)) for i in e: print i.text </code></pre> <p><hr /></p> <p>Both print: </p> <blockquote> <p>2260</p> </blockquote>
47
2009-08-23T20:02:48Z
[ "python", "xml", "xpath", "elementtree" ]
Need Help using XPath in ElementTree
1,319,385
<p>I am having a heck of a time using ElementTree 1.3 in Python. Essentially, ElementTree does absolutely nothing.</p> <p>My XML file looks like the following:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;ItemSearchResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2008-08-19"&gt; &lt;Items&gt; &lt;Item&gt; &lt;ItemAttributes&gt; &lt;ListPrice&gt; &lt;Amount&gt;2260&lt;/Amount&gt; &lt;/ListPrice&gt; &lt;/ItemAttributes&gt; &lt;Offers&gt; &lt;Offer&gt; &lt;OfferListing&gt; &lt;Price&gt; &lt;Amount&gt;1853&lt;/Amount&gt; &lt;/Price&gt; &lt;/OfferListing&gt; &lt;/Offer&gt; &lt;/Offers&gt; &lt;/Item&gt; &lt;/Items&gt; &lt;/ItemSearchResponse&gt; </code></pre> <p>All I want to do is extract the ListPrice.</p> <p>This is the code I am using...</p> <pre><code>&gt;&gt; from elementtree import ElementTree as ET &gt;&gt; fp = open("output.xml","r") &gt;&gt; element = ET.parse(fp).getroot() &gt;&gt; e = element.findall('ItemSearchResponse/Items/Item/ItemAttributes/ListPrice/Amount') &gt;&gt; for i in e: &gt;&gt; print i.text &gt;&gt; &gt;&gt; e &gt;&gt; </code></pre> <p>Absolutely no output. I also tried</p> <pre><code>&gt;&gt; e = element.findall('Items/Item/ItemAttributes/ListPrice/Amount') </code></pre> <p>No difference.</p> <p>What am I doing wrong?</p>
26
2009-08-23T19:48:21Z
1,319,457
<p>Element tree uses namespaces so all the elements in your xml have name like {<a href="http://webservices.amazon.com/AWSECommerceService/2008-08-19">http://webservices.amazon.com/AWSECommerceService/2008-08-19</a>}Items</p> <p>So make the search include the namespace e.g.</p> <pre><code>search = '{http://webservices.amazon.com/AWSECommerceService/2008-08-19}Items/{http://webservices.amazon.com/AWSECommerceService/2008-08-19}Item/{http://webservices.amazon.com/AWSECommerceService/2008-08-19}ItemAttributes/{http://webservices.amazon.com/AWSECommerceService/2008-08-19}ListPrice/{http://webservices.amazon.com/AWSECommerceService/2008-08-19}Amount' element.findall( search ) </code></pre> <p>gives the element corresponding to 2260 </p>
5
2009-08-23T20:23:54Z
[ "python", "xml", "xpath", "elementtree" ]
Need Help using XPath in ElementTree
1,319,385
<p>I am having a heck of a time using ElementTree 1.3 in Python. Essentially, ElementTree does absolutely nothing.</p> <p>My XML file looks like the following:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;ItemSearchResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2008-08-19"&gt; &lt;Items&gt; &lt;Item&gt; &lt;ItemAttributes&gt; &lt;ListPrice&gt; &lt;Amount&gt;2260&lt;/Amount&gt; &lt;/ListPrice&gt; &lt;/ItemAttributes&gt; &lt;Offers&gt; &lt;Offer&gt; &lt;OfferListing&gt; &lt;Price&gt; &lt;Amount&gt;1853&lt;/Amount&gt; &lt;/Price&gt; &lt;/OfferListing&gt; &lt;/Offer&gt; &lt;/Offers&gt; &lt;/Item&gt; &lt;/Items&gt; &lt;/ItemSearchResponse&gt; </code></pre> <p>All I want to do is extract the ListPrice.</p> <p>This is the code I am using...</p> <pre><code>&gt;&gt; from elementtree import ElementTree as ET &gt;&gt; fp = open("output.xml","r") &gt;&gt; element = ET.parse(fp).getroot() &gt;&gt; e = element.findall('ItemSearchResponse/Items/Item/ItemAttributes/ListPrice/Amount') &gt;&gt; for i in e: &gt;&gt; print i.text &gt;&gt; &gt;&gt; e &gt;&gt; </code></pre> <p>Absolutely no output. I also tried</p> <pre><code>&gt;&gt; e = element.findall('Items/Item/ItemAttributes/ListPrice/Amount') </code></pre> <p>No difference.</p> <p>What am I doing wrong?</p>
26
2009-08-23T19:48:21Z
1,319,575
<pre><code>from xml.etree import ElementTree as ET tree = ET.parse("output.xml") namespace = tree.getroot().tag[1:].split("}")[0] amount = tree.find(".//{%s}Amount" % namespace).text </code></pre> <p>Also, consider using <a href="http://codespeak.net/lxml/">lxml</a>. It's way faster.</p> <pre><code>from lxml import ElementTree as ET </code></pre>
6
2009-08-23T21:11:16Z
[ "python", "xml", "xpath", "elementtree" ]
Need Help using XPath in ElementTree
1,319,385
<p>I am having a heck of a time using ElementTree 1.3 in Python. Essentially, ElementTree does absolutely nothing.</p> <p>My XML file looks like the following:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;ItemSearchResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2008-08-19"&gt; &lt;Items&gt; &lt;Item&gt; &lt;ItemAttributes&gt; &lt;ListPrice&gt; &lt;Amount&gt;2260&lt;/Amount&gt; &lt;/ListPrice&gt; &lt;/ItemAttributes&gt; &lt;Offers&gt; &lt;Offer&gt; &lt;OfferListing&gt; &lt;Price&gt; &lt;Amount&gt;1853&lt;/Amount&gt; &lt;/Price&gt; &lt;/OfferListing&gt; &lt;/Offer&gt; &lt;/Offers&gt; &lt;/Item&gt; &lt;/Items&gt; &lt;/ItemSearchResponse&gt; </code></pre> <p>All I want to do is extract the ListPrice.</p> <p>This is the code I am using...</p> <pre><code>&gt;&gt; from elementtree import ElementTree as ET &gt;&gt; fp = open("output.xml","r") &gt;&gt; element = ET.parse(fp).getroot() &gt;&gt; e = element.findall('ItemSearchResponse/Items/Item/ItemAttributes/ListPrice/Amount') &gt;&gt; for i in e: &gt;&gt; print i.text &gt;&gt; &gt;&gt; e &gt;&gt; </code></pre> <p>Absolutely no output. I also tried</p> <pre><code>&gt;&gt; e = element.findall('Items/Item/ItemAttributes/ListPrice/Amount') </code></pre> <p>No difference.</p> <p>What am I doing wrong?</p>
26
2009-08-23T19:48:21Z
10,343,185
<p>I ended up stripping out the xmlns from the raw xml like that:</p> <pre><code>def strip_ns(xml_string): return re.sub('xmlns="[^"]+"', '', xml_string) </code></pre> <p>Obviously be very careful with this, but it worked well for me.</p>
5
2012-04-27T00:24:28Z
[ "python", "xml", "xpath", "elementtree" ]
Is this a good approach to avoid using SQLAlchemy/SQLObject?
1,319,585
<p>Rather than use an ORM, I am considering the following approach in Python and MySQL with no ORM (SQLObject/SQLAlchemy). I would like to get some feedback on whether this seems likely to have any negative long-term consequences since in the short-term view it seems fine from what I can tell.</p> <p>Rather than translate a row from the database into an object:</p> <ul> <li>each table is represented by a class</li> <li>a row is retrieved as a dict</li> <li><p>an object representing a cursor provides access to a table like so:</p> <p>cursor.mytable.get_by_ids(low, high)</p></li> <li><p>removing means setting the time_of_removal to the current time</p></li> </ul> <p>So essentially this does away with the need for an ORM since each table has a class to represent it and within that class, a separate dict represents each row.</p> <p>Type mapping is trivial because each dict (row) being a first class object in python/blub allows you to know the class of the object and, besides, the low-level database library in Python handles the conversion of types at the field level into their appropriate application-level types.</p> <p>If you see any potential problems with going down this road, please let me know. Thanks.</p>
3
2009-08-23T21:15:05Z
1,319,598
<p>That doesn't do away with the need for an ORM. That <strong>is</strong> an ORM. In which case, why reinvent the wheel?</p> <p>Is there a compelling reason you're trying to avoid using an established ORM?</p>
8
2009-08-23T21:23:54Z
[ "python", "sqlalchemy", "sqlobject" ]
Is this a good approach to avoid using SQLAlchemy/SQLObject?
1,319,585
<p>Rather than use an ORM, I am considering the following approach in Python and MySQL with no ORM (SQLObject/SQLAlchemy). I would like to get some feedback on whether this seems likely to have any negative long-term consequences since in the short-term view it seems fine from what I can tell.</p> <p>Rather than translate a row from the database into an object:</p> <ul> <li>each table is represented by a class</li> <li>a row is retrieved as a dict</li> <li><p>an object representing a cursor provides access to a table like so:</p> <p>cursor.mytable.get_by_ids(low, high)</p></li> <li><p>removing means setting the time_of_removal to the current time</p></li> </ul> <p>So essentially this does away with the need for an ORM since each table has a class to represent it and within that class, a separate dict represents each row.</p> <p>Type mapping is trivial because each dict (row) being a first class object in python/blub allows you to know the class of the object and, besides, the low-level database library in Python handles the conversion of types at the field level into their appropriate application-level types.</p> <p>If you see any potential problems with going down this road, please let me know. Thanks.</p>
3
2009-08-23T21:15:05Z
1,319,662
<p>You will still be using SQLAlchemy. ResultProxy is actually a dictionary once you go for .fetchmany() or similar.</p> <p>Use SQLAlchemy as a tool that makes managing connections easier, as well as executing statements. Documentation is pretty much separated in sections, so you will be reading just the part that you need.</p>
2
2009-08-23T21:48:45Z
[ "python", "sqlalchemy", "sqlobject" ]
Is this a good approach to avoid using SQLAlchemy/SQLObject?
1,319,585
<p>Rather than use an ORM, I am considering the following approach in Python and MySQL with no ORM (SQLObject/SQLAlchemy). I would like to get some feedback on whether this seems likely to have any negative long-term consequences since in the short-term view it seems fine from what I can tell.</p> <p>Rather than translate a row from the database into an object:</p> <ul> <li>each table is represented by a class</li> <li>a row is retrieved as a dict</li> <li><p>an object representing a cursor provides access to a table like so:</p> <p>cursor.mytable.get_by_ids(low, high)</p></li> <li><p>removing means setting the time_of_removal to the current time</p></li> </ul> <p>So essentially this does away with the need for an ORM since each table has a class to represent it and within that class, a separate dict represents each row.</p> <p>Type mapping is trivial because each dict (row) being a first class object in python/blub allows you to know the class of the object and, besides, the low-level database library in Python handles the conversion of types at the field level into their appropriate application-level types.</p> <p>If you see any potential problems with going down this road, please let me know. Thanks.</p>
3
2009-08-23T21:15:05Z
1,319,674
<p>web.py has in a decent db abstraction too (not an ORM). Queries are written in SQL (not specific to any rdbms), but your code remains compatible with any of the supported dbs (sqlite, mysql, postresql, and others).</p> <p>from <a href="http://webpy.org/cookbook/select" rel="nofollow">http://webpy.org/cookbook/select</a>:</p> <pre><code>myvar = dict(name="Bob") results = db.select('mytable', myvar, where="name = $name") </code></pre>
0
2009-08-23T21:55:10Z
[ "python", "sqlalchemy", "sqlobject" ]
Proper way to declare custom exceptions in modern Python?
1,319,615
<p>What's the proper way to declare custom exception classes in modern Python? My primary goal is to follow whatever standard other exception classes have, so that (for instance) any extra string I include in the exception is printed out by whatever tool caught the exception.</p> <p>By "modern Python" I mean something that will run in Python 2.5 but be 'correct' for the Python 2.6 and Python 3.* way of doing things. And by "custom" I mean an Exception object that can include extra data about the cause of the error: a string, maybe also some other arbitrary object relevant to the exception.</p> <p>I was tripped up by the following deprecation warning in Python 2.6.2:</p> <pre><code>&gt;&gt;&gt; class MyError(Exception): ... def __init__(self, message): ... self.message = message ... &gt;&gt;&gt; MyError("foo") _sandbox.py:3: DeprecationWarning: BaseException.message has been deprecated as of Python 2.6 </code></pre> <p>It seems crazy that <code>BaseException</code> has a special meaning for attributes named <code>message</code>. I gather from <A href="http://www.python.org/dev/peps/pep-0352/">PEP-352</a> that attribute did have a special meaning in 2.5 they're trying to deprecate away, so I guess that name (and that one alone) is now forbidden? Ugh.</p> <p>I'm also fuzzily aware that <code>Exception</code> has some magic parameter <code>args</code>, but I've never known how to use it. Nor am I sure it's the right way to do things going forward; a lot of the discussion I found online suggested they were trying to do away with args in Python 3.</p> <p>Update: two answers have suggested overriding <code>__init__</code>, and <code>__str__</code>/<code>__unicode__</code>/<code>__repr__</code>. That seems like a lot of typing, is it necessary?</p>
595
2009-08-23T21:29:29Z
1,319,660
<p>You should override <code>__repr__</code> or <code>__unicode__</code> methods instead of using message, the args you provide when you construct the exception will be in <code>args</code> member variable when you need.</p>
10
2009-08-23T21:46:54Z
[ "python", "exception" ]
Proper way to declare custom exceptions in modern Python?
1,319,615
<p>What's the proper way to declare custom exception classes in modern Python? My primary goal is to follow whatever standard other exception classes have, so that (for instance) any extra string I include in the exception is printed out by whatever tool caught the exception.</p> <p>By "modern Python" I mean something that will run in Python 2.5 but be 'correct' for the Python 2.6 and Python 3.* way of doing things. And by "custom" I mean an Exception object that can include extra data about the cause of the error: a string, maybe also some other arbitrary object relevant to the exception.</p> <p>I was tripped up by the following deprecation warning in Python 2.6.2:</p> <pre><code>&gt;&gt;&gt; class MyError(Exception): ... def __init__(self, message): ... self.message = message ... &gt;&gt;&gt; MyError("foo") _sandbox.py:3: DeprecationWarning: BaseException.message has been deprecated as of Python 2.6 </code></pre> <p>It seems crazy that <code>BaseException</code> has a special meaning for attributes named <code>message</code>. I gather from <A href="http://www.python.org/dev/peps/pep-0352/">PEP-352</a> that attribute did have a special meaning in 2.5 they're trying to deprecate away, so I guess that name (and that one alone) is now forbidden? Ugh.</p> <p>I'm also fuzzily aware that <code>Exception</code> has some magic parameter <code>args</code>, but I've never known how to use it. Nor am I sure it's the right way to do things going forward; a lot of the discussion I found online suggested they were trying to do away with args in Python 3.</p> <p>Update: two answers have suggested overriding <code>__init__</code>, and <code>__str__</code>/<code>__unicode__</code>/<code>__repr__</code>. That seems like a lot of typing, is it necessary?</p>
595
2009-08-23T21:29:29Z
1,319,675
<p>Maybe I missed the question, but why not:</p> <pre><code>class MyException(Exception): pass </code></pre> <p><strong>Edit:</strong> to override something (or pass extra args), do this:</p> <pre><code>class ValidationError(Exception): def __init__(self, message, errors): # Call the base class constructor with the parameters it needs super(ValidationError, self).__init__(message) # Now for your custom code... self.errors = errors </code></pre> <p>That way you could pass dict of error messages to the second param, and get to it later with <code>e.errors</code></p>
578
2009-08-23T21:55:23Z
[ "python", "exception" ]
Proper way to declare custom exceptions in modern Python?
1,319,615
<p>What's the proper way to declare custom exception classes in modern Python? My primary goal is to follow whatever standard other exception classes have, so that (for instance) any extra string I include in the exception is printed out by whatever tool caught the exception.</p> <p>By "modern Python" I mean something that will run in Python 2.5 but be 'correct' for the Python 2.6 and Python 3.* way of doing things. And by "custom" I mean an Exception object that can include extra data about the cause of the error: a string, maybe also some other arbitrary object relevant to the exception.</p> <p>I was tripped up by the following deprecation warning in Python 2.6.2:</p> <pre><code>&gt;&gt;&gt; class MyError(Exception): ... def __init__(self, message): ... self.message = message ... &gt;&gt;&gt; MyError("foo") _sandbox.py:3: DeprecationWarning: BaseException.message has been deprecated as of Python 2.6 </code></pre> <p>It seems crazy that <code>BaseException</code> has a special meaning for attributes named <code>message</code>. I gather from <A href="http://www.python.org/dev/peps/pep-0352/">PEP-352</a> that attribute did have a special meaning in 2.5 they're trying to deprecate away, so I guess that name (and that one alone) is now forbidden? Ugh.</p> <p>I'm also fuzzily aware that <code>Exception</code> has some magic parameter <code>args</code>, but I've never known how to use it. Nor am I sure it's the right way to do things going forward; a lot of the discussion I found online suggested they were trying to do away with args in Python 3.</p> <p>Update: two answers have suggested overriding <code>__init__</code>, and <code>__str__</code>/<code>__unicode__</code>/<code>__repr__</code>. That seems like a lot of typing, is it necessary?</p>
595
2009-08-23T21:29:29Z
1,319,680
<p>No, "message" is not forbidden. It's just deprecated. You application will work fine with using message. But you may want to get rid of the deprecation error, of course.</p> <p>When you create custom Exception classes for your application, many of them do not subclass just from Exception, but from others, like ValueError or similar. Then you have to adapt to their usage of variables.</p> <p>And if you have many exceptions in your application it's usually a good idea to have a common custom base class for all of them, so that users of your modules can do</p> <pre><code>try: ... except NelsonsExceptions: ... </code></pre> <p>And in that case you can do the <code>__init__ and __str__</code> needed there, so you don't have to repeat it for every exception. But simply calling the message variable something else than message does the trick.</p> <p>In any case, you only need the <code>__init__ or __str__</code> if you do something different from what Exception itself does. And because if the deprecation, you then need both, or you get an error. That's not a whole lot of extra code you need per class. ;)</p>
4
2009-08-23T21:58:47Z
[ "python", "exception" ]
Proper way to declare custom exceptions in modern Python?
1,319,615
<p>What's the proper way to declare custom exception classes in modern Python? My primary goal is to follow whatever standard other exception classes have, so that (for instance) any extra string I include in the exception is printed out by whatever tool caught the exception.</p> <p>By "modern Python" I mean something that will run in Python 2.5 but be 'correct' for the Python 2.6 and Python 3.* way of doing things. And by "custom" I mean an Exception object that can include extra data about the cause of the error: a string, maybe also some other arbitrary object relevant to the exception.</p> <p>I was tripped up by the following deprecation warning in Python 2.6.2:</p> <pre><code>&gt;&gt;&gt; class MyError(Exception): ... def __init__(self, message): ... self.message = message ... &gt;&gt;&gt; MyError("foo") _sandbox.py:3: DeprecationWarning: BaseException.message has been deprecated as of Python 2.6 </code></pre> <p>It seems crazy that <code>BaseException</code> has a special meaning for attributes named <code>message</code>. I gather from <A href="http://www.python.org/dev/peps/pep-0352/">PEP-352</a> that attribute did have a special meaning in 2.5 they're trying to deprecate away, so I guess that name (and that one alone) is now forbidden? Ugh.</p> <p>I'm also fuzzily aware that <code>Exception</code> has some magic parameter <code>args</code>, but I've never known how to use it. Nor am I sure it's the right way to do things going forward; a lot of the discussion I found online suggested they were trying to do away with args in Python 3.</p> <p>Update: two answers have suggested overriding <code>__init__</code>, and <code>__str__</code>/<code>__unicode__</code>/<code>__repr__</code>. That seems like a lot of typing, is it necessary?</p>
595
2009-08-23T21:29:29Z
10,270,732
<p>With modern Python Exceptions, you don't need to abuse <code>.message</code>, or override <code>.__str__()</code> or <code>.__repr__()</code> or any of it. If all you want is an informative message when your exception is raised, do this:</p> <pre><code>class MyException(Exception): pass raise MyException("My hovercraft is full of eels") </code></pre> <p>That will give a traceback ending with <code>MyException: My hovercraft is full of eels</code>.</p> <p>If you want more flexibiilty from the exception, you could pass a dictionary as the argument:</p> <pre><code>raise MyException({"message":"My hovercraft is full of animals", "animal":"eels"}) </code></pre> <p>However, to get at those details in an <code>except</code> block is a bit more complicated; they are stored in the <code>args</code> attribute, which is a list. You would need to do something like this:</p> <pre><code>try: raise MyException({"message":"My hovercraft is full of animals", "animal":"eels"}) except MyException as e: details = e.args[0] print(details["animal"]) </code></pre> <p>It is still possible to pass in multiple items into the exception, but this will be deprecated in the future. If you do need more than a single piece of information, then you should consider fully subclassing <code>Exception</code>.</p>
223
2012-04-22T18:18:17Z
[ "python", "exception" ]
Proper way to declare custom exceptions in modern Python?
1,319,615
<p>What's the proper way to declare custom exception classes in modern Python? My primary goal is to follow whatever standard other exception classes have, so that (for instance) any extra string I include in the exception is printed out by whatever tool caught the exception.</p> <p>By "modern Python" I mean something that will run in Python 2.5 but be 'correct' for the Python 2.6 and Python 3.* way of doing things. And by "custom" I mean an Exception object that can include extra data about the cause of the error: a string, maybe also some other arbitrary object relevant to the exception.</p> <p>I was tripped up by the following deprecation warning in Python 2.6.2:</p> <pre><code>&gt;&gt;&gt; class MyError(Exception): ... def __init__(self, message): ... self.message = message ... &gt;&gt;&gt; MyError("foo") _sandbox.py:3: DeprecationWarning: BaseException.message has been deprecated as of Python 2.6 </code></pre> <p>It seems crazy that <code>BaseException</code> has a special meaning for attributes named <code>message</code>. I gather from <A href="http://www.python.org/dev/peps/pep-0352/">PEP-352</a> that attribute did have a special meaning in 2.5 they're trying to deprecate away, so I guess that name (and that one alone) is now forbidden? Ugh.</p> <p>I'm also fuzzily aware that <code>Exception</code> has some magic parameter <code>args</code>, but I've never known how to use it. Nor am I sure it's the right way to do things going forward; a lot of the discussion I found online suggested they were trying to do away with args in Python 3.</p> <p>Update: two answers have suggested overriding <code>__init__</code>, and <code>__str__</code>/<code>__unicode__</code>/<code>__repr__</code>. That seems like a lot of typing, is it necessary?</p>
595
2009-08-23T21:29:29Z
18,108,623
<p>see how exceptions work by default if one <em>vs</em> more attributes are used (tracebacks omitted):</p> <pre><code>&gt;&gt;&gt; raise Exception('bad thing happened') Exception: bad thing happened &gt;&gt;&gt; raise Exception('bad thing happened', 'code is broken') Exception: ('bad thing happened', 'code is broken') </code></pre> <p>so you might want to have a sort of "<strong>exception template</strong>", working as an exception itself, in a compatible way:</p> <pre><code>&gt;&gt;&gt; nastyerr = NastyError('bad thing happened') &gt;&gt;&gt; raise nastyerr NastyError: bad thing happened &gt;&gt;&gt; raise nastyerr() NastyError: bad thing happened &gt;&gt;&gt; raise nastyerr('code is broken') NastyError: ('bad thing happened', 'code is broken') </code></pre> <p>this can be done easily with this subclass</p> <pre><code>class ExceptionTemplate(Exception): def __call__(self, *args): return self.__class__(*(self.args + args)) # ... class NastyError(ExceptionTemplate): pass </code></pre> <p>and if you don't like that default tuple-like representation, just add <code>__str__</code> method to the <code>ExceptionTemplate</code> class, like:</p> <pre><code> # ... def __str__(self): return ': '.join(self.args) </code></pre> <p>and you'll have</p> <pre><code>&gt;&gt;&gt; raise nastyerr('code is broken') NastyError: bad thing happened: code is broken </code></pre>
21
2013-08-07T16:23:56Z
[ "python", "exception" ]
Proper way to declare custom exceptions in modern Python?
1,319,615
<p>What's the proper way to declare custom exception classes in modern Python? My primary goal is to follow whatever standard other exception classes have, so that (for instance) any extra string I include in the exception is printed out by whatever tool caught the exception.</p> <p>By "modern Python" I mean something that will run in Python 2.5 but be 'correct' for the Python 2.6 and Python 3.* way of doing things. And by "custom" I mean an Exception object that can include extra data about the cause of the error: a string, maybe also some other arbitrary object relevant to the exception.</p> <p>I was tripped up by the following deprecation warning in Python 2.6.2:</p> <pre><code>&gt;&gt;&gt; class MyError(Exception): ... def __init__(self, message): ... self.message = message ... &gt;&gt;&gt; MyError("foo") _sandbox.py:3: DeprecationWarning: BaseException.message has been deprecated as of Python 2.6 </code></pre> <p>It seems crazy that <code>BaseException</code> has a special meaning for attributes named <code>message</code>. I gather from <A href="http://www.python.org/dev/peps/pep-0352/">PEP-352</a> that attribute did have a special meaning in 2.5 they're trying to deprecate away, so I guess that name (and that one alone) is now forbidden? Ugh.</p> <p>I'm also fuzzily aware that <code>Exception</code> has some magic parameter <code>args</code>, but I've never known how to use it. Nor am I sure it's the right way to do things going forward; a lot of the discussion I found online suggested they were trying to do away with args in Python 3.</p> <p>Update: two answers have suggested overriding <code>__init__</code>, and <code>__str__</code>/<code>__unicode__</code>/<code>__repr__</code>. That seems like a lot of typing, is it necessary?</p>
595
2009-08-23T21:29:29Z
26,938,914
<blockquote> <h1>"Proper way to declare custom exceptions in modern Python?"</h1> </blockquote> <p>This is fine, unless your exception is really a type of a more specific exception:</p> <pre><code>class MyException(Exception): pass </code></pre> <p>Or better (maybe perfect), instead of <code>pass</code> give a docstring:</p> <pre><code>class MyException(Exception): """Raise for my specific kind of exception""" </code></pre> <h2>Subclassing Exception Subclasses</h2> <p>From the <a href="https://docs.python.org/2/library/exceptions.html#exceptions.BaseException" rel="nofollow">docs</a></p> <blockquote> <p><code>Exception</code></p> <p>All built-in, non-system-exiting exceptions are derived from this class. All user-defined exceptions should also be derived from this class.</p> </blockquote> <p>That means that <strong>if</strong> your exception is a type of a more specific exception, subclass that exception instead of the generic <code>Exception</code> (and the result will be that you still derive from <code>Exception</code> as the docs recommend). Also, you can at least provide a docstring (and not be forced to use the <code>pass</code> keyword):</p> <pre><code>class MyAppValueError(ValueError): '''Raise when my specific value is wrong''' </code></pre> <p>Set attributes you create yourself with a custom <code>__init__</code>. Avoid passing a dict as a positional argument, future users of your code will thank you. If you use the deprecated message attribute, assigning it yourself will avoid a <code>DeprecationWarning</code>:</p> <pre><code>class MyAppValueError(ValueError): '''Raise when a specific subset of values in context of app is wrong''' def __init__(self, message, foo, *args): self.message = message # without this you may get DeprecationWarning # Special attribute you desire with your Error, # perhaps the value that caused the error?: self.foo = foo # allow users initialize misc. arguments as any other builtin Error super(MyAppValueError, self).__init__(message, foo, *args) </code></pre> <p>There's really no need to write your own <code>__str__</code> or <code>__repr__</code>. The builtin ones are very nice, and your <strong>cooperative inheritance</strong> ensures that you use it.</p> <h2>Critique of the top answer</h2> <blockquote> <p><em>Maybe I missed the question, but why not:</em></p> </blockquote> <pre><code>class MyException(Exception): pass </code></pre> <p>Again, the problem with the above is that in order to catch it, you'll either have to name it specifically (importing it if created elsewhere) or catch Exception, (but you're probably not prepared to handle all types of Exceptions, and you should only catch exceptions you are prepared to handle). Similar criticism to the below, but additionally that's not the way to initialize via <code>super</code>, and you'll get a <code>DeprecationWarning</code> if you access the message attribute:</p> <blockquote> <p><em>Edit: to override something (or pass extra args), do this:</em></p> </blockquote> <pre><code>class ValidationError(Exception): def __init__(self, message, errors): # Call the base class constructor with the parameters it needs super(ValidationError, self).__init__(message) # Now for your custom code... self.errors = errors </code></pre> <blockquote> <p><em>That way you could pass dict of error messages to the second param, and get to it later with e.errors</em></p> </blockquote> <p>It also requires exactly two arguments to be passed in (aside from the <code>self</code>.) No more, no less. That's an interesting constraint that future users may not appreciate. I'll demonstrate both errors:</p> <pre><code>&gt;&gt;&gt; ValidationError('foo', 'bar', 'baz').message Traceback (most recent call last): File "&lt;pyshell#10&gt;", line 1, in &lt;module&gt; ValidationError('foo', 'bar', 'baz').message TypeError: __init__() takes exactly 3 arguments (4 given) &gt;&gt;&gt; ValidationError('foo', 'bar').message __main__:1: DeprecationWarning: BaseException.message has been deprecated as of Python 2.6 'foo' </code></pre> <p>Compared to: </p> <pre><code>&gt;&gt;&gt; MyAppValueError('foo', 'FOO', 'bar').message 'foo' </code></pre>
53
2014-11-14T21:09:22Z
[ "python", "exception" ]
Key-ordered dict in Python
1,319,763
<p>I am looking for a solid implementation of an ordered associative array, that is, an ordered dictionary. I want the ordering in terms of keys, not of insertion order.</p> <p>More precisely, I am looking for a space-efficent implementation of a int-to-float (or string-to-float for another use case) mapping structure for which:</p> <ul> <li>Ordered iteration is O(n)</li> <li>Random access is O(1)</li> </ul> <p>The best I came up with was gluing a dict and a list of keys, keeping the last one ordered with bisect and insert.</p> <p>Any better ideas?</p>
24
2009-08-23T22:33:49Z
1,319,790
<p>An ordered tree is usually better for this cases, but random access is going to be log(n). You should keep into account also insertion and removal costs...</p>
4
2009-08-23T22:44:14Z
[ "python", "data-structures", "collections", "dictionary" ]
Key-ordered dict in Python
1,319,763
<p>I am looking for a solid implementation of an ordered associative array, that is, an ordered dictionary. I want the ordering in terms of keys, not of insertion order.</p> <p>More precisely, I am looking for a space-efficent implementation of a int-to-float (or string-to-float for another use case) mapping structure for which:</p> <ul> <li>Ordered iteration is O(n)</li> <li>Random access is O(1)</li> </ul> <p>The best I came up with was gluing a dict and a list of keys, keeping the last one ordered with bisect and insert.</p> <p>Any better ideas?</p>
24
2009-08-23T22:33:49Z
1,319,892
<p>You could build a dict that allows traversal by storing a pair <code>(value, next_key)</code> in each position. </p> <p>Random access:</p> <pre><code>my_dict[k][0] # for a key k </code></pre> <p>Traversal:</p> <pre><code>k = start_key # stored somewhere while k is not None: # next_key is None at the end of the list v, k = my_dict[k] yield v </code></pre> <p>Keep a pointer to <code>start</code> and <code>end</code> and you'll have efficient update for those cases where you just need to add onto the end of the list.</p> <p>Inserting in the middle is obviously O(n). Possibly you could build a <a href="http://en.wikipedia.org/wiki/Skiplist" rel="nofollow">skip list</a> on top of it if you need more speed.</p>
1
2009-08-23T23:42:24Z
[ "python", "data-structures", "collections", "dictionary" ]
Key-ordered dict in Python
1,319,763
<p>I am looking for a solid implementation of an ordered associative array, that is, an ordered dictionary. I want the ordering in terms of keys, not of insertion order.</p> <p>More precisely, I am looking for a space-efficent implementation of a int-to-float (or string-to-float for another use case) mapping structure for which:</p> <ul> <li>Ordered iteration is O(n)</li> <li>Random access is O(1)</li> </ul> <p>The best I came up with was gluing a dict and a list of keys, keeping the last one ordered with bisect and insert.</p> <p>Any better ideas?</p>
24
2009-08-23T22:33:49Z
1,320,113
<p>I'm not sure which python version are you working in, but in case you like to experiment, Python 3.1 includes and official implementation of Ordered dictionaries: <a href="http://www.python.org/dev/peps/pep-0372/" rel="nofollow">http://www.python.org/dev/peps/pep-0372/</a> <a href="http://docs.python.org/3.1/whatsnew/3.1.html#pep-372-ordered-dictionaries" rel="nofollow">http://docs.python.org/3.1/whatsnew/3.1.html#pep-372-ordered-dictionaries</a></p>
1
2009-08-24T01:37:18Z
[ "python", "data-structures", "collections", "dictionary" ]
Key-ordered dict in Python
1,319,763
<p>I am looking for a solid implementation of an ordered associative array, that is, an ordered dictionary. I want the ordering in terms of keys, not of insertion order.</p> <p>More precisely, I am looking for a space-efficent implementation of a int-to-float (or string-to-float for another use case) mapping structure for which:</p> <ul> <li>Ordered iteration is O(n)</li> <li>Random access is O(1)</li> </ul> <p>The best I came up with was gluing a dict and a list of keys, keeping the last one ordered with bisect and insert.</p> <p>Any better ideas?</p>
24
2009-08-23T22:33:49Z
1,320,137
<p>here's a pastie: I Had a need for something similar. Note however that this specific implementation is immutable, there are no inserts, once the instance is created: The exact performance doesn't quite match what you're asking for, however. Lookup is O(log n) and full scan is O(n). This works using the <code>bisect</code> module upon a tuple of key/value (tuple) pairs. Even if you can't use this precisely, you might have some success adapting it to your needs.</p> <pre><code>import bisect class dictuple(object): """ &gt;&gt;&gt; h0 = dictuple() &gt;&gt;&gt; h1 = dictuple({"apples": 1, "bananas":2}) &gt;&gt;&gt; h2 = dictuple({"bananas": 3, "mangoes": 5}) &gt;&gt;&gt; h1+h2 ('apples':1, 'bananas':3, 'mangoes':5) &gt;&gt;&gt; h1 &gt; h2 False &gt;&gt;&gt; h1 &gt; 6 False &gt;&gt;&gt; 'apples' in h1 True &gt;&gt;&gt; 'apples' in h2 False &gt;&gt;&gt; d1 = {} &gt;&gt;&gt; d1[h1] = "salad" &gt;&gt;&gt; d1[h1] 'salad' &gt;&gt;&gt; d1[h2] Traceback (most recent call last): ... KeyError: ('bananas':3, 'mangoes':5) """ def __new__(cls, *args, **kwargs): initial = {} args = [] if args is None else args for arg in args: initial.update(arg) initial.update(kwargs) instance = object.__new__(cls) instance.__items = tuple(sorted(initial.items(),key=lambda i:i[0])) return instance def __init__(self,*args, **kwargs): pass def __find(self,key): return bisect.bisect(self.__items, (key,)) def __getitem__(self, key): ind = self.__find(key) if self.__items[ind][0] == key: return self.__items[ind][1] raise KeyError(key) def __repr__(self): return "({0})".format(", ".join( "{0}:{1}".format(repr(item[0]),repr(item[1])) for item in self.__items)) def __contains__(self,key): ind = self.__find(key) return self.__items[ind][0] == key def __cmp__(self,other): return cmp(self.__class__.__name__, other.__class__.__name__ ) or cmp(self.__items, other.__items) def __eq__(self,other): return self.__items == other.__items def __format__(self,key): pass #def __ge__(self,key): # pass #def __getattribute__(self,key): # pass #def __gt__(self,key): # pass __seed = hash("dictuple") def __hash__(self): return dictuple.__seed^hash(self.__items) def __iter__(self): return self.iterkeys() def __len__(self): return len(self.__items) #def __reduce__(self,key): # pass #def __reduce_ex__(self,key): # pass #def __sizeof__(self,key): # pass @classmethod def fromkeys(cls,key,v=None): cls(dict.fromkeys(key,v)) def get(self,key, default): ind = self.__find(key) return self.__items[ind][1] if self.__items[ind][0] == key else default def has_key(self,key): ind = self.__find(key) return self.__items[ind][0] == key def items(self): return list(self.iteritems()) def iteritems(self): return iter(self.__items) def iterkeys(self): return (i[0] for i in self.__items) def itervalues(self): return (i[1] for i in self.__items) def keys(self): return list(self.iterkeys()) def values(self): return list(self.itervalues()) def __add__(self, other): _sum = dict(self.__items) _sum.update(other.__items) return self.__class__(_sum) if __name__ == "__main__": import doctest doctest.testmod() </code></pre>
0
2009-08-24T01:49:00Z
[ "python", "data-structures", "collections", "dictionary" ]
Key-ordered dict in Python
1,319,763
<p>I am looking for a solid implementation of an ordered associative array, that is, an ordered dictionary. I want the ordering in terms of keys, not of insertion order.</p> <p>More precisely, I am looking for a space-efficent implementation of a int-to-float (or string-to-float for another use case) mapping structure for which:</p> <ul> <li>Ordered iteration is O(n)</li> <li>Random access is O(1)</li> </ul> <p>The best I came up with was gluing a dict and a list of keys, keeping the last one ordered with bisect and insert.</p> <p>Any better ideas?</p>
24
2009-08-23T22:33:49Z
1,320,202
<p>"Random access O(1)" is an extremely exacting requirement which basically imposes an underlying hash table -- and I hope you do mean random READS only, because I think it can be mathematically proven than it's impossible in the general case to have O(1) writes as well as O(N) ordered iteration.</p> <p>I don't think you will find a pre-packaged container suited to your needs because they are so extreme -- O(log N) access would of course make all the difference in the world. To get the big-O behavior you want for reads and iterations you'll need to glue two data structures, essentially a dict and a heap (or sorted list or tree), and keep them in sync. Although you don't specify, I think you'll only get <em>amortized</em> behavior of the kind you want - unless you're truly willing to pay any performance hits for inserts and deletes, which is the literal implication of the specs you express but does seem a pretty unlikely real-life requirement.</p> <p>For O(1) read and <em>amortized</em> O(N) ordered iteration, just keep a list of all keys on the side of a dict. E.g.:</p> <pre><code>class Crazy(object): def __init__(self): self.d = {} self.L = [] self.sorted = True def __getitem__(self, k): return self.d[k] def __setitem__(self, k, v): if k not in self.d: self.L.append(k) self.sorted = False self.d[k] = v def __delitem__(self, k): del self.d[k] self.L.remove(k) def __iter__(self): if not self.sorted: self.L.sort() self.sorted = True return iter(self.L) </code></pre> <p>If you don't like the "amortized O(N) order" you can remove self.sorted and just repeat <code>self.L.sort()</code> in <code>__setitem__</code> itself. That makes writes O(N log N), of course (while I still had writes at O(1)). Either approach is viable and it's hard to think of one as intrinsically superior to the other. If you tend to do a bunch of writes then a bunch of iterations then the approach in the code above is best; if it's typically one write, one iteration, another write, another iteration, then it's just about a wash.</p> <p>BTW, this takes shameless advantage of the unusual (and wonderful;-) performance characteristics of Python's sort (aka "timsort"): among them, sorting a list that's mostly sorted but with a few extra items tacked on at the end is basically O(N) (if the tacked on items are few enough compared to the sorted prefix part). I hear Java's gaining this sort soon, as Josh Block was so impressed by a tech talk on Python's sort that he started coding it for the JVM on his laptop then and there. Most sytems (including I believe Jython as of today and IronPython too) basically have sorting as an O(N log N) operation, not taking advantage of "mostly ordered" inputs; "natural mergesort", which Tim Peters fashioned into Python's timsort of today, is a wonder in this respect.</p>
27
2009-08-24T02:20:48Z
[ "python", "data-structures", "collections", "dictionary" ]
Key-ordered dict in Python
1,319,763
<p>I am looking for a solid implementation of an ordered associative array, that is, an ordered dictionary. I want the ordering in terms of keys, not of insertion order.</p> <p>More precisely, I am looking for a space-efficent implementation of a int-to-float (or string-to-float for another use case) mapping structure for which:</p> <ul> <li>Ordered iteration is O(n)</li> <li>Random access is O(1)</li> </ul> <p>The best I came up with was gluing a dict and a list of keys, keeping the last one ordered with bisect and insert.</p> <p>Any better ideas?</p>
24
2009-08-23T22:33:49Z
1,320,943
<p>Here is my own implementation:</p> <pre><code>import bisect class KeyOrderedDict(object): __slots__ = ['d', 'l'] def __init__(self, *args, **kwargs): self.l = sorted(kwargs) self.d = kwargs def __setitem__(self, k, v): if not k in self.d: idx = bisect.bisect(self.l, k) self.l.insert(idx, k) self.d[k] = v def __getitem__(self, k): return self.d[k] def __delitem__(self, k): idx = bisect.bisect_left(self.l, k) del self.l[idx] del self.d[k] def __iter__(self): return iter(self.l) def __contains__(self, k): return k in self.d </code></pre> <p>The use of bisect keeps self.l ordered, and insertion is O(n) (because of the insert, but not a killer in my case, because I append far more often than truly insert, so the usual case is amortized O(1)). Access is O(1), and iteration O(n). But maybe someone had invented (in C) something with a more clever structure ?</p>
3
2009-08-24T07:38:59Z
[ "python", "data-structures", "collections", "dictionary" ]
Key-ordered dict in Python
1,319,763
<p>I am looking for a solid implementation of an ordered associative array, that is, an ordered dictionary. I want the ordering in terms of keys, not of insertion order.</p> <p>More precisely, I am looking for a space-efficent implementation of a int-to-float (or string-to-float for another use case) mapping structure for which:</p> <ul> <li>Ordered iteration is O(n)</li> <li>Random access is O(1)</li> </ul> <p>The best I came up with was gluing a dict and a list of keys, keeping the last one ordered with bisect and insert.</p> <p>Any better ideas?</p>
24
2009-08-23T22:33:49Z
11,072,522
<p>The ordereddict package ( <a href="http://anthon.home.xs4all.nl/Python/ordereddict/" rel="nofollow">http://anthon.home.xs4all.nl/Python/ordereddict/</a> ) that I implemented back in 2007 includes sorteddict. sorteddict is a KSO ( Key Sorted Order) dictionary. It is implemented in C and very space efficient and several times faster than a pure Python implementation. Downside is that only works with CPython.</p> <pre><code>&gt;&gt;&gt; from _ordereddict import sorteddict &gt;&gt;&gt; x = sorteddict() &gt;&gt;&gt; x[1] = 1.0 &gt;&gt;&gt; x[3] = 3.3 &gt;&gt;&gt; x[2] = 2.2 &gt;&gt;&gt; print x sorteddict([(1, 1.0), (2, 2.2), (3, 3.3)]) &gt;&gt;&gt; for i in x: ... print i, x[i] ... 1 1.0 2 2.2 3 3.3 &gt;&gt;&gt; </code></pre> <p>Sorry for the late reply, maybe this answer can help others find that library.</p>
1
2012-06-17T15:31:44Z
[ "python", "data-structures", "collections", "dictionary" ]
Key-ordered dict in Python
1,319,763
<p>I am looking for a solid implementation of an ordered associative array, that is, an ordered dictionary. I want the ordering in terms of keys, not of insertion order.</p> <p>More precisely, I am looking for a space-efficent implementation of a int-to-float (or string-to-float for another use case) mapping structure for which:</p> <ul> <li>Ordered iteration is O(n)</li> <li>Random access is O(1)</li> </ul> <p>The best I came up with was gluing a dict and a list of keys, keeping the last one ordered with bisect and insert.</p> <p>Any better ideas?</p>
24
2009-08-23T22:33:49Z
18,091,573
<p>For "string to float" problem you can use a Trie - it provides O(1) access time and O(n) sorted iteration. By "sorted" I mean "sorted alphabetically by key" - it seems that the question implies the same.</p> <p>Some implementations (each with its own strong and weak points):</p> <ul> <li><a href="https://github.com/biopython/biopython" rel="nofollow">https://github.com/biopython/biopython</a> has Bio.trie module with a full-featured Trie; other Trie packages are more memory-effcient;</li> <li><a href="https://github.com/kmike/datrie" rel="nofollow">https://github.com/kmike/datrie</a> - random insertions could be slow, keys alphabet must be known in advance;</li> <li><a href="https://github.com/kmike/hat-trie" rel="nofollow">https://github.com/kmike/hat-trie</a> - all operations are fast, but many dict methods are not implemented; underlying C library supports sorted iteration, but it is not implemented in a wrapper;</li> <li><a href="https://github.com/kmike/marisa-trie" rel="nofollow">https://github.com/kmike/marisa-trie</a> - very memory efficient, but doesn't support insertions; iteration is not sorted by default but can be made sorted (there is an example in docs);</li> <li><a href="https://github.com/kmike/DAWG" rel="nofollow">https://github.com/kmike/DAWG</a> - can be seen as a minimized Trie; very fast and memory efficient, but doesn't support insertions; has size limits (several GB of data)</li> </ul>
0
2013-08-06T22:24:30Z
[ "python", "data-structures", "collections", "dictionary" ]
Key-ordered dict in Python
1,319,763
<p>I am looking for a solid implementation of an ordered associative array, that is, an ordered dictionary. I want the ordering in terms of keys, not of insertion order.</p> <p>More precisely, I am looking for a space-efficent implementation of a int-to-float (or string-to-float for another use case) mapping structure for which:</p> <ul> <li>Ordered iteration is O(n)</li> <li>Random access is O(1)</li> </ul> <p>The best I came up with was gluing a dict and a list of keys, keeping the last one ordered with bisect and insert.</p> <p>Any better ideas?</p>
24
2009-08-23T22:33:49Z
22,996,715
<p>The <a href="http://www.grantjenks.com/docs/sortedcontainers/">sortedcontainers</a> module provides a <a href="http://www.grantjenks.com/docs/sortedcontainers/sorteddict.html">SortedDict</a> type that meets your requirements. It basically glues a <a href="http://www.grantjenks.com/docs/sortedcontainers/sortedlist.html">SortedList</a> and dict type together. The dict provides O(1) lookup and the SortedList provides O(N) iteration (it's extremely fast). The whole module is pure-Python and has <a href="http://www.grantjenks.com/docs/sortedcontainers/performance.html">benchmark graphs</a> to backup the performance claims (fast-as-C implementations). SortedDict is also fully tested with 100% coverage and hours of stress. It's compatible with Python 2.6 through 3.4.</p>
6
2014-04-10T18:58:34Z
[ "python", "data-structures", "collections", "dictionary" ]
How to submit data of a flash form? [python]
1,319,895
<p>I would like to know if it is possible to submit a flash form from python and, if it is, how? I have done form submitting from python before, but the forms were HTML not flash. I really have no idea on how to do this. In my research about this I kept getting 'Ming'. However, Ming is only to create .swf files and that's not what I intend to do.</p> <p>Any help on this is greatly appreciated.</p>
3
2009-08-23T23:42:52Z
1,319,907
<p>You can set the url attribute (I think it's url, please correct me if I'm wrong) on a Flash form control to a Python script - then it will pass it through HTTP POST like any normal HTML form.</p> <p>You've got nothing to be afraid of, it uses the same protocol to communicate, it's just a different submission process.</p>
1
2009-08-23T23:50:18Z
[ "python", "flash", "forms" ]
How to submit data of a flash form? [python]
1,319,895
<p>I would like to know if it is possible to submit a flash form from python and, if it is, how? I have done form submitting from python before, but the forms were HTML not flash. I really have no idea on how to do this. In my research about this I kept getting 'Ming'. However, Ming is only to create .swf files and that's not what I intend to do.</p> <p>Any help on this is greatly appreciated.</p>
3
2009-08-23T23:42:52Z
1,320,103
<p>For your flash app, there's no difference if the backend is python, php or anything, so you can follow a normal "php + flash contact form" guide and then build the backend using django or any other python web framework, receive the information from the http request (GET or POST, probably the last one) and do whatever you wanted to do with them.</p> <p>Notice the response from python to flash works the same as with php, it's just http content, so you can use XML or even better, JSON.</p>
0
2009-08-24T01:30:45Z
[ "python", "flash", "forms" ]
urlopen, BeautifulSoup and UTF-8 Issue
1,320,591
<p>I am just trying to retrieve a web page, but somehow a foreign character is embedded in the HTML file. This character is not visible when I use "View Source."</p> <pre><code>isbn = 9780141187983 url = "http://search.barnesandnoble.com/booksearch/isbninquiry.asp?ean=%s" % isbn opener = urllib2.build_opener() url_opener = opener.open(url) page = url_opener.read() html = BeautifulSoup(page) html #This line causes error. Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 21555: ordinal not in range(128) </code></pre> <p>I also tried...</p> <pre><code>html = BeautifulSoup(page.encode('utf-8')) </code></pre> <p>How can I read this web page into BeautifulSoup without getting this error?</p>
2
2009-08-24T05:17:24Z
1,320,669
<p>This error is probably actually happening when you try to <em>print</em> the representation of the BeautifulSoup file, which will happen automatically if, as I suspect, you are working in the interactive console. </p> <pre><code># This code will work fine, note we are assigning the result # of the BeautifulSoup object to prevent it from printing immediately. from BeautifulSoup import BeautifulSoup soup = BeautifulSoup(u'\xa0') # This will probably show the error you saw print soup # And this would probably be fine print soup.encode('utf-8') </code></pre>
11
2009-08-24T05:58:34Z
[ "python", "utf-8", "urllib2", "beautifulsoup" ]
urlopen, BeautifulSoup and UTF-8 Issue
1,320,591
<p>I am just trying to retrieve a web page, but somehow a foreign character is embedded in the HTML file. This character is not visible when I use "View Source."</p> <pre><code>isbn = 9780141187983 url = "http://search.barnesandnoble.com/booksearch/isbninquiry.asp?ean=%s" % isbn opener = urllib2.build_opener() url_opener = opener.open(url) page = url_opener.read() html = BeautifulSoup(page) html #This line causes error. Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 21555: ordinal not in range(128) </code></pre> <p>I also tried...</p> <pre><code>html = BeautifulSoup(page.encode('utf-8')) </code></pre> <p>How can I read this web page into BeautifulSoup without getting this error?</p>
2
2009-08-24T05:17:24Z
34,416,469
<p>You could try the following :</p> <pre><code>import codecs f = codecs.open(filename,'r','utf-8') soup = BeautifulSoup(f.read(),"html.parser") </code></pre> <p>I encountered a similar problem with bs4</p>
0
2015-12-22T12:58:27Z
[ "python", "utf-8", "urllib2", "beautifulsoup" ]
How to encrypt a string using the key
1,320,671
<p>I have a 'public key' in a variable named varkey, for getting the public key I used the urllib and stored that public key in a variable. Now I want to encrypt a msg/string using the public key.</p> <p>It's ok if somebody could lead me to some library.</p>
2
2009-08-24T06:00:00Z
1,320,681
<p>You might want to have a look at:</p> <p><a href="http://www.example-code.com/python/encryption.asp" rel="nofollow">http://www.example-code.com/python/encryption.asp</a></p> <p>or this</p> <p><a href="http://passingcuriosity.com/2009/aes-encryption-in-python-with-m2crypto/" rel="nofollow">http://passingcuriosity.com/2009/aes-encryption-in-python-with-m2crypto/</a></p>
0
2009-08-24T06:04:45Z
[ "python", "encryption" ]
How to encrypt a string using the key
1,320,671
<p>I have a 'public key' in a variable named varkey, for getting the public key I used the urllib and stored that public key in a variable. Now I want to encrypt a msg/string using the public key.</p> <p>It's ok if somebody could lead me to some library.</p>
2
2009-08-24T06:00:00Z
1,320,686
<p>You could use MD5 or SHA1 hashing along with your key...</p>
-2
2009-08-24T06:05:21Z
[ "python", "encryption" ]
How to encrypt a string using the key
1,320,671
<p>I have a 'public key' in a variable named varkey, for getting the public key I used the urllib and stored that public key in a variable. Now I want to encrypt a msg/string using the public key.</p> <p>It's ok if somebody could lead me to some library.</p>
2
2009-08-24T06:00:00Z
1,320,693
<p>From my recent python experience, python doesn't do encryption natively. You need to use an external (3rd party) package. Each of these, obviously, offers a different experience. Which are you using? This will probably determine how your syntax will vary.</p>
1
2009-08-24T06:06:10Z
[ "python", "encryption" ]
How to encrypt a string using the key
1,320,671
<p>I have a 'public key' in a variable named varkey, for getting the public key I used the urllib and stored that public key in a variable. Now I want to encrypt a msg/string using the public key.</p> <p>It's ok if somebody could lead me to some library.</p>
2
2009-08-24T06:00:00Z
1,480,380
<p>My blog post (the passingcuriosity.com link in John Boker's answer) does AES -- a symmetric encryption algorithm -- using the M2Crypto library. M2Crypto is a Python wrapper around OpenSSL. The API is pretty much a straight translation of OpenSSL's into Python, so the somewhat sketchy documentation shouldn't be too much of a problem. If the public key encryption algorithm you need to use is supported by M2Crypto, then you could very well use it to do your public key cryptography.</p> <p>I found the <a href="http://svn.osafoundation.org/m2crypto/trunk/tests/">M2Crypto test suite</a> to be a useful example of using its API. In particular, the RSA (in test_rsa.py), PGP (in test_pgp.py), and EVP (in test_evp.py) tests will help you figure out how to set up and use the library. Do be aware that they are unit-tests, so it can be a little tricky to figure out exactly what code is necessary and what is an artefact of being a test.</p> <p>PS: As I'm new, my posts can only contain one link so I had to delete most of them. Sorry.</p> <h3>Example</h3> <pre><code>from M2Crypto import RSA rsa = RSA.load_pub_key('rsa.pub.pem') encrypted = rsa.public_encrypt('your message', RSA.pkcs1_oaep_padding) print encrypted.encode('base64') </code></pre> <h3>Output</h3> <pre> X3iTasRwRdW0qPRQBXiKN5zvPa3LBiCDnA3HLH172wXTEr4LNq2Kl32PCcXpIMxh7j9CmysLyWu5 GLQ18rUNqi9ydG4ihwz3v3xeNMG9O3/Oc1XsHqqIRI8MrCWTTEbAWaXFX1YVulVLaVy0elODECKV 4e9gCN+5dx/aG9LtPOE= </pre>
6
2009-09-26T03:41:39Z
[ "python", "encryption" ]
How to encrypt a string using the key
1,320,671
<p>I have a 'public key' in a variable named varkey, for getting the public key I used the urllib and stored that public key in a variable. Now I want to encrypt a msg/string using the public key.</p> <p>It's ok if somebody could lead me to some library.</p>
2
2009-08-24T06:00:00Z
1,480,597
<p>Here's the script that demonstrates how to encrypt a message using M2Crypto (<code>$ easy_install m2crypto</code>) given that public key is in <code>varkey</code> variable:</p> <pre><code>#!/usr/bin/env python import urllib2 from M2Crypto import BIO, RSA def readkey(filename): try: key = open(filename).read() except IOError: key = urllib2.urlopen( 'http://svn.osafoundation.org/m2crypto/trunk/tests/' + filename ).read() open(filename, 'w').write(key) return key def test(): message = 'disregard the -man- (I mean file) behind curtain' varkey = readkey('rsa.pub.pem') # demonstrate how to load key from a string bio = BIO.MemoryBuffer(varkey) rsa = RSA.load_pub_key_bio(bio) # encrypt encrypted = rsa.public_encrypt(message, RSA.pkcs1_oaep_padding) print encrypted.encode('base64') del rsa, bio # decrypt read_password = lambda *args: 'qwerty' rsa = RSA.load_key_string(readkey('rsa.priv2.pem'), read_password) decrypted = rsa.private_decrypt(encrypted, RSA.pkcs1_oaep_padding) print decrypted assert message == decrypted if __name__ == "__main__": test() </code></pre> <h3>Output</h3> <pre> gyLD3B6jXspHu+o7M/TGLAqALihw7183E2effp9ALYfu8azYEPwMpjbw9nVSwJ4VvX3TBa4V0HAU n6x3xslvOnegv8dv3MestEcTH9b3r2U1rsKJc1buouuc+MR77Powj9JOdizQPT22HQ2VpEAKFMK+ 8zHbkJkgh4K5XUejmIk= disregard the -man- (I mean file) behind curtain </pre>
3
2009-09-26T06:46:29Z
[ "python", "encryption" ]
How to encrypt a string using the key
1,320,671
<p>I have a 'public key' in a variable named varkey, for getting the public key I used the urllib and stored that public key in a variable. Now I want to encrypt a msg/string using the public key.</p> <p>It's ok if somebody could lead me to some library.</p>
2
2009-08-24T06:00:00Z
3,123,241
<p>Very funny. Have you ever heard about "RSAError: data too large for key size" ? No???? Try your sample with more long message:</p> <pre><code>encrypted = rsa.public_encrypt('My blog post (the passingcuriosity.com link in John Boker's answer) does AES -- a symmetric encryption algorithm -- using the M2Crypto library', RSA.pkcs1_oaep_padding) </code></pre> <hr> <p>best regards</p>
1
2010-06-26T08:28:21Z
[ "python", "encryption" ]
Good graph traversal algorithm
1,320,688
<p>Abstract problem : I have a graph of about 250,000 nodes and the average connectivity is around 10. Finding a node's connections is a long process (10 seconds lets say). Saving a node to the database also takes about 10 seconds. I can check if a node is already present in the db very quickly. Allowing concurrency, but not having more than 10 long requests at a time, how would you traverse the graph to gain the highest coverage the quickest.</p> <p>Concrete problem : I'm trying to scrape a website user pages. To discover new users I'm fetching the friend list from already known users. I've already imported about 10% of the graph but I keep getting stuck in cycles or using too much memory remembering too many nodes.</p> <p>My current implementation : </p> <pre><code>def run() : import_pool = ThreadPool(10) user_pool = ThreadPool(1) do_user("arcaneCoder", import_pool, user_pool) def do_user(user, import_pool, user_pool) : id = user alias = models.Alias.get(id) # if its been updates in the last 7 days if alias and alias.modified + datetime.timedelta(days=7) &gt; datetime.datetime.now() : sys.stderr.write("Skipping: %s\n" % user) else : sys.stderr.write("Importing: %s\n" % user) while import_pool.num_jobs() &gt; 20 : print "Too many queued jobs, sleeping" time.sleep(15) import_pool.add_job(alias_view.import_id, [id], lambda rv : sys.stderr.write("Done Importing %s\n" % user)) sys.stderr.write("Crawling: %s\n" % user) users = crawl(id, 5) if len(users) &gt;= 2 : for user in random.sample(users, 2) : if (user_pool.num_jobs() &lt; 100) : user_pool.add_job(do_user, [user, import_pool, user_pool]) def crawl(id, limit=50) : '''returns the first 'limit' friends of a user''' *not relevant* </code></pre> <p>Problems of current implementation :</p> <ul> <li>Gets stuck in cliques that I've already imported, thereby wasting time and the importing threads are idle.</li> <li>Will add more as they get pointed out.</li> </ul> <p>So, marginal improvments are welcome, as well as full rewrites. Thanks!</p>
11
2009-08-24T06:05:32Z
1,320,714
<p>I am really confused as to why it takes 10 seconds to add a node to the DB. That sounds like a problem. What database are you using? Do you have severe platform restrictions?</p> <p>With modern systems, and their oodles of memory, I would recommend a nice simple cache of some kind. You should be able to create a very quick cache of user information that would allow you to avoid repeated work. When you have encountered a node already, stop processing. This will avoid cycling forever in cliques.</p> <p>If you need to allow for rehashing existing nodes after a while, you can use a last_visit_number which would be a global value in the dB. If the node has that number, then this crawl is the one that encountered it. If you want to automatically revisit any nodes, you just need to bump the last_visit_number before starting the crawl.</p> <p>By your description, I am not quite sure how you are getting stuck.</p> <p>Edit ------ I just noticed you had a concrete question. In order to increase how quickly you pull in new data, I would keep track of the number of times a given user was linked to in your data (imported or not yet imported). When choosing a user to crawl, I would pick users that have a low number of links. I would specifically go for either the lowest number of links or a random choice among the users with the lowest number of links.</p> <p>Jacob</p>
2
2009-08-24T06:15:06Z
[ "python", "performance", "algorithm", "language-agnostic", "graph-traversal" ]
Good graph traversal algorithm
1,320,688
<p>Abstract problem : I have a graph of about 250,000 nodes and the average connectivity is around 10. Finding a node's connections is a long process (10 seconds lets say). Saving a node to the database also takes about 10 seconds. I can check if a node is already present in the db very quickly. Allowing concurrency, but not having more than 10 long requests at a time, how would you traverse the graph to gain the highest coverage the quickest.</p> <p>Concrete problem : I'm trying to scrape a website user pages. To discover new users I'm fetching the friend list from already known users. I've already imported about 10% of the graph but I keep getting stuck in cycles or using too much memory remembering too many nodes.</p> <p>My current implementation : </p> <pre><code>def run() : import_pool = ThreadPool(10) user_pool = ThreadPool(1) do_user("arcaneCoder", import_pool, user_pool) def do_user(user, import_pool, user_pool) : id = user alias = models.Alias.get(id) # if its been updates in the last 7 days if alias and alias.modified + datetime.timedelta(days=7) &gt; datetime.datetime.now() : sys.stderr.write("Skipping: %s\n" % user) else : sys.stderr.write("Importing: %s\n" % user) while import_pool.num_jobs() &gt; 20 : print "Too many queued jobs, sleeping" time.sleep(15) import_pool.add_job(alias_view.import_id, [id], lambda rv : sys.stderr.write("Done Importing %s\n" % user)) sys.stderr.write("Crawling: %s\n" % user) users = crawl(id, 5) if len(users) &gt;= 2 : for user in random.sample(users, 2) : if (user_pool.num_jobs() &lt; 100) : user_pool.add_job(do_user, [user, import_pool, user_pool]) def crawl(id, limit=50) : '''returns the first 'limit' friends of a user''' *not relevant* </code></pre> <p>Problems of current implementation :</p> <ul> <li>Gets stuck in cliques that I've already imported, thereby wasting time and the importing threads are idle.</li> <li>Will add more as they get pointed out.</li> </ul> <p>So, marginal improvments are welcome, as well as full rewrites. Thanks!</p>
11
2009-08-24T06:05:32Z
1,320,716
<p>To remember IDs of the users you've already visited, you need a map of a length of 250,000 integers. That's far from "too much". Just maintain such a map and only traverse through the edges that lead to the already undiscovered users, adding them to that map at the point of finding such edge.</p> <p>As far I can see, you're close to implement Breadth-first search (BFS). Check google about the details of this algorithm. And, of course, do not forget about mutexes -- you'll need them.</p>
7
2009-08-24T06:15:54Z
[ "python", "performance", "algorithm", "language-agnostic", "graph-traversal" ]
Good graph traversal algorithm
1,320,688
<p>Abstract problem : I have a graph of about 250,000 nodes and the average connectivity is around 10. Finding a node's connections is a long process (10 seconds lets say). Saving a node to the database also takes about 10 seconds. I can check if a node is already present in the db very quickly. Allowing concurrency, but not having more than 10 long requests at a time, how would you traverse the graph to gain the highest coverage the quickest.</p> <p>Concrete problem : I'm trying to scrape a website user pages. To discover new users I'm fetching the friend list from already known users. I've already imported about 10% of the graph but I keep getting stuck in cycles or using too much memory remembering too many nodes.</p> <p>My current implementation : </p> <pre><code>def run() : import_pool = ThreadPool(10) user_pool = ThreadPool(1) do_user("arcaneCoder", import_pool, user_pool) def do_user(user, import_pool, user_pool) : id = user alias = models.Alias.get(id) # if its been updates in the last 7 days if alias and alias.modified + datetime.timedelta(days=7) &gt; datetime.datetime.now() : sys.stderr.write("Skipping: %s\n" % user) else : sys.stderr.write("Importing: %s\n" % user) while import_pool.num_jobs() &gt; 20 : print "Too many queued jobs, sleeping" time.sleep(15) import_pool.add_job(alias_view.import_id, [id], lambda rv : sys.stderr.write("Done Importing %s\n" % user)) sys.stderr.write("Crawling: %s\n" % user) users = crawl(id, 5) if len(users) &gt;= 2 : for user in random.sample(users, 2) : if (user_pool.num_jobs() &lt; 100) : user_pool.add_job(do_user, [user, import_pool, user_pool]) def crawl(id, limit=50) : '''returns the first 'limit' friends of a user''' *not relevant* </code></pre> <p>Problems of current implementation :</p> <ul> <li>Gets stuck in cliques that I've already imported, thereby wasting time and the importing threads are idle.</li> <li>Will add more as they get pointed out.</li> </ul> <p>So, marginal improvments are welcome, as well as full rewrites. Thanks!</p>
11
2009-08-24T06:05:32Z
1,320,755
<p>There is no particular algorithm that will help you optimise the construction of a graph from scratch. One way or another, you are going to have to visit each node at least once. Whether you do this <a href="http://en.wikipedia.org/wiki/Depth-first%5Fsearch" rel="nofollow">depth first</a> or <a href="http://en.wikipedia.org/wiki/Breadth-first%5Fsearch" rel="nofollow">breadth first</a> is irrelevant from a speed perspective. <a href="http://stackoverflow.com/users/40180/theran">Theran</a> correctly points out in a comment below that breadth-first search, by exploring nearer nodes first, may give you a more useful graph immediately, before the whole graph is completed; this may or may not be a concern for you. He also notes that the neatest version of depth-first search is implemented using recursion, which could potentially be a problem for you. Note that recursion is not required, however; you can add incompletely explored nodes to a stack and process them linearly if you wish.</p> <p>If you do a simple existence check for new nodes (O(1) if you use a hash for lookup), then cycles will not be a problem at all. Cycles are only a concern if you do not store the complete graph. You can optimise searches through the graph, but the construction step itself will always take linear time.</p> <p>I agree with other posters that the size of your graph should not be a problem. 250,000 is not very large!</p> <p>Regarding concurrent execution; the graph is updated by all threads, so it needs to be a synchronised data structure. Since this is Python, you can make use of the <a href="http://docs.python.org/library/queue.html" rel="nofollow">Queue</a> module to store new links still to be processed by your threads.</p>
2
2009-08-24T06:30:09Z
[ "python", "performance", "algorithm", "language-agnostic", "graph-traversal" ]
Good graph traversal algorithm
1,320,688
<p>Abstract problem : I have a graph of about 250,000 nodes and the average connectivity is around 10. Finding a node's connections is a long process (10 seconds lets say). Saving a node to the database also takes about 10 seconds. I can check if a node is already present in the db very quickly. Allowing concurrency, but not having more than 10 long requests at a time, how would you traverse the graph to gain the highest coverage the quickest.</p> <p>Concrete problem : I'm trying to scrape a website user pages. To discover new users I'm fetching the friend list from already known users. I've already imported about 10% of the graph but I keep getting stuck in cycles or using too much memory remembering too many nodes.</p> <p>My current implementation : </p> <pre><code>def run() : import_pool = ThreadPool(10) user_pool = ThreadPool(1) do_user("arcaneCoder", import_pool, user_pool) def do_user(user, import_pool, user_pool) : id = user alias = models.Alias.get(id) # if its been updates in the last 7 days if alias and alias.modified + datetime.timedelta(days=7) &gt; datetime.datetime.now() : sys.stderr.write("Skipping: %s\n" % user) else : sys.stderr.write("Importing: %s\n" % user) while import_pool.num_jobs() &gt; 20 : print "Too many queued jobs, sleeping" time.sleep(15) import_pool.add_job(alias_view.import_id, [id], lambda rv : sys.stderr.write("Done Importing %s\n" % user)) sys.stderr.write("Crawling: %s\n" % user) users = crawl(id, 5) if len(users) &gt;= 2 : for user in random.sample(users, 2) : if (user_pool.num_jobs() &lt; 100) : user_pool.add_job(do_user, [user, import_pool, user_pool]) def crawl(id, limit=50) : '''returns the first 'limit' friends of a user''' *not relevant* </code></pre> <p>Problems of current implementation :</p> <ul> <li>Gets stuck in cliques that I've already imported, thereby wasting time and the importing threads are idle.</li> <li>Will add more as they get pointed out.</li> </ul> <p>So, marginal improvments are welcome, as well as full rewrites. Thanks!</p>
11
2009-08-24T06:05:32Z
1,320,846
<p>Although you say that getting a friend list takes a lot of time (10 seconds or more), a variant of good-old Dijkstra's algorithm just might work:</p> <ol> <li>Get any node.</li> <li>Get a connection from any node you already loaded.</li> <li>If the other end hasn't been loaded yet, add the node to the graph.</li> <li>Go to step 2.</li> </ol> <p>The trick is to select the connection you load in step 2 in a smart way. A few short remarks about this:</p> <ul> <li>You should somehow prevent the same connection to be loaded twice or more often. Selecting a random connection and discard it if it's been loaded already is very inefficient if you're after all connections.</li> <li>If you want to load all connections eventually, load all connections of a node at the same time.</li> </ul> <p>In order to really say something about efficiency, please provide more details about datastructure.</p>
0
2009-08-24T07:04:43Z
[ "python", "performance", "algorithm", "language-agnostic", "graph-traversal" ]
Count number of files with certain extension in Python
1,320,731
<p>I am fairly new to Python and I am trying to figure out the most efficient way to count the number of .TIF files in a particular sub-directory.</p> <p>Doing some searching, I found one example (I have not tested), which claimed to count all of the files in a directory:</p> <pre><code>file_count = sum((len(f) for _, _, f in os.walk(myPath))) </code></pre> <p>This is fine, but I need to only count TIF files. My directory will contain other files types, but I only want to count TIFs.</p> <p>Currently I am using the following code:</p> <pre><code>tifCounter = 0 for root, dirs, files in os.walk(myPath): for file in files: if file.endswith('.tif'): tifCounter += 1 </code></pre> <p>It works fine, but the looping seems to be excessive/expensive to me. Any way to do this more efficiently?</p> <p>Thanks.</p>
16
2009-08-24T06:20:54Z
1,320,739
<p>Your code is fine. </p> <p>Yes, you're going to need to loop over those files to filter out the .tif files, but looping over a small in-memory array is negligible compared to the work of scanning the file directory to find these files in the first place, which you have to do anyway.</p> <p>I wouldn't worry about optimizing this code.</p>
4
2009-08-24T06:24:47Z
[ "python", "file", "count" ]
Count number of files with certain extension in Python
1,320,731
<p>I am fairly new to Python and I am trying to figure out the most efficient way to count the number of .TIF files in a particular sub-directory.</p> <p>Doing some searching, I found one example (I have not tested), which claimed to count all of the files in a directory:</p> <pre><code>file_count = sum((len(f) for _, _, f in os.walk(myPath))) </code></pre> <p>This is fine, but I need to only count TIF files. My directory will contain other files types, but I only want to count TIFs.</p> <p>Currently I am using the following code:</p> <pre><code>tifCounter = 0 for root, dirs, files in os.walk(myPath): for file in files: if file.endswith('.tif'): tifCounter += 1 </code></pre> <p>It works fine, but the looping seems to be excessive/expensive to me. Any way to do this more efficiently?</p> <p>Thanks.</p>
16
2009-08-24T06:20:54Z
1,320,744
<p>Something has to iterate over all files in the directory, and look at every single file name - whether that's your code or a library routine. So no matter what the specific solution, they will all have roughly the same cost.</p> <p>If you think it's too much code, and if you don't actually need to search subdirectories recursively, you can use the <code>glob</code> module:</p> <pre><code>tifCounter = len(glob.glob1(myPath,"*.tif")) </code></pre>
23
2009-08-24T06:26:35Z
[ "python", "file", "count" ]
Count number of files with certain extension in Python
1,320,731
<p>I am fairly new to Python and I am trying to figure out the most efficient way to count the number of .TIF files in a particular sub-directory.</p> <p>Doing some searching, I found one example (I have not tested), which claimed to count all of the files in a directory:</p> <pre><code>file_count = sum((len(f) for _, _, f in os.walk(myPath))) </code></pre> <p>This is fine, but I need to only count TIF files. My directory will contain other files types, but I only want to count TIFs.</p> <p>Currently I am using the following code:</p> <pre><code>tifCounter = 0 for root, dirs, files in os.walk(myPath): for file in files: if file.endswith('.tif'): tifCounter += 1 </code></pre> <p>It works fine, but the looping seems to be excessive/expensive to me. Any way to do this more efficiently?</p> <p>Thanks.</p>
16
2009-08-24T06:20:54Z
1,320,780
<p>If you do need to search recursively, or for some other reason don't want to use the <code>glob</code> module, you could use</p> <pre><code>file_count = sum(len(f for f in fs if f.lower().endswith('.tif')) for _, _, fs in os.walk(myPath)) </code></pre> <p>This is the "Pythonic" way to adapt the example you found for your purposes. But it's not going to be significantly faster or more efficient than the loop you've been using; it's just a really compact syntax for more or less the same thing.</p>
2
2009-08-24T06:39:08Z
[ "python", "file", "count" ]
Count number of files with certain extension in Python
1,320,731
<p>I am fairly new to Python and I am trying to figure out the most efficient way to count the number of .TIF files in a particular sub-directory.</p> <p>Doing some searching, I found one example (I have not tested), which claimed to count all of the files in a directory:</p> <pre><code>file_count = sum((len(f) for _, _, f in os.walk(myPath))) </code></pre> <p>This is fine, but I need to only count TIF files. My directory will contain other files types, but I only want to count TIFs.</p> <p>Currently I am using the following code:</p> <pre><code>tifCounter = 0 for root, dirs, files in os.walk(myPath): for file in files: if file.endswith('.tif'): tifCounter += 1 </code></pre> <p>It works fine, but the looping seems to be excessive/expensive to me. Any way to do this more efficiently?</p> <p>Thanks.</p>
16
2009-08-24T06:20:54Z
1,321,138
<p>For this particular use case, if you don't want to recursively search in the subdirectory, you can use <code>os.listdir</code>:</p> <pre><code>len([f for f in os.listdir(myPath) if f.endswith('.tif') and os.path.isfile(os.path.join(myPath, f))]) </code></pre>
3
2009-08-24T08:33:22Z
[ "python", "file", "count" ]
Detect and delete locked file in python
1,320,812
<p>I want to detect whether a file is locked, using python on Unix. It's OK to delete the file, assuming that it helps detects whether the file was locked.</p> <p>The file could have been originally opened exclusively by another process. Documentation seems to suggest that os.unlink won't necessarily return an error if the file is locked. </p> <p>Ideas? </p>
3
2009-08-24T06:51:04Z
1,320,880
<p>From the <a href="http://docs.python.org/library/fcntl.html" rel="nofollow">fcntl</a> docs:</p> <blockquote> <p>fcntl.lockf(fd, operation[, length[, start[, whence]]])</p> <p>If LOCK_NB is used and the lock cannot be acquired, an IOError will be raised and the exception will have an errno attribute set to EACCES or EAGAIN (depending on the operating system; for portability, check for both values).</p> </blockquote> <p>This uses the underlying unix <code>flock</code> mechanism, so looks like it should do what you want. Also note there is also <a href="http://docs.python.org/library/os.html#os.open" rel="nofollow"><code>os.open</code></a>, which may be more platform-independent.</p>
6
2009-08-24T07:14:24Z
[ "python" ]
Detect and delete locked file in python
1,320,812
<p>I want to detect whether a file is locked, using python on Unix. It's OK to delete the file, assuming that it helps detects whether the file was locked.</p> <p>The file could have been originally opened exclusively by another process. Documentation seems to suggest that os.unlink won't necessarily return an error if the file is locked. </p> <p>Ideas? </p>
3
2009-08-24T06:51:04Z
1,321,060
<p>The best way to check if a file is locked is to try to lock it. The <a href="http://docs.python.org/library/fcntl.html">fcntl module</a> will do this in Python, e.g.</p> <p><code>fcntl.lockf(fileobj.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)</code></p> <p>This will raise an IOError if the file is already locked; if it doesn't, you can then call</p> <p><code>fcntl.lockf(fileobj.fileno(), fcntl.LOCK_UN)</code></p> <p>To unlock it again.</p> <p>Note that unlike Windows, opening a file for writing does not automatically give you an exclusive lock in Unix. Also note that the fcntl module is not available on Windows; you'll need to use <a href="http://docs.python.org/library/os.html#os.open">os.open</a>, which is a much less friendly but more portable interface (and may require re-opening the file again).</p>
6
2009-08-24T08:12:00Z
[ "python" ]
How to start a COM server implemented in python?
1,320,954
<p>I am using python for making a COM local server. In fact, the whole COM part is implemented in a dll and my python script is calling that dll thanks to ctypes. It works ok when I run the script manually.</p> <p>I would like to see my server automatically ran when a COM client request it. I know that it is possible by giving the command line as value of the LocalServer32 registry key.</p> <p>Unfortunatelly, I can't manage to see windows running my python script properly. I've tried to use python and pythonw with a similar problems. It seems that windows is adding a "-Embedding" flag to the command line and I guess that it can be a problem for python.</p> <p>Any ideas?</p> <p>Does anybody how to avoid the "-Embedding" flag in the command line?</p>
1
2009-08-24T07:41:53Z
1,321,024
<p>The "-embedding" flag is <a href="http://msdn.microsoft.com/en-us/library/aa908849.aspx" rel="nofollow">added by COM automatically</a>, the purpose of which is so that the server application can parse this flag to determine that it was run by COM.</p> <blockquote> <p>COM appends the "-Embedding" flag to the string, so the application that uses flags will need to parse the whole string and check for the -Embedding flag. The following code example shows the setting for this value.</p> </blockquote> <p>You will need to handle this in your server code.</p>
0
2009-08-24T08:02:00Z
[ "python", "windows", "com" ]
How to extend distutils with a simple post install script?
1,321,270
<p>I need to run a simple script after the modules and programs have been installed. I'm having a little trouble finding straight-forward documentation on how to do this. It looks like I need to inherit from distutils.command.install, override some methods and add this object to the setup script. The specifics are a bit hazy though and it seems like a lot of effort for such a simple hook. Does anyone know an easy way to do this? </p>
33
2009-08-24T09:11:33Z
1,321,345
<p>I dug through distutils source for a day to learn enough about it to make a bunch of custom commands. It's not pretty, but it does work.</p> <pre><code>import distutils.core from distutils.command.install import install ... class my_install(install): def run(self): install.run(self) # Custom stuff here # distutils.command.install actually has some nice helper methods # and interfaces. I strongly suggest reading the docstrings. ... distutils.core.setup(..., cmdclass=dict(install=my_install), ...) </code></pre>
28
2009-08-24T09:27:59Z
[ "python", "distutils" ]
How to extend distutils with a simple post install script?
1,321,270
<p>I need to run a simple script after the modules and programs have been installed. I'm having a little trouble finding straight-forward documentation on how to do this. It looks like I need to inherit from distutils.command.install, override some methods and add this object to the setup script. The specifics are a bit hazy though and it seems like a lot of effort for such a simple hook. Does anyone know an easy way to do this? </p>
33
2009-08-24T09:11:33Z
1,321,356
<p>OK, I figured it out. The idea is basically to extend one of the distutils commands and overwrite the run method. To tell distutils to use the new class you can use the cmdclass variable.</p> <pre><code>from distutils.core import setup from distutils.command.install_data import install_data class post_install(install_data): def run(self): # Call parent install_data.run(self) # Execute commands print "Running" setup(name="example", cmdclass={"install_data": post_install}, ... ) </code></pre> <p>Hope this will help someone else.</p>
12
2009-08-24T09:31:05Z
[ "python", "distutils" ]
How to extend distutils with a simple post install script?
1,321,270
<p>I need to run a simple script after the modules and programs have been installed. I'm having a little trouble finding straight-forward documentation on how to do this. It looks like I need to inherit from distutils.command.install, override some methods and add this object to the setup script. The specifics are a bit hazy though and it seems like a lot of effort for such a simple hook. Does anyone know an easy way to do this? </p>
33
2009-08-24T09:11:33Z
11,134,662
<p>I couldn't make <a href="http://stackoverflow.com/a/1321345/572616">Joe Wreschnig</a>s answer work and tweaked his answer analogous to the extending distutils <a href="http://docs.python.org/distutils/extending.html">documentation</a>. I came up with this code which works fine on my machine.</p> <pre><code>from distutils import core from distutils.command.install import install ... class my_install(install): def run(self): install.run(self) # Custom stuff here # distutils.command.install actually has some nice helper methods # and interfaces. I strongly suggest reading the docstrings. ... distutils.core.setup(..., cmdclass={'install': my_install}) </code></pre> <p>Note: I didn't edit the answer of Joe since I am uncertain why his answer wasn't working on my machine.</p>
5
2012-06-21T08:53:00Z
[ "python", "distutils" ]
How to extend distutils with a simple post install script?
1,321,270
<p>I need to run a simple script after the modules and programs have been installed. I'm having a little trouble finding straight-forward documentation on how to do this. It looks like I need to inherit from distutils.command.install, override some methods and add this object to the setup script. The specifics are a bit hazy though and it seems like a lot of effort for such a simple hook. Does anyone know an easy way to do this? </p>
33
2009-08-24T09:11:33Z
19,677,464
<p>I got an error when I tried the accepted answer here (might be because I'm using Python 2.6 in this particular case, not sure). This occurred for both 'setup.py install' and 'pip install':</p> <pre><code>sudo python setup.py install </code></pre> <p>fails with <em>error: error in setup.cfg: command 'my_install' has no such option 'single_version_externally_managed'</em></p> <p>AND</p> <pre><code>sudo pip install . -U </code></pre> <p>fails more verbosely but also with <em>error: option --single-version-externally-managed not recognized</em></p> <h2>Variation on the accepted answer</h2> <p>Replacing the imports from <em>distutils</em> with <em>setuptools</em> solved the problem for me: </p> <pre><code>from setuptools import setup from setuptools.command.install import install </code></pre>
-1
2013-10-30T08:41:04Z
[ "python", "distutils" ]
What are the required functionnalities of ETL frameworks?
1,321,396
<p>I am writing an ETL (in python with a mongodb backend) and was wondering : what kind of standard functions and tools an ETL should have to be called an ETL ? </p> <p>This ETL will be as general purpose as possible, with a scriptable and modular approach. Mostly it will be used to keep different databases in sync, and to import/export datasets in different formats (xml and csv) I don't need any multidimensional tools, but it is a possibility that it'll needed later.</p>
11
2009-08-24T09:41:16Z
1,321,429
<p>Here's a random list, in no particular order:</p> <ol> <li>Connect to a wide range of sources, including all the major relational databases.</li> <li>Handle non-relational data sources like text files, Excel, XML, etc.</li> <li>Allow multiple sources to be mapped into a single target.</li> <li>Provide a tool to help map from source to target fields.</li> <li>Offer a framework for injecting transformations at will.</li> <li>Programmable API for writing complex transformations.</li> <li>Optimize load process for speed.</li> </ol>
4
2009-08-24T09:49:33Z
[ "python", "mongodb", "etl" ]
What are the required functionnalities of ETL frameworks?
1,321,396
<p>I am writing an ETL (in python with a mongodb backend) and was wondering : what kind of standard functions and tools an ETL should have to be called an ETL ? </p> <p>This ETL will be as general purpose as possible, with a scriptable and modular approach. Mostly it will be used to keep different databases in sync, and to import/export datasets in different formats (xml and csv) I don't need any multidimensional tools, but it is a possibility that it'll needed later.</p>
11
2009-08-24T09:41:16Z
1,321,585
<p>Let's think of the ETL use cases for a moment.</p> <ol> <li>Extract. <ul> <li>Read databases through a generic DB-API adapter.</li> <li>Read flat files through a similar adapter.</li> <li>Read spreadsheets through a similar adapter.</li> </ul></li> <li>Cleanse. <ul> <li>Arbitrary rules</li> <li>Filter and reject</li> <li>Replace</li> <li>Add columns of data</li> </ul></li> <li>Profile Data. <ul> <li>Statistical frequency tables.</li> </ul></li> <li>Transform (see cleanse, they're two use cases with the same implementation)</li> <li>Do dimensional conformance lookups. <ul> <li>Replace values, or add values.</li> </ul></li> <li>Aggregate. <ul> <li>At any point in the pipeline</li> </ul></li> <li>Load. <ul> <li>Or prepare a flat-file and run the DB product's loader.</li> </ul></li> </ol> <p>Further, there are some additional requirements that aren't single use cases.</p> <ul> <li><p>Each individual operation has to be a separate process that can be connected in a Unix pipeline, with individual records flowing from process to process. This uses <em>all</em> the CPU resources. </p></li> <li><p>You need some kind of time-based scheduler for places that have trouble reasoning out their ETL preconditions.</p></li> <li><p>You need an event-based schedule for places that can figure out the preconditions for ETL processing steps. </p></li> </ul> <p>Note. Since ETL is I/O bound, multiple threads does you little good. Since each process runs for a long time -- especially if you have thousands of rows of data to process -- the overhead of "heavyweight" processes doesn't hurt.</p>
16
2009-08-24T10:26:51Z
[ "python", "mongodb", "etl" ]
What are the required functionnalities of ETL frameworks?
1,321,396
<p>I am writing an ETL (in python with a mongodb backend) and was wondering : what kind of standard functions and tools an ETL should have to be called an ETL ? </p> <p>This ETL will be as general purpose as possible, with a scriptable and modular approach. Mostly it will be used to keep different databases in sync, and to import/export datasets in different formats (xml and csv) I don't need any multidimensional tools, but it is a possibility that it'll needed later.</p>
11
2009-08-24T09:41:16Z
1,321,885
<p>Automatic / heuristic mapping of column names. E.g simple string mappings:</p> <p>DB1: customerId</p> <p>DB2: customer_id</p> <p>I find a lot of the work I (have) done in DTS / SSIS could've been automatically generated.</p> <ul> <li>not necessarily "required functionality", but would keep a lot of your users very happy indeed.</li> </ul>
0
2009-08-24T11:38:42Z
[ "python", "mongodb", "etl" ]
How to use the same widget twice in pygtk?
1,321,655
<p>This doesn't work well:</p> <pre><code> image_log = gtk.Image() image_log.set_from_file("test.png") self.out_button = gtk.Button() self.out_button.add(image_log) self.err_button = gtk.Button() self.err_button.add(image_log) another_box.pack_start(self.out_button, False) another_box.pack_start(self.err_button, False) </code></pre> <p>The problem is, image_log is used twice and GTK doesn't like it. Is there some .copy() method? Or should I just use plain vanilla deepcopy?</p> <p><strong>EDIT:</strong> Looks like there is no default way to clone objects in GTK. Factory will do the trick in this case.</p> <p>GTK warning:</p> <pre><code>app/gui.py:248: GtkWarning: gtk_box_pack: assertion `child-&gt;parent == NULL' failed hbox_errlog.pack_start(image_log) </code></pre>
2
2009-08-24T10:46:59Z
1,321,678
<p>Why not</p> <pre><code>image_log = gtk.Image() image_log.set_from_file("test.png") image_logb = gtk.Image() image_logb.set_from_file("test.png") self.out_button = gtk.Button() self.out_button.add(image_log) self.err_button = gtk.Button() self.err_button.add(image_logb) another_box.pack_start(self.out_button, False) another_box.pack_start(self.err_button, False) </code></pre> <p>It is only an extra 2 lines of code, and maybe more efficient than cloning/copying the first image object.</p> <p>That way you can treat <code>out_button</code> and <code>err_button</code> independently. But it should make sense to use the same <code>gtk.Image()</code> object for both buttons ... it is just an image.</p> <p><strong>Edit</strong> To avoid duplication (seems like <em>overkill</em> though) you could write a factory for gtk.Image() objects from the same image.</p> <pre><code>def gtkimage_factory(num_objs, image_file): i=0 imglist = [] while i&lt;num_objs: img_ob = gtk.Image() img_ob.set_from_file(image_file) imglist.append( img_ob ) i+=1 return imglist </code></pre> <p>Or something along those lines, you get the idea. But a factory seems like overkill unless you are producing <strong>loads</strong> of these things and need them independently parented in GTK. Then...</p> <pre><code>image_list = gtkimg_factory(2, "test.png") self.out_button = gtk.Button() self.out_button.add(image_list[0]) self.err_button = gtk.Button() self.err_button.add(image_list[1]) another_box.pack_start(self.out_button, False) another_box.pack_start(self.err_button, False) </code></pre> <p>Maybe it is something to do with GTK resource management?</p>
1
2009-08-24T10:50:49Z
[ "python", "widget", "pygtk" ]
How to use the same widget twice in pygtk?
1,321,655
<p>This doesn't work well:</p> <pre><code> image_log = gtk.Image() image_log.set_from_file("test.png") self.out_button = gtk.Button() self.out_button.add(image_log) self.err_button = gtk.Button() self.err_button.add(image_log) another_box.pack_start(self.out_button, False) another_box.pack_start(self.err_button, False) </code></pre> <p>The problem is, image_log is used twice and GTK doesn't like it. Is there some .copy() method? Or should I just use plain vanilla deepcopy?</p> <p><strong>EDIT:</strong> Looks like there is no default way to clone objects in GTK. Factory will do the trick in this case.</p> <p>GTK warning:</p> <pre><code>app/gui.py:248: GtkWarning: gtk_box_pack: assertion `child-&gt;parent == NULL' failed hbox_errlog.pack_start(image_log) </code></pre>
2
2009-08-24T10:46:59Z
1,321,714
<p>You could use a factory function to reduce code duplication</p> <pre><code>def make_image_from_file(fname): im = gtk.Image() im.set_from_file(fname) return im self.out_button.set_image(make_image_from_file(..)) </code></pre> <h1>Revisiting</h1> <p>There is a much more natural way. You will like it. In PyGTK 2.12+:</p> <pre><code>gtk.image_new_from_file(filename) </code></pre> <p>I had something in the back of my mind telling me this, but I didn't look it up.</p> <p><a href="http://www.pygtk.org/docs/pygtk/class-gtkimage.html#function-gtk--image-new-from-file" rel="nofollow">http://www.pygtk.org/docs/pygtk/class-gtkimage.html#function-gtk--image-new-from-file</a></p>
2
2009-08-24T10:59:29Z
[ "python", "widget", "pygtk" ]
How to use the same widget twice in pygtk?
1,321,655
<p>This doesn't work well:</p> <pre><code> image_log = gtk.Image() image_log.set_from_file("test.png") self.out_button = gtk.Button() self.out_button.add(image_log) self.err_button = gtk.Button() self.err_button.add(image_log) another_box.pack_start(self.out_button, False) another_box.pack_start(self.err_button, False) </code></pre> <p>The problem is, image_log is used twice and GTK doesn't like it. Is there some .copy() method? Or should I just use plain vanilla deepcopy?</p> <p><strong>EDIT:</strong> Looks like there is no default way to clone objects in GTK. Factory will do the trick in this case.</p> <p>GTK warning:</p> <pre><code>app/gui.py:248: GtkWarning: gtk_box_pack: assertion `child-&gt;parent == NULL' failed hbox_errlog.pack_start(image_log) </code></pre>
2
2009-08-24T10:46:59Z
6,002,963
<p>Use</p> <pre><code>def clone_widget(widget): widget2=widget.__class__() for prop in dir(widget): if prop.startswith("set_") and prop not in ["set_buffer"]: prop_value=None try: prop_value=getattr(widget, prop.replace("set_","get_") )() except: try: prop_value=getattr(widget, prop.replace("set_","") ) except: continue if prop_value == None: continue try: getattr(widget2, prop)( prop_value ) except: pass return widget2 </code></pre> <p>All this try ... except blocks are there because not all properties could be copied by using set_prop(get_prop). I haven't tested this for all properties and widgets yet, but it worked well for gtkEntry. Maybe this is slow, but it's nice the use :)</p>
2
2011-05-14T15:53:37Z
[ "python", "widget", "pygtk" ]
Grant anonymous access to a specific url/action in Plone
1,321,828
<p>I am running Plone 3.2.3 and I have installed <a href="http://plone.org/products/humainemailman/releases/1.0" rel="nofollow">HumaineMailman</a> so that the users on the website can subscribe and unsubscribe themselves from our various mailinglists. HumaineMailman works very simple. There is a special URL/action that gives you a plain text list of all e-mail addresses that are subscribed on a list. For example:</p> <p><a href="http://www.example.org/mailman_autolist_update?list=mylist@example.org&amp;password=secret" rel="nofollow">http://www.example.org/mailman_autolist_update?list=mylist@example.org&amp;password=secret</a></p> <p>You're supposed to simply wget that URL and feed the plain text list into Mailman's sync_members. Easy.</p> <p>The problem is that Plone does not allow me to access that URL anonymously. When I am logged in as administrator I can access the URL in my browser and see the list of e-mail addresses. But when I am not logged in (and when retrieving that URL using wget) then Plone redirects me to the login page.</p> <p>How do I tell plone that I want to allow anonymous access to that URL/action? The action itself (in code) is defined in Products/HumaineMailman/skins/mailman_autolist_update.py.</p> <p>Thanks in advance!</p>
0
2009-08-24T11:24:08Z
1,322,115
<p>Figure out what permission is protecting that page, and give that permission to the Anonymous role in the Plone root.</p>
1
2009-08-24T12:35:37Z
[ "python", "plone", "zope", "mailman" ]
Grant anonymous access to a specific url/action in Plone
1,321,828
<p>I am running Plone 3.2.3 and I have installed <a href="http://plone.org/products/humainemailman/releases/1.0" rel="nofollow">HumaineMailman</a> so that the users on the website can subscribe and unsubscribe themselves from our various mailinglists. HumaineMailman works very simple. There is a special URL/action that gives you a plain text list of all e-mail addresses that are subscribed on a list. For example:</p> <p><a href="http://www.example.org/mailman_autolist_update?list=mylist@example.org&amp;password=secret" rel="nofollow">http://www.example.org/mailman_autolist_update?list=mylist@example.org&amp;password=secret</a></p> <p>You're supposed to simply wget that URL and feed the plain text list into Mailman's sync_members. Easy.</p> <p>The problem is that Plone does not allow me to access that URL anonymously. When I am logged in as administrator I can access the URL in my browser and see the list of e-mail addresses. But when I am not logged in (and when retrieving that URL using wget) then Plone redirects me to the login page.</p> <p>How do I tell plone that I want to allow anonymous access to that URL/action? The action itself (in code) is defined in Products/HumaineMailman/skins/mailman_autolist_update.py.</p> <p>Thanks in advance!</p>
0
2009-08-24T11:24:08Z
1,322,933
<p>HumaineMailman needs ManagePortal permissions. Those are too much to give to Anonymous so Lennarts answer didn't solve it for me. Instead, I edited HumaineMailman and redeclared the respective function calls as public. This is a slight security risk though. My Plone is behind an Apache proxy so I compensated by only allow access to the memberlist from localhost (where the wget synchronisation script and mailman itself are running as well).</p>
0
2009-08-24T15:03:49Z
[ "python", "plone", "zope", "mailman" ]
Grant anonymous access to a specific url/action in Plone
1,321,828
<p>I am running Plone 3.2.3 and I have installed <a href="http://plone.org/products/humainemailman/releases/1.0" rel="nofollow">HumaineMailman</a> so that the users on the website can subscribe and unsubscribe themselves from our various mailinglists. HumaineMailman works very simple. There is a special URL/action that gives you a plain text list of all e-mail addresses that are subscribed on a list. For example:</p> <p><a href="http://www.example.org/mailman_autolist_update?list=mylist@example.org&amp;password=secret" rel="nofollow">http://www.example.org/mailman_autolist_update?list=mylist@example.org&amp;password=secret</a></p> <p>You're supposed to simply wget that URL and feed the plain text list into Mailman's sync_members. Easy.</p> <p>The problem is that Plone does not allow me to access that URL anonymously. When I am logged in as administrator I can access the URL in my browser and see the list of e-mail addresses. But when I am not logged in (and when retrieving that URL using wget) then Plone redirects me to the login page.</p> <p>How do I tell plone that I want to allow anonymous access to that URL/action? The action itself (in code) is defined in Products/HumaineMailman/skins/mailman_autolist_update.py.</p> <p>Thanks in advance!</p>
0
2009-08-24T11:24:08Z
1,413,867
<p>There are a couple ways to address this without apache or redeclaring security (which would make me nervous too)</p> <pre><code>http://www.example.org:8080/mailman_autolist_update?list=mylist@example.org&amp;password=secret&amp;__ac_name=**USERNAME**&amp;__ac_password=**PASSWORD**&amp;pwd_empty=0&amp;cookies_enabled=1&amp;js_enabled=0&amp;form.submitted=1" </code></pre> <p>I frequently use this trick in scripts with a special user only does "services". There is also a HTTP Auth trick that looks like http://<strong>USERNAME:PASSWORD@</strong>www.example.org/mailman_autolist_update?list=mylist@example.org&amp;password=secret which may or may not be supported depending on your client lib.</p> <p>Alternatively, if that code is running in a (script) Python then you can add a metadata file (myScript.py.<strong>metadata</strong>) and give that script a proxy permission of Manager.i.e.</p> <pre><code>[default] title = Do something useful in the c/py that requires elevated privs proxy = Manager </code></pre>
2
2009-09-12T00:36:39Z
[ "python", "plone", "zope", "mailman" ]
Vim python's buffer.append(line) switch window's focus
1,321,936
<p>I am trying to fill Vim's buffer from separate thread by using this python code.</p> <pre><code>python &lt;&lt; PYTHON_CODE import vim import time buffer_number = -1 class AppendLineTest( Thread ): def run(self): buffer = vim.buffers[buffer_number - 1] for i in range(10): buffer.append('Line number %s' % i) time.sleep(1) PYTHON_CODE function! s:test() split TestBuffer exec 'python buffer_number = '.bufnr('%') setlocal noswapfile setlocal bufhidden=delete setlocal buftype=nofile setlocal nobuflisted setlocal nonumber setlocal nowrap setlocal nocursorline python AppendLineTest().start() endfunction command! -nargs=0 PythonAppendTest call s:test() </code></pre> <p>I am not sure that accessing Vim's buffers from separate threads are allowed and wonder is there some safe dispatch way. But if it is allowed, I would like to get rid of the cursor jumping when append line taking place.</p> <p>So to reproduce the behavior, save the code to some name.vim file and open it in the Vim. Then </p> <pre><code>:source % </code></pre> <p>And then </p> <pre><code>PythonAppendTest </code></pre> <p>Lines will be added 10 times to the temporary buffer. Just move cursor back to the window where you were and you will understand what I am talking about.</p> <p>If you wonder why can someone need to add lines to buffers from the separate thread, here is an example: </p> <ul> <li>unix top </li> <li>unix tail </li> <li>rss</li> <li>email</li> </ul> <p>While you work, they are appearing in some predefined buffer.</p> <p>Thanks in advance.</p>
2
2009-08-24T11:58:43Z
1,322,007
<p>I don't think Vim is very tolerant of multiple threads without patching. There's a lot more detail in the discussion <a href="http://groups.google.com/group/vim%5Fdev/browse%5Fthread/thread/0c7fc4b78bd62c92?pli=1" rel="nofollow">at this link</a>, but I suspect that what you want is far from trivial.</p>
2
2009-08-24T12:15:37Z
[ "python", "vim", "plugins" ]
Is it possible to use Panda3D inside a wxPython app?
1,322,041
<p>I'm developing a wxPython application. Will it be possible to embed a 3D animation controlled by Panda3D inside the gui?</p> <p>Bonus question: Do you think that Panda3D is the best choice? (My interest is physical simulations, and no, I don't need an engine that supports Physics, my program is responsible for calculating the physics, I just need an engine to show it well.)</p>
6
2009-08-24T12:21:46Z
1,323,506
<p>Yes - the Panda3D wiki has a mention of <a href="http://www.panda3d.org/wiki/index.php/Main%5FLoop" rel="nofollow">using wxPython to handle GUI duties</a>.</p> <p>There's also some threads on the Panda3D forum (<a href="http://www.panda3d.org/phpbb2/viewtopic.php?t=2397" rel="nofollow">1</a>, <a href="http://www.panda3d.org/phpbb2/viewtopic.php?p=43081" rel="nofollow">2</a>) which might help.</p> <p>Another popular choice for simulation visualization in Python is VPython; it is <a href="http://mientki.ruhosting.nl/data%5Fwww/pylab%5Fworks/pw%5Fvpython%5Fdocking.html" rel="nofollow">also dockable in wx</a>.</p>
3
2009-08-24T16:48:48Z
[ "python", "3d", "wxpython" ]
to restrict parameter values strictly with in bounds
1,322,049
<p>I am trying to optimize a function using l_bfgs constraint optimization routine in scipy. But the optimization routine passes values to the function, which are not with in the Bounds.</p> <p>my full code looks like,</p> <pre><code>def humpy(aParams): aParams = numpy.asarray(aParams) print aParams #### # connect to some other software for simulation # data[1] &amp; data[2] are read ##### objective function val = sum(0.5*(data[1] - data[2])**2) print val return val #### def approx_fprime(): #### Initial = numpy.asarray([10.0, 15.0, 50.0, 10.0]) interval = [(5.0, 60000.0),(10.0, 50000.0),(26.0, 100000.0),(8.0, 50000.0)] opt = optimize.fmin_l_bfgs(humpy,Initial,fprime=approx_fprime, bounds=interval ,pgtol=1.0000000000001e-05,iprint=1, maxfun=50000) print 'optimized parameters',opt[0] print 'Optimized function value', opt[1] ####### the end #### </code></pre> <p>based on the initial values(Initial) and bounds(interval) opt = optimize.fmin_l_bfgs() will pass values to my software for simulation, but the values passed should be with in 'bounds'. Thats not the case..see below the values passed at various iterations</p> <pre><code>iter 1 = [ 10.23534209 15.1717302 50.5117245 10.28731118] iter 2 = [ 10.23534209 15.1717302 50.01160842 10.39018429] [ 11.17671043 15.85865102 50.05804208 11.43655591] [ 11.17671043 15.85865102 50.05804208 11.43655591] [ 11.28847754 15.85865102 50.05804208 11.43655591] [ 11.17671043 16.01723753 50.05804208 11.43655591] [ 11.17671043 15.85865102 50.5586225 11.43655591] ............... ............... ............... [ 49.84670071 -4.4139714 62.2536381 23.3155698847] </code></pre> <p>at this iteration -4.4139714 is passed to my 2nd parameter but it should vary from (10.0, 50000.0), from where come -4.4139714 i don't know?</p> <p>where should i change in the code? so that it passed values which should be with in bounds</p>
0
2009-08-24T12:23:20Z
1,322,244
<p>You are trying to do bitwise exclusive or (the ^ operator) on floats, which makes no sense, so I don't think your code is actually the code you have problems with. However, I changed the ^ to ** assuming that was what you meant, and had no problems. The code worked fine for me with that change. The parameters are restricted exactly as defined.</p> <p>Python 2.5.</p>
1
2009-08-24T12:57:54Z
[ "python", "scipy" ]
to restrict parameter values strictly with in bounds
1,322,049
<p>I am trying to optimize a function using l_bfgs constraint optimization routine in scipy. But the optimization routine passes values to the function, which are not with in the Bounds.</p> <p>my full code looks like,</p> <pre><code>def humpy(aParams): aParams = numpy.asarray(aParams) print aParams #### # connect to some other software for simulation # data[1] &amp; data[2] are read ##### objective function val = sum(0.5*(data[1] - data[2])**2) print val return val #### def approx_fprime(): #### Initial = numpy.asarray([10.0, 15.0, 50.0, 10.0]) interval = [(5.0, 60000.0),(10.0, 50000.0),(26.0, 100000.0),(8.0, 50000.0)] opt = optimize.fmin_l_bfgs(humpy,Initial,fprime=approx_fprime, bounds=interval ,pgtol=1.0000000000001e-05,iprint=1, maxfun=50000) print 'optimized parameters',opt[0] print 'Optimized function value', opt[1] ####### the end #### </code></pre> <p>based on the initial values(Initial) and bounds(interval) opt = optimize.fmin_l_bfgs() will pass values to my software for simulation, but the values passed should be with in 'bounds'. Thats not the case..see below the values passed at various iterations</p> <pre><code>iter 1 = [ 10.23534209 15.1717302 50.5117245 10.28731118] iter 2 = [ 10.23534209 15.1717302 50.01160842 10.39018429] [ 11.17671043 15.85865102 50.05804208 11.43655591] [ 11.17671043 15.85865102 50.05804208 11.43655591] [ 11.28847754 15.85865102 50.05804208 11.43655591] [ 11.17671043 16.01723753 50.05804208 11.43655591] [ 11.17671043 15.85865102 50.5586225 11.43655591] ............... ............... ............... [ 49.84670071 -4.4139714 62.2536381 23.3155698847] </code></pre> <p>at this iteration -4.4139714 is passed to my 2nd parameter but it should vary from (10.0, 50000.0), from where come -4.4139714 i don't know?</p> <p>where should i change in the code? so that it passed values which should be with in bounds</p>
0
2009-08-24T12:23:20Z
1,322,413
<p>Are you asking about doing something like this?</p> <pre><code>def humpy(aParams): aParams = numpy.asarray(aParams) x = aParams[0] y = aParams[1] z = aParams[2] u = aParams[3] v = aParams[4] assert 2 &lt;= x &lt;= 50000 assert 1 &lt;= y &lt;= 35000 assert 1 &lt;= z &lt;= 45000 assert 2 &lt;= u &lt;= 50000 assert 2 &lt;= v &lt;= 60000 val=100.0*((y-x**2.0)^2.0+(z-y**2.0)^2.0+(u-z**2.0)^2.0+(v-u**2.0)^2.0)+(1-x)^2.0+(1-y)^2.0+(1-z)^2.0+(1-u)^2.0 return val </code></pre>
0
2009-08-24T13:28:06Z
[ "python", "scipy" ]
Determine if Python variable is an instance of a built-in type
1,322,068
<p>I need to determine if a given Python variable is an instance of native type: <code>str</code>, <code>int</code>, <code>float</code>, <code>bool</code>, <code>list</code>, <code>dict</code> and so on. Is there elegant way to doing it?</p> <p>Or is this the only way: </p> <pre><code>if myvar in (str, int, float, bool): # do something </code></pre>
11
2009-08-24T12:27:22Z
1,322,086
<p>Built in type function may be helpful:</p> <pre><code>&gt;&gt;&gt; a = 5 &gt;&gt;&gt; type(a) &lt;type 'int'&gt; </code></pre>
1
2009-08-24T12:31:27Z
[ "python", "variables", "instance" ]
Determine if Python variable is an instance of a built-in type
1,322,068
<p>I need to determine if a given Python variable is an instance of native type: <code>str</code>, <code>int</code>, <code>float</code>, <code>bool</code>, <code>list</code>, <code>dict</code> and so on. Is there elegant way to doing it?</p> <p>Or is this the only way: </p> <pre><code>if myvar in (str, int, float, bool): # do something </code></pre>
11
2009-08-24T12:27:22Z
1,322,090
<p>What is a "native type" in Python? Please don't base your code on types, use <a href="http://en.wikipedia.org/wiki/Duck%5FTyping" rel="nofollow">Duck Typing</a>.</p>
2
2009-08-24T12:31:47Z
[ "python", "variables", "instance" ]
Determine if Python variable is an instance of a built-in type
1,322,068
<p>I need to determine if a given Python variable is an instance of native type: <code>str</code>, <code>int</code>, <code>float</code>, <code>bool</code>, <code>list</code>, <code>dict</code> and so on. Is there elegant way to doing it?</p> <p>Or is this the only way: </p> <pre><code>if myvar in (str, int, float, bool): # do something </code></pre>
11
2009-08-24T12:27:22Z
1,322,099
<p>Not that I know why you would want to do it, as there isn't any "simple" types in Python, it's all objects. But this works:</p> <pre><code>type(theobject).__name__ in dir(__builtins__) </code></pre> <p>But explicitly listing the types is probably better as it's clearer. Or even better: Changing the application so you don't need to know the difference.</p> <p>Update: The problem that needs solving is how to make a serializer for objects, even those built-in. The best way to do this is not to make a big phat serializer that treats builtins differently, but to look up serializers based on type.</p> <p>Something like this:</p> <pre><code>def IntSerializer(theint): return str(theint) def StringSerializer(thestring): return repr(thestring) def MyOwnSerializer(value): return "whatever" serializers = { int: IntSerializer, str: StringSerializer, mymodel.myclass: MyOwnSerializer, } def serialize(ob): try: return ob.serialize() #For objects that know they need to be serialized except AttributeError: # Look up the serializer amongst the serializer based on type. # Default to using "repr" (works for most builtins). return serializers.get(type(ob), repr)(ob) </code></pre> <p>This way you can easily add new serializers, and the code is easy to maintain and clear, as each type has its own serializer. Notice how the fact that some types are builtin became completely irrelevant. :)</p>
5
2009-08-24T12:32:47Z
[ "python", "variables", "instance" ]
Determine if Python variable is an instance of a built-in type
1,322,068
<p>I need to determine if a given Python variable is an instance of native type: <code>str</code>, <code>int</code>, <code>float</code>, <code>bool</code>, <code>list</code>, <code>dict</code> and so on. Is there elegant way to doing it?</p> <p>Or is this the only way: </p> <pre><code>if myvar in (str, int, float, bool): # do something </code></pre>
11
2009-08-24T12:27:22Z
1,322,152
<p>The best way to achieve this is to collect the types in a list of tuple called <code>primitiveTypes</code> and:</p> <pre><code>if isinstance(myvar, primitiveTypes): ... </code></pre> <p>The <a href="http://docs.python.org/library/types.html" rel="nofollow"><code>types</code> module</a> contains collections of all important types which can help to build the list/tuple.</p> <p><a href="http://docs.python.org/2/library/functions.html#isinstance" rel="nofollow">Works since Python 2.2</a></p>
10
2009-08-24T12:42:49Z
[ "python", "variables", "instance" ]
Determine if Python variable is an instance of a built-in type
1,322,068
<p>I need to determine if a given Python variable is an instance of native type: <code>str</code>, <code>int</code>, <code>float</code>, <code>bool</code>, <code>list</code>, <code>dict</code> and so on. Is there elegant way to doing it?</p> <p>Or is this the only way: </p> <pre><code>if myvar in (str, int, float, bool): # do something </code></pre>
11
2009-08-24T12:27:22Z
1,322,311
<p>You appear to be interested in assuring the simplejson will handle your types. This is done trivially by </p> <pre><code>try: json.dumps( object ) except TypeError: print "Can't convert", object </code></pre> <p>Which is more reliable than trying to guess which types your JSON implementation handles.</p>
6
2009-08-24T13:08:58Z
[ "python", "variables", "instance" ]
Determine if Python variable is an instance of a built-in type
1,322,068
<p>I need to determine if a given Python variable is an instance of native type: <code>str</code>, <code>int</code>, <code>float</code>, <code>bool</code>, <code>list</code>, <code>dict</code> and so on. Is there elegant way to doing it?</p> <p>Or is this the only way: </p> <pre><code>if myvar in (str, int, float, bool): # do something </code></pre>
11
2009-08-24T12:27:22Z
1,325,236
<p>building off of S.Lott's answer you should have something like this:</p> <pre><code> from simplejson import JSONEncoder class JSONEncodeAll(JSONEncoder): def default(self, obj): try: return JSONEncoder.default(self, obj) except TypeError: ## optionally # try: # # you'd have to add this per object, but if an object wants to do something # # special then it can do whatever it wants # return obj.__json__() # except AttributeError: ## # ...do whatever you are doing now... # (which should be creating an object simplejson understands) </code></pre> <p>to use:</p> <pre><code> >>> json = JSONEncodeAll() >>> json.encode(myObject) # whatever myObject looks like when it passes through your serialization code </code></pre> <p>these calls will use your special class and if simplejson can take care of the object it will. Otherwise your catchall functionality will be triggered, and possibly (depending if you use the optional part) an object can define it's own serialization</p>
0
2009-08-24T23:00:24Z
[ "python", "variables", "instance" ]
Determine if Python variable is an instance of a built-in type
1,322,068
<p>I need to determine if a given Python variable is an instance of native type: <code>str</code>, <code>int</code>, <code>float</code>, <code>bool</code>, <code>list</code>, <code>dict</code> and so on. Is there elegant way to doing it?</p> <p>Or is this the only way: </p> <pre><code>if myvar in (str, int, float, bool): # do something </code></pre>
11
2009-08-24T12:27:22Z
17,795,199
<p>This is an old question but it seems none of the answers actually answer the specific question: "(How-to) Determine if Python variable is an instance of a built-in type". Note that it's not "[...] of a <strong>specific/given</strong> built-in type" but of <strong>a</strong>.</p> <p>The proper way to <em>determine if a given object is an instance of a buil-in type/class</em> is to check if the type of the object happens to be defined in the module <code>__builtin__</code>.</p> <pre><code>def is_builtin_class_instance(obj): return obj.__class__.__module__ == '__builtin__' </code></pre> <p>Warning: if <code>obj</code> is a class and not an instance, no matter if that class is built-in or not, True will be returned since a class is also an object, an instance of <code>type</code> (i.e. <code>AnyClass.__class__</code> is <code>type</code>).</p>
4
2013-07-22T18:52:30Z
[ "python", "variables", "instance" ]
Determine if Python variable is an instance of a built-in type
1,322,068
<p>I need to determine if a given Python variable is an instance of native type: <code>str</code>, <code>int</code>, <code>float</code>, <code>bool</code>, <code>list</code>, <code>dict</code> and so on. Is there elegant way to doing it?</p> <p>Or is this the only way: </p> <pre><code>if myvar in (str, int, float, bool): # do something </code></pre>
11
2009-08-24T12:27:22Z
29,275,079
<p>you can access all these types by <code>types</code> module:</p> <pre><code>`builtin_types = [ i for i in types.__dict__.values() if isinstance(i, type)]` </code></pre> <p>as a reminder, import module <code>types</code> first</p> <pre><code>def isBuiltinTypes(var): return type(var) in [i for i in types.__dict__.values() if isinstance(i, type)] and not isinstance(var, types.InstanceType) </code></pre>
1
2015-03-26T09:35:34Z
[ "python", "variables", "instance" ]
gotchas where Numpy differs from straight python?
1,322,380
<p>Folks,</p> <p>is there a collection of gotchas where Numpy differs from python, points that have puzzled and cost time ?</p> <blockquote> <p>"The horror of that moment I shall never never forget !"<br /> "You will, though," the Queen said, "if you don't make a memorandum of it."</p> </blockquote> <p>For example, NaNs are always trouble, anywhere. If you can explain this without running it, give yourself a point --</p> <pre><code>from numpy import array, NaN, isnan pynan = float("nan") print pynan is pynan, pynan is NaN, NaN is NaN a = (0, pynan) print a, a[1] is pynan, any([aa is pynan for aa in a]) a = array(( 0, NaN )) print a, a[1] is NaN, isnan( a[1] ) </code></pre> <p>(I'm not knocking numpy, lots of good work there, just think a FAQ or Wiki of gotchas would be useful.)</p> <p>Edit: I was hoping to collect half a dozen gotchas (surprises for people learning Numpy).<br /> Then, if there are common gotchas or, better, common explanations, we could talk about adding them to a community Wiki (where ?) It doesn't look like we have enough so far.</p>
23
2009-08-24T13:21:37Z
1,322,431
<pre><code>print pynan is pynan, pynan is NaN, NaN is NaN </code></pre> <p>This tests identity, that is if it is the same object. The result should therefore obviously be True, False, True, because when you do float(whatever) you are creating a new float object.</p> <pre><code>a = (0, pynan) print a, a[1] is pynan, any([aa is pynan for aa in a]) </code></pre> <p>I don't know what it is that you find surprising with this.</p> <pre><code>a = array(( 0, NaN )) print a, a[1] is NaN, isnan( a[1] ) </code></pre> <p>This I did have to run. :-) When you stick NaN into an array it's converted into a numpy.float64 object, which is why a[1] is NaN fails.</p> <p>This all seems fairly unsurprising to me. But then I don't really know anything much about NumPy. :-)</p>
3
2009-08-24T13:31:25Z
[ "python", "numpy" ]
gotchas where Numpy differs from straight python?
1,322,380
<p>Folks,</p> <p>is there a collection of gotchas where Numpy differs from python, points that have puzzled and cost time ?</p> <blockquote> <p>"The horror of that moment I shall never never forget !"<br /> "You will, though," the Queen said, "if you don't make a memorandum of it."</p> </blockquote> <p>For example, NaNs are always trouble, anywhere. If you can explain this without running it, give yourself a point --</p> <pre><code>from numpy import array, NaN, isnan pynan = float("nan") print pynan is pynan, pynan is NaN, NaN is NaN a = (0, pynan) print a, a[1] is pynan, any([aa is pynan for aa in a]) a = array(( 0, NaN )) print a, a[1] is NaN, isnan( a[1] ) </code></pre> <p>(I'm not knocking numpy, lots of good work there, just think a FAQ or Wiki of gotchas would be useful.)</p> <p>Edit: I was hoping to collect half a dozen gotchas (surprises for people learning Numpy).<br /> Then, if there are common gotchas or, better, common explanations, we could talk about adding them to a community Wiki (where ?) It doesn't look like we have enough so far.</p>
23
2009-08-24T13:21:37Z
1,322,468
<p><code>NaN</code> is not a singleton like <code>None</code>, so you can't really use the is check on it. What makes it a bit tricky is that <code>NaN == NaN</code> is <code>False</code> as IEEE-754 requires. That's why you need to use the <code>numpy.isnan()</code> function to check if a float is not a number. Or the standard library <code>math.isnan()</code> if you're using Python 2.6+.</p>
12
2009-08-24T13:36:41Z
[ "python", "numpy" ]
gotchas where Numpy differs from straight python?
1,322,380
<p>Folks,</p> <p>is there a collection of gotchas where Numpy differs from python, points that have puzzled and cost time ?</p> <blockquote> <p>"The horror of that moment I shall never never forget !"<br /> "You will, though," the Queen said, "if you don't make a memorandum of it."</p> </blockquote> <p>For example, NaNs are always trouble, anywhere. If you can explain this without running it, give yourself a point --</p> <pre><code>from numpy import array, NaN, isnan pynan = float("nan") print pynan is pynan, pynan is NaN, NaN is NaN a = (0, pynan) print a, a[1] is pynan, any([aa is pynan for aa in a]) a = array(( 0, NaN )) print a, a[1] is NaN, isnan( a[1] ) </code></pre> <p>(I'm not knocking numpy, lots of good work there, just think a FAQ or Wiki of gotchas would be useful.)</p> <p>Edit: I was hoping to collect half a dozen gotchas (surprises for people learning Numpy).<br /> Then, if there are common gotchas or, better, common explanations, we could talk about adding them to a community Wiki (where ?) It doesn't look like we have enough so far.</p>
23
2009-08-24T13:21:37Z
1,323,233
<p>I think this one is funny:</p> <pre><code>&gt;&gt;&gt; import numpy as n &gt;&gt;&gt; a = n.array([[1,2],[3,4]]) &gt;&gt;&gt; a[1], a[0] = a[0], a[1] &gt;&gt;&gt; a array([[1, 2], [1, 2]]) </code></pre> <p>For Python lists on the other hand this works as intended:</p> <pre><code>&gt;&gt;&gt; b = [[1,2],[3,4]] &gt;&gt;&gt; b[1], b[0] = b[0], b[1] &gt;&gt;&gt; b [[3, 4], [1, 2]] </code></pre> <p>Funny side note: numpy itself had a bug in the <code>shuffle</code> function, because it used that notation :-) (see <a href="http://mail.scipy.org/pipermail/numpy-discussion/2006-November/024783.html">here</a>).</p> <p>The reason is that in the first case we are dealing with <em>views</em> of the array, so the values are overwritten in-place.</p>
20
2009-08-24T15:58:42Z
[ "python", "numpy" ]
gotchas where Numpy differs from straight python?
1,322,380
<p>Folks,</p> <p>is there a collection of gotchas where Numpy differs from python, points that have puzzled and cost time ?</p> <blockquote> <p>"The horror of that moment I shall never never forget !"<br /> "You will, though," the Queen said, "if you don't make a memorandum of it."</p> </blockquote> <p>For example, NaNs are always trouble, anywhere. If you can explain this without running it, give yourself a point --</p> <pre><code>from numpy import array, NaN, isnan pynan = float("nan") print pynan is pynan, pynan is NaN, NaN is NaN a = (0, pynan) print a, a[1] is pynan, any([aa is pynan for aa in a]) a = array(( 0, NaN )) print a, a[1] is NaN, isnan( a[1] ) </code></pre> <p>(I'm not knocking numpy, lots of good work there, just think a FAQ or Wiki of gotchas would be useful.)</p> <p>Edit: I was hoping to collect half a dozen gotchas (surprises for people learning Numpy).<br /> Then, if there are common gotchas or, better, common explanations, we could talk about adding them to a community Wiki (where ?) It doesn't look like we have enough so far.</p>
23
2009-08-24T13:21:37Z
1,324,939
<p>The biggest gotcha for me was that almost every standard operator is overloaded to distribute across the array.</p> <p>Define a list and an array</p> <pre><code>&gt;&gt;&gt; l = range(10) &gt;&gt;&gt; l [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] &gt;&gt;&gt; import numpy &gt;&gt;&gt; a = numpy.array(l) &gt;&gt;&gt; a array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) </code></pre> <p>Multiplication duplicates the python list, but distributes over the numpy array</p> <pre><code>&gt;&gt;&gt; l * 2 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9] &gt;&gt;&gt; a * 2 array([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18]) </code></pre> <p>Addition and division are not defined on python lists</p> <pre><code>&gt;&gt;&gt; l + 2 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: can only concatenate list (not "int") to list &gt;&gt;&gt; a + 2 array([ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) &gt;&gt;&gt; l / 2.0 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unsupported operand type(s) for /: 'list' and 'float' &gt;&gt;&gt; a / 2.0 array([ 0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5]) </code></pre> <p>Numpy overloads to treat lists like arrays sometimes</p> <pre><code>&gt;&gt;&gt; a + a array([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18]) &gt;&gt;&gt; a + l array([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18]) </code></pre>
19
2009-08-24T21:44:02Z
[ "python", "numpy" ]
gotchas where Numpy differs from straight python?
1,322,380
<p>Folks,</p> <p>is there a collection of gotchas where Numpy differs from python, points that have puzzled and cost time ?</p> <blockquote> <p>"The horror of that moment I shall never never forget !"<br /> "You will, though," the Queen said, "if you don't make a memorandum of it."</p> </blockquote> <p>For example, NaNs are always trouble, anywhere. If you can explain this without running it, give yourself a point --</p> <pre><code>from numpy import array, NaN, isnan pynan = float("nan") print pynan is pynan, pynan is NaN, NaN is NaN a = (0, pynan) print a, a[1] is pynan, any([aa is pynan for aa in a]) a = array(( 0, NaN )) print a, a[1] is NaN, isnan( a[1] ) </code></pre> <p>(I'm not knocking numpy, lots of good work there, just think a FAQ or Wiki of gotchas would be useful.)</p> <p>Edit: I was hoping to collect half a dozen gotchas (surprises for people learning Numpy).<br /> Then, if there are common gotchas or, better, common explanations, we could talk about adding them to a community Wiki (where ?) It doesn't look like we have enough so far.</p>
23
2009-08-24T13:21:37Z
1,411,629
<p>from Neil Martinsen-Burrell in <a href="http://mail.scipy.org/pipermail/numpy-discussion/2009-September/045041.html" rel="nofollow">numpy-discussion</a> 7 Sept --</p> <blockquote> <p>The ndarray type available in Numpy is not conceptually an extension of Python's iterables. If you'd like to help other Numpy users with this issue, you can edit the documentation in the online documentation editor at <a href="http://docs.scipy.org/numpy/docs/numpy-docs/user/index.rst" rel="nofollow">numpy-docs</a></p> </blockquote>
2
2009-09-11T15:30:19Z
[ "python", "numpy" ]
gotchas where Numpy differs from straight python?
1,322,380
<p>Folks,</p> <p>is there a collection of gotchas where Numpy differs from python, points that have puzzled and cost time ?</p> <blockquote> <p>"The horror of that moment I shall never never forget !"<br /> "You will, though," the Queen said, "if you don't make a memorandum of it."</p> </blockquote> <p>For example, NaNs are always trouble, anywhere. If you can explain this without running it, give yourself a point --</p> <pre><code>from numpy import array, NaN, isnan pynan = float("nan") print pynan is pynan, pynan is NaN, NaN is NaN a = (0, pynan) print a, a[1] is pynan, any([aa is pynan for aa in a]) a = array(( 0, NaN )) print a, a[1] is NaN, isnan( a[1] ) </code></pre> <p>(I'm not knocking numpy, lots of good work there, just think a FAQ or Wiki of gotchas would be useful.)</p> <p>Edit: I was hoping to collect half a dozen gotchas (surprises for people learning Numpy).<br /> Then, if there are common gotchas or, better, common explanations, we could talk about adding them to a community Wiki (where ?) It doesn't look like we have enough so far.</p>
23
2009-08-24T13:21:37Z
1,413,996
<p>The truth value of a Numpy array differs from that of a python sequence type, where any non-empty sequence is true.</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; l = [0,1,2,3] &gt;&gt;&gt; a = np.arange(4) &gt;&gt;&gt; if l: print "Im true" ... Im true &gt;&gt;&gt; if a: print "Im true" ... Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() &gt;&gt;&gt; </code></pre> <p>The numerical types are true when they are non-zero and as a collection of numbers, the Nupy array inherits this definition. But with a collection of numbers, truth could reasonably mean "all elements are non-zero" or "at least one element is non-zero". Numpy refuses to guess which definition is meant and raises the above exception. Using the .any() and .all() methods allows one to specify which meaning of true is meant.</p> <pre><code>&gt;&gt;&gt; if a.any(): print "Im true" ... Im true &gt;&gt;&gt; if a.all(): print "Im true" ... &gt;&gt;&gt; </code></pre>
6
2009-09-12T01:45:23Z
[ "python", "numpy" ]
gotchas where Numpy differs from straight python?
1,322,380
<p>Folks,</p> <p>is there a collection of gotchas where Numpy differs from python, points that have puzzled and cost time ?</p> <blockquote> <p>"The horror of that moment I shall never never forget !"<br /> "You will, though," the Queen said, "if you don't make a memorandum of it."</p> </blockquote> <p>For example, NaNs are always trouble, anywhere. If you can explain this without running it, give yourself a point --</p> <pre><code>from numpy import array, NaN, isnan pynan = float("nan") print pynan is pynan, pynan is NaN, NaN is NaN a = (0, pynan) print a, a[1] is pynan, any([aa is pynan for aa in a]) a = array(( 0, NaN )) print a, a[1] is NaN, isnan( a[1] ) </code></pre> <p>(I'm not knocking numpy, lots of good work there, just think a FAQ or Wiki of gotchas would be useful.)</p> <p>Edit: I was hoping to collect half a dozen gotchas (surprises for people learning Numpy).<br /> Then, if there are common gotchas or, better, common explanations, we could talk about adding them to a community Wiki (where ?) It doesn't look like we have enough so far.</p>
23
2009-08-24T13:21:37Z
1,414,038
<p>Slicing creates views, not copies.</p> <pre><code>&gt;&gt;&gt; l = [1, 2, 3, 4] &gt;&gt;&gt; s = l[2:3] &gt;&gt;&gt; s[0] = 5 &gt;&gt;&gt; l [1, 2, 3, 4] &gt;&gt;&gt; a = array([1, 2, 3, 4]) &gt;&gt;&gt; s = a[2:3] &gt;&gt;&gt; s[0] = 5 &gt;&gt;&gt; a array([1, 2, 5, 4]) </code></pre>
7
2009-09-12T02:19:46Z
[ "python", "numpy" ]
gotchas where Numpy differs from straight python?
1,322,380
<p>Folks,</p> <p>is there a collection of gotchas where Numpy differs from python, points that have puzzled and cost time ?</p> <blockquote> <p>"The horror of that moment I shall never never forget !"<br /> "You will, though," the Queen said, "if you don't make a memorandum of it."</p> </blockquote> <p>For example, NaNs are always trouble, anywhere. If you can explain this without running it, give yourself a point --</p> <pre><code>from numpy import array, NaN, isnan pynan = float("nan") print pynan is pynan, pynan is NaN, NaN is NaN a = (0, pynan) print a, a[1] is pynan, any([aa is pynan for aa in a]) a = array(( 0, NaN )) print a, a[1] is NaN, isnan( a[1] ) </code></pre> <p>(I'm not knocking numpy, lots of good work there, just think a FAQ or Wiki of gotchas would be useful.)</p> <p>Edit: I was hoping to collect half a dozen gotchas (surprises for people learning Numpy).<br /> Then, if there are common gotchas or, better, common explanations, we could talk about adding them to a community Wiki (where ?) It doesn't look like we have enough so far.</p>
23
2009-08-24T13:21:37Z
3,791,525
<p>I found the fact that multiplying up lists of elements just creates view of elements caught me out.</p> <pre><code>&gt;&gt;&gt; a=[0]*5 &gt;&gt;&gt;a [0,0,0,0,0] &gt;&gt;&gt;a[2] = 1 &gt;&gt;&gt;a [0,0,1,0,0] &gt;&gt;&gt;b = [np.ones(3)]*5 &gt;&gt;&gt;b [array([ 1., 1., 1.]), array([ 1., 1., 1.]), array([ 1., 1., 1.]), array([ 1., 1., 1.]), array([ 1., 1., 1.])] &gt;&gt;&gt;b[2][1] = 2 &gt;&gt;&gt;b [array([ 1., 2., 1.]), array([ 1., 2., 1.]), array([ 1., 2., 1.]), array([ 1., 2., 1.]), array([ 1., 2., 1.])] </code></pre> <p>So if you create a list of elements like this and intend to do different operations on them you are scuppered ...</p> <p>A straightforward solution is to iteratively create each of the arrays (using a 'for loop' or list comprehension) or use a higher dimensional array (where e.g. each of these 1D arrays is a row in your 2D array, which is generally faster).</p>
2
2010-09-24T22:39:20Z
[ "python", "numpy" ]
gotchas where Numpy differs from straight python?
1,322,380
<p>Folks,</p> <p>is there a collection of gotchas where Numpy differs from python, points that have puzzled and cost time ?</p> <blockquote> <p>"The horror of that moment I shall never never forget !"<br /> "You will, though," the Queen said, "if you don't make a memorandum of it."</p> </blockquote> <p>For example, NaNs are always trouble, anywhere. If you can explain this without running it, give yourself a point --</p> <pre><code>from numpy import array, NaN, isnan pynan = float("nan") print pynan is pynan, pynan is NaN, NaN is NaN a = (0, pynan) print a, a[1] is pynan, any([aa is pynan for aa in a]) a = array(( 0, NaN )) print a, a[1] is NaN, isnan( a[1] ) </code></pre> <p>(I'm not knocking numpy, lots of good work there, just think a FAQ or Wiki of gotchas would be useful.)</p> <p>Edit: I was hoping to collect half a dozen gotchas (surprises for people learning Numpy).<br /> Then, if there are common gotchas or, better, common explanations, we could talk about adding them to a community Wiki (where ?) It doesn't look like we have enough so far.</p>
23
2009-08-24T13:21:37Z
6,065,203
<p>Because <code>__eq__</code> does not return a bool, using numpy arrays in any kind of containers prevents equality testing without a container-specific work around.</p> <p>Example:</p> <pre><code>&gt;&gt;&gt; import numpy &gt;&gt;&gt; a = numpy.array(range(3)) &gt;&gt;&gt; b = numpy.array(range(3)) &gt;&gt;&gt; a == b array([ True, True, True], dtype=bool) &gt;&gt;&gt; x = (a, 'banana') &gt;&gt;&gt; y = (b, 'banana') &gt;&gt;&gt; x == y Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() </code></pre> <p>This is a horrible problem. For example, you cannot write unittests for containers which use <code>TestCase.assertEqual()</code> and must instead write custom comparison functions. Suppose we write a work-around function <code>special_eq_for_numpy_and_tuples</code>. Now we can do this in a unittest:</p> <pre><code>x = (array1, 'deserialized') y = (array2, 'deserialized') self.failUnless( special_eq_for_numpy_and_tuples(x, y) ) </code></pre> <p>Now we must do this for every container type we might use to store numpy arrays. Furthermore, <code>__eq__</code> might return a bool rather than an array of bools:</p> <pre><code>&gt;&gt;&gt; a = numpy.array(range(3)) &gt;&gt;&gt; b = numpy.array(range(5)) &gt;&gt;&gt; a == b False </code></pre> <p>Now each of our container-specific equality comparison functions must also handle that special case.</p> <p>Maybe we can patch over this wart with a subclass?</p> <pre><code>&gt;&gt;&gt; class SaneEqualityArray (numpy.ndarray): ... def __eq__(self, other): ... return isinstance(other, SaneEqualityArray) and self.shape == other.shape and (numpy.ndarray.__eq__(self, other)).all() ... &gt;&gt;&gt; a = SaneEqualityArray( (2, 3) ) &gt;&gt;&gt; a.fill(7) &gt;&gt;&gt; b = SaneEqualityArray( (2, 3) ) &gt;&gt;&gt; b.fill(7) &gt;&gt;&gt; a == b True &gt;&gt;&gt; x = (a, 'banana') &gt;&gt;&gt; y = (b, 'banana') &gt;&gt;&gt; x == y True &gt;&gt;&gt; c = SaneEqualityArray( (7, 7) ) &gt;&gt;&gt; c.fill(7) &gt;&gt;&gt; a == c False </code></pre> <p>That seems to do the right thing. The class should also explicitly export elementwise comparison, since that is often useful.</p>
23
2011-05-19T21:43:35Z
[ "python", "numpy" ]
gotchas where Numpy differs from straight python?
1,322,380
<p>Folks,</p> <p>is there a collection of gotchas where Numpy differs from python, points that have puzzled and cost time ?</p> <blockquote> <p>"The horror of that moment I shall never never forget !"<br /> "You will, though," the Queen said, "if you don't make a memorandum of it."</p> </blockquote> <p>For example, NaNs are always trouble, anywhere. If you can explain this without running it, give yourself a point --</p> <pre><code>from numpy import array, NaN, isnan pynan = float("nan") print pynan is pynan, pynan is NaN, NaN is NaN a = (0, pynan) print a, a[1] is pynan, any([aa is pynan for aa in a]) a = array(( 0, NaN )) print a, a[1] is NaN, isnan( a[1] ) </code></pre> <p>(I'm not knocking numpy, lots of good work there, just think a FAQ or Wiki of gotchas would be useful.)</p> <p>Edit: I was hoping to collect half a dozen gotchas (surprises for people learning Numpy).<br /> Then, if there are common gotchas or, better, common explanations, we could talk about adding them to a community Wiki (where ?) It doesn't look like we have enough so far.</p>
23
2009-08-24T13:21:37Z
6,876,084
<p>(Related, but a NumPy vs. SciPy gotcha, rather than NumPy vs Python)</p> <hr> <p>Slicing beyond an array's real size works differently:</p> <pre><code>&gt;&gt;&gt; import numpy, scipy.sparse &gt;&gt;&gt; m = numpy.random.rand(2, 5) # create a 2x5 dense matrix &gt;&gt;&gt; print m[:3, :] # works like list slicing in Python: clips to real size [[ 0.12245393 0.20642799 0.98128601 0.06102106 0.74091038] [ 0.0527411 0.9131837 0.6475907 0.27900378 0.22396443]] &gt;&gt;&gt; s = scipy.sparse.lil_matrix(m) # same for csr_matrix and other sparse formats &gt;&gt;&gt; print s[:3, :] # doesn't clip! IndexError: row index out of bounds </code></pre> <p>So when slicing <code>scipy.sparse</code> arrays, you must make manually sure your slice bounds are within range. This differs from how both NumPy and plain Python work.</p>
5
2011-07-29T16:21:20Z
[ "python", "numpy" ]
gotchas where Numpy differs from straight python?
1,322,380
<p>Folks,</p> <p>is there a collection of gotchas where Numpy differs from python, points that have puzzled and cost time ?</p> <blockquote> <p>"The horror of that moment I shall never never forget !"<br /> "You will, though," the Queen said, "if you don't make a memorandum of it."</p> </blockquote> <p>For example, NaNs are always trouble, anywhere. If you can explain this without running it, give yourself a point --</p> <pre><code>from numpy import array, NaN, isnan pynan = float("nan") print pynan is pynan, pynan is NaN, NaN is NaN a = (0, pynan) print a, a[1] is pynan, any([aa is pynan for aa in a]) a = array(( 0, NaN )) print a, a[1] is NaN, isnan( a[1] ) </code></pre> <p>(I'm not knocking numpy, lots of good work there, just think a FAQ or Wiki of gotchas would be useful.)</p> <p>Edit: I was hoping to collect half a dozen gotchas (surprises for people learning Numpy).<br /> Then, if there are common gotchas or, better, common explanations, we could talk about adding them to a community Wiki (where ?) It doesn't look like we have enough so far.</p>
23
2009-08-24T13:21:37Z
7,384,044
<p>Not such a big gotcha: With boolean slicing, I sometimes wish I could do </p> <pre><code> x[ 3 &lt;= y &lt; 7 ] </code></pre> <p>like the python double comparison. Instead, I have to write </p> <pre><code> x[ np.logical_and(3&lt;=y, y&lt;7) ] </code></pre> <p>(Unless you know something better?)</p> <p>Also, np.logical_and and np.logical_or only take two arguments each, I would like them to take a variable number, or a list, so I could feed in more than just two logical clauses.</p> <p>(numpy 1.3, maybe this has all changed in later versions.)</p>
2
2011-09-12T06:26:24Z
[ "python", "numpy" ]
gotchas where Numpy differs from straight python?
1,322,380
<p>Folks,</p> <p>is there a collection of gotchas where Numpy differs from python, points that have puzzled and cost time ?</p> <blockquote> <p>"The horror of that moment I shall never never forget !"<br /> "You will, though," the Queen said, "if you don't make a memorandum of it."</p> </blockquote> <p>For example, NaNs are always trouble, anywhere. If you can explain this without running it, give yourself a point --</p> <pre><code>from numpy import array, NaN, isnan pynan = float("nan") print pynan is pynan, pynan is NaN, NaN is NaN a = (0, pynan) print a, a[1] is pynan, any([aa is pynan for aa in a]) a = array(( 0, NaN )) print a, a[1] is NaN, isnan( a[1] ) </code></pre> <p>(I'm not knocking numpy, lots of good work there, just think a FAQ or Wiki of gotchas would be useful.)</p> <p>Edit: I was hoping to collect half a dozen gotchas (surprises for people learning Numpy).<br /> Then, if there are common gotchas or, better, common explanations, we could talk about adding them to a community Wiki (where ?) It doesn't look like we have enough so far.</p>
23
2009-08-24T13:21:37Z
14,986,289
<pre><code>In [1]: bool([]) Out[1]: False In [2]: bool(array([])) Out[2]: False In [3]: bool([0]) Out[3]: True In [4]: bool(array([0])) Out[4]: False </code></pre> <p>So don't test for the emptiness of an array by checking its truth value. Use <code>size(array())</code>.</p> <p>And don't use <code>len(array())</code>, either:</p> <pre><code>In [1]: size(array([])) Out[1]: 0 In [2]: len(array([])) Out[2]: 0 In [3]: size(array([0])) Out[3]: 1 In [4]: len(array([0])) Out[4]: 1 In [5]: size(array(0)) Out[5]: 1 In [6]: len(array(0)) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-6-5b2872696128&gt; in &lt;module&gt;() ----&gt; 1 len(array(0)) TypeError: len() of unsized object </code></pre>
6
2013-02-20T17:35:11Z
[ "python", "numpy" ]
gotchas where Numpy differs from straight python?
1,322,380
<p>Folks,</p> <p>is there a collection of gotchas where Numpy differs from python, points that have puzzled and cost time ?</p> <blockquote> <p>"The horror of that moment I shall never never forget !"<br /> "You will, though," the Queen said, "if you don't make a memorandum of it."</p> </blockquote> <p>For example, NaNs are always trouble, anywhere. If you can explain this without running it, give yourself a point --</p> <pre><code>from numpy import array, NaN, isnan pynan = float("nan") print pynan is pynan, pynan is NaN, NaN is NaN a = (0, pynan) print a, a[1] is pynan, any([aa is pynan for aa in a]) a = array(( 0, NaN )) print a, a[1] is NaN, isnan( a[1] ) </code></pre> <p>(I'm not knocking numpy, lots of good work there, just think a FAQ or Wiki of gotchas would be useful.)</p> <p>Edit: I was hoping to collect half a dozen gotchas (surprises for people learning Numpy).<br /> Then, if there are common gotchas or, better, common explanations, we could talk about adding them to a community Wiki (where ?) It doesn't look like we have enough so far.</p>
23
2009-08-24T13:21:37Z
14,986,378
<p>No one seems to have mentioned this so far:</p> <pre><code>&gt;&gt;&gt; all(False for i in range(3)) False &gt;&gt;&gt; from numpy import all &gt;&gt;&gt; all(False for i in range(3)) True &gt;&gt;&gt; any(False for i in range(3)) False &gt;&gt;&gt; from numpy import any &gt;&gt;&gt; any(False for i in range(3)) True </code></pre> <p>numpy's <code>any</code> and <code>all</code> don't play nicely with generators, and don't raise any error warning you that they don't.</p>
2
2013-02-20T17:39:45Z
[ "python", "numpy" ]