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
sequence
How do you split a list into evenly sized chunks?
312,443
<p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p> <p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p> <p>This should work:</p> <pre><code>l = range(1, 1000) print chunks(l, 10) -&gt; [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ] </code></pre> <p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p> <p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most “pythonic” way to iterate over a list in chunks?</a></p>
959
2008-11-23T12:15:52Z
18,793,562
<ul> <li>Works with any iterable</li> <li>Inner data is generator object (not a list)</li> <li>One liner</li> </ul> <pre> In [259]: get_in_chunks = lambda itr,n: ( (v for _,v in g) for _,g in itertools.groupby(enumerate(itr),lambda (ind,_): ind/n)) In [260]: list(list(x) for x in get_in_chunks(range(30),7)) Out[260]: [[0, 1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12, 13], [14, 15, 16, 17, 18, 19, 20], [21, 22, 23, 24, 25, 26, 27], [28, 29]] </pre>
2
2013-09-13T19:11:44Z
[ "python", "list", "split", "chunks" ]
How do you split a list into evenly sized chunks?
312,443
<p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p> <p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p> <p>This should work:</p> <pre><code>l = range(1, 1000) print chunks(l, 10) -&gt; [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ] </code></pre> <p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p> <p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most “pythonic” way to iterate over a list in chunks?</a></p>
959
2008-11-23T12:15:52Z
18,970,810
<pre><code>def chunked(iterable, size): chunk = () for item in iterable: chunk += (item,) if len(chunk) % size == 0: yield chunk chunk = () if chunk: yield chunk </code></pre>
0
2013-09-23T23:57:43Z
[ "python", "list", "split", "chunks" ]
How do you split a list into evenly sized chunks?
312,443
<p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p> <p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p> <p>This should work:</p> <pre><code>l = range(1, 1000) print chunks(l, 10) -&gt; [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ] </code></pre> <p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p> <p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most “pythonic” way to iterate over a list in chunks?</a></p>
959
2008-11-23T12:15:52Z
19,264,525
<p>I like the Python doc's version proposed by tzot and J.F.Sebastian a lot, but it has two shortcomings:</p> <ul> <li>it is not very explicit</li> <li>I usually don't want a fill value in the last chunk</li> </ul> <p>I'm using this one a lot in my code:</p> <pre><code>from itertools import islice def chunks(n, iterable): iterable = iter(iterable) while True: yield tuple(islice(iterable, n)) or iterable.next() </code></pre> <p>UPDATE: A lazy chunks version:</p> <pre><code>from itertools import chain, islice def chunks(n, iterable): iterable = iter(iterable) while True: yield chain([next(iterable)], islice(iterable, n-1)) </code></pre>
11
2013-10-09T06:17:29Z
[ "python", "list", "split", "chunks" ]
How do you split a list into evenly sized chunks?
312,443
<p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p> <p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p> <p>This should work:</p> <pre><code>l = range(1, 1000) print chunks(l, 10) -&gt; [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ] </code></pre> <p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p> <p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most “pythonic” way to iterate over a list in chunks?</a></p>
959
2008-11-23T12:15:52Z
20,106,816
<p>The <a href="https://github.com/pytoolz/toolz">toolz</a> library has the <code>partition</code> function for this:</p> <pre><code>from toolz.itertoolz.core import partition list(partition(2, [1, 2, 3, 4])) [(1, 2), (3, 4)] </code></pre>
5
2013-11-20T20:55:22Z
[ "python", "list", "split", "chunks" ]
How do you split a list into evenly sized chunks?
312,443
<p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p> <p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p> <p>This should work:</p> <pre><code>l = range(1, 1000) print chunks(l, 10) -&gt; [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ] </code></pre> <p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p> <p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most “pythonic” way to iterate over a list in chunks?</a></p>
959
2008-11-23T12:15:52Z
20,228,836
<p>Yes, it is an old question, but I had to post this one, because it is even a little shorter than the similar ones. Yes, the result looks scrambled, but if it is just about even length...</p> <pre><code>&gt;&gt;&gt; n = 3 # number of groups &gt;&gt;&gt; biglist = range(30) &gt;&gt;&gt; &gt;&gt;&gt; [ biglist[i::n] for i in xrange(n) ] [[0, 3, 6, 9, 12, 15, 18, 21, 24, 27], [1, 4, 7, 10, 13, 16, 19, 22, 25, 28], [2, 5, 8, 11, 14, 17, 20, 23, 26, 29]] </code></pre>
-1
2013-11-26T21:58:03Z
[ "python", "list", "split", "chunks" ]
How do you split a list into evenly sized chunks?
312,443
<p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p> <p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p> <p>This should work:</p> <pre><code>l = range(1, 1000) print chunks(l, 10) -&gt; [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ] </code></pre> <p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p> <p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most “pythonic” way to iterate over a list in chunks?</a></p>
959
2008-11-23T12:15:52Z
21,767,522
<h2>Critique of other answers here:</h2> <p>None of these answers are evenly sized chunks, they all leave a runt chunk at the end, so they're not completely balanced. If you were using these functions to distribute work, you've built-in the prospect of one likely finishing well before the others, so it would sit around doing nothing while the others continued working hard.</p> <p>For example, the current top answer ends with:</p> <pre><code>[60, 61, 62, 63, 64, 65, 66, 67, 68, 69], [70, 71, 72, 73, 74]] </code></pre> <p>I just hate that runt at the end!</p> <p>Others, like <code>list(grouper(3, xrange(7)))</code>, and <code>chunk(xrange(7), 3)</code> both return: <code>[(0, 1, 2), (3, 4, 5), (6, None, None)]</code>. The <code>None</code>'s are just padding, and rather inelegant in my opinion. They are NOT evenly chunking the iterables.</p> <p>Why can't we divide these better?</p> <h2>My Solution(s)</h2> <p>Here's a balanced solution, adapted from a function I've used in production (Note in Python 3 to replace <code>xrange</code> with <code>range</code>):</p> <pre><code>def baskets_from(items, maxbaskets=25): baskets = [[] for _ in xrange(maxbaskets)] # in Python 3 use range for i, item in enumerate(items): baskets[i % maxbaskets].append(item) return filter(None, baskets) </code></pre> <p>And I created a generator that does the same if you put it into a list:</p> <pre><code>def iter_baskets_from(items, maxbaskets=3): '''generates evenly balanced baskets from indexable iterable''' item_count = len(items) baskets = min(item_count, maxbaskets) for x_i in xrange(baskets): yield [items[y_i] for y_i in xrange(x_i, item_count, baskets)] </code></pre> <p>And finally, since I see that all of the above functions return elements in a contiguous order (as they were given):</p> <pre><code>def iter_baskets_contiguous(items, maxbaskets=3, item_count=None): ''' generates balanced baskets from iterable, contiguous contents provide item_count if providing a iterator that doesn't support len() ''' item_count = item_count or len(items) baskets = min(item_count, maxbaskets) items = iter(items) floor = item_count // baskets ceiling = floor + 1 stepdown = item_count % baskets for x_i in xrange(baskets): length = ceiling if x_i &lt; stepdown else floor yield [items.next() for _ in xrange(length)] </code></pre> <h2>Output</h2> <p>To test them out:</p> <pre><code>print(baskets_from(xrange(6), 8)) print(list(iter_baskets_from(xrange(6), 8))) print(list(iter_baskets_contiguous(xrange(6), 8))) print(baskets_from(xrange(22), 8)) print(list(iter_baskets_from(xrange(22), 8))) print(list(iter_baskets_contiguous(xrange(22), 8))) print(baskets_from('ABCDEFG', 3)) print(list(iter_baskets_from('ABCDEFG', 3))) print(list(iter_baskets_contiguous('ABCDEFG', 3))) print(baskets_from(xrange(26), 5)) print(list(iter_baskets_from(xrange(26), 5))) print(list(iter_baskets_contiguous(xrange(26), 5))) </code></pre> <p>Which prints out:</p> <pre><code>[[0], [1], [2], [3], [4], [5]] [[0], [1], [2], [3], [4], [5]] [[0], [1], [2], [3], [4], [5]] [[0, 8, 16], [1, 9, 17], [2, 10, 18], [3, 11, 19], [4, 12, 20], [5, 13, 21], [6, 14], [7, 15]] [[0, 8, 16], [1, 9, 17], [2, 10, 18], [3, 11, 19], [4, 12, 20], [5, 13, 21], [6, 14], [7, 15]] [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14], [15, 16, 17], [18, 19], [20, 21]] [['A', 'D', 'G'], ['B', 'E'], ['C', 'F']] [['A', 'D', 'G'], ['B', 'E'], ['C', 'F']] [['A', 'B', 'C'], ['D', 'E'], ['F', 'G']] [[0, 5, 10, 15, 20, 25], [1, 6, 11, 16, 21], [2, 7, 12, 17, 22], [3, 8, 13, 18, 23], [4, 9, 14, 19, 24]] [[0, 5, 10, 15, 20, 25], [1, 6, 11, 16, 21], [2, 7, 12, 17, 22], [3, 8, 13, 18, 23], [4, 9, 14, 19, 24]] [[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25]] </code></pre> <p>Notice that the contiguous generator provide chunks in the same length patterns as the other two, but the items are all in order, and they are as evenly divided as one may divide a list of discrete elements.</p>
13
2014-02-13T23:07:17Z
[ "python", "list", "split", "chunks" ]
How do you split a list into evenly sized chunks?
312,443
<p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p> <p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p> <p>This should work:</p> <pre><code>l = range(1, 1000) print chunks(l, 10) -&gt; [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ] </code></pre> <p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p> <p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most “pythonic” way to iterate over a list in chunks?</a></p>
959
2008-11-23T12:15:52Z
22,045,226
<p>I'm surprised nobody has thought of using <code>iter</code>'s <a href="http://docs.python.org/2/library/functions.html#iter">two-argument form</a>:</p> <pre><code>from itertools import islice def chunk(it, size): it = iter(it) return iter(lambda: tuple(islice(it, size)), ()) </code></pre> <p>Demo:</p> <pre><code>&gt;&gt;&gt; list(chunk(range(14), 3)) [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11), (12, 13)] </code></pre> <p>This works with any iterable and produces output lazily. It returns tuples rather than iterators, but I think it has a certain elegance nonetheless. It also doesn't pad; if you want padding, a simple variation on the above will suffice:</p> <pre><code>from itertools import islice, chain, repeat def chunk_pad(it, size, padval=None): it = chain(iter(it), repeat(padval)) return iter(lambda: tuple(islice(it, size)), (padval,) * size) </code></pre> <p>Demo:</p> <pre><code>&gt;&gt;&gt; list(chunk_pad(range(14), 3)) [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11), (12, 13, None)] &gt;&gt;&gt; list(chunk_pad(range(14), 3, 'a')) [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11), (12, 13, 'a')] </code></pre> <p>Like the <code>izip_longest</code>-based solutions, the above <em>always</em> pads. As far as I know, there's no one- or two-line itertools recipe for a function that <em>optionally</em> pads. By combining the above two approaches, this one comes pretty close:</p> <pre><code>_no_padding = object() def chunk(it, size, padval=_no_padding): if padval == _no_padding: it = iter(it) sentinel = () else: it = chain(iter(it), repeat(padval)) sentinel = (padval,) * size return iter(lambda: tuple(islice(it, size)), sentinel) </code></pre> <p>Demo:</p> <pre><code>&gt;&gt;&gt; list(chunk(range(14), 3)) [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11), (12, 13)] &gt;&gt;&gt; list(chunk(range(14), 3, None)) [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11), (12, 13, None)] &gt;&gt;&gt; list(chunk(range(14), 3, 'a')) [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11), (12, 13, 'a')] </code></pre> <p>I believe this is the shortest chunker proposed that offers optional padding. </p>
29
2014-02-26T15:02:00Z
[ "python", "list", "split", "chunks" ]
How do you split a list into evenly sized chunks?
312,443
<p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p> <p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p> <p>This should work:</p> <pre><code>l = range(1, 1000) print chunks(l, 10) -&gt; [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ] </code></pre> <p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p> <p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most “pythonic” way to iterate over a list in chunks?</a></p>
959
2008-11-23T12:15:52Z
22,138,685
<p>I wrote a small library expressly for this purpose, available <a href="https://github.com/rectangletangle/iterlib" rel="nofollow">here</a>. The library's <code>chunked</code> function is particularly efficient because it's implemented as a <a href="https://wiki.python.org/moin/Generators" rel="nofollow">generator</a>, so a substantial amount of memory can be saved in certain situations. It also doesn't rely on the slice notation, so any arbitrary iterator can be used.</p> <pre><code>import iterlib print list(iterlib.chunked(xrange(1, 1000), 10)) # prints [(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), (11, 12, 13, 14, 15, 16, 17, 18, 19, 20), ...] </code></pre>
1
2014-03-03T04:30:24Z
[ "python", "list", "split", "chunks" ]
How do you split a list into evenly sized chunks?
312,443
<p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p> <p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p> <p>This should work:</p> <pre><code>l = range(1, 1000) print chunks(l, 10) -&gt; [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ] </code></pre> <p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p> <p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most “pythonic” way to iterate over a list in chunks?</a></p>
959
2008-11-23T12:15:52Z
25,650,543
<p>Like @AaronHall I got here looking for roughly evenly sized chunks. There are different interpretations of that. In my case, if the desired size is N, I would like each group to be of size>=N. Thus, the orphans which are created in most of the above should be redistributed to other groups.</p> <p>This can be done using:</p> <pre><code>def nChunks(l, n): """ Yield n successive chunks from l. Works for lists, pandas dataframes, etc """ newn = int(1.0 * len(l) / n + 0.5) for i in xrange(0, n-1): yield l[i*newn:i*newn+newn] yield l[n*newn-newn:] </code></pre> <p>(from <a href="http://stackoverflow.com/questions/2130016/splitting-a-list-of-arbitrary-size-into-only-roughly-n-equal-parts">splitting a list of arbitrary size into only roughly N-equal parts</a>) by simply calling it as nChunks(l,l/n) or nChunks(l,floor(l/n))</p>
1
2014-09-03T17:43:15Z
[ "python", "list", "split", "chunks" ]
How do you split a list into evenly sized chunks?
312,443
<p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p> <p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p> <p>This should work:</p> <pre><code>l = range(1, 1000) print chunks(l, 10) -&gt; [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ] </code></pre> <p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p> <p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most “pythonic” way to iterate over a list in chunks?</a></p>
959
2008-11-23T12:15:52Z
27,371,167
<p>letting r be the chunk size and L be the initial list, you can do. </p> <pre><code>chunkL = [ [i for i in L[r*k:r*(k+1)] ] for k in range(len(L)/r)] </code></pre>
1
2014-12-09T03:54:49Z
[ "python", "list", "split", "chunks" ]
How do you split a list into evenly sized chunks?
312,443
<p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p> <p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p> <p>This should work:</p> <pre><code>l = range(1, 1000) print chunks(l, 10) -&gt; [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ] </code></pre> <p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p> <p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most “pythonic” way to iterate over a list in chunks?</a></p>
959
2008-11-23T12:15:52Z
28,756,559
<p>Use list comprehensions:</p> <pre><code>l = [1,2,3,4,5,6,7,8,9,10,11,12] k = 5 #chunk size print [tuple(l[x:y]) for (x, y) in [(x, x+k) for x in range(0, len(l), k)]] </code></pre>
0
2015-02-27T02:33:35Z
[ "python", "list", "split", "chunks" ]
How do you split a list into evenly sized chunks?
312,443
<p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p> <p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p> <p>This should work:</p> <pre><code>l = range(1, 1000) print chunks(l, 10) -&gt; [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ] </code></pre> <p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p> <p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most “pythonic” way to iterate over a list in chunks?</a></p>
959
2008-11-23T12:15:52Z
28,786,255
<p>Another more explicit version.</p> <pre><code>def chunkList(initialList, chunkSize): """ This function chunks a list into sub lists that have a length equals to chunkSize. Example: lst = [3, 4, 9, 7, 1, 1, 2, 3] print(chunkList(lst, 3)) returns [[3, 4, 9], [7, 1, 1], [2, 3]] """ finalList = [] for i in range(0, len(initialList), chunkSize): finalList.append(initialList[i:i+chunkSize]) return finalList </code></pre>
4
2015-02-28T20:05:03Z
[ "python", "list", "split", "chunks" ]
How do you split a list into evenly sized chunks?
312,443
<p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p> <p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p> <p>This should work:</p> <pre><code>l = range(1, 1000) print chunks(l, 10) -&gt; [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ] </code></pre> <p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p> <p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most “pythonic” way to iterate over a list in chunks?</a></p>
959
2008-11-23T12:15:52Z
29,009,933
<p>I saw the most awesome Python-ish answer in a <a href="http://stackoverflow.com/questions/23286254/convert-list-to-a-list-of-tuples-python">duplicate</a> of this question:</p> <pre><code>l = range(1,15) i = iter(l) print zip(i,i,i) </code></pre> <p>You can create n-tuple for any n.</p>
18
2015-03-12T12:36:10Z
[ "python", "list", "split", "chunks" ]
How do you split a list into evenly sized chunks?
312,443
<p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p> <p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p> <p>This should work:</p> <pre><code>l = range(1, 1000) print chunks(l, 10) -&gt; [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ] </code></pre> <p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p> <p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most “pythonic” way to iterate over a list in chunks?</a></p>
959
2008-11-23T12:15:52Z
29,707,187
<p>The answer above (by koffein) has a little problem: the list is always split into an equal number of splits, not equal number of items per partition. This is my version. The "// chs + 1" takes into account that the number of items may not be divideable exactly by the partition size, so the last partition will only be partially filled.</p> <pre><code># Given 'l' is your list chs = 12 # Your chunksize partitioned = [ l[i*chs:(i*chs)+chs] for i in range((len(l) // chs)+1) ] </code></pre>
1
2015-04-17T18:48:35Z
[ "python", "list", "split", "chunks" ]
How do you split a list into evenly sized chunks?
312,443
<p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p> <p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p> <p>This should work:</p> <pre><code>l = range(1, 1000) print chunks(l, 10) -&gt; [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ] </code></pre> <p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p> <p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most “pythonic” way to iterate over a list in chunks?</a></p>
959
2008-11-23T12:15:52Z
31,178,232
<p>code:</p> <pre><code>def split_list(the_list, chunk_size): result_list = [] while the_list: result_list.append(the_list[:chunk_size]) the_list = the_list[chunk_size:] return result_list a_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print split_list(a_list, 3) </code></pre> <p>result:</p> <pre><code>[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]] </code></pre>
3
2015-07-02T07:32:49Z
[ "python", "list", "split", "chunks" ]
How do you split a list into evenly sized chunks?
312,443
<p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p> <p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p> <p>This should work:</p> <pre><code>l = range(1, 1000) print chunks(l, 10) -&gt; [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ] </code></pre> <p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p> <p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most “pythonic” way to iterate over a list in chunks?</a></p>
959
2008-11-23T12:15:52Z
31,442,939
<pre><code>a = [1, 2, 3, 4, 5, 6, 7, 8, 9] CHUNK = 4 [a[i*CHUNK:(i+1)*CHUNK] for i in xrange((len(a) + CHUNK - 1) / CHUNK )] </code></pre>
2
2015-07-15T23:27:19Z
[ "python", "list", "split", "chunks" ]
How do you split a list into evenly sized chunks?
312,443
<p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p> <p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p> <p>This should work:</p> <pre><code>l = range(1, 1000) print chunks(l, 10) -&gt; [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ] </code></pre> <p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p> <p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most “pythonic” way to iterate over a list in chunks?</a></p>
959
2008-11-23T12:15:52Z
32,658,232
<p>I have come up to following solution without creation temorary list object, which should work with any iterable object. Please note that this version for Python 2.x:</p> <pre><code>def chunked(iterable, size): stop = [] it = iter(iterable) def _next_chunk(): try: for _ in xrange(size): yield next(it) except StopIteration: stop.append(True) return while not stop: yield _next_chunk() for it in chunked(xrange(16), 4): print list(it) </code></pre> <p>Output:</p> <pre><code>[0, 1, 2, 3] [4, 5, 6, 7] [8, 9, 10, 11] [12, 13, 14, 15] [] </code></pre> <p>As you can see if len(iterable) % size == 0 then we have additional empty iterator object. But I do not think that it is big problem.</p>
0
2015-09-18T17:54:39Z
[ "python", "list", "split", "chunks" ]
How do you split a list into evenly sized chunks?
312,443
<p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p> <p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p> <p>This should work:</p> <pre><code>l = range(1, 1000) print chunks(l, 10) -&gt; [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ] </code></pre> <p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p> <p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most “pythonic” way to iterate over a list in chunks?</a></p>
959
2008-11-23T12:15:52Z
33,180,285
<p>Since I had to do something like this, here's my solution given a generator and a batch size:</p> <pre><code>def pop_n_elems_from_generator(g, n): elems = [] try: for idx in xrange(0, n): elems.append(g.next()) return elems except StopIteration: return elems </code></pre>
0
2015-10-16T22:09:29Z
[ "python", "list", "split", "chunks" ]
How do you split a list into evenly sized chunks?
312,443
<p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p> <p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p> <p>This should work:</p> <pre><code>l = range(1, 1000) print chunks(l, 10) -&gt; [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ] </code></pre> <p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p> <p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most “pythonic” way to iterate over a list in chunks?</a></p>
959
2008-11-23T12:15:52Z
33,510,840
<p>At this point, I think we need a <strong>recursive generator</strong>, just in case...</p> <p>In python 2:</p> <pre><code>def chunks(li, n): if li == []: return yield li[:n] for e in chunks(li[n:], n): yield e </code></pre> <p>In python 3:</p> <pre><code>def chunks(li, n): if li == []: return yield li[:n] yield from chunks(li[n:], n) </code></pre> <p>Also, in case of massive Alien invasion, a <strong>decorated recursive generator</strong> might become handy:</p> <pre><code>def dec(gen): def new_gen(li, n): for e in gen(li, n): if e == []: return yield e return new_gen @dec def chunks(li, n): yield li[:n] for e in chunks(li[n:], n): yield e </code></pre>
5
2015-11-03T23:10:50Z
[ "python", "list", "split", "chunks" ]
How do you split a list into evenly sized chunks?
312,443
<p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p> <p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p> <p>This should work:</p> <pre><code>l = range(1, 1000) print chunks(l, 10) -&gt; [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ] </code></pre> <p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p> <p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most “pythonic” way to iterate over a list in chunks?</a></p>
959
2008-11-23T12:15:52Z
33,517,774
<p>At this point, I think we need the obligatory anonymous-recursive function.</p> <pre><code>Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args))) chunks = Y(lambda f: lambda n: [n[0][:n[1]]] + f((n[0][n[1]:], n[1])) if len(n[0]) &gt; 0 else []) </code></pre>
2
2015-11-04T09:12:27Z
[ "python", "list", "split", "chunks" ]
How do you split a list into evenly sized chunks?
312,443
<p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p> <p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p> <p>This should work:</p> <pre><code>l = range(1, 1000) print chunks(l, 10) -&gt; [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ] </code></pre> <p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p> <p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most “pythonic” way to iterate over a list in chunks?</a></p>
959
2008-11-23T12:15:52Z
34,322,647
<pre><code>[AA[i:i+SS] for i in range(len(AA))[::SS]] </code></pre> <p>Where AA is array, SS is chunk size. For example:</p> <pre><code>&gt;&gt;&gt; AA=range(10,21);SS=3 &gt;&gt;&gt; [AA[i:i+SS] for i in range(len(AA))[::SS]] [[10, 11, 12], [13, 14, 15], [16, 17, 18], [19, 20]] # or [range(10, 13), range(13, 16), range(16, 19), range(19, 21)] in py3 </code></pre>
4
2015-12-16T21:42:56Z
[ "python", "list", "split", "chunks" ]
How do you split a list into evenly sized chunks?
312,443
<p>I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive.</p> <p>I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators.</p> <p>This should work:</p> <pre><code>l = range(1, 1000) print chunks(l, 10) -&gt; [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ] </code></pre> <p>I was looking for something useful in <code>itertools</code> but I couldn't find anything obviously useful. Might've missed it, though.</p> <p>Related question: <a href="http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks">What is the most “pythonic” way to iterate over a list in chunks?</a></p>
959
2008-11-23T12:15:52Z
38,808,533
<p>As per <a href="http://stackoverflow.com/a/21767522/15055">this answer</a>, the top-voted answer leaves a 'runt' at the end. Here's my solution to really get about as evenly-sized chunks as you can, with no runts. It basically tries to pick exactly the fractional spot where it should split the list, but just rounds it off to the nearest integer:</p> <pre><code>from __future__ import division # not needed in Python 3 def n_even_chunks(l, n): """Yield n as even chunks as possible from l.""" last = 0 for i in range(1, n+1): cur = int(round(i * (len(l) / n))) yield l[last:cur] last = cur </code></pre> <p>Demonstration:</p> <pre><code>&gt;&gt;&gt; pprint.pprint(list(n_even_chunks(list(range(100)), 9))) [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21], [22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32], [33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43], [44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55], [56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66], [67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77], [78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88], [89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]] &gt;&gt;&gt; pprint.pprint(list(n_even_chunks(list(range(100)), 11))) [[0, 1, 2, 3, 4, 5, 6, 7, 8], [9, 10, 11, 12, 13, 14, 15, 16, 17], [18, 19, 20, 21, 22, 23, 24, 25, 26], [27, 28, 29, 30, 31, 32, 33, 34, 35], [36, 37, 38, 39, 40, 41, 42, 43, 44], [45, 46, 47, 48, 49, 50, 51, 52, 53, 54], [55, 56, 57, 58, 59, 60, 61, 62, 63], [64, 65, 66, 67, 68, 69, 70, 71, 72], [73, 74, 75, 76, 77, 78, 79, 80, 81], [82, 83, 84, 85, 86, 87, 88, 89, 90], [91, 92, 93, 94, 95, 96, 97, 98, 99]] </code></pre> <p>Compare to the top-voted <code>chunks</code> answer:</p> <pre><code>&gt;&gt;&gt; pprint.pprint(list(chunks(list(range(100)), 100//9))) [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21], [22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32], [33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43], [44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54], [55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65], [66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76], [77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87], [88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98], [99]] &gt;&gt;&gt; pprint.pprint(list(chunks(list(range(100)), 100//11))) [[0, 1, 2, 3, 4, 5, 6, 7, 8], [9, 10, 11, 12, 13, 14, 15, 16, 17], [18, 19, 20, 21, 22, 23, 24, 25, 26], [27, 28, 29, 30, 31, 32, 33, 34, 35], [36, 37, 38, 39, 40, 41, 42, 43, 44], [45, 46, 47, 48, 49, 50, 51, 52, 53], [54, 55, 56, 57, 58, 59, 60, 61, 62], [63, 64, 65, 66, 67, 68, 69, 70, 71], [72, 73, 74, 75, 76, 77, 78, 79, 80], [81, 82, 83, 84, 85, 86, 87, 88, 89], [90, 91, 92, 93, 94, 95, 96, 97, 98], [99]] </code></pre>
1
2016-08-06T20:44:07Z
[ "python", "list", "split", "chunks" ]
Python 2.6 + JCC + Pylucene issue
312,444
<p>Greetings,</p> <p>I'm trying to use pylucene in Python 2.6. Since there's no windows build for 2.6, I try to build the source code.</p> <p>First of all, I build JCC (windows, using cygwin)</p> <pre><code>python setup.py build running build running build_py [...] building 'jcc' extension error: None python setup.py install running install [...] copying jcc\config.py -&gt; build\lib.win32-2.6\jcc copying jcc\classes\org\osafoundation\jcc\PythonException.class -&gt; build\lib.win32-2.6\jcc\classes\org\osafoundation\jcc running build_ext building 'jcc' extension error: None </code></pre> <p>Notice that it won't copy anything on my "F:\Python26\Lib\site-packages" directory. I don't know why. So that, I don't know if it's really installed or not.</p> <p>Now, I'll make pylucene</p> <pre><code>make /cygdrive/f/Python26//python.exe -m jcc --shared --jar lucene-java-2.4.0/build/lucene-core-2.4.0.jar [...] 'doc:(I)Lorg/apache/lucene/document/Document;' --version 2.4.0 --files 2 --build f:\Python26\python.exe: No module named jcc make: *** [compile] Error 1 </code></pre> <p>So, it seems JCC wasn't installed at all.</p> <p>Then, I try to copy the "jcc build" under F:\Python26\Lib\site-packages, and I try to make pylucene again:</p> <pre><code>make [...] f:\Python26\python.exe: jcc is a package and cannot be directly executed make: *** [compile] Error 1 </code></pre> <p>Has anyone else seen this and found a workaround?</p>
5
2008-11-23T12:17:18Z
312,586
<p>try:</p> <blockquote> <p>/cygdrive/f/Python26//python.exe setup.py build</p> </blockquote> <p>and</p> <blockquote> <p>/cygdrive/f/Python26//python.exe setup.py build setup.py install</p> </blockquote> <p>I believe you are using python from cygwin for instaling jcc and python from windows for running...</p>
1
2008-11-23T14:48:46Z
[ "python", "pylucene", "jcc" ]
Python 2.6 + JCC + Pylucene issue
312,444
<p>Greetings,</p> <p>I'm trying to use pylucene in Python 2.6. Since there's no windows build for 2.6, I try to build the source code.</p> <p>First of all, I build JCC (windows, using cygwin)</p> <pre><code>python setup.py build running build running build_py [...] building 'jcc' extension error: None python setup.py install running install [...] copying jcc\config.py -&gt; build\lib.win32-2.6\jcc copying jcc\classes\org\osafoundation\jcc\PythonException.class -&gt; build\lib.win32-2.6\jcc\classes\org\osafoundation\jcc running build_ext building 'jcc' extension error: None </code></pre> <p>Notice that it won't copy anything on my "F:\Python26\Lib\site-packages" directory. I don't know why. So that, I don't know if it's really installed or not.</p> <p>Now, I'll make pylucene</p> <pre><code>make /cygdrive/f/Python26//python.exe -m jcc --shared --jar lucene-java-2.4.0/build/lucene-core-2.4.0.jar [...] 'doc:(I)Lorg/apache/lucene/document/Document;' --version 2.4.0 --files 2 --build f:\Python26\python.exe: No module named jcc make: *** [compile] Error 1 </code></pre> <p>So, it seems JCC wasn't installed at all.</p> <p>Then, I try to copy the "jcc build" under F:\Python26\Lib\site-packages, and I try to make pylucene again:</p> <pre><code>make [...] f:\Python26\python.exe: jcc is a package and cannot be directly executed make: *** [compile] Error 1 </code></pre> <p>Has anyone else seen this and found a workaround?</p>
5
2008-11-23T12:17:18Z
2,046,369
<p>Few checkpoints</p> <ul> <li><p><code>error: None</code> mean there is an error on building, it was NOT success, so the extensions does not get build</p></li> <li><p>if you are using cygwin, I guess you need to use cygwin version of python, but according to this you using windows version, which is installed in F:\Python - <code>/cygdrive/f/Python26//python.exe</code>,</p></li> <li><p>I suggest you to try with <a href="http://www.mingw.org/" rel="nofollow">mingw32</a>, install mingw32 and try <code>python setup.py build -c mingw32</code> and <code>python setup.py install</code></p></li> </ul>
1
2010-01-12T02:45:07Z
[ "python", "pylucene", "jcc" ]
Python 2.6 + JCC + Pylucene issue
312,444
<p>Greetings,</p> <p>I'm trying to use pylucene in Python 2.6. Since there's no windows build for 2.6, I try to build the source code.</p> <p>First of all, I build JCC (windows, using cygwin)</p> <pre><code>python setup.py build running build running build_py [...] building 'jcc' extension error: None python setup.py install running install [...] copying jcc\config.py -&gt; build\lib.win32-2.6\jcc copying jcc\classes\org\osafoundation\jcc\PythonException.class -&gt; build\lib.win32-2.6\jcc\classes\org\osafoundation\jcc running build_ext building 'jcc' extension error: None </code></pre> <p>Notice that it won't copy anything on my "F:\Python26\Lib\site-packages" directory. I don't know why. So that, I don't know if it's really installed or not.</p> <p>Now, I'll make pylucene</p> <pre><code>make /cygdrive/f/Python26//python.exe -m jcc --shared --jar lucene-java-2.4.0/build/lucene-core-2.4.0.jar [...] 'doc:(I)Lorg/apache/lucene/document/Document;' --version 2.4.0 --files 2 --build f:\Python26\python.exe: No module named jcc make: *** [compile] Error 1 </code></pre> <p>So, it seems JCC wasn't installed at all.</p> <p>Then, I try to copy the "jcc build" under F:\Python26\Lib\site-packages, and I try to make pylucene again:</p> <pre><code>make [...] f:\Python26\python.exe: jcc is a package and cannot be directly executed make: *** [compile] Error 1 </code></pre> <p>Has anyone else seen this and found a workaround?</p>
5
2008-11-23T12:17:18Z
3,048,703
<p>that just can build jcc and install,</p> <p>top full code.</p> <p>13998bytes</p> <p>when import,report error.</p> <pre><code>&gt;&gt;&gt; import jcc Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "D:\Python26\lib\site-packages\jcc-2.5.1-py2.6-win32.egg\jcc\__init__.py" , line 29, in &lt;module&gt; from _jcc import initVM ImportError: DLL load failed: 找不到指定的模块。(cant find appointed modules) &gt;&gt;&gt; </code></pre>
0
2010-06-15T20:16:18Z
[ "python", "pylucene", "jcc" ]
No Module named django.core
312,549
<p>I have updated to latest Django version 1.0.2 after uninstalling my old Django version.But now when I run django-admin.py I get the following error. How can I resolve this?</p> <pre><code>Traceback (most recent call last): File "C:\Python25\Lib\site-packages\django\bin\django-admin.py", line 2, in &lt;module&gt; from django.core import management ImportError: No module named django.core </code></pre>
62
2008-11-23T14:09:24Z
325,295
<p>You must make sure that django is in your PYTHONPATH.</p> <p>To test, just do a <code>import django</code> from a python shell. There should be no output:</p> <pre><code>ActivePython 2.5.1.1 (ActiveState Software Inc.) based on Python 2.5.1 (r251:54863, May 1 2007, 17:47:05) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import django &gt;&gt;&gt; </code></pre> <p>If you installed django via <code>setuptools</code> (<code>easy_install</code>, or with the <code>setup.py</code> included with django), then check in your <code>site-packages</code> if the <code>.pth</code> file (<code>easy-install.pth</code>, <code>django.pth</code>, ...) point to the correct folder.</p> <p>HIH.</p>
34
2008-11-28T08:40:35Z
[ "python", "django" ]
No Module named django.core
312,549
<p>I have updated to latest Django version 1.0.2 after uninstalling my old Django version.But now when I run django-admin.py I get the following error. How can I resolve this?</p> <pre><code>Traceback (most recent call last): File "C:\Python25\Lib\site-packages\django\bin\django-admin.py", line 2, in &lt;module&gt; from django.core import management ImportError: No module named django.core </code></pre>
62
2008-11-23T14:09:24Z
2,081,421
<p>I'm sure it's related to something incorrect in my setup, but I am having the same problem, and it works properly if I call it thusly</p> <pre><code>c:\somedir&gt;python c:\Python26\scripts\django-admin.py startproject mysite </code></pre>
8
2010-01-17T15:21:48Z
[ "python", "django" ]
No Module named django.core
312,549
<p>I have updated to latest Django version 1.0.2 after uninstalling my old Django version.But now when I run django-admin.py I get the following error. How can I resolve this?</p> <pre><code>Traceback (most recent call last): File "C:\Python25\Lib\site-packages\django\bin\django-admin.py", line 2, in &lt;module&gt; from django.core import management ImportError: No module named django.core </code></pre>
62
2008-11-23T14:09:24Z
2,154,450
<p>As usual, an install script failed to set world read/execute permissions :) Do this:</p> <pre><code>sudo find /usr/lib/python2.5/site-packages/django -type d -exec chmod go+rx {} \; sudo find /usr/lib/python2.5/site-packages/django -type f -exec chmod go+r {} \; </code></pre>
0
2010-01-28T12:29:27Z
[ "python", "django" ]
No Module named django.core
312,549
<p>I have updated to latest Django version 1.0.2 after uninstalling my old Django version.But now when I run django-admin.py I get the following error. How can I resolve this?</p> <pre><code>Traceback (most recent call last): File "C:\Python25\Lib\site-packages\django\bin\django-admin.py", line 2, in &lt;module&gt; from django.core import management ImportError: No module named django.core </code></pre>
62
2008-11-23T14:09:24Z
2,172,329
<p>You can get around this problem by providing the full path to your django-admin.py file</p> <pre><code>python c:\python25\scripts\django-admin.py startproject mysite </code></pre>
18
2010-01-31T16:08:18Z
[ "python", "django" ]
No Module named django.core
312,549
<p>I have updated to latest Django version 1.0.2 after uninstalling my old Django version.But now when I run django-admin.py I get the following error. How can I resolve this?</p> <pre><code>Traceback (most recent call last): File "C:\Python25\Lib\site-packages\django\bin\django-admin.py", line 2, in &lt;module&gt; from django.core import management ImportError: No module named django.core </code></pre>
62
2008-11-23T14:09:24Z
2,352,728
<p>I encountered this problem today, it turned out that I had C:\Python26 in my path and .py files were associated to Python 3.1. Repairing the proper version of Python, either through Programs and Features or by running the .msi, will fix the associations.</p>
16
2010-02-28T21:21:39Z
[ "python", "django" ]
No Module named django.core
312,549
<p>I have updated to latest Django version 1.0.2 after uninstalling my old Django version.But now when I run django-admin.py I get the following error. How can I resolve this?</p> <pre><code>Traceback (most recent call last): File "C:\Python25\Lib\site-packages\django\bin\django-admin.py", line 2, in &lt;module&gt; from django.core import management ImportError: No module named django.core </code></pre>
62
2008-11-23T14:09:24Z
2,398,649
<p>This worked for me with bitnami djangostack:</p> <pre><code>python apps\django\django\bin\django-admin.py startproject mysite </code></pre>
5
2010-03-08T00:30:52Z
[ "python", "django" ]
No Module named django.core
312,549
<p>I have updated to latest Django version 1.0.2 after uninstalling my old Django version.But now when I run django-admin.py I get the following error. How can I resolve this?</p> <pre><code>Traceback (most recent call last): File "C:\Python25\Lib\site-packages\django\bin\django-admin.py", line 2, in &lt;module&gt; from django.core import management ImportError: No module named django.core </code></pre>
62
2008-11-23T14:09:24Z
2,923,096
<p>If your path variables are correct and from the python shell you can do: from django.core import management , make sure you're including "python" before "django-admin.py" as such: python django-admin.py startproject thelittlethings </p>
1
2010-05-27T16:49:34Z
[ "python", "django" ]
No Module named django.core
312,549
<p>I have updated to latest Django version 1.0.2 after uninstalling my old Django version.But now when I run django-admin.py I get the following error. How can I resolve this?</p> <pre><code>Traceback (most recent call last): File "C:\Python25\Lib\site-packages\django\bin\django-admin.py", line 2, in &lt;module&gt; from django.core import management ImportError: No module named django.core </code></pre>
62
2008-11-23T14:09:24Z
3,720,366
<p>Thanks for posting the question and answers. I have two versions of Python installed, but root was pointing to the /usr/bin version, and I wanted to use the 2.7 version of Python in /usr/local/bin. After rebuilding/reinstalling Django and mysqldb, all is well and I'm not getting the error.</p>
0
2010-09-15T17:59:01Z
[ "python", "django" ]
No Module named django.core
312,549
<p>I have updated to latest Django version 1.0.2 after uninstalling my old Django version.But now when I run django-admin.py I get the following error. How can I resolve this?</p> <pre><code>Traceback (most recent call last): File "C:\Python25\Lib\site-packages\django\bin\django-admin.py", line 2, in &lt;module&gt; from django.core import management ImportError: No module named django.core </code></pre>
62
2008-11-23T14:09:24Z
4,573,897
<p>Small quick fix is just to create symlink <code>ln -s $SOMEWHERE/lib/python2.6/site-packages/django/ ./django</code></p>
0
2011-01-01T11:24:35Z
[ "python", "django" ]
No Module named django.core
312,549
<p>I have updated to latest Django version 1.0.2 after uninstalling my old Django version.But now when I run django-admin.py I get the following error. How can I resolve this?</p> <pre><code>Traceback (most recent call last): File "C:\Python25\Lib\site-packages\django\bin\django-admin.py", line 2, in &lt;module&gt; from django.core import management ImportError: No module named django.core </code></pre>
62
2008-11-23T14:09:24Z
4,721,682
<p>I had the same problem, it was clear that I had a <code>PYTHONPATH</code> configuration issue. The solution is quite simple, just create a file with this name <code>django.pth</code> in your <code>PYTHONHOME\Lib\site-packages</code> directory where <code>PYTHONHOME</code> is the directory where Python is installed (mine is: C:\Python27). Add the following line to the <code>django.pth</code> file:</p> <pre><code>PYTHONHOME\Lib\site-packages\django </code></pre> <p>Of course you have to change <code>PYTHONHOME</code> to your Python's installation directory as I explained.</p> <p>Note that you can edit the <code>django.pth</code> to include any directory that you want to be included in the <code>PYTHONPATH</code>. Actually, you can name that file as you wish, <code>path.pth</code> for example if you want it to be more general and to include several directory paths.</p>
0
2011-01-18T07:54:57Z
[ "python", "django" ]
No Module named django.core
312,549
<p>I have updated to latest Django version 1.0.2 after uninstalling my old Django version.But now when I run django-admin.py I get the following error. How can I resolve this?</p> <pre><code>Traceback (most recent call last): File "C:\Python25\Lib\site-packages\django\bin\django-admin.py", line 2, in &lt;module&gt; from django.core import management ImportError: No module named django.core </code></pre>
62
2008-11-23T14:09:24Z
5,151,255
<p>I had the same problem in windows xp. The reason was i installed multiple python versions(2.6,3.2).windows's PATH is set correctly to python26, but the .py file is associated with python32. I want the .py file is associated with python26.To solve it, the easit way is to right click the *.py(such as django-admin.py),choose "open with"->"choose program..."->"Browse..." (select c:\python26\python.ext)->"Ok". Then we can run django-admin.py in the cmd without the need for the expatiatory prefix "c:\python26\lib\site-packages\django\bin".</p>
2
2011-03-01T06:31:43Z
[ "python", "django" ]
No Module named django.core
312,549
<p>I have updated to latest Django version 1.0.2 after uninstalling my old Django version.But now when I run django-admin.py I get the following error. How can I resolve this?</p> <pre><code>Traceback (most recent call last): File "C:\Python25\Lib\site-packages\django\bin\django-admin.py", line 2, in &lt;module&gt; from django.core import management ImportError: No module named django.core </code></pre>
62
2008-11-23T14:09:24Z
5,257,054
<p>The simplest solution though not the most elegant is to copy the django-admin.py from the Scripts folder. The Scripts folder will be found under your Python installation . On my computer it is in C:\Python26\Scripts. Then paste the django-admin.py into the folder you are trying to run the file from. It is true that the use of the System path will give flexibility. This is a particular solution if you are in a hurry. Then type for instance python django-admin.py startproject fluffyteaspoons and you will create the project fluffyteaspoons</p>
1
2011-03-10T08:20:27Z
[ "python", "django" ]
No Module named django.core
312,549
<p>I have updated to latest Django version 1.0.2 after uninstalling my old Django version.But now when I run django-admin.py I get the following error. How can I resolve this?</p> <pre><code>Traceback (most recent call last): File "C:\Python25\Lib\site-packages\django\bin\django-admin.py", line 2, in &lt;module&gt; from django.core import management ImportError: No module named django.core </code></pre>
62
2008-11-23T14:09:24Z
8,186,132
<p>It was a PYTHONPATH environment variable issue for me, as others mentioned above, but noone has really shown how to set it for people that could use the extra instruction.</p> <p><strong>Linux (bash)</strong></p> <p>I set this variable in my bashrc file in my home folder (.bashrc is the file for me since my shell is /bin/bash).</p> <pre><code>vim ~/.bashrc export PYTHONPATH=/usr/local/python-2.7.2/lib/python2.7/site-packages:$PYTHONPATH source ~/.bashrc </code></pre> <p>The path should be wherever your django source is. Mine is located at /usr/local/python-2.7.2/lib/python2.7/site-packages/django, so I just specified /usr/local/python-2.7.2/lib/python2.7/site-packages without the django portion.</p> <p><strong>OSX</strong></p> <p>On OSX the path is <code>/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages</code> and you can add it to <code>/etc/profile</code>:</p> <pre><code>sudo echo "PYTHONPATH=/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages:$PYTHONPATH" &gt;&gt; /etc/profile source /etc/profile </code></pre>
9
2011-11-18T17:07:18Z
[ "python", "django" ]
No Module named django.core
312,549
<p>I have updated to latest Django version 1.0.2 after uninstalling my old Django version.But now when I run django-admin.py I get the following error. How can I resolve this?</p> <pre><code>Traceback (most recent call last): File "C:\Python25\Lib\site-packages\django\bin\django-admin.py", line 2, in &lt;module&gt; from django.core import management ImportError: No module named django.core </code></pre>
62
2008-11-23T14:09:24Z
8,528,185
<p>In my case, I'm on OS X Lion and I've installed Python with <a href="http://mxcl.github.com/homebrew/" rel="nofollow">homebrew</a> I was getting the same error, but none of the solutions posted here helped me. In my case I just had to edit the script:</p> <pre><code>vim /usr/local/share/python/django-admin.py </code></pre> <p>And I noticed that the first line was wrong, as it was pointing to the system's python installation:</p> <pre><code>#!/usr/bin/python </code></pre> <p>I just modified it to point to homebrew's installation:</p> <pre><code>#!/usr/local/bin/python </code></pre> <p>And it worked :)</p>
1
2011-12-15T23:47:01Z
[ "python", "django" ]
No Module named django.core
312,549
<p>I have updated to latest Django version 1.0.2 after uninstalling my old Django version.But now when I run django-admin.py I get the following error. How can I resolve this?</p> <pre><code>Traceback (most recent call last): File "C:\Python25\Lib\site-packages\django\bin\django-admin.py", line 2, in &lt;module&gt; from django.core import management ImportError: No module named django.core </code></pre>
62
2008-11-23T14:09:24Z
9,840,898
<p>I know that this is an old question, but I just had the same problem, in my case, it was because the I am using virtualenv with django, but .py file extensions in Windows are associated with the main Python installation, so running the django-admin.py are directly from the command prompt causes it run with the main Python installation without django installed.</p> <p>So, since i dont know if there is any hash pound equivalent in Windows, I worked around this by running python followed by the full path of the django-admin.py, or you can also modify the virtualenv batch script to change the file associations and change it back when you deactivate it (although I am not sure how to do it, as I am not really familiar with batch script).</p> <p>Hope this helps,</p>
1
2012-03-23T14:24:32Z
[ "python", "django" ]
No Module named django.core
312,549
<p>I have updated to latest Django version 1.0.2 after uninstalling my old Django version.But now when I run django-admin.py I get the following error. How can I resolve this?</p> <pre><code>Traceback (most recent call last): File "C:\Python25\Lib\site-packages\django\bin\django-admin.py", line 2, in &lt;module&gt; from django.core import management ImportError: No module named django.core </code></pre>
62
2008-11-23T14:09:24Z
10,070,104
<p>I have the same problem on Windows and it seems I've found the problem. I have both 2.7 and 3.x installed. It seems it has something to do with the associate program of .py:</p> <p>In commandline type: </p> <blockquote> <p>assoc .py</p> </blockquote> <p>and the result is:</p> <p>.py=Python.File</p> <p>which means .py is associated with Python.File</p> <p>then I tried this:</p> <blockquote> <p>ftype Python.File</p> </blockquote> <p>I got:</p> <p>Python.File="C:\Python32\python.exe" "%1" %*</p> <p>which means in commandline .py is associated with my Python 3.2 installation -- and that's why I can't just type "django-admin.py blah blah" to use django.</p> <p>ALL you need to do is change the association:</p> <blockquote> <p>ftype Python.File="C:\Python27\python.exe" "%1" %*</p> </blockquote> <p>then everythong's okay!</p>
39
2012-04-09T07:13:06Z
[ "python", "django" ]
No Module named django.core
312,549
<p>I have updated to latest Django version 1.0.2 after uninstalling my old Django version.But now when I run django-admin.py I get the following error. How can I resolve this?</p> <pre><code>Traceback (most recent call last): File "C:\Python25\Lib\site-packages\django\bin\django-admin.py", line 2, in &lt;module&gt; from django.core import management ImportError: No module named django.core </code></pre>
62
2008-11-23T14:09:24Z
10,311,785
<p>Well.. I do something radical. I unistall python and I delete from Environment <code>Variables/PATH this: ;C:\Python26\Scripts;C:\Python26.</code> And Its work... I had your problem before.</p>
0
2012-04-25T08:11:12Z
[ "python", "django" ]
No Module named django.core
312,549
<p>I have updated to latest Django version 1.0.2 after uninstalling my old Django version.But now when I run django-admin.py I get the following error. How can I resolve this?</p> <pre><code>Traceback (most recent call last): File "C:\Python25\Lib\site-packages\django\bin\django-admin.py", line 2, in &lt;module&gt; from django.core import management ImportError: No module named django.core </code></pre>
62
2008-11-23T14:09:24Z
12,572,784
<p>This worked on Mac OS X</p> <p>In the terminal run python In python: import sys print sys.path</p> <p>Look for the site packages path. I found this in the output of sys.path: '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages'</p> <p>exit python. Find where your current site-packages are. Mine were at /Library/Python/2.6/site-packages </p> <p>Now be careful: Check the content of site-packages to be sure it is empty. That is, directory /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages should be empty, or just contain a readme file. If it is, delete that directory, because you are now about to make a symlink.</p> <p>ln -s /Library/Python/2.6/site-packages /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages</p> <p>If you don't delete the folder you will put the symlink in the folder. </p> <p>Other options are to add the path to the sys.path. I elected the symlink route because I have a couple of versions of python, I don't want several versions of Django, and just wanted to point to the known working copy.</p>
1
2012-09-24T20:56:05Z
[ "python", "django" ]
No Module named django.core
312,549
<p>I have updated to latest Django version 1.0.2 after uninstalling my old Django version.But now when I run django-admin.py I get the following error. How can I resolve this?</p> <pre><code>Traceback (most recent call last): File "C:\Python25\Lib\site-packages\django\bin\django-admin.py", line 2, in &lt;module&gt; from django.core import management ImportError: No module named django.core </code></pre>
62
2008-11-23T14:09:24Z
12,716,409
<p>I had the same problem and recalled that I had installed iPython the previous afternoon. I uninstalled iPython and the problem went away. Incidentally, I am working with virtualenv. I had installed iPython in the system-wide site-packages directory, so I just re-installed iPython inside each virtualenv that I am using. After installing iPython yesterday I had noticed a warning message (from version 0.13 of iPython) that it had detected that I was using virtualenv and that if I ran into any trouble I should install iPyton inside each virtualenv.</p>
2
2012-10-03T20:30:54Z
[ "python", "django" ]
No Module named django.core
312,549
<p>I have updated to latest Django version 1.0.2 after uninstalling my old Django version.But now when I run django-admin.py I get the following error. How can I resolve this?</p> <pre><code>Traceback (most recent call last): File "C:\Python25\Lib\site-packages\django\bin\django-admin.py", line 2, in &lt;module&gt; from django.core import management ImportError: No module named django.core </code></pre>
62
2008-11-23T14:09:24Z
14,547,802
<p>I just got the same ImportError in Windows Vista having Python 2.7 and 3.2 installed and using virualenv with Python 2.7 and Django 1.4.3.</p> <p>I changed the file association of .py files in Explorer from 3.2 to 2.7. Rightclicking a .py file and changing settings. I still got the ImportError.</p> <p>I ran <code>cmd.exe</code> as an administrator and copypasted the earlier <code>ftype</code> stuff. After an error, noted that double quotes don't get copied correctly from browser to cmd. Rewrote the command in cmd, but I still got the ImportError.</p> <p>In root of the actived virtual environment, I explicitly gave the <code>python</code> command and the path to django-admin.py from there. <code>(env_p27) C:\Users\Gemmu\env_p27&gt;python .\Scripts\django-admin.py startproject mysite</code></p> <p>That worked.</p> <p>Thanks for all the help for everyone.</p>
0
2013-01-27T13:22:58Z
[ "python", "django" ]
No Module named django.core
312,549
<p>I have updated to latest Django version 1.0.2 after uninstalling my old Django version.But now when I run django-admin.py I get the following error. How can I resolve this?</p> <pre><code>Traceback (most recent call last): File "C:\Python25\Lib\site-packages\django\bin\django-admin.py", line 2, in &lt;module&gt; from django.core import management ImportError: No module named django.core </code></pre>
62
2008-11-23T14:09:24Z
15,173,302
<p>If you are using Windows, then Don't run with 'django-admin.py', since this will call your outer python.exe to execute and it cannot read into the django inside the virtual environemnt. Try 'python django-admin.py' to use your python.exe inside your environment. </p>
6
2013-03-02T10:16:13Z
[ "python", "django" ]
No Module named django.core
312,549
<p>I have updated to latest Django version 1.0.2 after uninstalling my old Django version.But now when I run django-admin.py I get the following error. How can I resolve this?</p> <pre><code>Traceback (most recent call last): File "C:\Python25\Lib\site-packages\django\bin\django-admin.py", line 2, in &lt;module&gt; from django.core import management ImportError: No module named django.core </code></pre>
62
2008-11-23T14:09:24Z
17,991,527
<p>This happened to me because I ran <code>pip</code> as <code>sudo</code> while my virtualenv is setup to not import outside site packages so Django was installed for the root user but not in the virtualenv, even though I had virtualenv activated when I ran sudo.</p> <p>Solution switch to root, activate venv then do pip install.</p>
1
2013-08-01T10:29:30Z
[ "python", "django" ]
No Module named django.core
312,549
<p>I have updated to latest Django version 1.0.2 after uninstalling my old Django version.But now when I run django-admin.py I get the following error. How can I resolve this?</p> <pre><code>Traceback (most recent call last): File "C:\Python25\Lib\site-packages\django\bin\django-admin.py", line 2, in &lt;module&gt; from django.core import management ImportError: No module named django.core </code></pre>
62
2008-11-23T14:09:24Z
20,797,090
<p>I realized this happen because I didn't run <code>python setup.py install</code>. That setup the environment.</p>
0
2013-12-27T08:01:43Z
[ "python", "django" ]
No Module named django.core
312,549
<p>I have updated to latest Django version 1.0.2 after uninstalling my old Django version.But now when I run django-admin.py I get the following error. How can I resolve this?</p> <pre><code>Traceback (most recent call last): File "C:\Python25\Lib\site-packages\django\bin\django-admin.py", line 2, in &lt;module&gt; from django.core import management ImportError: No module named django.core </code></pre>
62
2008-11-23T14:09:24Z
32,341,585
<p>To tack on to what <a href="http://stackoverflow.com/users/1376351/lichenbo">lichenbo</a> said... If you are using Windows, then Don't run with 'django-admin.py'...</p> <p>I'm running inside a virtual environment, so the path and command to create a new project looks like: </p> <pre><code>(DjangoEnv) C:\users\timreilly\Envs\django\Scripts\django-admin.exe startproject myproject </code></pre> <p>DjangoEnv is the name of my virtual environment.</p>
0
2015-09-01T22:02:24Z
[ "python", "django" ]
No Module named django.core
312,549
<p>I have updated to latest Django version 1.0.2 after uninstalling my old Django version.But now when I run django-admin.py I get the following error. How can I resolve this?</p> <pre><code>Traceback (most recent call last): File "C:\Python25\Lib\site-packages\django\bin\django-admin.py", line 2, in &lt;module&gt; from django.core import management ImportError: No module named django.core </code></pre>
62
2008-11-23T14:09:24Z
35,263,660
<p>After reading a lot I found a solution that works for me.</p> <p>I have</p> <pre><code> django version 1.9.2 </code></pre> <ol> <li><p>Set all system variable in "path".No duplicate copy in user variable nor in the PYTHONPATH . <a href="http://i.stack.imgur.com/pygwL.png" rel="nofollow"><img src="http://i.stack.imgur.com/pygwL.png" alt="enter image description here"></a></p></li> <li><p>Then set Value in regedit</p></li> </ol> <p><a href="http://i.stack.imgur.com/HtlWl.png" rel="nofollow"><img src="http://i.stack.imgur.com/HtlWl.png" alt="enter image description here"></a></p> <ol start="3"> <li><p>made a virtualenv in desired folder by command</p> <p>virtualenv VENV</p></li> <li><p>And finally in cmd </p></li> </ol> <p><strong><em>used command</em></strong></p> <pre><code>django-admin.py startproject MySite ***and not this*** python django-admin.py startproject MySite </code></pre> <p>at the root folder of the "VENV"</p> <p>And It worked</p>
0
2016-02-08T06:35:41Z
[ "python", "django" ]
Debugging pylons in Eclipse under Ubuntu
312,599
<p>I am trying to get pylons to debug in Eclipse under Ubuntu. Specifically. I am not sure what to use for the 'Main Module' on the Run configurations dialog.</p> <p>(<a href="http://stackoverflow.com/questions/147650/debug-pylons-application-through-eclipse">this</a> is a similar question on stackoverflow, but I think it applies to windows as I can't find paster-script.py on my system)</p> <p>Can anyone help?</p>
1
2008-11-23T15:05:37Z
314,913
<p>I've managed to fix this now.</p> <p>In <code>Window&gt;Preferences&gt;Pydev&gt;Interpreter-Python</code> remove the python interpreter and reload it (select <code>New</code>) after installing pylons.</p> <p>In the Terminal cd into the projects directory. Then type <code>sudo python setup.py develop</code> Not sure what this does, but it does the trick (if any one wants to fill me in, please do)</p> <p>In <code>Run&gt;Open Debug Dialog</code> enter the location of paster in <code>Main Module</code>. For me this is <code>/usr/bin/paster</code> . Then in the <code>Arguments</code> tab in <code>Program arguments</code> enter <code>serve /locationOfYourProject/development.ini</code></p> <p>All set to go. It took a lot of search for me to find out that it does not work if the arguments includes <code>--reload</code></p>
4
2008-11-24T17:59:18Z
[ "python", "eclipse", "debugging", "ubuntu", "pylons" ]
Debugging pylons in Eclipse under Ubuntu
312,599
<p>I am trying to get pylons to debug in Eclipse under Ubuntu. Specifically. I am not sure what to use for the 'Main Module' on the Run configurations dialog.</p> <p>(<a href="http://stackoverflow.com/questions/147650/debug-pylons-application-through-eclipse">this</a> is a similar question on stackoverflow, but I think it applies to windows as I can't find paster-script.py on my system)</p> <p>Can anyone help?</p>
1
2008-11-23T15:05:37Z
371,006
<p>I got it running basically almost the same way - although you do not have to do the setup.py develop step - it works fine without that. </p> <p>What it does is that is sets global link to your project directory for a python package named after your project name.</p>
1
2008-12-16T11:09:15Z
[ "python", "eclipse", "debugging", "ubuntu", "pylons" ]
Debugging pylons in Eclipse under Ubuntu
312,599
<p>I am trying to get pylons to debug in Eclipse under Ubuntu. Specifically. I am not sure what to use for the 'Main Module' on the Run configurations dialog.</p> <p>(<a href="http://stackoverflow.com/questions/147650/debug-pylons-application-through-eclipse">this</a> is a similar question on stackoverflow, but I think it applies to windows as I can't find paster-script.py on my system)</p> <p>Can anyone help?</p>
1
2008-11-23T15:05:37Z
435,204
<p>I do need this step "sudo python setup.py develop" to get it running.. otherwise it throw out some exceptions.</p> <p>btw, the setup.py is the one in your created project.</p>
1
2009-01-12T11:48:15Z
[ "python", "eclipse", "debugging", "ubuntu", "pylons" ]
Debugging pylons in Eclipse under Ubuntu
312,599
<p>I am trying to get pylons to debug in Eclipse under Ubuntu. Specifically. I am not sure what to use for the 'Main Module' on the Run configurations dialog.</p> <p>(<a href="http://stackoverflow.com/questions/147650/debug-pylons-application-through-eclipse">this</a> is a similar question on stackoverflow, but I think it applies to windows as I can't find paster-script.py on my system)</p> <p>Can anyone help?</p>
1
2008-11-23T15:05:37Z
439,418
<p>Haven't tried on Eclipse, but I bet the solution I have been using to debug Pylons apps in WingIDE will work here too.</p> <ol> <li><p>Write the following two-liner (name it run_me.py or similarly) and save it in your project directory:</p> <p>from paste.script.serve import ServeCommand</p> <p>ServeCommand("serve").run(["development.ini"])</p></li> <li><p>Set this file as main debug target (aka main module)</p></li> <li><p>Enjoy.</p></li> </ol>
0
2009-01-13T15:39:03Z
[ "python", "eclipse", "debugging", "ubuntu", "pylons" ]
Python, optparse and file mask
312,673
<pre><code>if __name__=='__main__': parser = OptionParser() parser.add_option("-i", "--input_file", dest="input_filename", help="Read input from FILE", metavar="FILE") (options, args) = parser.parse_args() print options </code></pre> <p>result is</p> <pre><code>$ python convert.py -i video_* {'input_filename': 'video_1.wmv'} </code></pre> <p>there are video_[1-6].wmv in the current folder. Question is why video_* become video_1.wmv. What i'm doing wrong?</p>
3
2008-11-23T16:12:42Z
312,677
<p>Python has nothing to do with this -- it's the shell.</p> <p>Call</p> <pre><code>$ python convert.py -i 'video_*' </code></pre> <p>and it will pass in that wildcard.</p> <p>The other six values were passed in as args, not attached to the <code>-i</code>, exactly as if you'd run <code>python convert.py -i video_1 video_2 video_3 video_4 video_5 video_6</code>, and the <code>-i</code> only attaches to the immediate next parameter.</p> <p>That said, your best bet might to be just read your input filenames from <code>args</code>, rather than using <code>options.input</code>.</p>
8
2008-11-23T16:20:25Z
[ "python", "optparse" ]
Python, optparse and file mask
312,673
<pre><code>if __name__=='__main__': parser = OptionParser() parser.add_option("-i", "--input_file", dest="input_filename", help="Read input from FILE", metavar="FILE") (options, args) = parser.parse_args() print options </code></pre> <p>result is</p> <pre><code>$ python convert.py -i video_* {'input_filename': 'video_1.wmv'} </code></pre> <p>there are video_[1-6].wmv in the current folder. Question is why video_* become video_1.wmv. What i'm doing wrong?</p>
3
2008-11-23T16:12:42Z
312,678
<p>Print out args and you'll see where the other files are going...</p> <p>They are being converted to separate arguments in argv, and optparse only takes the first one as the value for the input_filename option.</p>
2
2008-11-23T16:20:51Z
[ "python", "optparse" ]
Python, optparse and file mask
312,673
<pre><code>if __name__=='__main__': parser = OptionParser() parser.add_option("-i", "--input_file", dest="input_filename", help="Read input from FILE", metavar="FILE") (options, args) = parser.parse_args() print options </code></pre> <p>result is</p> <pre><code>$ python convert.py -i video_* {'input_filename': 'video_1.wmv'} </code></pre> <p>there are video_[1-6].wmv in the current folder. Question is why video_* become video_1.wmv. What i'm doing wrong?</p>
3
2008-11-23T16:12:42Z
312,816
<p>It isn't obvious, even if you read some of the standards (like <a href="http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap12.html" rel="nofollow">this</a> or <a href="http://www.faqs.org/docs/artu/ch10s05.html" rel="nofollow">this</a>).</p> <p>The <em>args</em> part of a command line are -- almost universally -- the input files.</p> <p>There are only very rare odd-ball cases where an input file is specified as an option. It does happen, but it's very rare.</p> <p>Also, the output files are never named as <em>args</em>. They almost always are provided as named options. </p> <p>The idea is that</p> <ol> <li><p>Most programs can (and should) read from stdin. The command-line argument of <code>-</code> is a code for "stdin". If no arguments are given, stdin is the fallback plan.</p></li> <li><p>If your program opens any files, it may as well open an unlimited number of files specified on the command line. The shell facilitates this by expanding wild-cards for you. [Windows doesn't do this for you, however.]</p></li> <li><p>You program should never overwrite a file without an explicit command-line options, like '-o somefile' to write to a file. </p></li> </ol> <p>Note that <code>cp</code>, <code>mv</code>, <code>rm</code> are the big examples of programs that don't follow these standards.</p>
0
2008-11-23T18:54:25Z
[ "python", "optparse" ]
Python, optparse and file mask
312,673
<pre><code>if __name__=='__main__': parser = OptionParser() parser.add_option("-i", "--input_file", dest="input_filename", help="Read input from FILE", metavar="FILE") (options, args) = parser.parse_args() print options </code></pre> <p>result is</p> <pre><code>$ python convert.py -i video_* {'input_filename': 'video_1.wmv'} </code></pre> <p>there are video_[1-6].wmv in the current folder. Question is why video_* become video_1.wmv. What i'm doing wrong?</p>
3
2008-11-23T16:12:42Z
312,903
<p>To clarify:</p> <pre><code>aprogram -e *.wmv </code></pre> <p>on a Linux shell, all wildcards (*.wmv) are expanded by the shell. So <code>aprogram</code> actually recieves the arguments:</p> <pre><code>sys.argv == ['aprogram', '-e', '1.wmv', '2.wmv', '3.wmv'] </code></pre> <p>Like <a href="http://stackoverflow.com/questions/312673/python-optparse-and-file-mask#312677">Charles</a> said, you can quote the argument to get it to pass in literally:</p> <pre><code>aprogram -e "*.wmv" </code></pre> <p>This will pass in:</p> <pre><code>sys.argv == ['aprogram', '-e', '*.wmv'] </code></pre>
0
2008-11-23T20:22:25Z
[ "python", "optparse" ]
Python: Problem with overloaded constructors
312,695
<p>WARNING: I have been learning Python for all of 10 minutes so apologies for any stupid questions!</p> <p>I have written the following code, however I get the following exception: </p> <blockquote> <p>Message File Name Line Position Traceback Node 31 exceptions.TypeError: this constructor takes no arguments</p> </blockquote> <pre><code>class Computer: name = "Computer1" ip = "0.0.0.0" screenSize = 17 def Computer(compName, compIp, compScreenSize): name = compName ip = compIp screenSize = compScreenSize printStats() return def Computer(): printStats() return def printStats(): print "Computer Statistics: --------------------------------" print "Name:" + name print "IP:" + ip print "ScreenSize:" , screenSize // cannot concatenate 'str' and 'tuple' objects print "-----------------------------------------------------" return comp1 = Computer() comp2 = Computer("The best computer in the world", "27.1.0.128",22) </code></pre> <p>Any thoughts?</p>
7
2008-11-23T16:41:56Z
312,698
<p>Constructors in Python are called <code>__init__</code>. You must also use "self" as the first argument for all methods in your class, and use that to set instance variables in the class.</p> <pre><code>class Computer: def __init__(self, compName = "Computer1", compIp = "0.0.0.0", compScreenSize = 22): self.name = compName self.ip = compIp self.screenSize = compScreenSize self.printStats() def printStats(self): print "Computer Statistics: --------------------------------" print "Name:", self.name print "IP:", self.ip print "ScreenSize:", self.screenSize print "-----------------------------------------------------" comp1 = Computer() comp2 = Computer("The best computer in the world", "27.1.0.128",22) </code></pre>
5
2008-11-23T16:44:22Z
[ "python", "exception", "constructor-overloading" ]
Python: Problem with overloaded constructors
312,695
<p>WARNING: I have been learning Python for all of 10 minutes so apologies for any stupid questions!</p> <p>I have written the following code, however I get the following exception: </p> <blockquote> <p>Message File Name Line Position Traceback Node 31 exceptions.TypeError: this constructor takes no arguments</p> </blockquote> <pre><code>class Computer: name = "Computer1" ip = "0.0.0.0" screenSize = 17 def Computer(compName, compIp, compScreenSize): name = compName ip = compIp screenSize = compScreenSize printStats() return def Computer(): printStats() return def printStats(): print "Computer Statistics: --------------------------------" print "Name:" + name print "IP:" + ip print "ScreenSize:" , screenSize // cannot concatenate 'str' and 'tuple' objects print "-----------------------------------------------------" return comp1 = Computer() comp2 = Computer("The best computer in the world", "27.1.0.128",22) </code></pre> <p>Any thoughts?</p>
7
2008-11-23T16:41:56Z
312,699
<p>That isn't valid python.</p> <p>The constructor for a Python class is <code>def __init__(self, ...):</code> and you cannot overload it.</p> <p>What you can do is use defaults for the arguments, eg.</p> <pre><code>class Computer: def __init__(self, compName="Computer1", compIp="0.0.0.0", compScreenSize=17): self.name = compName self.ip = compIp self.screenSize = compScreenSize self.printStats() return def printStats(self): print "Computer Statistics: --------------------------------" print "Name : %s" % self.name print "IP : %s" % self.ip print "ScreenSize: %s" % self.screenSize print "-----------------------------------------------------" return comp1 = Computer() comp2 = Computer("The best computer in the world", "27.1.0.128",22) </code></pre>
1
2008-11-23T16:46:02Z
[ "python", "exception", "constructor-overloading" ]
Python: Problem with overloaded constructors
312,695
<p>WARNING: I have been learning Python for all of 10 minutes so apologies for any stupid questions!</p> <p>I have written the following code, however I get the following exception: </p> <blockquote> <p>Message File Name Line Position Traceback Node 31 exceptions.TypeError: this constructor takes no arguments</p> </blockquote> <pre><code>class Computer: name = "Computer1" ip = "0.0.0.0" screenSize = 17 def Computer(compName, compIp, compScreenSize): name = compName ip = compIp screenSize = compScreenSize printStats() return def Computer(): printStats() return def printStats(): print "Computer Statistics: --------------------------------" print "Name:" + name print "IP:" + ip print "ScreenSize:" , screenSize // cannot concatenate 'str' and 'tuple' objects print "-----------------------------------------------------" return comp1 = Computer() comp2 = Computer("The best computer in the world", "27.1.0.128",22) </code></pre> <p>Any thoughts?</p>
7
2008-11-23T16:41:56Z
312,701
<p>For a start, look <a href="http://docs.python.org/tutorial/classes.html#class-objects" rel="nofollow">here</a>.</p>
2
2008-11-23T16:46:08Z
[ "python", "exception", "constructor-overloading" ]
Python: Problem with overloaded constructors
312,695
<p>WARNING: I have been learning Python for all of 10 minutes so apologies for any stupid questions!</p> <p>I have written the following code, however I get the following exception: </p> <blockquote> <p>Message File Name Line Position Traceback Node 31 exceptions.TypeError: this constructor takes no arguments</p> </blockquote> <pre><code>class Computer: name = "Computer1" ip = "0.0.0.0" screenSize = 17 def Computer(compName, compIp, compScreenSize): name = compName ip = compIp screenSize = compScreenSize printStats() return def Computer(): printStats() return def printStats(): print "Computer Statistics: --------------------------------" print "Name:" + name print "IP:" + ip print "ScreenSize:" , screenSize // cannot concatenate 'str' and 'tuple' objects print "-----------------------------------------------------" return comp1 = Computer() comp2 = Computer("The best computer in the world", "27.1.0.128",22) </code></pre> <p>Any thoughts?</p>
7
2008-11-23T16:41:56Z
312,703
<p>There are a number of things to point out:</p> <ol> <li>All instance methods in Python have an explicit self argument.</li> <li>Constructors are called <code>__init__</code>.</li> <li>You cannot overload methods. You can achieve a similar effect by using default method arguments.</li> </ol> <p><strong>C++:</strong></p> <pre><code>class comp { std::string m_name; foo(std::string name); }; foo::foo(std::string name) : m_name(name) {} </code></pre> <p><strong>Python:</strong></p> <pre><code>class comp: def __init__(self, name=None): if name: self.name = name else: self.name = 'defaultName' </code></pre>
2
2008-11-23T16:48:45Z
[ "python", "exception", "constructor-overloading" ]
Python: Problem with overloaded constructors
312,695
<p>WARNING: I have been learning Python for all of 10 minutes so apologies for any stupid questions!</p> <p>I have written the following code, however I get the following exception: </p> <blockquote> <p>Message File Name Line Position Traceback Node 31 exceptions.TypeError: this constructor takes no arguments</p> </blockquote> <pre><code>class Computer: name = "Computer1" ip = "0.0.0.0" screenSize = 17 def Computer(compName, compIp, compScreenSize): name = compName ip = compIp screenSize = compScreenSize printStats() return def Computer(): printStats() return def printStats(): print "Computer Statistics: --------------------------------" print "Name:" + name print "IP:" + ip print "ScreenSize:" , screenSize // cannot concatenate 'str' and 'tuple' objects print "-----------------------------------------------------" return comp1 = Computer() comp2 = Computer("The best computer in the world", "27.1.0.128",22) </code></pre> <p>Any thoughts?</p>
7
2008-11-23T16:41:56Z
312,704
<p>Ah, these are common gotchas for new python developers.</p> <p>First, the constructor should be called: </p> <pre><code>__init__() </code></pre> <p>Your second issue is forgetting to include the self parameter to your class methods. </p> <p>Furthermore, when you define the second constructor, you're replacing the definition of the Computer() method. Python is extremely dynamic and will cheerfully let you redefine class methods.</p> <p>The more pythonic way is probably to use default values for the parameters if you don't want to make them required.</p>
1
2008-11-23T16:49:23Z
[ "python", "exception", "constructor-overloading" ]
Python: Problem with overloaded constructors
312,695
<p>WARNING: I have been learning Python for all of 10 minutes so apologies for any stupid questions!</p> <p>I have written the following code, however I get the following exception: </p> <blockquote> <p>Message File Name Line Position Traceback Node 31 exceptions.TypeError: this constructor takes no arguments</p> </blockquote> <pre><code>class Computer: name = "Computer1" ip = "0.0.0.0" screenSize = 17 def Computer(compName, compIp, compScreenSize): name = compName ip = compIp screenSize = compScreenSize printStats() return def Computer(): printStats() return def printStats(): print "Computer Statistics: --------------------------------" print "Name:" + name print "IP:" + ip print "ScreenSize:" , screenSize // cannot concatenate 'str' and 'tuple' objects print "-----------------------------------------------------" return comp1 = Computer() comp2 = Computer("The best computer in the world", "27.1.0.128",22) </code></pre> <p>Any thoughts?</p>
7
2008-11-23T16:41:56Z
312,727
<p>I'm going to assume you're coming from a Java-ish background, so there are a few key differences to point out.</p> <pre><code>class Computer(object): """Docstrings are used kind of like Javadoc to document classes and members. They are the first thing inside a class or method. You probably want to extend object, to make it a "new-style" class. There are reasons for this that are a bit complex to explain.""" # everything down here is a static variable, unlike in Java or C# where # declarations here are for what members a class has. All instance # variables in Python are dynamic, unless you specifically tell Python # otherwise. defaultName = "belinda" defaultRes = (1024, 768) defaultIP = "192.168.5.307" def __init__(self, name=defaultName, resolution=defaultRes, ip=defaultIP): """Constructors in Python are called __init__. Methods with names like __something__ often have special significance to the Python interpreter. The first argument to any class method is a reference to the current object, called "self" by convention. You can use default function arguments instead of function overloading.""" self.name = name self.resolution = resolution self.ip = ip # and so on def printStats(self): """You could instead use a __str__(self, ...) function to return this string. Then you could simply do "print(str(computer))" if you wanted to.""" print "Computer Statistics: --------------------------------" print "Name:" + self.name print "IP:" + self.ip print "ScreenSize:" , self.resolution //cannot concatenate 'str' and 'tuple' objects print "-----------------------------------------------------" </code></pre>
36
2008-11-23T17:09:12Z
[ "python", "exception", "constructor-overloading" ]
Python: Problem with overloaded constructors
312,695
<p>WARNING: I have been learning Python for all of 10 minutes so apologies for any stupid questions!</p> <p>I have written the following code, however I get the following exception: </p> <blockquote> <p>Message File Name Line Position Traceback Node 31 exceptions.TypeError: this constructor takes no arguments</p> </blockquote> <pre><code>class Computer: name = "Computer1" ip = "0.0.0.0" screenSize = 17 def Computer(compName, compIp, compScreenSize): name = compName ip = compIp screenSize = compScreenSize printStats() return def Computer(): printStats() return def printStats(): print "Computer Statistics: --------------------------------" print "Name:" + name print "IP:" + ip print "ScreenSize:" , screenSize // cannot concatenate 'str' and 'tuple' objects print "-----------------------------------------------------" return comp1 = Computer() comp2 = Computer("The best computer in the world", "27.1.0.128",22) </code></pre> <p>Any thoughts?</p>
7
2008-11-23T16:41:56Z
312,746
<p>dude get yourself a python book. Dive into Python is pretty good. </p>
4
2008-11-23T17:31:44Z
[ "python", "exception", "constructor-overloading" ]
Python: Problem with overloaded constructors
312,695
<p>WARNING: I have been learning Python for all of 10 minutes so apologies for any stupid questions!</p> <p>I have written the following code, however I get the following exception: </p> <blockquote> <p>Message File Name Line Position Traceback Node 31 exceptions.TypeError: this constructor takes no arguments</p> </blockquote> <pre><code>class Computer: name = "Computer1" ip = "0.0.0.0" screenSize = 17 def Computer(compName, compIp, compScreenSize): name = compName ip = compIp screenSize = compScreenSize printStats() return def Computer(): printStats() return def printStats(): print "Computer Statistics: --------------------------------" print "Name:" + name print "IP:" + ip print "ScreenSize:" , screenSize // cannot concatenate 'str' and 'tuple' objects print "-----------------------------------------------------" return comp1 = Computer() comp2 = Computer("The best computer in the world", "27.1.0.128",22) </code></pre> <p>Any thoughts?</p>
7
2008-11-23T16:41:56Z
439,595
<p>Python does not support function overloading.</p>
1
2009-01-13T16:11:29Z
[ "python", "exception", "constructor-overloading" ]
Python equivalent of continuations with Ruby
312,794
<p>What is the Python equivalent of the following code in Ruby?</p> <pre><code>def loop cont=nil for i in 1..4 puts i callcc {|continuation| cont=continuation} if i==2 end return cont end &gt; c=loop 1 2 3 4 &gt; c.call 3 4 </code></pre> <p>Reference: <a href="http://www-128.ibm.com/developerworks/java/library/os-lightweight9/" rel="nofollow">Secrets of lightweight development success, Part 9: Continuations-based frameworks</a></p>
7
2008-11-23T18:25:01Z
312,801
<p>take a look at the <a href="http://www.python.org/doc/2.6/reference/simple_stmts.html#the-yield-statement" rel="nofollow">yield</a> statement to make generators.</p> <p>I don't speak any ruby, but it seems like you're looking for this:</p> <pre><code>def loop(): for i in xrange(1,5): print i if i == 2: yield for i in loop(): print "pass" </code></pre> <p>Edit: I realize this is basically a specialization of real continuations, but it should be sufficient for most purposes. Use <code>yield</code> to return the continuation and the <code>.next()</code> message on the generator (returned by just calling <code>loop()</code>) to reenter.</p>
2
2008-11-23T18:31:52Z
[ "python", "ruby", "continuations" ]
Python equivalent of continuations with Ruby
312,794
<p>What is the Python equivalent of the following code in Ruby?</p> <pre><code>def loop cont=nil for i in 1..4 puts i callcc {|continuation| cont=continuation} if i==2 end return cont end &gt; c=loop 1 2 3 4 &gt; c.call 3 4 </code></pre> <p>Reference: <a href="http://www-128.ibm.com/developerworks/java/library/os-lightweight9/" rel="nofollow">Secrets of lightweight development success, Part 9: Continuations-based frameworks</a></p>
7
2008-11-23T18:25:01Z
312,802
<p>The article you quoted contains a link to <a href="http://www.ps.uni-sb.de/~duchier/python/continuations.html">Continuations Made Simple And Illustrated</a> in the Resources section, which talks about continuations in the Python language.</p>
5
2008-11-23T18:33:09Z
[ "python", "ruby", "continuations" ]
Python equivalent of continuations with Ruby
312,794
<p>What is the Python equivalent of the following code in Ruby?</p> <pre><code>def loop cont=nil for i in 1..4 puts i callcc {|continuation| cont=continuation} if i==2 end return cont end &gt; c=loop 1 2 3 4 &gt; c.call 3 4 </code></pre> <p>Reference: <a href="http://www-128.ibm.com/developerworks/java/library/os-lightweight9/" rel="nofollow">Secrets of lightweight development success, Part 9: Continuations-based frameworks</a></p>
7
2008-11-23T18:25:01Z
312,941
<pre><code>def loop(): def f(i, cont=[None]): for i in range(i, 5): print i if i == 2: cont[0] = lambda i=i+1: f(i) return cont[0] return f(1) if __name__ == '__main__': c = loop() c() </code></pre>
0
2008-11-23T20:52:30Z
[ "python", "ruby", "continuations" ]
Python equivalent of continuations with Ruby
312,794
<p>What is the Python equivalent of the following code in Ruby?</p> <pre><code>def loop cont=nil for i in 1..4 puts i callcc {|continuation| cont=continuation} if i==2 end return cont end &gt; c=loop 1 2 3 4 &gt; c.call 3 4 </code></pre> <p>Reference: <a href="http://www-128.ibm.com/developerworks/java/library/os-lightweight9/" rel="nofollow">Secrets of lightweight development success, Part 9: Continuations-based frameworks</a></p>
7
2008-11-23T18:25:01Z
313,073
<p>Using <a href="http://www.fiber-space.de/generator_tools/doc/generator_tools.html#mozTocId557432" rel="nofollow"><code>generator_tools</code></a> (to install: '<code>$ easy_install generator_tools</code>'):</p> <pre><code>from generator_tools import copy_generator def _callg(generator, generator_copy=None): for _ in generator: # run to the end pass if generator_copy is not None: return lambda: _callg(copy_generator(generator_copy)) def loop(c): c.next() # advance to yield's expression return _callg(c, copy_generator(c)) if __name__ == '__main__': def loop_gen(): i = 1 while i &lt;= 4: print i if i == 2: yield i += 1 c = loop(loop_gen()) print("c:", c) for _ in range(2): print("c():", c()) </code></pre> <p>Output:</p> <pre><code>1 2 3 4 ('c:', &lt;function &lt;lambda&gt; at 0x00A9AC70&gt;) 3 4 ('c():', None) 3 4 ('c():', None) </code></pre>
2
2008-11-23T23:01:14Z
[ "python", "ruby", "continuations" ]
Python equivalent of continuations with Ruby
312,794
<p>What is the Python equivalent of the following code in Ruby?</p> <pre><code>def loop cont=nil for i in 1..4 puts i callcc {|continuation| cont=continuation} if i==2 end return cont end &gt; c=loop 1 2 3 4 &gt; c.call 3 4 </code></pre> <p>Reference: <a href="http://www-128.ibm.com/developerworks/java/library/os-lightweight9/" rel="nofollow">Secrets of lightweight development success, Part 9: Continuations-based frameworks</a></p>
7
2008-11-23T18:25:01Z
4,328,519
<p>There are many weak workarounds which work in special cases (see other answers to this question), but there is no Python language construct which is equivalent to <code>callcc</code> or which can be used to build something equivalent to <code>callcc</code>.</p> <p>You may want to try <a href="http://www.stackless.com/" rel="nofollow">Stackless Python</a> or the <a href="http://pypi.python.org/pypi/greenlet" rel="nofollow">greenlet</a> Python extension, both of which provide coroutines, based on which it is possible to build one-shot continutations, but that's still weaker than Ruby's <code>callcc</code> (which provides full continuations).</p>
2
2010-12-01T20:00:43Z
[ "python", "ruby", "continuations" ]
Django authentication and Ajax - URLs that require login
312,925
<p>I want to add some <a href="http://en.wikipedia.org/wiki/Ajax%5F%28programming%29">Ajax</a>-niceness to my Django-coded website. </p> <p>In my Django code, I use the <code>@login_required</code> decorator from <code>django.contrib.auth.decorators</code> to mark which view requires authentication. The default behavior when a not authenticated user clicks it is to redirect him/her to login page, and then pass the target page. </p> <p>What I saw on some sites, and really liked, is that when user clicks a link leading to a place restricted to logged-only users, instead of getting redirected to a login page, he/she gets a popup window (via JavaScript) asking him/her to log in or register. There's no redirection part, so no need for a user to use the "back" key if he/she decides he/she really doesn't like the website enough to waste the time registering.</p> <p>So, the qestion is: how would you manage the task of automatically marking some links as "restricted" so JavaScript can handle their <code>onclick</code> event and display a "please log in" popup? </p>
45
2008-11-23T20:35:16Z
313,015
<p>Sounds like a page template possibility.</p> <ol> <li><p>You could pass a <code>LINK_VIA</code> (or something) that you provide as <code>onClick="return popup(this, 'arg')"</code> or <code>None</code>. Each link would be <code>&lt;A HREF="link" {{LINK_VIA}}&gt;some text&lt;/a&gt;</code>.</p> <ul> <li>For anonymous sessions, <code>LINK_VIA</code> has a value.</li> <li>For logged in sessions, <code>LINK_VIA</code> is None</li> </ul></li> <li><p>You could use an <code>{% if %}</code> statement around your <code>&lt;A HREF=...&gt;</code> tags. This seems wordy.</p></li> <li><p>You could write your own custom tag with for <code>{% link_via %}</code>. I'm not familiar enough with this, but you can provide the link and text as strings and your tag can generate one of two kinds of links. </p></li> </ol>
5
2008-11-23T21:53:30Z
[ "javascript", "python", "django", "authentication" ]
Django authentication and Ajax - URLs that require login
312,925
<p>I want to add some <a href="http://en.wikipedia.org/wiki/Ajax%5F%28programming%29">Ajax</a>-niceness to my Django-coded website. </p> <p>In my Django code, I use the <code>@login_required</code> decorator from <code>django.contrib.auth.decorators</code> to mark which view requires authentication. The default behavior when a not authenticated user clicks it is to redirect him/her to login page, and then pass the target page. </p> <p>What I saw on some sites, and really liked, is that when user clicks a link leading to a place restricted to logged-only users, instead of getting redirected to a login page, he/she gets a popup window (via JavaScript) asking him/her to log in or register. There's no redirection part, so no need for a user to use the "back" key if he/she decides he/she really doesn't like the website enough to waste the time registering.</p> <p>So, the qestion is: how would you manage the task of automatically marking some links as "restricted" so JavaScript can handle their <code>onclick</code> event and display a "please log in" popup? </p>
45
2008-11-23T20:35:16Z
313,074
<p>I would agree with <a href="http://stackoverflow.com/questions/312925/django-authentication-and-ajax-urls-that-require-login#313015">S.Lott</a></p> <p>Make a check in the template, if the user is logged in, just put the link as usual, if not, put something like </p> <pre><code>&lt;a href="{{link}}" onclick="return login_popup()"&gt; </code></pre> <p>where login_popup would return false if the user says cancel.</p> <p>This could be probably be done much easier in <a href="http://jinja.pocoo.org/2/">Jinja2</a> through its <a href="http://jinja.pocoo.org/2/documentation/templates#macros">macros</a>.</p> <p>If the template doesn't know which urls require the user to login, you probably need to re-consider your design.</p> <p>If you must, I guess you can do the same thing that the django url dispatcher does to discover the view function. <br> see: <code>django.core.urlresolvers</code></p> <p>once you've grabbed the view function you can check if it's decorated with @login_required. </p> <p>This would be done in a custom tag probably. <br> If you use Jinja2, you won't need the tag, just implement the function and expose it to the Environment, it's simple but you'll have to do a bit of reading on the API of Jinja2)</p>
5
2008-11-23T23:02:44Z
[ "javascript", "python", "django", "authentication" ]
Django authentication and Ajax - URLs that require login
312,925
<p>I want to add some <a href="http://en.wikipedia.org/wiki/Ajax%5F%28programming%29">Ajax</a>-niceness to my Django-coded website. </p> <p>In my Django code, I use the <code>@login_required</code> decorator from <code>django.contrib.auth.decorators</code> to mark which view requires authentication. The default behavior when a not authenticated user clicks it is to redirect him/her to login page, and then pass the target page. </p> <p>What I saw on some sites, and really liked, is that when user clicks a link leading to a place restricted to logged-only users, instead of getting redirected to a login page, he/she gets a popup window (via JavaScript) asking him/her to log in or register. There's no redirection part, so no need for a user to use the "back" key if he/she decides he/she really doesn't like the website enough to waste the time registering.</p> <p>So, the qestion is: how would you manage the task of automatically marking some links as "restricted" so JavaScript can handle their <code>onclick</code> event and display a "please log in" popup? </p>
45
2008-11-23T20:35:16Z
523,196
<p>I am facing the same issue, and, like you, I would like a simple decorator to wrap around a Django ajax view in order to handle authentication in the same way that I have other views. One approach that seems promising to me is to use such a decorator in conjunction with JavaScript that looks for a certain value in the response.</p> <p>Here is <s>first</s> revised draft of the decorator:</p> <pre><code>from functools import wraps def ajax_login_required(view_func): @wraps(view_func) def wrapper(request, *args, **kwargs): if request.user.is_authenticated(): return view_func(request, *args, **kwargs) json = simplejson.dumps({ 'not_authenticated': True }) return HttpResponse(json, mimetype='application/json') return wrapper </code></pre> <p>Here is the view:</p> <pre><code>@ajax_login_required def ajax_update_module(request, module_slug, action): # Etc ... return HttpResponse(json, mimetype='application/json') </code></pre> <p>And here is the JavaScript (jQuery):</p> <pre><code>$.post('/restricted-url/', data, function(json) { if (json.not_authenticated) { alert('Not authorized.'); // Or something in a message DIV return; } // Etc ... }); </code></pre> <hr> <p><strong>EDIT</strong>: I've attempted to use <code>functools.wraps</code>, as suggested. I have not actually used this decorator in working code, so beware of possible bugs.</p>
50
2009-02-07T05:20:02Z
[ "javascript", "python", "django", "authentication" ]
Django authentication and Ajax - URLs that require login
312,925
<p>I want to add some <a href="http://en.wikipedia.org/wiki/Ajax%5F%28programming%29">Ajax</a>-niceness to my Django-coded website. </p> <p>In my Django code, I use the <code>@login_required</code> decorator from <code>django.contrib.auth.decorators</code> to mark which view requires authentication. The default behavior when a not authenticated user clicks it is to redirect him/her to login page, and then pass the target page. </p> <p>What I saw on some sites, and really liked, is that when user clicks a link leading to a place restricted to logged-only users, instead of getting redirected to a login page, he/she gets a popup window (via JavaScript) asking him/her to log in or register. There's no redirection part, so no need for a user to use the "back" key if he/she decides he/she really doesn't like the website enough to waste the time registering.</p> <p>So, the qestion is: how would you manage the task of automatically marking some links as "restricted" so JavaScript can handle their <code>onclick</code> event and display a "please log in" popup? </p>
45
2008-11-23T20:35:16Z
39,063,319
<p>Here is proposed version of the decorator with wrap.__doc__ , wrap.__name__</p> <pre><code>from functools import wraps def ajax_login_required(function): def wrap(request, *args, **kwargs): if request.user.is_authenticated(): return function(request, *args, **kwargs) json = simplejson.dumps({ 'not_authenticated': True }) return HttpResponse(json, mimetype='application/json') wrap.__doc__ = function.__doc__ wrap.__name__ = function.__name__ return wrap </code></pre>
1
2016-08-21T10:44:48Z
[ "javascript", "python", "django", "authentication" ]
Python as FastCGI under windows and apache
312,928
<p>I need to run a simple request/response python module under an existing system with windows/apache/FastCGI.</p> <p>All the FastCGI wrappers for python I tried work for Linux only (they use socket.fromfd() and other such shticks).</p> <p>Is there a wrapper that runs under windows?</p>
6
2008-11-23T20:39:15Z
312,930
<p>A <a href="http://code.djangoproject.com/ticket/8742" rel="nofollow">Django bug</a> suggests that <a href="http://pypi.python.org/pypi/python-fastcgi" rel="nofollow">python-fastcgi</a> will work for you, and its PyPI page reports that it works on Windows.</p>
1
2008-11-23T20:43:16Z
[ "python", "windows", "apache", "fastcgi" ]
Python as FastCGI under windows and apache
312,928
<p>I need to run a simple request/response python module under an existing system with windows/apache/FastCGI.</p> <p>All the FastCGI wrappers for python I tried work for Linux only (they use socket.fromfd() and other such shticks).</p> <p>Is there a wrapper that runs under windows?</p>
6
2008-11-23T20:39:15Z
312,994
<p>I'd suggest <a href="http://www.modpython.org/" rel="nofollow">mod_python</a> or <a href="http://code.google.com/p/modwsgi/" rel="nofollow">mod_wsgi</a>.</p>
0
2008-11-23T21:36:14Z
[ "python", "windows", "apache", "fastcgi" ]
Python as FastCGI under windows and apache
312,928
<p>I need to run a simple request/response python module under an existing system with windows/apache/FastCGI.</p> <p>All the FastCGI wrappers for python I tried work for Linux only (they use socket.fromfd() and other such shticks).</p> <p>Is there a wrapper that runs under windows?</p>
6
2008-11-23T20:39:15Z
318,517
<p>You might find it easier to ditch FastCGI altogether and just run a python webserver on a localhost port. Then just use mod_rewrite to map the apache urls to the internal webserver.</p> <p>(I started offering FastCGI at my hosting company and to my surprise, nearly everyone ditched it in favor of just running their own web server on the ports I provided them.)</p>
2
2008-11-25T19:08:44Z
[ "python", "windows", "apache", "fastcgi" ]
Django Admin Interface Does Not Use Subclass's __unicode__()
313,054
<p>(Django 1.x, Python 2.6.x)</p> <p>I have models to the tune of:</p> <pre><code>class Animal(models.Model): pass class Cat(Animal): def __unicode__(self): return "This is a cat" class Dog(Animal): def __unicode__(self): return "This is a dog" class AnimalHome(models.Model): animal = models.ForeignKey(Animal) </code></pre> <p>I have instantiated no Animals, because this is supposed to be a virtual class. I have instantiated Cats and Dogs, but in the Admin Page for AnimalHome, my choices for Animals are displayed as "Animal object" (the default __unicode__(), I guess) as opposed to the __unicode__ I have defined for the two subclasses. Help.</p> <p><hr /></p> <p>The abstract base class issue is a red herring wrt to this question, I think. Even if Animal was not supposed to be abstract, I still have the problem that, for some reason, since the ForeignKey is defined on Animal and not one of its subclasses, the superclass method is being called instead of the subclass. In OO programming when you call object.method() you're supposed to get the lowest-subclass's implementation, and you have to do extra work to get any superclass's implementation. So why is it that having __unicode__ defined on the subclasses is not sufficient for --- actually the problem might be that __unicode__ is not getting called at all because introspection on the Animal class reveals that it's not defined. So maybe if I define __unicode__ for Animal and have it call subclasses' __unicode__ I could get the desired effect.</p> <p><hr /></p> <p>Okay, I think that I understand the ORM issues. Both these answers have helped me understand this, thank you. While experimenting with this, I discovered that when Django saves a subclassed model, it does two things: (1) it creates a row for the subclassed object in the superclass's table, and (2) it makes the PK in the subclass table identical to the PK assigned in the superclass table. This PK in the subclass table is named superclass_ptr. Based upon this I've concocted the following. I'd appreciate feedback.</p> <pre><code>Class Animal(models.Model) def __unicode__(self): if Dog.objects.filter(pk=self.pk).count() &gt; 0: return unicode(Dog.objects.get(pk=self.pk)) elif Cat.objects.filter(pk=self.pk).count() &gt; 0: return unicode(Cat.objects.get(pk=self.pk)) else: return "An Animal!" </code></pre> <p><hr /></p> <p>It seems that Lawrence is most on-point wrt this question. Cat and Dog will have disjoint PK sets (and any subclass of Animal will have a PK identical to the record of its superclass), but unfortunately Django does not perform any work behind the scenes a la: "I'm an Animal. I know Animals have subclasses Dog and Cat. Specifically, I'm Animal number 3, and furthermore I just checked and there's a Cat number 3 too. That means that I'm actually Cat number 3". Even though this seems entirely possible and very reasonable (since a Cat won't do anything an Animal couldn't do itself) using Python's introspection. Thank you all.</p>
4
2008-11-23T22:44:57Z
313,102
<p>Django (and relational data bases in general) do not work this way. Even when using an ORM like Django's you don't work with class hierarchies like this.</p> <p>There are two possible solutions to your problem:</p> <p>(1) give a "name" attibute the the Animal model, then add entities with names from ['Dog', 'Cat']. This will show the animals' names in the foreign key selection box.</p> <p>(2) If you <strong>really need to</strong> link your foreign key to different models (which really is not the usual way to use an RDBMS) you should read about <a href="http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#id1" rel="nofollow">Generic Relations</a> in the docs on the contenttypes framework.</p> <p>My advice is (1), though.</p>
3
2008-11-23T23:22:06Z
[ "python", "django", "django-admin" ]
Django Admin Interface Does Not Use Subclass's __unicode__()
313,054
<p>(Django 1.x, Python 2.6.x)</p> <p>I have models to the tune of:</p> <pre><code>class Animal(models.Model): pass class Cat(Animal): def __unicode__(self): return "This is a cat" class Dog(Animal): def __unicode__(self): return "This is a dog" class AnimalHome(models.Model): animal = models.ForeignKey(Animal) </code></pre> <p>I have instantiated no Animals, because this is supposed to be a virtual class. I have instantiated Cats and Dogs, but in the Admin Page for AnimalHome, my choices for Animals are displayed as "Animal object" (the default __unicode__(), I guess) as opposed to the __unicode__ I have defined for the two subclasses. Help.</p> <p><hr /></p> <p>The abstract base class issue is a red herring wrt to this question, I think. Even if Animal was not supposed to be abstract, I still have the problem that, for some reason, since the ForeignKey is defined on Animal and not one of its subclasses, the superclass method is being called instead of the subclass. In OO programming when you call object.method() you're supposed to get the lowest-subclass's implementation, and you have to do extra work to get any superclass's implementation. So why is it that having __unicode__ defined on the subclasses is not sufficient for --- actually the problem might be that __unicode__ is not getting called at all because introspection on the Animal class reveals that it's not defined. So maybe if I define __unicode__ for Animal and have it call subclasses' __unicode__ I could get the desired effect.</p> <p><hr /></p> <p>Okay, I think that I understand the ORM issues. Both these answers have helped me understand this, thank you. While experimenting with this, I discovered that when Django saves a subclassed model, it does two things: (1) it creates a row for the subclassed object in the superclass's table, and (2) it makes the PK in the subclass table identical to the PK assigned in the superclass table. This PK in the subclass table is named superclass_ptr. Based upon this I've concocted the following. I'd appreciate feedback.</p> <pre><code>Class Animal(models.Model) def __unicode__(self): if Dog.objects.filter(pk=self.pk).count() &gt; 0: return unicode(Dog.objects.get(pk=self.pk)) elif Cat.objects.filter(pk=self.pk).count() &gt; 0: return unicode(Cat.objects.get(pk=self.pk)) else: return "An Animal!" </code></pre> <p><hr /></p> <p>It seems that Lawrence is most on-point wrt this question. Cat and Dog will have disjoint PK sets (and any subclass of Animal will have a PK identical to the record of its superclass), but unfortunately Django does not perform any work behind the scenes a la: "I'm an Animal. I know Animals have subclasses Dog and Cat. Specifically, I'm Animal number 3, and furthermore I just checked and there's a Cat number 3 too. That means that I'm actually Cat number 3". Even though this seems entirely possible and very reasonable (since a Cat won't do anything an Animal couldn't do itself) using Python's introspection. Thank you all.</p>
4
2008-11-23T22:44:57Z
313,105
<p>You want an <a href="http://docs.djangoproject.com/en/dev/topics/db/models/#id5" rel="nofollow">Abstract base class</a> ("virtual" doesn't mean anything in Python.)</p> <p>From the documentation:</p> <pre><code>class CommonInfo(models.Model): name = models.CharField(max_length=100) age = models.PositiveIntegerField() class Meta: abstract = True </code></pre> <p><hr /></p> <p>Edit</p> <p>"In OO programming when you call object.method() you're supposed to get the lowest-subclass's implementation."</p> <p>True. But not the whole story.</p> <p>This is not a OO issue. Or even a Python or Django issue. This is an ORM issue.</p> <p>The question is "What object is reconstructed at the end of the FK reference?" And the answer is that there's no standard, obvious answer of how to handle the transformation from FK value to object. </p> <p>I've got a row in <code>AnimalHome</code> with an <code>animals</code> value of 42. It refers to <code>Animal.objects.get(pk=42)</code>. Which subclass of Animal? Cat? Dog? How does the ORM layer know if it should do <code>Dog.objects.get(pk=42)</code> or <code>Cat.objects.get(pk=42)</code>?</p> <p>"But wait," you say. "It should fetch the Animal object, not a Dog or Cat object." You can hope for that, but that's not how the Django ORM works. Each class is a distinct table. Cat and Dog are -- by definition -- separate tables, with separate queries. You're not using an object store. You're using ORM to relational tables.</p> <p><hr /></p> <p>Edit</p> <p>First, your query only works if Dog and Cat share a common key generator, and don't have an overlapping set of PK's.</p> <p>If you have a Dog with PK of 42 AND a Cat with PK of 42, you've got a problem. And since you can't easily control the key generation, your solution can't work.</p> <p>Run Time Type Identification is bad. It's not Object-Oriented in a number of ways. Almost anything you can do to avoid RTTI is better than an ever-expanding sequence of if-statements to distinguish subclasses.</p> <p>However, the model you're trying to build is -- specifically -- a pathological problem for ORM systems. Indeed, so specifically pathological that I'm almost willing to bet it's homework. [There are pathological problems for pure SQL systems, also. They often show up as homework.]</p> <p>The issue is that the ORM cannot do what you think it should do. So you have two choices.</p> <ul> <li>Stop using Django.</li> <li>Do something Django does directly.</li> <li>Break OO design guidelines and resort to brittle things like RTTI, which make it remarkably hard to add another subclass of animals.</li> </ul> <p>Consider this way to do RTTI -- it includes the class name as well as the PK</p> <pre><code>KIND_CHOICES = ( ( "DOG", "Dog" ), ( "CAT", "Cat" ), ) class Animal( models.Model ): kind = models.CharField( max_length= 1, choices=KIND_CHOICES ) fk = models.IntegerField() def get_kind( self ): if kind == "DOG": return Dog.objects.get( pk = fk ) elif kind == "CAT": return Cat.objects.get( pk = fk ) </code></pre>
6
2008-11-23T23:23:44Z
[ "python", "django", "django-admin" ]
Django Admin Interface Does Not Use Subclass's __unicode__()
313,054
<p>(Django 1.x, Python 2.6.x)</p> <p>I have models to the tune of:</p> <pre><code>class Animal(models.Model): pass class Cat(Animal): def __unicode__(self): return "This is a cat" class Dog(Animal): def __unicode__(self): return "This is a dog" class AnimalHome(models.Model): animal = models.ForeignKey(Animal) </code></pre> <p>I have instantiated no Animals, because this is supposed to be a virtual class. I have instantiated Cats and Dogs, but in the Admin Page for AnimalHome, my choices for Animals are displayed as "Animal object" (the default __unicode__(), I guess) as opposed to the __unicode__ I have defined for the two subclasses. Help.</p> <p><hr /></p> <p>The abstract base class issue is a red herring wrt to this question, I think. Even if Animal was not supposed to be abstract, I still have the problem that, for some reason, since the ForeignKey is defined on Animal and not one of its subclasses, the superclass method is being called instead of the subclass. In OO programming when you call object.method() you're supposed to get the lowest-subclass's implementation, and you have to do extra work to get any superclass's implementation. So why is it that having __unicode__ defined on the subclasses is not sufficient for --- actually the problem might be that __unicode__ is not getting called at all because introspection on the Animal class reveals that it's not defined. So maybe if I define __unicode__ for Animal and have it call subclasses' __unicode__ I could get the desired effect.</p> <p><hr /></p> <p>Okay, I think that I understand the ORM issues. Both these answers have helped me understand this, thank you. While experimenting with this, I discovered that when Django saves a subclassed model, it does two things: (1) it creates a row for the subclassed object in the superclass's table, and (2) it makes the PK in the subclass table identical to the PK assigned in the superclass table. This PK in the subclass table is named superclass_ptr. Based upon this I've concocted the following. I'd appreciate feedback.</p> <pre><code>Class Animal(models.Model) def __unicode__(self): if Dog.objects.filter(pk=self.pk).count() &gt; 0: return unicode(Dog.objects.get(pk=self.pk)) elif Cat.objects.filter(pk=self.pk).count() &gt; 0: return unicode(Cat.objects.get(pk=self.pk)) else: return "An Animal!" </code></pre> <p><hr /></p> <p>It seems that Lawrence is most on-point wrt this question. Cat and Dog will have disjoint PK sets (and any subclass of Animal will have a PK identical to the record of its superclass), but unfortunately Django does not perform any work behind the scenes a la: "I'm an Animal. I know Animals have subclasses Dog and Cat. Specifically, I'm Animal number 3, and furthermore I just checked and there's a Cat number 3 too. That means that I'm actually Cat number 3". Even though this seems entirely possible and very reasonable (since a Cat won't do anything an Animal couldn't do itself) using Python's introspection. Thank you all.</p>
4
2008-11-23T22:44:57Z
314,030
<p>This is along the lines of what S.Lott suggested, but without the if/elif/..., which can become increasingly awkward and hard to maintain as the number of subclasses you need to support grows.</p> <pre><code>class Cat(models.Model): def __unicode__(self): return u'A Cat!' class Dog(models.Model): def __unicode__(self): return u'A Dog!' class Eel(models.Model): def __unicode__(self): return u'An Eel!' ANIMALS = { 'CAT': {'model': Cat, 'name': 'Cat'}, 'DOG': {'model': Dog, 'name': 'Dog'}, 'EEL': {'model': Eel, 'name': 'Eel'}, } KIND_CHOICES = tuple((key, ANIMALS[key]['name']) for key in ANIMALS) class Animal(models.Model): kind = models.CharField(max_length=3, choices=KIND_CHOICES) fk = models.IntegerField() def get_kind(self): return ANIMALS[self.kind]['model'].objects.get(pk=self.fk) def __unicode__(self): return unicode(self.get_kind()) </code></pre> <p>Something very similar can also be done with Django's multi-table inheritance (search Django's docs for it). For example:</p> <pre><code>ANIMALS = { 'CAT': {'model_name': 'Cat', 'name': 'Cat'}, 'DOG': {'model_name': 'Dog', 'name': 'Dog'}, 'EEL': {'model_name': 'Eel', 'name': 'Eel'}, } KIND_CHOICES = tuple((key, ANIMALS[key]['name']) for key in ANIMALS) class Animal(models.Model): kind = models.CharField(max_length=3, choices=KIND_CHOICES) def get_kind(self): return getattr(self, ANIMALS[self.kind]['model_name'].lower()) def __unicode__(self): return unicode(self.get_kind()) class Cat(Animal): def __unicode__(self): return u'A Cat!' class Dog(Animal): def __unicode__(self): return u'A Dog!' class Eel(Animal): def __unicode__(self): return u'An Eel!' </code></pre> <p>I personally prefer the second option, since the subclasses' instances will have all of the fields defined in the parent class auto-magically, which allows for clearer and more concise code. (For instace, if the Animal class had a 'gender' field, then Cat.objects.filter(gender='MALE') would work).</p>
2
2008-11-24T12:28:56Z
[ "python", "django", "django-admin" ]
Django Admin Interface Does Not Use Subclass's __unicode__()
313,054
<p>(Django 1.x, Python 2.6.x)</p> <p>I have models to the tune of:</p> <pre><code>class Animal(models.Model): pass class Cat(Animal): def __unicode__(self): return "This is a cat" class Dog(Animal): def __unicode__(self): return "This is a dog" class AnimalHome(models.Model): animal = models.ForeignKey(Animal) </code></pre> <p>I have instantiated no Animals, because this is supposed to be a virtual class. I have instantiated Cats and Dogs, but in the Admin Page for AnimalHome, my choices for Animals are displayed as "Animal object" (the default __unicode__(), I guess) as opposed to the __unicode__ I have defined for the two subclasses. Help.</p> <p><hr /></p> <p>The abstract base class issue is a red herring wrt to this question, I think. Even if Animal was not supposed to be abstract, I still have the problem that, for some reason, since the ForeignKey is defined on Animal and not one of its subclasses, the superclass method is being called instead of the subclass. In OO programming when you call object.method() you're supposed to get the lowest-subclass's implementation, and you have to do extra work to get any superclass's implementation. So why is it that having __unicode__ defined on the subclasses is not sufficient for --- actually the problem might be that __unicode__ is not getting called at all because introspection on the Animal class reveals that it's not defined. So maybe if I define __unicode__ for Animal and have it call subclasses' __unicode__ I could get the desired effect.</p> <p><hr /></p> <p>Okay, I think that I understand the ORM issues. Both these answers have helped me understand this, thank you. While experimenting with this, I discovered that when Django saves a subclassed model, it does two things: (1) it creates a row for the subclassed object in the superclass's table, and (2) it makes the PK in the subclass table identical to the PK assigned in the superclass table. This PK in the subclass table is named superclass_ptr. Based upon this I've concocted the following. I'd appreciate feedback.</p> <pre><code>Class Animal(models.Model) def __unicode__(self): if Dog.objects.filter(pk=self.pk).count() &gt; 0: return unicode(Dog.objects.get(pk=self.pk)) elif Cat.objects.filter(pk=self.pk).count() &gt; 0: return unicode(Cat.objects.get(pk=self.pk)) else: return "An Animal!" </code></pre> <p><hr /></p> <p>It seems that Lawrence is most on-point wrt this question. Cat and Dog will have disjoint PK sets (and any subclass of Animal will have a PK identical to the record of its superclass), but unfortunately Django does not perform any work behind the scenes a la: "I'm an Animal. I know Animals have subclasses Dog and Cat. Specifically, I'm Animal number 3, and furthermore I just checked and there's a Cat number 3 too. That means that I'm actually Cat number 3". Even though this seems entirely possible and very reasonable (since a Cat won't do anything an Animal couldn't do itself) using Python's introspection. Thank you all.</p>
4
2008-11-23T22:44:57Z
314,719
<p>ForeignKey(Animal) is just that, a foreign key reference to a row in the Animal table. There's nothing in the underlying SQL schema that indicates that the table is being used as a superclass, so you get back an Animal object.</p> <p>To work around this:</p> <p>First, you want the base class to be non-abstract. This is necessary for the ForeignKey anyway, and also ensures that Dog and Cat will have disjunct primary key sets.</p> <p>Now, Django implements inheritance using a OneToOneField. Because of this, <strong>an instance of a base class that has a subclass instance gets a reference to that instance, named appropriately.</strong> This means you can do:</p> <pre><code>class Animal(models.Model): def __unicode__(self): if hasattr(self, 'dog'): return self.dog.__unicode__() elif hasattr(self, 'cat'): return self.cat.__unicode__() else: return 'Animal' </code></pre> <p>This also answers your question to Ber about a <strong>unicode</strong>() that's dependent on other subclass attributes. You're actually calling the appropriate method on the subclass instance now.</p> <p>Now, this does suggest that, since Django's already looking for subclass instances behind the scenes, the code could just go all the way and return a Cat or Dog instance instead of an Animal. You'll have to take up that question with the devs. :)</p>
5
2008-11-24T16:40:56Z
[ "python", "django", "django-admin" ]
Django Admin Interface Does Not Use Subclass's __unicode__()
313,054
<p>(Django 1.x, Python 2.6.x)</p> <p>I have models to the tune of:</p> <pre><code>class Animal(models.Model): pass class Cat(Animal): def __unicode__(self): return "This is a cat" class Dog(Animal): def __unicode__(self): return "This is a dog" class AnimalHome(models.Model): animal = models.ForeignKey(Animal) </code></pre> <p>I have instantiated no Animals, because this is supposed to be a virtual class. I have instantiated Cats and Dogs, but in the Admin Page for AnimalHome, my choices for Animals are displayed as "Animal object" (the default __unicode__(), I guess) as opposed to the __unicode__ I have defined for the two subclasses. Help.</p> <p><hr /></p> <p>The abstract base class issue is a red herring wrt to this question, I think. Even if Animal was not supposed to be abstract, I still have the problem that, for some reason, since the ForeignKey is defined on Animal and not one of its subclasses, the superclass method is being called instead of the subclass. In OO programming when you call object.method() you're supposed to get the lowest-subclass's implementation, and you have to do extra work to get any superclass's implementation. So why is it that having __unicode__ defined on the subclasses is not sufficient for --- actually the problem might be that __unicode__ is not getting called at all because introspection on the Animal class reveals that it's not defined. So maybe if I define __unicode__ for Animal and have it call subclasses' __unicode__ I could get the desired effect.</p> <p><hr /></p> <p>Okay, I think that I understand the ORM issues. Both these answers have helped me understand this, thank you. While experimenting with this, I discovered that when Django saves a subclassed model, it does two things: (1) it creates a row for the subclassed object in the superclass's table, and (2) it makes the PK in the subclass table identical to the PK assigned in the superclass table. This PK in the subclass table is named superclass_ptr. Based upon this I've concocted the following. I'd appreciate feedback.</p> <pre><code>Class Animal(models.Model) def __unicode__(self): if Dog.objects.filter(pk=self.pk).count() &gt; 0: return unicode(Dog.objects.get(pk=self.pk)) elif Cat.objects.filter(pk=self.pk).count() &gt; 0: return unicode(Cat.objects.get(pk=self.pk)) else: return "An Animal!" </code></pre> <p><hr /></p> <p>It seems that Lawrence is most on-point wrt this question. Cat and Dog will have disjoint PK sets (and any subclass of Animal will have a PK identical to the record of its superclass), but unfortunately Django does not perform any work behind the scenes a la: "I'm an Animal. I know Animals have subclasses Dog and Cat. Specifically, I'm Animal number 3, and furthermore I just checked and there's a Cat number 3 too. That means that I'm actually Cat number 3". Even though this seems entirely possible and very reasonable (since a Cat won't do anything an Animal couldn't do itself) using Python's introspection. Thank you all.</p>
4
2008-11-23T22:44:57Z
316,717
<p>Regarding Generic Relations, note that normal Django queries cannot span GenerecForeignKey relations. Using multi-table inheritance avoids this issue at the cost of being a less generic solution.</p> <p>From the docs:</p> <blockquote> <p>Due to the way GenericForeignKey is implemented, you cannot use such fields directly with filters (filter() and exclude(), for example) via the database API. They aren't normal field objects. These examples will not work:</p> </blockquote> <pre><code># This will fail &gt;&gt;&gt; TaggedItem.objects.filter(content_object=guido) # This will also fail &gt;&gt;&gt; TaggedItem.objects.get(content_object=guido) </code></pre>
1
2008-11-25T08:44:04Z
[ "python", "django", "django-admin" ]
Django Admin Interface Does Not Use Subclass's __unicode__()
313,054
<p>(Django 1.x, Python 2.6.x)</p> <p>I have models to the tune of:</p> <pre><code>class Animal(models.Model): pass class Cat(Animal): def __unicode__(self): return "This is a cat" class Dog(Animal): def __unicode__(self): return "This is a dog" class AnimalHome(models.Model): animal = models.ForeignKey(Animal) </code></pre> <p>I have instantiated no Animals, because this is supposed to be a virtual class. I have instantiated Cats and Dogs, but in the Admin Page for AnimalHome, my choices for Animals are displayed as "Animal object" (the default __unicode__(), I guess) as opposed to the __unicode__ I have defined for the two subclasses. Help.</p> <p><hr /></p> <p>The abstract base class issue is a red herring wrt to this question, I think. Even if Animal was not supposed to be abstract, I still have the problem that, for some reason, since the ForeignKey is defined on Animal and not one of its subclasses, the superclass method is being called instead of the subclass. In OO programming when you call object.method() you're supposed to get the lowest-subclass's implementation, and you have to do extra work to get any superclass's implementation. So why is it that having __unicode__ defined on the subclasses is not sufficient for --- actually the problem might be that __unicode__ is not getting called at all because introspection on the Animal class reveals that it's not defined. So maybe if I define __unicode__ for Animal and have it call subclasses' __unicode__ I could get the desired effect.</p> <p><hr /></p> <p>Okay, I think that I understand the ORM issues. Both these answers have helped me understand this, thank you. While experimenting with this, I discovered that when Django saves a subclassed model, it does two things: (1) it creates a row for the subclassed object in the superclass's table, and (2) it makes the PK in the subclass table identical to the PK assigned in the superclass table. This PK in the subclass table is named superclass_ptr. Based upon this I've concocted the following. I'd appreciate feedback.</p> <pre><code>Class Animal(models.Model) def __unicode__(self): if Dog.objects.filter(pk=self.pk).count() &gt; 0: return unicode(Dog.objects.get(pk=self.pk)) elif Cat.objects.filter(pk=self.pk).count() &gt; 0: return unicode(Cat.objects.get(pk=self.pk)) else: return "An Animal!" </code></pre> <p><hr /></p> <p>It seems that Lawrence is most on-point wrt this question. Cat and Dog will have disjoint PK sets (and any subclass of Animal will have a PK identical to the record of its superclass), but unfortunately Django does not perform any work behind the scenes a la: "I'm an Animal. I know Animals have subclasses Dog and Cat. Specifically, I'm Animal number 3, and furthermore I just checked and there's a Cat number 3 too. That means that I'm actually Cat number 3". Even though this seems entirely possible and very reasonable (since a Cat won't do anything an Animal couldn't do itself) using Python's introspection. Thank you all.</p>
4
2008-11-23T22:44:57Z
19,987,924
<p>You can use the <a href="https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/" rel="nofollow">django content framework</a></p> <p>I made an example of how to implement you models here -> </p> <p><a href="https://github.com/jmg/django_content_types_example/blob/master/generic_models/models.py" rel="nofollow">https://github.com/jmg/django_content_types_example/blob/master/generic_models/models.py</a></p> <p>And here you can see how to use the orm -> </p> <p><a href="https://github.com/jmg/django_content_types_example/blob/master/generic_models/tests.py" rel="nofollow">https://github.com/jmg/django_content_types_example/blob/master/generic_models/tests.py</a></p>
1
2013-11-14T20:41:18Z
[ "python", "django", "django-admin" ]
Are there problems developing Django on Jython?
314,234
<p><b> The background </b> </p> <p>I'm building a fair-sized web application with a friend in my own time, and we've decided to go with the Django framework on Python. Django provides us with a lot of features we're going to need, so please don't suggest alternative frameworks.</p> <p>The only decision I'm having trouble with, is whether we use Python or Jython to develop our application. Now I'm pretty familiar with Java and could possibly benefit from the libraries within the JDK. I know minimal Python, but am using this project as an opportunity to learn a new language - so the majority of work will be written in Python.</p> <p>The attractiveness of Jython is of course the JVM. The number of python/django enabled web-hosts is extremely minimal - whereas I'm assuming I could drop a jython/django application on a huge variety of hosts. This isn't a massive design decision, but still one I think needs to be decided. I'd really prefer jython over python for the jvm accessibility alone.</p> <p><b> Questions </b> </p> <p>Does Jython have many limitations compared to regular python? Will running django on jython cause problems? How quick is the Jython team to release updates alongside Python? Will Django work as advertised on Jython (with very minimal pre-configuration)?</p> <p><b> Decision </b></p> <p>Thanks for the helpful comments. What I think I'm going to do is develop in Jython for the JVM support - but to try to only use Python code/libraries. Portability isn't a major concern so if I need a library in the JDK (not readily available in python), I'll use it. As long as Django is fully supported, I'm happy.</p>
13
2008-11-24T14:17:17Z
314,287
<p>Django is supposed to be jython-compatible sinc version 1.0.</p> <p><a href="http://wiki.python.org/jython/DjangoOnJython" rel="nofollow">This tutorial</a> is a bit outdated, but from there you can see there are no special issues.</p>
0
2008-11-24T14:32:30Z
[ "python", "django", "jvm", "jython" ]
Are there problems developing Django on Jython?
314,234
<p><b> The background </b> </p> <p>I'm building a fair-sized web application with a friend in my own time, and we've decided to go with the Django framework on Python. Django provides us with a lot of features we're going to need, so please don't suggest alternative frameworks.</p> <p>The only decision I'm having trouble with, is whether we use Python or Jython to develop our application. Now I'm pretty familiar with Java and could possibly benefit from the libraries within the JDK. I know minimal Python, but am using this project as an opportunity to learn a new language - so the majority of work will be written in Python.</p> <p>The attractiveness of Jython is of course the JVM. The number of python/django enabled web-hosts is extremely minimal - whereas I'm assuming I could drop a jython/django application on a huge variety of hosts. This isn't a massive design decision, but still one I think needs to be decided. I'd really prefer jython over python for the jvm accessibility alone.</p> <p><b> Questions </b> </p> <p>Does Jython have many limitations compared to regular python? Will running django on jython cause problems? How quick is the Jython team to release updates alongside Python? Will Django work as advertised on Jython (with very minimal pre-configuration)?</p> <p><b> Decision </b></p> <p>Thanks for the helpful comments. What I think I'm going to do is develop in Jython for the JVM support - but to try to only use Python code/libraries. Portability isn't a major concern so if I need a library in the JDK (not readily available in python), I'll use it. As long as Django is fully supported, I'm happy.</p>
13
2008-11-24T14:17:17Z
314,296
<p>Django does <a href="http://wiki.python.org/jython/DjangoOnJython" rel="nofollow">work on Jython</a>, although you'll need to use the development release of Jython, since technically Jython 2.5 is still in beta. However, Django 1.0 and up should work unmodified.</p> <p>So as to whether you should use the regular Python implementation or Jython, I'd say it's a matter of whether you prefer having all the Java libraries available or all of the Python libraries. At this point you can expect almost everything in the Python standard library to work with Jython, but there are still plenty of third-party packages which will not work, especially C extension modules. I'd personally recommend going with regular Python, but if you've got a ton of JVM experience and want to stick with what you know, then I can respect that.</p> <p>As for finding Python hosting, <a href="http://wiki.python.org/moin/PythonHosting" rel="nofollow">this page might be helpful</a>.</p>
3
2008-11-24T14:35:35Z
[ "python", "django", "jvm", "jython" ]
Are there problems developing Django on Jython?
314,234
<p><b> The background </b> </p> <p>I'm building a fair-sized web application with a friend in my own time, and we've decided to go with the Django framework on Python. Django provides us with a lot of features we're going to need, so please don't suggest alternative frameworks.</p> <p>The only decision I'm having trouble with, is whether we use Python or Jython to develop our application. Now I'm pretty familiar with Java and could possibly benefit from the libraries within the JDK. I know minimal Python, but am using this project as an opportunity to learn a new language - so the majority of work will be written in Python.</p> <p>The attractiveness of Jython is of course the JVM. The number of python/django enabled web-hosts is extremely minimal - whereas I'm assuming I could drop a jython/django application on a huge variety of hosts. This isn't a massive design decision, but still one I think needs to be decided. I'd really prefer jython over python for the jvm accessibility alone.</p> <p><b> Questions </b> </p> <p>Does Jython have many limitations compared to regular python? Will running django on jython cause problems? How quick is the Jython team to release updates alongside Python? Will Django work as advertised on Jython (with very minimal pre-configuration)?</p> <p><b> Decision </b></p> <p>Thanks for the helpful comments. What I think I'm going to do is develop in Jython for the JVM support - but to try to only use Python code/libraries. Portability isn't a major concern so if I need a library in the JDK (not readily available in python), I'll use it. As long as Django is fully supported, I'm happy.</p>
13
2008-11-24T14:17:17Z
314,448
<p>I'd say that if you like Django, you'll also like Python. Don't make the (far too common) mistake of mixing past language's experience while you learn a new one. Only after mastering Python, you'll have the experience to judge if a hybrid language is better than either one.</p> <p>It's true that very few cheap hostings offer Django preinstalled; but it's quite probable that that will change, given that it's the most similar environment to Google's app engine. (and most GAE projects can be made to run on Django)</p>
3
2008-11-24T15:17:55Z
[ "python", "django", "jvm", "jython" ]
Are there problems developing Django on Jython?
314,234
<p><b> The background </b> </p> <p>I'm building a fair-sized web application with a friend in my own time, and we've decided to go with the Django framework on Python. Django provides us with a lot of features we're going to need, so please don't suggest alternative frameworks.</p> <p>The only decision I'm having trouble with, is whether we use Python or Jython to develop our application. Now I'm pretty familiar with Java and could possibly benefit from the libraries within the JDK. I know minimal Python, but am using this project as an opportunity to learn a new language - so the majority of work will be written in Python.</p> <p>The attractiveness of Jython is of course the JVM. The number of python/django enabled web-hosts is extremely minimal - whereas I'm assuming I could drop a jython/django application on a huge variety of hosts. This isn't a massive design decision, but still one I think needs to be decided. I'd really prefer jython over python for the jvm accessibility alone.</p> <p><b> Questions </b> </p> <p>Does Jython have many limitations compared to regular python? Will running django on jython cause problems? How quick is the Jython team to release updates alongside Python? Will Django work as advertised on Jython (with very minimal pre-configuration)?</p> <p><b> Decision </b></p> <p>Thanks for the helpful comments. What I think I'm going to do is develop in Jython for the JVM support - but to try to only use Python code/libraries. Portability isn't a major concern so if I need a library in the JDK (not readily available in python), I'll use it. As long as Django is fully supported, I'm happy.</p>
13
2008-11-24T14:17:17Z
315,110
<p>I have recently started working on an open source desktop project in my spare time. So this may not apply. I came to the same the question. I decided that I should write as much of the code as possible in python (and Django) and target all the platforms CPython, Jython, and IronPython.</p> <p>Then, I decided that I would write plugins that would interface with libraries on different implementations (for example, different GUI libraries).</p> <p>Why? I decided early on that longevity of my code may depend on targeting not only CPython but also virtual machines. For today's purposes CPython is the way to go because of speed, but who knows about tomorrow. If you code is flexible enough, you may not have to decide on targeting one.</p> <p>The downside to this approach is that you will have more code to create and maintain.</p>
1
2008-11-24T19:10:44Z
[ "python", "django", "jvm", "jython" ]
Comparing multiple dictionaries in Python
314,583
<p>I'm new to Python and am running to a problem I can't google my way out of. I've built a GUI using wxPython and ObjectiveListView. In its very center, the GUI has a list control displaying data in X rows (the data is loaded by the user) and in five columns.</p> <p>When the user selects multiple entries from the list control (pressing CTRL or shift while clicking), the ObjectiveListView module gives me a list of dictionaries, the dictionaries containing the data in the rows of the list control. This is exactly what I want, good!</p> <p>The returned list looks something like this:</p> <pre><code>print MyList [{'id':1023, 'type':'Purchase', 'date':'23.8.2008', 'sum':'-21,90', 'target':'Apple Store'}, {'id':1024, 'type':'Purchase', 'date':'24.8.2008', 'sum':'-21,90', 'target':'Apple Store'}, {'id':23, 'type':'Purchase', 'date':'2.8.2008', 'sum':'-21,90', 'target':'Apple Store'}] </code></pre> <p>All the dictionaries have the same keys, but the values change. The 'id' value is unique. Here the problems start. I want to get the common values for all the items the user selected. In the above list they would be 'sum':'-21,90' and 'target':'Apple Store'.</p> <p>I don't know how to properly compare the dicts in the list. One big problem is that I don't know beforehand how many dicts the list contains, since it's decided by the user.</p> <p>I have a vague idea that list comprehensions would be the way to go, but I only know how to compare two lists with list comprehensions, not n lists. Any help would be appreciated.</p>
4
2008-11-24T16:02:37Z
314,621
<p>Sorry, yes, 'type':'Purchase' is also one of the common values.Should have logged in to edit the question.</p>
0
2008-11-24T16:13:34Z
[ "python", "data-mining" ]
Comparing multiple dictionaries in Python
314,583
<p>I'm new to Python and am running to a problem I can't google my way out of. I've built a GUI using wxPython and ObjectiveListView. In its very center, the GUI has a list control displaying data in X rows (the data is loaded by the user) and in five columns.</p> <p>When the user selects multiple entries from the list control (pressing CTRL or shift while clicking), the ObjectiveListView module gives me a list of dictionaries, the dictionaries containing the data in the rows of the list control. This is exactly what I want, good!</p> <p>The returned list looks something like this:</p> <pre><code>print MyList [{'id':1023, 'type':'Purchase', 'date':'23.8.2008', 'sum':'-21,90', 'target':'Apple Store'}, {'id':1024, 'type':'Purchase', 'date':'24.8.2008', 'sum':'-21,90', 'target':'Apple Store'}, {'id':23, 'type':'Purchase', 'date':'2.8.2008', 'sum':'-21,90', 'target':'Apple Store'}] </code></pre> <p>All the dictionaries have the same keys, but the values change. The 'id' value is unique. Here the problems start. I want to get the common values for all the items the user selected. In the above list they would be 'sum':'-21,90' and 'target':'Apple Store'.</p> <p>I don't know how to properly compare the dicts in the list. One big problem is that I don't know beforehand how many dicts the list contains, since it's decided by the user.</p> <p>I have a vague idea that list comprehensions would be the way to go, but I only know how to compare two lists with list comprehensions, not n lists. Any help would be appreciated.</p>
4
2008-11-24T16:02:37Z
314,633
<pre><code>&gt;&gt;&gt; mysets = (set(x.items()) for x in MyList) &gt;&gt;&gt; reduce(lambda a,b: a.intersection(b), mysets) set([('sum', '-21,90'), ('type', 'Purchase'), ('target', 'Apple Store')]) </code></pre> <p>First, I've created a generator that will convert the list of dicts into an iterable sequence of sets of key,value pairs. You could use a list comprehension here but this way doesn't convert your entire list into yet another list, useful if you don't know how big it will be.</p> <p>Then I've used reduce to apply a function that finds the common values between each set. It finds the intersection of set 1 &amp; set 2, which is itself a set, then the intersection of that set &amp; set 3 etc. The mysets generator will happily feed each set on demand to the reduce function until its done.</p> <p>I believe reduce has been deprecated as a built-in in Python 3.0, but should still be available in functools.</p> <p>You could of course make it a one-liner by replacing mysets in the reduce with the generator expression, but that reduces the readability IMO. In practice I'd probably even go one step further and break the lambda out into its own line as well:</p> <pre><code>&gt;&gt;&gt; mysets = (set(x.items()) for x in MyList) &gt;&gt;&gt; find_common = lambda a,b: a.intersection(b) &gt;&gt;&gt; reduce(find_common, mysets) set([('sum', '-21,90'), ('type', 'Purchase'), ('target', 'Apple Store')]) </code></pre> <p>And if you need the end result to be a dict, just wrap it like so:</p> <pre><code>&gt;&gt;&gt; dict(reduce(find_common, mysets)) {'sum': '-21,90', 'type': 'Purchase', 'target': 'Apple Store'} </code></pre> <p>dict can accept any iterator of key,value pairs, such as the set of tuples returned at the end.</p>
7
2008-11-24T16:16:20Z
[ "python", "data-mining" ]
Comparing multiple dictionaries in Python
314,583
<p>I'm new to Python and am running to a problem I can't google my way out of. I've built a GUI using wxPython and ObjectiveListView. In its very center, the GUI has a list control displaying data in X rows (the data is loaded by the user) and in five columns.</p> <p>When the user selects multiple entries from the list control (pressing CTRL or shift while clicking), the ObjectiveListView module gives me a list of dictionaries, the dictionaries containing the data in the rows of the list control. This is exactly what I want, good!</p> <p>The returned list looks something like this:</p> <pre><code>print MyList [{'id':1023, 'type':'Purchase', 'date':'23.8.2008', 'sum':'-21,90', 'target':'Apple Store'}, {'id':1024, 'type':'Purchase', 'date':'24.8.2008', 'sum':'-21,90', 'target':'Apple Store'}, {'id':23, 'type':'Purchase', 'date':'2.8.2008', 'sum':'-21,90', 'target':'Apple Store'}] </code></pre> <p>All the dictionaries have the same keys, but the values change. The 'id' value is unique. Here the problems start. I want to get the common values for all the items the user selected. In the above list they would be 'sum':'-21,90' and 'target':'Apple Store'.</p> <p>I don't know how to properly compare the dicts in the list. One big problem is that I don't know beforehand how many dicts the list contains, since it's decided by the user.</p> <p>I have a vague idea that list comprehensions would be the way to go, but I only know how to compare two lists with list comprehensions, not n lists. Any help would be appreciated.</p>
4
2008-11-24T16:02:37Z
314,751
<p>First, we need a function to compute intersection of two dictionaries:</p> <pre><code>def IntersectDicts( d1, d2 ) : return dict(filter(lambda (k,v) : k in d2 and d2[k] == v, d1.items())) </code></pre> <p>Then we can use it to process any number of dictionaries:</p> <pre><code>result = reduce(IntersectDicts, MyList) </code></pre>
2
2008-11-24T16:50:20Z
[ "python", "data-mining" ]
Comparing multiple dictionaries in Python
314,583
<p>I'm new to Python and am running to a problem I can't google my way out of. I've built a GUI using wxPython and ObjectiveListView. In its very center, the GUI has a list control displaying data in X rows (the data is loaded by the user) and in five columns.</p> <p>When the user selects multiple entries from the list control (pressing CTRL or shift while clicking), the ObjectiveListView module gives me a list of dictionaries, the dictionaries containing the data in the rows of the list control. This is exactly what I want, good!</p> <p>The returned list looks something like this:</p> <pre><code>print MyList [{'id':1023, 'type':'Purchase', 'date':'23.8.2008', 'sum':'-21,90', 'target':'Apple Store'}, {'id':1024, 'type':'Purchase', 'date':'24.8.2008', 'sum':'-21,90', 'target':'Apple Store'}, {'id':23, 'type':'Purchase', 'date':'2.8.2008', 'sum':'-21,90', 'target':'Apple Store'}] </code></pre> <p>All the dictionaries have the same keys, but the values change. The 'id' value is unique. Here the problems start. I want to get the common values for all the items the user selected. In the above list they would be 'sum':'-21,90' and 'target':'Apple Store'.</p> <p>I don't know how to properly compare the dicts in the list. One big problem is that I don't know beforehand how many dicts the list contains, since it's decided by the user.</p> <p>I have a vague idea that list comprehensions would be the way to go, but I only know how to compare two lists with list comprehensions, not n lists. Any help would be appreciated.</p>
4
2008-11-24T16:02:37Z
314,834
<p>My answer is identical to Matthew Trevor's, except for one difference:</p> <pre><code>&gt;&gt;&gt; mysets = (set(x.items()) for x in MyList) &gt;&gt;&gt; reduce(set.intersection, mysets) set([('sum', '-21,90'), ('type', 'Purchase'), ('target', 'Apple Store')]) </code></pre> <p>Here I use <code>set.intersection</code> instead of creating a new lambda. In my opinion this is more readable, as this intuitively reads as "reduce is reducing this list using the set intersection operator." This should also be much faster, as <code>set.intersection</code> is a built-in C function.</p> <p>To fully answer your question, you can extract the values using a list comprehension:</p> <pre><code>&gt;&gt;&gt; mysets = (set(x.items()) for x in MyList) &gt;&gt;&gt; result = reduce(set.intersection, mysets) &gt;&gt;&gt; values = [r[1] for r in result] &gt;&gt;&gt; values ['-21,90', 'Purchase', 'Apple Store'] </code></pre> <p>This would end up on one line for me. but that's entirely up to you:</p> <pre><code>&gt;&gt;&gt; [r[1] for r in reduce(set.intersection, (set(x.items()) for x in myList))] ['-21,90', 'Purchase', 'Apple Store'] </code></pre>
6
2008-11-24T17:22:57Z
[ "python", "data-mining" ]
Comparing multiple dictionaries in Python
314,583
<p>I'm new to Python and am running to a problem I can't google my way out of. I've built a GUI using wxPython and ObjectiveListView. In its very center, the GUI has a list control displaying data in X rows (the data is loaded by the user) and in five columns.</p> <p>When the user selects multiple entries from the list control (pressing CTRL or shift while clicking), the ObjectiveListView module gives me a list of dictionaries, the dictionaries containing the data in the rows of the list control. This is exactly what I want, good!</p> <p>The returned list looks something like this:</p> <pre><code>print MyList [{'id':1023, 'type':'Purchase', 'date':'23.8.2008', 'sum':'-21,90', 'target':'Apple Store'}, {'id':1024, 'type':'Purchase', 'date':'24.8.2008', 'sum':'-21,90', 'target':'Apple Store'}, {'id':23, 'type':'Purchase', 'date':'2.8.2008', 'sum':'-21,90', 'target':'Apple Store'}] </code></pre> <p>All the dictionaries have the same keys, but the values change. The 'id' value is unique. Here the problems start. I want to get the common values for all the items the user selected. In the above list they would be 'sum':'-21,90' and 'target':'Apple Store'.</p> <p>I don't know how to properly compare the dicts in the list. One big problem is that I don't know beforehand how many dicts the list contains, since it's decided by the user.</p> <p>I have a vague idea that list comprehensions would be the way to go, but I only know how to compare two lists with list comprehensions, not n lists. Any help would be appreciated.</p>
4
2008-11-24T16:02:37Z
315,424
<p>Since you're only looking for the common set, you can compare the keys in the first dictionary to the keys in all other dictionaries:</p> <pre><code>common = {} for k in MyList[0]: for i in xrange(1,len(MyList)): if MyList[0][k] != MyList[i][k]: continue common[k] = MyList[0][k] &gt;&gt;&gt; common {'sum': '-21,90', 'type': 'Purchase', 'target': 'Apple Store'} </code></pre>
1
2008-11-24T20:49:36Z
[ "python", "data-mining" ]
Python 2.5.2 and Solaris 8 (gcc 3.4.2) build issues
314,749
<p>I'm trying to build python 2.5.2 on Solaris 8 using gcc 3.4.2. I can't see any immediate errors in the ./configure step but, once built and i enter the python shell doing an import time errors with :</p> <pre><code>Python 2.5.2 (r252:60911, Nov 21 2008, 18:45:42) [GCC 3.4.2] on sunos5 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import time Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named time </code></pre> <p>What am i doing wrong? From what i can see with a cursory google is that there might be an error with libstdc++.so, but i can't find any hard details.</p> <p>Any suggestions would be most welcome.</p> <p>Many thanks,</p> <p>Al.</p>
3
2008-11-24T16:49:58Z
326,018
<p>The time module is not built by default in Python, if you build from a source distribution you need to explicitly enable all the modules you want to compile. </p> <p>Open up Modules/Setup.dist in the python source tree and comment out the line which says:</p> <pre> #time timemodule.c </pre> <p>To enable the build of time module. Also remember that you need to recompile Python for this to take an effect.</p>
1
2008-11-28T15:22:16Z
[ "python", "gcc", "build-process", "solaris", "environment-variables" ]
How to debug Web2py applications?
315,165
<p>Is it possible? By debug I mean setting breakpoints, inspect values and advance step by step.</p>
16
2008-11-24T19:27:05Z
315,318
<p>I haven't used web2py, but if it runs in a terminal window, you can use standard pdb stuff. Add this line somewhere in your code:</p> <pre><code>import pdb; pdb.set_trace() </code></pre> <p>This will invoke the debugger and break. Then you can use <a href="http://docs.python.org/lib/module-pdb.html" rel="nofollow">PDB</a> commands: n to step to the next line, l to list code, s to step into a function, p to print values, etc.</p>
8
2008-11-24T20:22:22Z
[ "python", "debugging", "web2py" ]
How to debug Web2py applications?
315,165
<p>Is it possible? By debug I mean setting breakpoints, inspect values and advance step by step.</p>
16
2008-11-24T19:27:05Z
318,501
<p>You can do remote debugging of python web apps over TCP/IP with <a href="http://winpdb.org/" rel="nofollow">winpdb</a>.</p>
9
2008-11-25T19:03:51Z
[ "python", "debugging", "web2py" ]
How to debug Web2py applications?
315,165
<p>Is it possible? By debug I mean setting breakpoints, inspect values and advance step by step.</p>
16
2008-11-24T19:27:05Z
806,233
<p>One can debug applications built on Web2py using the following set-up:</p> <ol> <li>Eclipse IDE</li> <li>Install Pydev into Eclipse</li> <li>Set Breakpoints on your code as needed</li> <li>Within Eclipse right-click the file web2py.py and select Debug As -> Python Run</li> <li>When a breakpoint is hit Eclipse will jump to the breakpoint where you can inspect variables and step thru the code</li> </ol>
8
2009-04-30T10:04:10Z
[ "python", "debugging", "web2py" ]
How to debug Web2py applications?
315,165
<p>Is it possible? By debug I mean setting breakpoints, inspect values and advance step by step.</p>
16
2008-11-24T19:27:05Z
1,705,626
<p>Yes, it is possible, Due to the "span prevention" I am still not allowed to post screenshots, but here is a full screenshot hosted at my website:</p> <p><a href="http://static.techfuel.net/debug%5Fweb2py.png" rel="nofollow">http://static.techfuel.net/debug_web2py.png</a></p>
1
2009-11-10T04:29:57Z
[ "python", "debugging", "web2py" ]
How to debug Web2py applications?
315,165
<p>Is it possible? By debug I mean setting breakpoints, inspect values and advance step by step.</p>
16
2008-11-24T19:27:05Z
2,781,947
<p>As Carl stated, it is as easy as:</p> <ol> <li>Installing PyDev in Eclipse</li> <li>Right Click on your Web2Py project, selecting Debug As > Python Run</li> <li>Selecting web2py.py as the file to run</li> </ol> <p>No other plugins or downloads are needed.</p>
0
2010-05-06T14:42:37Z
[ "python", "debugging", "web2py" ]
How to debug Web2py applications?
315,165
<p>Is it possible? By debug I mean setting breakpoints, inspect values and advance step by step.</p>
16
2008-11-24T19:27:05Z
4,049,236
<p>Here is an article on debugging python with pdb, which will work with web2py. <a href="http://sontek.net/debugging-python-with-pdb" rel="nofollow">http://sontek.net/debugging-python-with-pdb</a></p>
0
2010-10-29T05:29:31Z
[ "python", "debugging", "web2py" ]