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
list
Scripts to documents (Matlab's publish functionality in python)
877,145
<p>Matlab has this great tool called <a href="http://www.mathworks.com/access/helpdesk/help/techdoc/index.html?/access/helpdesk/help/techdoc/ref/publish.html">publish</a>. This tool converts a regular matlab script with minimal formatting stuff into structured, nice looking reports (HTML, LateX, RTF). It is capable of handling graphics, mathematical formulae etc.</p> <p>Is there a similar tool for Python?</p>
5
2009-05-18T10:51:44Z
877,309
<p>There's <a href="http://gael-varoquaux.info/computers/pyreport/">pyreport</a>. It captures the "captures its output, compiling it to a pretty report in a pdf or an html file". With this, you can write scripts that print out your source, getting a nice report in the end.</p>
5
2009-05-18T11:43:07Z
[ "python", "matlab", "reporting", "report" ]
python dict.add_by_value(dict_2)?
877,295
<p>The problem:</p> <pre><code>&gt;&gt;&gt; a = dict(a=1,b=2 ) &gt;&gt;&gt; b = dict( b=3,c=2) &gt;&gt;&gt; c = ??? c = {'a': 1, 'b': 5, 'c': 2} </code></pre> <p>So, the idea is two add to dictionaries by int/float values in the shortest form. Here's one solution that I've devised, but I don't like it, cause it's long:</p> <pre><code>c = dict([(i,a.get(i,0) + b.get(i,0)) for i in set(a.keys()+b.keys())]) </code></pre> <p>I think there must be a shorter/concise solution (maybe something to do with reduce and operator module? itertools?)... Any ideas?</p> <p><hr /></p> <p>Update: I'm really hoping to find something more elegant like "reduce(operator.add, key = itemgetter(0), a+b)". (Obviously that isn't real code, but you should get the idea). But it seems that may be a dream.</p> <p><hr /></p> <p>Update: Still loking for more concise solutions. Maybe groupby can help? The solution I've come up with using "reduce"/"groupby" isn't actually concise:</p> <pre><code>from itertools import groupby from operator import itemgetter,add c = dict( [(i,reduce(add,map(itemgetter(1), v))) \ for i,v in groupby(sorted(a.items()+b.items()), itemgetter(0))] ) </code></pre>
9
2009-05-18T11:40:11Z
877,348
<p>I think one line of code is already pretty short :)</p> <p>I may become "half a line", it you use <a href="http://docs.python.org/library/collections.html#collections.defaultdict" rel="nofollow">defaultdict</a> and remove some unnecessary list and set creations:</p> <pre><code>from collections import defaultdict a = defaultdict(int, a=1, b=2) b = defaultdict(int, b=3, c=4) c = dict((k, a[k]+b[k]) for k in (a.keys() + b.keys())) print c </code></pre>
4
2009-05-18T11:55:33Z
[ "python", "code-golf", "dictionary" ]
python dict.add_by_value(dict_2)?
877,295
<p>The problem:</p> <pre><code>&gt;&gt;&gt; a = dict(a=1,b=2 ) &gt;&gt;&gt; b = dict( b=3,c=2) &gt;&gt;&gt; c = ??? c = {'a': 1, 'b': 5, 'c': 2} </code></pre> <p>So, the idea is two add to dictionaries by int/float values in the shortest form. Here's one solution that I've devised, but I don't like it, cause it's long:</p> <pre><code>c = dict([(i,a.get(i,0) + b.get(i,0)) for i in set(a.keys()+b.keys())]) </code></pre> <p>I think there must be a shorter/concise solution (maybe something to do with reduce and operator module? itertools?)... Any ideas?</p> <p><hr /></p> <p>Update: I'm really hoping to find something more elegant like "reduce(operator.add, key = itemgetter(0), a+b)". (Obviously that isn't real code, but you should get the idea). But it seems that may be a dream.</p> <p><hr /></p> <p>Update: Still loking for more concise solutions. Maybe groupby can help? The solution I've come up with using "reduce"/"groupby" isn't actually concise:</p> <pre><code>from itertools import groupby from operator import itemgetter,add c = dict( [(i,reduce(add,map(itemgetter(1), v))) \ for i,v in groupby(sorted(a.items()+b.items()), itemgetter(0))] ) </code></pre>
9
2009-05-18T11:40:11Z
877,363
<p>In my first impression, I will write:</p> <pre><code>&gt;&gt;&gt; c = a.copy() &gt;&gt;&gt; for k in b: c[k] = c.get(k, 0) + b[k] </code></pre>
5
2009-05-18T11:58:41Z
[ "python", "code-golf", "dictionary" ]
python dict.add_by_value(dict_2)?
877,295
<p>The problem:</p> <pre><code>&gt;&gt;&gt; a = dict(a=1,b=2 ) &gt;&gt;&gt; b = dict( b=3,c=2) &gt;&gt;&gt; c = ??? c = {'a': 1, 'b': 5, 'c': 2} </code></pre> <p>So, the idea is two add to dictionaries by int/float values in the shortest form. Here's one solution that I've devised, but I don't like it, cause it's long:</p> <pre><code>c = dict([(i,a.get(i,0) + b.get(i,0)) for i in set(a.keys()+b.keys())]) </code></pre> <p>I think there must be a shorter/concise solution (maybe something to do with reduce and operator module? itertools?)... Any ideas?</p> <p><hr /></p> <p>Update: I'm really hoping to find something more elegant like "reduce(operator.add, key = itemgetter(0), a+b)". (Obviously that isn't real code, but you should get the idea). But it seems that may be a dream.</p> <p><hr /></p> <p>Update: Still loking for more concise solutions. Maybe groupby can help? The solution I've come up with using "reduce"/"groupby" isn't actually concise:</p> <pre><code>from itertools import groupby from operator import itemgetter,add c = dict( [(i,reduce(add,map(itemgetter(1), v))) \ for i,v in groupby(sorted(a.items()+b.items()), itemgetter(0))] ) </code></pre>
9
2009-05-18T11:40:11Z
877,395
<p>If you want short code, you're there.</p> <p>If you want clean code, inherit from Ber's <code>defaultdict</code> and overload <code>__add__</code>:</p> <pre><code>from collections import defaultdict class summable(defaultdict): def __add__(self, rhs): new = summable() for i in (self.keys() + rhs.keys()): new[i] = self.get(i, 0) + rhs.get(i, 0) return new a = summable(int, a=1, b=2) b = summable(int, b=3, c=4) c = a + b print c </code></pre> <p>Gives:</p> <pre><code>&gt;&gt;&gt; defaultdict(None, {'a': 1, 'c': 4, 'b': 5}) &gt;&gt;&gt; </code></pre>
5
2009-05-18T12:05:28Z
[ "python", "code-golf", "dictionary" ]
python dict.add_by_value(dict_2)?
877,295
<p>The problem:</p> <pre><code>&gt;&gt;&gt; a = dict(a=1,b=2 ) &gt;&gt;&gt; b = dict( b=3,c=2) &gt;&gt;&gt; c = ??? c = {'a': 1, 'b': 5, 'c': 2} </code></pre> <p>So, the idea is two add to dictionaries by int/float values in the shortest form. Here's one solution that I've devised, but I don't like it, cause it's long:</p> <pre><code>c = dict([(i,a.get(i,0) + b.get(i,0)) for i in set(a.keys()+b.keys())]) </code></pre> <p>I think there must be a shorter/concise solution (maybe something to do with reduce and operator module? itertools?)... Any ideas?</p> <p><hr /></p> <p>Update: I'm really hoping to find something more elegant like "reduce(operator.add, key = itemgetter(0), a+b)". (Obviously that isn't real code, but you should get the idea). But it seems that may be a dream.</p> <p><hr /></p> <p>Update: Still loking for more concise solutions. Maybe groupby can help? The solution I've come up with using "reduce"/"groupby" isn't actually concise:</p> <pre><code>from itertools import groupby from operator import itemgetter,add c = dict( [(i,reduce(add,map(itemgetter(1), v))) \ for i,v in groupby(sorted(a.items()+b.items()), itemgetter(0))] ) </code></pre>
9
2009-05-18T11:40:11Z
878,168
<p>solving not in terms of "length" but performance, I'd do the following:</p> <pre><code>&gt;&gt;&gt; from collections import defaultdict &gt;&gt;&gt; def d_sum(a, b): d = defaultdict(int, a) for k, v in b.items(): d[k] += v return dict(d) &gt;&gt;&gt; a = {'a': 1, 'b': 2} &gt;&gt;&gt; b = {'c': 2, 'b': 3} &gt;&gt;&gt; d_sum(a, b) {'a': 1, 'c': 2, 'b': 5} </code></pre> <p>it's also py3k-compatible, unlike your original code.</p>
8
2009-05-18T15:00:51Z
[ "python", "code-golf", "dictionary" ]
python dict.add_by_value(dict_2)?
877,295
<p>The problem:</p> <pre><code>&gt;&gt;&gt; a = dict(a=1,b=2 ) &gt;&gt;&gt; b = dict( b=3,c=2) &gt;&gt;&gt; c = ??? c = {'a': 1, 'b': 5, 'c': 2} </code></pre> <p>So, the idea is two add to dictionaries by int/float values in the shortest form. Here's one solution that I've devised, but I don't like it, cause it's long:</p> <pre><code>c = dict([(i,a.get(i,0) + b.get(i,0)) for i in set(a.keys()+b.keys())]) </code></pre> <p>I think there must be a shorter/concise solution (maybe something to do with reduce and operator module? itertools?)... Any ideas?</p> <p><hr /></p> <p>Update: I'm really hoping to find something more elegant like "reduce(operator.add, key = itemgetter(0), a+b)". (Obviously that isn't real code, but you should get the idea). But it seems that may be a dream.</p> <p><hr /></p> <p>Update: Still loking for more concise solutions. Maybe groupby can help? The solution I've come up with using "reduce"/"groupby" isn't actually concise:</p> <pre><code>from itertools import groupby from operator import itemgetter,add c = dict( [(i,reduce(add,map(itemgetter(1), v))) \ for i,v in groupby(sorted(a.items()+b.items()), itemgetter(0))] ) </code></pre>
9
2009-05-18T11:40:11Z
878,746
<pre><code>def GenerateSum(): for k in set(a).union(b): yield k, a.get(k, 0) + b.get(k, 0) e = dict(GenerateSum()) print e </code></pre> <p>or, with a one liner:</p> <pre><code> print dict((k, a.get(k,0) + b.get(k,0)) for k in set(a).union(b)) </code></pre>
1
2009-05-18T17:05:09Z
[ "python", "code-golf", "dictionary" ]
python dict.add_by_value(dict_2)?
877,295
<p>The problem:</p> <pre><code>&gt;&gt;&gt; a = dict(a=1,b=2 ) &gt;&gt;&gt; b = dict( b=3,c=2) &gt;&gt;&gt; c = ??? c = {'a': 1, 'b': 5, 'c': 2} </code></pre> <p>So, the idea is two add to dictionaries by int/float values in the shortest form. Here's one solution that I've devised, but I don't like it, cause it's long:</p> <pre><code>c = dict([(i,a.get(i,0) + b.get(i,0)) for i in set(a.keys()+b.keys())]) </code></pre> <p>I think there must be a shorter/concise solution (maybe something to do with reduce and operator module? itertools?)... Any ideas?</p> <p><hr /></p> <p>Update: I'm really hoping to find something more elegant like "reduce(operator.add, key = itemgetter(0), a+b)". (Obviously that isn't real code, but you should get the idea). But it seems that may be a dream.</p> <p><hr /></p> <p>Update: Still loking for more concise solutions. Maybe groupby can help? The solution I've come up with using "reduce"/"groupby" isn't actually concise:</p> <pre><code>from itertools import groupby from operator import itemgetter,add c = dict( [(i,reduce(add,map(itemgetter(1), v))) \ for i,v in groupby(sorted(a.items()+b.items()), itemgetter(0))] ) </code></pre>
9
2009-05-18T11:40:11Z
1,009,430
<p>The first thing I think of is a bit more efficient and (IMO) a bit more elegant, but still too much typing. Actually, it's about equivalent to kcwu's.</p> <pre><code>c = reduce(lambda(d, k): [d.update({k: d.get(k, 0) + b[k]}), d][1], b, a.copy()) </code></pre> <p>It's really a shame that <code>dict.update</code> doesn't return <code>self</code>. I guess it's not the Python way. If it did, the <code>[..., d][1]</code> trick would be unnecessary.</p> <p><hr /></p> <blockquote> <p>Perl: "Easy things are easy, hard things are possible"</p> </blockquote> <pre><code>%a = (a =&gt; 1, b =&gt; 2); %b = (b =&gt; 3, c =&gt; 2); %c = (%a, map {$_ =&gt; $a{$_} + $b{$_}} keys %b); </code></pre> <blockquote> <p>Haskell: <s>"Easy things are hard, hard things are easy"</s> "Hard things are easy, the impossible just happened"</p> </blockquote> <pre><code>import qualified Data.Map as M a = M.fromList [('a', 1), ('b', 2)] b = M.fromList [('b', 3), ('c', 2)] c = M.unionWith (+) a b </code></pre>
3
2009-06-17T20:44:17Z
[ "python", "code-golf", "dictionary" ]
python dict.add_by_value(dict_2)?
877,295
<p>The problem:</p> <pre><code>&gt;&gt;&gt; a = dict(a=1,b=2 ) &gt;&gt;&gt; b = dict( b=3,c=2) &gt;&gt;&gt; c = ??? c = {'a': 1, 'b': 5, 'c': 2} </code></pre> <p>So, the idea is two add to dictionaries by int/float values in the shortest form. Here's one solution that I've devised, but I don't like it, cause it's long:</p> <pre><code>c = dict([(i,a.get(i,0) + b.get(i,0)) for i in set(a.keys()+b.keys())]) </code></pre> <p>I think there must be a shorter/concise solution (maybe something to do with reduce and operator module? itertools?)... Any ideas?</p> <p><hr /></p> <p>Update: I'm really hoping to find something more elegant like "reduce(operator.add, key = itemgetter(0), a+b)". (Obviously that isn't real code, but you should get the idea). But it seems that may be a dream.</p> <p><hr /></p> <p>Update: Still loking for more concise solutions. Maybe groupby can help? The solution I've come up with using "reduce"/"groupby" isn't actually concise:</p> <pre><code>from itertools import groupby from operator import itemgetter,add c = dict( [(i,reduce(add,map(itemgetter(1), v))) \ for i,v in groupby(sorted(a.items()+b.items()), itemgetter(0))] ) </code></pre>
9
2009-05-18T11:40:11Z
1,027,258
<h3>Comment for <a href="http://stackoverflow.com/questions/877295/python-dict-addbyvaluedict2/877395#877395">@John Pirie's answer</a>:</h3> <p>Here's implementation that doesn't use <code>(self.keys() + rhs.keys())</code>:</p> <pre><code>from collections import defaultdict class sumdict(defaultdict): def __add__(self, rhs): d = self.copy() d += rhs return d __radd__ = lambda self, lhs: self + lhs def __iadd__(self, rhs): for k, v in rhs.items(): self[k] += v return self a = sumdict(int, a=1, b=2) b = dict(b=3, c=4) c = b + a a += b assert a == c == {'a': 1, 'c': 4, 'b': 5} != b </code></pre>
2
2009-06-22T13:37:11Z
[ "python", "code-golf", "dictionary" ]
python dict.add_by_value(dict_2)?
877,295
<p>The problem:</p> <pre><code>&gt;&gt;&gt; a = dict(a=1,b=2 ) &gt;&gt;&gt; b = dict( b=3,c=2) &gt;&gt;&gt; c = ??? c = {'a': 1, 'b': 5, 'c': 2} </code></pre> <p>So, the idea is two add to dictionaries by int/float values in the shortest form. Here's one solution that I've devised, but I don't like it, cause it's long:</p> <pre><code>c = dict([(i,a.get(i,0) + b.get(i,0)) for i in set(a.keys()+b.keys())]) </code></pre> <p>I think there must be a shorter/concise solution (maybe something to do with reduce and operator module? itertools?)... Any ideas?</p> <p><hr /></p> <p>Update: I'm really hoping to find something more elegant like "reduce(operator.add, key = itemgetter(0), a+b)". (Obviously that isn't real code, but you should get the idea). But it seems that may be a dream.</p> <p><hr /></p> <p>Update: Still loking for more concise solutions. Maybe groupby can help? The solution I've come up with using "reduce"/"groupby" isn't actually concise:</p> <pre><code>from itertools import groupby from operator import itemgetter,add c = dict( [(i,reduce(add,map(itemgetter(1), v))) \ for i,v in groupby(sorted(a.items()+b.items()), itemgetter(0))] ) </code></pre>
9
2009-05-18T11:40:11Z
11,837,857
<p>Easiest to just use a <code>Counter</code></p> <pre><code>&gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; a = dict(a=1,b=2 ) &gt;&gt;&gt; b = dict( b=3,c=2) &gt;&gt;&gt; Counter(a)+Counter(b) Counter({'b': 5, 'c': 2, 'a': 1}) &gt;&gt;&gt; dict(Counter({'b': 5, 'c': 2, 'a': 1})) {'a': 1, 'c': 2, 'b': 5} </code></pre>
7
2012-08-07T00:42:22Z
[ "python", "code-golf", "dictionary" ]
try... except... except... : how to avoid repeating code
877,440
<ul> <li>I'd like to avoid writting <code>errorCount += 1</code> in more than one place.</li> <li>I'm looking for a better way than</li> </ul> <pre> success = False try: ... else: success = True finally: if success: storage.store.commit() else: storage.store.rollback() </pre> <ul> <li>I'm trying to avoid <code>store.rollback()</code> in every except clause.</li> </ul> <p>Any idea on how to do this?</p> <pre><code>count = 0 successCount = 0 errorCount = 0 for row in rows: success = False count += 1 newOrder = storage.RepeatedOrder() storage.store.add(newOrder) try: try: newOrder.customer = customers[row.customer_id] except KeyError: raise CustomerNotFoundError, (row.customer_id,) newOrder.nextDate = dates[row.weekday] _fillOrder(newOrder, row.id) except CustomerNotFoundError as e: errorCount += 1 print u"Error: Customer not found. order_id: {0}, customer_id: {1}".format(row.id, e.id) except ProductNotFoundError as e: errorCount += 1 print u"Error: Product not found. order_id: {0}, product_id: {1}".format(row.id, e.id) else: success = True successCount += 1 finally: if success: storage.store.commit() else: storage.store.rollback() print u"{0} of {1} repeated orders imported. {2} error(s).".format(successCount, count, errorCount) </code></pre>
3
2009-05-18T12:14:41Z
877,456
<p>You could simply wrap up your exception implementation inside an exception specific container class, that way you could also avoid all these explicit print calls (which may come in handy once you change your interface, e.g. when supporting a GUI), instead you would have a method like error(msg), which in turn could internally increase the error count accordingly. In other words, simply set up an external helper class that manages your exception handling stuff.</p>
2
2009-05-18T12:18:30Z
[ "python", "try-catch", "dry" ]
try... except... except... : how to avoid repeating code
877,440
<ul> <li>I'd like to avoid writting <code>errorCount += 1</code> in more than one place.</li> <li>I'm looking for a better way than</li> </ul> <pre> success = False try: ... else: success = True finally: if success: storage.store.commit() else: storage.store.rollback() </pre> <ul> <li>I'm trying to avoid <code>store.rollback()</code> in every except clause.</li> </ul> <p>Any idea on how to do this?</p> <pre><code>count = 0 successCount = 0 errorCount = 0 for row in rows: success = False count += 1 newOrder = storage.RepeatedOrder() storage.store.add(newOrder) try: try: newOrder.customer = customers[row.customer_id] except KeyError: raise CustomerNotFoundError, (row.customer_id,) newOrder.nextDate = dates[row.weekday] _fillOrder(newOrder, row.id) except CustomerNotFoundError as e: errorCount += 1 print u"Error: Customer not found. order_id: {0}, customer_id: {1}".format(row.id, e.id) except ProductNotFoundError as e: errorCount += 1 print u"Error: Product not found. order_id: {0}, product_id: {1}".format(row.id, e.id) else: success = True successCount += 1 finally: if success: storage.store.commit() else: storage.store.rollback() print u"{0} of {1} repeated orders imported. {2} error(s).".format(successCount, count, errorCount) </code></pre>
3
2009-05-18T12:14:41Z
877,462
<p>If you like cumulate the errors why you don't cumulate the errors? If you put the error messages on a list the size of the list gives the information you need. You can even postprocess something. You can decide easy if an error occured and print is called only at a single place</p>
0
2009-05-18T12:19:37Z
[ "python", "try-catch", "dry" ]
try... except... except... : how to avoid repeating code
877,440
<ul> <li>I'd like to avoid writting <code>errorCount += 1</code> in more than one place.</li> <li>I'm looking for a better way than</li> </ul> <pre> success = False try: ... else: success = True finally: if success: storage.store.commit() else: storage.store.rollback() </pre> <ul> <li>I'm trying to avoid <code>store.rollback()</code> in every except clause.</li> </ul> <p>Any idea on how to do this?</p> <pre><code>count = 0 successCount = 0 errorCount = 0 for row in rows: success = False count += 1 newOrder = storage.RepeatedOrder() storage.store.add(newOrder) try: try: newOrder.customer = customers[row.customer_id] except KeyError: raise CustomerNotFoundError, (row.customer_id,) newOrder.nextDate = dates[row.weekday] _fillOrder(newOrder, row.id) except CustomerNotFoundError as e: errorCount += 1 print u"Error: Customer not found. order_id: {0}, customer_id: {1}".format(row.id, e.id) except ProductNotFoundError as e: errorCount += 1 print u"Error: Product not found. order_id: {0}, product_id: {1}".format(row.id, e.id) else: success = True successCount += 1 finally: if success: storage.store.commit() else: storage.store.rollback() print u"{0} of {1} repeated orders imported. {2} error(s).".format(successCount, count, errorCount) </code></pre>
3
2009-05-18T12:14:41Z
877,467
<p>Well, according to this page, part 7.4:</p> <p><a href="http://docs.python.org/reference/compound%5Fstmts.html" rel="nofollow">http://docs.python.org/reference/compound_stmts.html</a></p> <p>This is possible with python ver. >= 2.6. I mean try..except..finally construction.</p>
0
2009-05-18T12:21:18Z
[ "python", "try-catch", "dry" ]
try... except... except... : how to avoid repeating code
877,440
<ul> <li>I'd like to avoid writting <code>errorCount += 1</code> in more than one place.</li> <li>I'm looking for a better way than</li> </ul> <pre> success = False try: ... else: success = True finally: if success: storage.store.commit() else: storage.store.rollback() </pre> <ul> <li>I'm trying to avoid <code>store.rollback()</code> in every except clause.</li> </ul> <p>Any idea on how to do this?</p> <pre><code>count = 0 successCount = 0 errorCount = 0 for row in rows: success = False count += 1 newOrder = storage.RepeatedOrder() storage.store.add(newOrder) try: try: newOrder.customer = customers[row.customer_id] except KeyError: raise CustomerNotFoundError, (row.customer_id,) newOrder.nextDate = dates[row.weekday] _fillOrder(newOrder, row.id) except CustomerNotFoundError as e: errorCount += 1 print u"Error: Customer not found. order_id: {0}, customer_id: {1}".format(row.id, e.id) except ProductNotFoundError as e: errorCount += 1 print u"Error: Product not found. order_id: {0}, product_id: {1}".format(row.id, e.id) else: success = True successCount += 1 finally: if success: storage.store.commit() else: storage.store.rollback() print u"{0} of {1} repeated orders imported. {2} error(s).".format(successCount, count, errorCount) </code></pre>
3
2009-05-18T12:14:41Z
877,483
<p>My suggestion would to write an <code>logError()</code> method that increments <code>errorCount</code> (make it a member variable) and prints the error. Since your exception code is similar, you could also shorten your code by doing this:</p> <pre><code>try: # something except (CustomerNotFoundError, ProductNotFoundError), e: logError(e) </code></pre> <p>You can print whatever you want based on <code>e</code>.</p> <p>Also, you don't need to track succeses: <code>successCount = len(rows) - errorCount</code></p>
3
2009-05-18T12:25:37Z
[ "python", "try-catch", "dry" ]
try... except... except... : how to avoid repeating code
877,440
<ul> <li>I'd like to avoid writting <code>errorCount += 1</code> in more than one place.</li> <li>I'm looking for a better way than</li> </ul> <pre> success = False try: ... else: success = True finally: if success: storage.store.commit() else: storage.store.rollback() </pre> <ul> <li>I'm trying to avoid <code>store.rollback()</code> in every except clause.</li> </ul> <p>Any idea on how to do this?</p> <pre><code>count = 0 successCount = 0 errorCount = 0 for row in rows: success = False count += 1 newOrder = storage.RepeatedOrder() storage.store.add(newOrder) try: try: newOrder.customer = customers[row.customer_id] except KeyError: raise CustomerNotFoundError, (row.customer_id,) newOrder.nextDate = dates[row.weekday] _fillOrder(newOrder, row.id) except CustomerNotFoundError as e: errorCount += 1 print u"Error: Customer not found. order_id: {0}, customer_id: {1}".format(row.id, e.id) except ProductNotFoundError as e: errorCount += 1 print u"Error: Product not found. order_id: {0}, product_id: {1}".format(row.id, e.id) else: success = True successCount += 1 finally: if success: storage.store.commit() else: storage.store.rollback() print u"{0} of {1} repeated orders imported. {2} error(s).".format(successCount, count, errorCount) </code></pre>
3
2009-05-18T12:14:41Z
877,485
<p>This look like a possible application of Python's new <code>with</code> statement. It allows to to unwind operations and release resources securely no matter what outcome a block of code had.</p> <p>Read about it in <a href="http://www.python.org/dev/peps/pep-0343/" rel="nofollow">PEP 343</a></p>
8
2009-05-18T12:25:52Z
[ "python", "try-catch", "dry" ]
What's the simplest way to extend a numpy array in 2 dimensions?
877,479
<p>I have a 2d array that looks like this:</p> <pre><code>XX xx </code></pre> <p>What's the most efficient way to add an extra row and column:</p> <pre><code>xxy xxy yyy </code></pre> <p>For bonus points, I'd like to also be able to knock out single rows and columns, so for example in the matrix below I'd like to be able to knock out all of the a's leaving only the x's - specifically I'm trying to delete the nth row and the nth column at the same time - and I want to be able to do this as quickly as possible:</p> <pre><code>xxaxx xxaxx aaaaa xxaxx xxaxx </code></pre>
31
2009-05-18T12:24:11Z
877,564
<p>The shortest in terms of lines of code i can think of is for the first question.</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; p = np.array([[1,2],[3,4]]) &gt;&gt;&gt; p = np.append(p, [[5,6]], 0) &gt;&gt;&gt; p = np.append(p, [[7],[8],[9]],1) &gt;&gt;&gt; p array([[1, 2, 7], [3, 4, 8], [5, 6, 9]]) </code></pre> <p>And the for the second question</p> <pre><code> p = np.array(range(20)) &gt;&gt;&gt; p.shape = (4,5) &gt;&gt;&gt; p array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19]]) &gt;&gt;&gt; n = 2 &gt;&gt;&gt; p = np.append(p[:n],p[n+1:],0) &gt;&gt;&gt; p = np.append(p[...,:n],p[...,n+1:],1) &gt;&gt;&gt; p array([[ 0, 1, 3, 4], [ 5, 6, 8, 9], [15, 16, 18, 19]]) </code></pre>
35
2009-05-18T12:47:07Z
[ "python", "arrays", "math", "numpy" ]
What's the simplest way to extend a numpy array in 2 dimensions?
877,479
<p>I have a 2d array that looks like this:</p> <pre><code>XX xx </code></pre> <p>What's the most efficient way to add an extra row and column:</p> <pre><code>xxy xxy yyy </code></pre> <p>For bonus points, I'd like to also be able to knock out single rows and columns, so for example in the matrix below I'd like to be able to knock out all of the a's leaving only the x's - specifically I'm trying to delete the nth row and the nth column at the same time - and I want to be able to do this as quickly as possible:</p> <pre><code>xxaxx xxaxx aaaaa xxaxx xxaxx </code></pre>
31
2009-05-18T12:24:11Z
5,650,582
<p><strong>A useful alternative answer to the first question, using the examples from</strong> tomeedee’s <strong>answer, would be to use numpy’s</strong> vstack <strong>and</strong> column_stack <strong>methods:</strong></p> <p>Given a matrix p,</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; p = np.array([ [1,2] , [3,4] ]) </code></pre> <p>an augmented matrix can be generated by:</p> <pre><code>&gt;&gt;&gt; p = np.vstack( [ p , [5 , 6] ] ) &gt;&gt;&gt; p = np.column_stack( [ p , [ 7 , 8 , 9 ] ] ) &gt;&gt;&gt; p array([[1, 2, 7], [3, 4, 8], [5, 6, 9]]) </code></pre> <p>These methods may be convenient in practice than np.append() as they allow 1D arrays to be appended to a matrix without any modification, in contrast to the following scenario:</p> <pre><code>&gt;&gt;&gt; p = np.array([ [ 1 , 2 ] , [ 3 , 4 ] , [ 5 , 6 ] ] ) &gt;&gt;&gt; p = np.append( p , [ 7 , 8 , 9 ] , 1 ) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python2.6/dist-packages/numpy/lib/function_base.py", line 3234, in append return concatenate((arr, values), axis=axis) ValueError: arrays must have same number of dimensions </code></pre> <p><strong>In answer to the second question, a nice way to remove rows and columns is to use logical array indexing as follows:</strong></p> <p>Given a matrix p,</p> <pre><code>&gt;&gt;&gt; p = np.arange( 20 ).reshape( ( 4 , 5 ) ) </code></pre> <p>suppose we want to remove row 1 and column 2:</p> <pre><code>&gt;&gt;&gt; r , c = 1 , 2 &gt;&gt;&gt; p = p [ np.arange( p.shape[0] ) != r , : ] &gt;&gt;&gt; p = p [ : , np.arange( p.shape[1] ) != c ] &gt;&gt;&gt; p array([[ 0, 1, 3, 4], [10, 11, 13, 14], [15, 16, 18, 19]]) </code></pre> <p>Note - for reformed Matlab users - if you wanted to do these in a one-liner you need to index twice:</p> <pre><code>&gt;&gt;&gt; p = np.arange( 20 ).reshape( ( 4 , 5 ) ) &gt;&gt;&gt; p = p [ np.arange( p.shape[0] ) != r , : ] [ : , np.arange( p.shape[1] ) != c ] </code></pre> <p>This technique can also be extended to remove <em>sets</em> of rows and columns, so if we wanted to remove rows 0 &amp; 2 and columns 1, 2 &amp; 3 we could use numpy's <strong>setdiff1d</strong> function to generate the desired logical index:</p> <pre><code>&gt;&gt;&gt; p = np.arange( 20 ).reshape( ( 4 , 5 ) ) &gt;&gt;&gt; r = [ 0 , 2 ] &gt;&gt;&gt; c = [ 1 , 2 , 3 ] &gt;&gt;&gt; p = p [ np.setdiff1d( np.arange( p.shape[0] ), r ) , : ] &gt;&gt;&gt; p = p [ : , np.setdiff1d( np.arange( p.shape[1] ) , c ) ] &gt;&gt;&gt; p array([[ 5, 9], [15, 19]]) </code></pre>
31
2011-04-13T14:04:28Z
[ "python", "arrays", "math", "numpy" ]
What's the simplest way to extend a numpy array in 2 dimensions?
877,479
<p>I have a 2d array that looks like this:</p> <pre><code>XX xx </code></pre> <p>What's the most efficient way to add an extra row and column:</p> <pre><code>xxy xxy yyy </code></pre> <p>For bonus points, I'd like to also be able to knock out single rows and columns, so for example in the matrix below I'd like to be able to knock out all of the a's leaving only the x's - specifically I'm trying to delete the nth row and the nth column at the same time - and I want to be able to do this as quickly as possible:</p> <pre><code>xxaxx xxaxx aaaaa xxaxx xxaxx </code></pre>
31
2009-05-18T12:24:11Z
7,096,433
<p>Answer to the first question:</p> <p>Use numpy.append.</p> <p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.append.html#numpy.append" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/generated/numpy.append.html#numpy.append</a></p> <p>Answer to the second question:</p> <p>Use numpy.delete</p> <p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.delete.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/generated/numpy.delete.html</a></p>
2
2011-08-17T16:41:26Z
[ "python", "arrays", "math", "numpy" ]
What's the simplest way to extend a numpy array in 2 dimensions?
877,479
<p>I have a 2d array that looks like this:</p> <pre><code>XX xx </code></pre> <p>What's the most efficient way to add an extra row and column:</p> <pre><code>xxy xxy yyy </code></pre> <p>For bonus points, I'd like to also be able to knock out single rows and columns, so for example in the matrix below I'd like to be able to knock out all of the a's leaving only the x's - specifically I'm trying to delete the nth row and the nth column at the same time - and I want to be able to do this as quickly as possible:</p> <pre><code>xxaxx xxaxx aaaaa xxaxx xxaxx </code></pre>
31
2009-05-18T12:24:11Z
14,139,115
<p>I find it much easier to "extend" via assigning in a bigger matrix. E.g.</p> <pre><code>import numpy as np p = np.array([[1,2], [3,4]]) g = np.array(range(20)) g.shape = (4,5) g[0:2, 0:2] = p </code></pre> <p>Here are the arrays:</p> <p><code>p</code></p> <pre><code> array([[1, 2], [3, 4]]) </code></pre> <p><code>g</code>:</p> <pre><code>array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19]]) </code></pre> <p>and the resulting <code>g</code> after assignment:</p> <pre><code> array([[ 1, 2, 2, 3, 4], [ 3, 4, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19]]) </code></pre>
4
2013-01-03T12:37:50Z
[ "python", "arrays", "math", "numpy" ]
What's the simplest way to extend a numpy array in 2 dimensions?
877,479
<p>I have a 2d array that looks like this:</p> <pre><code>XX xx </code></pre> <p>What's the most efficient way to add an extra row and column:</p> <pre><code>xxy xxy yyy </code></pre> <p>For bonus points, I'd like to also be able to knock out single rows and columns, so for example in the matrix below I'd like to be able to knock out all of the a's leaving only the x's - specifically I'm trying to delete the nth row and the nth column at the same time - and I want to be able to do this as quickly as possible:</p> <pre><code>xxaxx xxaxx aaaaa xxaxx xxaxx </code></pre>
31
2009-05-18T12:24:11Z
17,301,073
<p>maybe you need this.</p> <pre><code>&gt;&gt;&gt; x = np.array([11,22]) &gt;&gt;&gt; y = np.array([18,7,6]) &gt;&gt;&gt; z = np.array([1,3,5]) &gt;&gt;&gt; np.concatenate((x,y,z)) array([11, 22, 18, 7, 6, 1, 3, 5]) </code></pre>
0
2013-06-25T15:11:56Z
[ "python", "arrays", "math", "numpy" ]
What's the simplest way to extend a numpy array in 2 dimensions?
877,479
<p>I have a 2d array that looks like this:</p> <pre><code>XX xx </code></pre> <p>What's the most efficient way to add an extra row and column:</p> <pre><code>xxy xxy yyy </code></pre> <p>For bonus points, I'd like to also be able to knock out single rows and columns, so for example in the matrix below I'd like to be able to knock out all of the a's leaving only the x's - specifically I'm trying to delete the nth row and the nth column at the same time - and I want to be able to do this as quickly as possible:</p> <pre><code>xxaxx xxaxx aaaaa xxaxx xxaxx </code></pre>
31
2009-05-18T12:24:11Z
18,207,897
<p>Another elegant solution to the <strong>first question</strong> may be the <code>insert</code> command:</p> <pre><code>p = np.array([[1,2],[3,4]]) p = np.insert(p, 2, values=0, axis=1) # insert values before column 2 </code></pre> <p>Leads to:</p> <pre><code>array([[1, 2, 0], [3, 4, 0]]) </code></pre> <p><code>insert</code> may be slower than <code>append</code> but allows you to fill the whole row/column with one value easily.</p> <p>As for the <strong>second question</strong>, <code>delete</code> has been suggested before:</p> <pre><code>p = np.delete(p, 2, axis=1) </code></pre> <p>Which restores the original array again:</p> <pre><code>array([[1, 2], [3, 4]]) </code></pre>
6
2013-08-13T11:29:16Z
[ "python", "arrays", "math", "numpy" ]
What's the simplest way to extend a numpy array in 2 dimensions?
877,479
<p>I have a 2d array that looks like this:</p> <pre><code>XX xx </code></pre> <p>What's the most efficient way to add an extra row and column:</p> <pre><code>xxy xxy yyy </code></pre> <p>For bonus points, I'd like to also be able to knock out single rows and columns, so for example in the matrix below I'd like to be able to knock out all of the a's leaving only the x's - specifically I'm trying to delete the nth row and the nth column at the same time - and I want to be able to do this as quickly as possible:</p> <pre><code>xxaxx xxaxx aaaaa xxaxx xxaxx </code></pre>
31
2009-05-18T12:24:11Z
32,546,514
<p>You can use: </p> <pre><code>&gt;&gt;&gt; np.concatenate([array1, array2, ...]) </code></pre> <p>e.g.</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a = [[1, 2, 3],[10, 20, 30]] &gt;&gt;&gt; b = [[100,200,300]] &gt;&gt;&gt; a = np.array(a) # not necessary, but numpy objects prefered to built-in &gt;&gt;&gt; b = np.array(b) # "^ &gt;&gt;&gt; a array([[ 1, 2, 3], [10, 20, 30]]) &gt;&gt;&gt; b array([[100, 200, 300]]) &gt;&gt;&gt; c = np.concatenate([a,b]) &gt;&gt;&gt; c array([[ 1, 2, 3], [ 10, 20, 30], [100, 200, 300]]) &gt;&gt;&gt; print c [[ 1 2 3] [ 10 20 30] [100 200 300]] </code></pre> <p>~-+-~-+-~-+-~ </p> <p>Sometimes, you will come across trouble if a numpy array object is initialized with incomplete values for its shape property. This problem is fixed by assigning to the shape property the tuple: (array_length, element_length).</p> <p>Note: Here, 'array_length' and 'element_length' are integer parameters, which you substitute values in for. A 'tuple' is just a pair of numbers in parentheses.</p> <p>e.g.</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a = np.array([[1,2,3],[10,20,30]]) &gt;&gt;&gt; b = np.array([100,200,300]) # initialize b with incorrect dimensions &gt;&gt;&gt; a.shape (2, 3) &gt;&gt;&gt; b.shape (3,) &gt;&gt;&gt; c = np.concatenate([a,b]) Traceback (most recent call last): File "&lt;pyshell#191&gt;", line 1, in &lt;module&gt; c = np.concatenate([a,b]) ValueError: all the input arrays must have same number of dimensions &gt;&gt;&gt; b.shape = (1,3) &gt;&gt;&gt; c = np.concatenate([a,b]) &gt;&gt;&gt; c array([[ 1, 2, 3], [ 10, 20, 30], [100, 200, 300]]) </code></pre>
1
2015-09-13T05:08:32Z
[ "python", "arrays", "math", "numpy" ]
Fastest way to convert a Numpy array into a sparse dictionary?
877,578
<p>I'm interested in converting a numpy array into a sparse dictionary as quickly as possible. Let me elaborate:</p> <p>Given the array:</p> <pre><code>numpy.array([12,0,0,0,3,0,0,1]) </code></pre> <p>I wish to produce the dictionary:</p> <pre><code>{0:12, 4:3, 7:1} </code></pre> <p>As you can see, we are simply converting the sequence type into an explicit mapping from indices that are nonzero to their values.</p> <p>In order to make this a bit more interesting, I offer the following test harness to try out alternatives:</p> <pre><code>from timeit import Timer if __name__ == "__main__": s = "import numpy; from itertools import izip; from numpy import nonzero, flatnonzero; vector = numpy.random.poisson(0.1, size=10000);" ms = [ "f = flatnonzero(vector); dict( zip( f, vector[f] ) )" , "f = flatnonzero(vector); dict( izip( f, vector[f] ) )" , "f = nonzero(vector); dict( izip( f[0], vector[f] ) )" , "n = vector &gt; 0; i = numpy.arange(len(vector))[n]; v = vector[n]; dict(izip(i,v))" , "i = flatnonzero(vector); v = vector[vector &gt; 0]; dict(izip(i,v))" , "dict( zip( flatnonzero(vector), vector[flatnonzero(vector)] ) )" , "dict( zip( flatnonzero(vector), vector[nonzero(vector)] ) )" , "dict( (i, x) for i,x in enumerate(vector) if x &gt; 0);" ] for m in ms: print " %.2fs" % Timer(m, s).timeit(1000), m </code></pre> <p>I'm using a poisson distribution to simulate the sort of arrays I am interested in converting.</p> <p>Here are my results so far:</p> <pre><code> 0.78s f = flatnonzero(vector); dict( zip( f, vector[f] ) ) 0.73s f = flatnonzero(vector); dict( izip( f, vector[f] ) ) 0.71s f = nonzero(vector); dict( izip( f[0], vector[f] ) ) 0.67s n = vector &gt; 0; i = numpy.arange(len(vector))[n]; v = vector[n]; dict(izip(i,v)) 0.81s i = flatnonzero(vector); v = vector[vector &gt; 0]; dict(izip(i,v)) 1.01s dict( zip( flatnonzero(vector), vector[flatnonzero(vector)] ) ) 1.03s dict( zip( flatnonzero(vector), vector[nonzero(vector)] ) ) 4.90s dict( (i, x) for i,x in enumerate(vector) if x &gt; 0); </code></pre> <p>As you can see, the fastest solution I have found is</p> <pre><code>n = vector &gt; 0; i = numpy.arange(len(vector))[n] v = vector[n] dict(izip(i,v)) </code></pre> <p>Any faster way?</p> <p>Edit: The step</p> <pre><code>i = numpy.arange(len(vector))[n] </code></pre> <p>Seems particularly clumsy- generating an entire array before selecting only some elements, particularly when we know it might only be around 1/10 of the elements getting selected. I think this might still be improved. </p>
4
2009-05-18T12:52:21Z
878,138
<p>I wonder if chief time cost is resizing the dict as it grows.</p> <p>Would be nice if dict had a method (or instantiation option) to specify a start size; so if we knew it was going to be big, python could save time and just do one big mem alloc up front, rather than what I assume are additional allocs as we grow.</p>
2
2009-05-18T14:53:36Z
[ "python", "performance", "numpy" ]
Fastest way to convert a Numpy array into a sparse dictionary?
877,578
<p>I'm interested in converting a numpy array into a sparse dictionary as quickly as possible. Let me elaborate:</p> <p>Given the array:</p> <pre><code>numpy.array([12,0,0,0,3,0,0,1]) </code></pre> <p>I wish to produce the dictionary:</p> <pre><code>{0:12, 4:3, 7:1} </code></pre> <p>As you can see, we are simply converting the sequence type into an explicit mapping from indices that are nonzero to their values.</p> <p>In order to make this a bit more interesting, I offer the following test harness to try out alternatives:</p> <pre><code>from timeit import Timer if __name__ == "__main__": s = "import numpy; from itertools import izip; from numpy import nonzero, flatnonzero; vector = numpy.random.poisson(0.1, size=10000);" ms = [ "f = flatnonzero(vector); dict( zip( f, vector[f] ) )" , "f = flatnonzero(vector); dict( izip( f, vector[f] ) )" , "f = nonzero(vector); dict( izip( f[0], vector[f] ) )" , "n = vector &gt; 0; i = numpy.arange(len(vector))[n]; v = vector[n]; dict(izip(i,v))" , "i = flatnonzero(vector); v = vector[vector &gt; 0]; dict(izip(i,v))" , "dict( zip( flatnonzero(vector), vector[flatnonzero(vector)] ) )" , "dict( zip( flatnonzero(vector), vector[nonzero(vector)] ) )" , "dict( (i, x) for i,x in enumerate(vector) if x &gt; 0);" ] for m in ms: print " %.2fs" % Timer(m, s).timeit(1000), m </code></pre> <p>I'm using a poisson distribution to simulate the sort of arrays I am interested in converting.</p> <p>Here are my results so far:</p> <pre><code> 0.78s f = flatnonzero(vector); dict( zip( f, vector[f] ) ) 0.73s f = flatnonzero(vector); dict( izip( f, vector[f] ) ) 0.71s f = nonzero(vector); dict( izip( f[0], vector[f] ) ) 0.67s n = vector &gt; 0; i = numpy.arange(len(vector))[n]; v = vector[n]; dict(izip(i,v)) 0.81s i = flatnonzero(vector); v = vector[vector &gt; 0]; dict(izip(i,v)) 1.01s dict( zip( flatnonzero(vector), vector[flatnonzero(vector)] ) ) 1.03s dict( zip( flatnonzero(vector), vector[nonzero(vector)] ) ) 4.90s dict( (i, x) for i,x in enumerate(vector) if x &gt; 0); </code></pre> <p>As you can see, the fastest solution I have found is</p> <pre><code>n = vector &gt; 0; i = numpy.arange(len(vector))[n] v = vector[n] dict(izip(i,v)) </code></pre> <p>Any faster way?</p> <p>Edit: The step</p> <pre><code>i = numpy.arange(len(vector))[n] </code></pre> <p>Seems particularly clumsy- generating an entire array before selecting only some elements, particularly when we know it might only be around 1/10 of the elements getting selected. I think this might still be improved. </p>
4
2009-05-18T12:52:21Z
1,048,340
<p>Tried this?</p> <p>from numpy import where</p> <p>i = where(vector > 0)[0]</p>
0
2009-06-26T10:15:58Z
[ "python", "performance", "numpy" ]
Fastest way to convert a Numpy array into a sparse dictionary?
877,578
<p>I'm interested in converting a numpy array into a sparse dictionary as quickly as possible. Let me elaborate:</p> <p>Given the array:</p> <pre><code>numpy.array([12,0,0,0,3,0,0,1]) </code></pre> <p>I wish to produce the dictionary:</p> <pre><code>{0:12, 4:3, 7:1} </code></pre> <p>As you can see, we are simply converting the sequence type into an explicit mapping from indices that are nonzero to their values.</p> <p>In order to make this a bit more interesting, I offer the following test harness to try out alternatives:</p> <pre><code>from timeit import Timer if __name__ == "__main__": s = "import numpy; from itertools import izip; from numpy import nonzero, flatnonzero; vector = numpy.random.poisson(0.1, size=10000);" ms = [ "f = flatnonzero(vector); dict( zip( f, vector[f] ) )" , "f = flatnonzero(vector); dict( izip( f, vector[f] ) )" , "f = nonzero(vector); dict( izip( f[0], vector[f] ) )" , "n = vector &gt; 0; i = numpy.arange(len(vector))[n]; v = vector[n]; dict(izip(i,v))" , "i = flatnonzero(vector); v = vector[vector &gt; 0]; dict(izip(i,v))" , "dict( zip( flatnonzero(vector), vector[flatnonzero(vector)] ) )" , "dict( zip( flatnonzero(vector), vector[nonzero(vector)] ) )" , "dict( (i, x) for i,x in enumerate(vector) if x &gt; 0);" ] for m in ms: print " %.2fs" % Timer(m, s).timeit(1000), m </code></pre> <p>I'm using a poisson distribution to simulate the sort of arrays I am interested in converting.</p> <p>Here are my results so far:</p> <pre><code> 0.78s f = flatnonzero(vector); dict( zip( f, vector[f] ) ) 0.73s f = flatnonzero(vector); dict( izip( f, vector[f] ) ) 0.71s f = nonzero(vector); dict( izip( f[0], vector[f] ) ) 0.67s n = vector &gt; 0; i = numpy.arange(len(vector))[n]; v = vector[n]; dict(izip(i,v)) 0.81s i = flatnonzero(vector); v = vector[vector &gt; 0]; dict(izip(i,v)) 1.01s dict( zip( flatnonzero(vector), vector[flatnonzero(vector)] ) ) 1.03s dict( zip( flatnonzero(vector), vector[nonzero(vector)] ) ) 4.90s dict( (i, x) for i,x in enumerate(vector) if x &gt; 0); </code></pre> <p>As you can see, the fastest solution I have found is</p> <pre><code>n = vector &gt; 0; i = numpy.arange(len(vector))[n] v = vector[n] dict(izip(i,v)) </code></pre> <p>Any faster way?</p> <p>Edit: The step</p> <pre><code>i = numpy.arange(len(vector))[n] </code></pre> <p>Seems particularly clumsy- generating an entire array before selecting only some elements, particularly when we know it might only be around 1/10 of the elements getting selected. I think this might still be improved. </p>
4
2009-05-18T12:52:21Z
6,198,963
<p>use the sparse matrix in scipy as bridge:</p> <pre><code>from scipy.sparse import * import numpy a=numpy.array([12,0,0,0,3,0,0,1]) m=csr_matrix(a) d={} for i in m.nonzero()[1]: d[i]=m[0,i] print d </code></pre>
1
2011-06-01T09:24:59Z
[ "python", "performance", "numpy" ]
Fastest way to convert a Numpy array into a sparse dictionary?
877,578
<p>I'm interested in converting a numpy array into a sparse dictionary as quickly as possible. Let me elaborate:</p> <p>Given the array:</p> <pre><code>numpy.array([12,0,0,0,3,0,0,1]) </code></pre> <p>I wish to produce the dictionary:</p> <pre><code>{0:12, 4:3, 7:1} </code></pre> <p>As you can see, we are simply converting the sequence type into an explicit mapping from indices that are nonzero to their values.</p> <p>In order to make this a bit more interesting, I offer the following test harness to try out alternatives:</p> <pre><code>from timeit import Timer if __name__ == "__main__": s = "import numpy; from itertools import izip; from numpy import nonzero, flatnonzero; vector = numpy.random.poisson(0.1, size=10000);" ms = [ "f = flatnonzero(vector); dict( zip( f, vector[f] ) )" , "f = flatnonzero(vector); dict( izip( f, vector[f] ) )" , "f = nonzero(vector); dict( izip( f[0], vector[f] ) )" , "n = vector &gt; 0; i = numpy.arange(len(vector))[n]; v = vector[n]; dict(izip(i,v))" , "i = flatnonzero(vector); v = vector[vector &gt; 0]; dict(izip(i,v))" , "dict( zip( flatnonzero(vector), vector[flatnonzero(vector)] ) )" , "dict( zip( flatnonzero(vector), vector[nonzero(vector)] ) )" , "dict( (i, x) for i,x in enumerate(vector) if x &gt; 0);" ] for m in ms: print " %.2fs" % Timer(m, s).timeit(1000), m </code></pre> <p>I'm using a poisson distribution to simulate the sort of arrays I am interested in converting.</p> <p>Here are my results so far:</p> <pre><code> 0.78s f = flatnonzero(vector); dict( zip( f, vector[f] ) ) 0.73s f = flatnonzero(vector); dict( izip( f, vector[f] ) ) 0.71s f = nonzero(vector); dict( izip( f[0], vector[f] ) ) 0.67s n = vector &gt; 0; i = numpy.arange(len(vector))[n]; v = vector[n]; dict(izip(i,v)) 0.81s i = flatnonzero(vector); v = vector[vector &gt; 0]; dict(izip(i,v)) 1.01s dict( zip( flatnonzero(vector), vector[flatnonzero(vector)] ) ) 1.03s dict( zip( flatnonzero(vector), vector[nonzero(vector)] ) ) 4.90s dict( (i, x) for i,x in enumerate(vector) if x &gt; 0); </code></pre> <p>As you can see, the fastest solution I have found is</p> <pre><code>n = vector &gt; 0; i = numpy.arange(len(vector))[n] v = vector[n] dict(izip(i,v)) </code></pre> <p>Any faster way?</p> <p>Edit: The step</p> <pre><code>i = numpy.arange(len(vector))[n] </code></pre> <p>Seems particularly clumsy- generating an entire array before selecting only some elements, particularly when we know it might only be around 1/10 of the elements getting selected. I think this might still be improved. </p>
4
2009-05-18T12:52:21Z
26,672,912
<pre><code>&gt;&gt;&gt; a=np.array([12,0,0,0,3,0,0,1]) &gt;&gt;&gt; {i:a[i] for i in np.nonzero(a)[0]} {0: 12, 4: 3, 7: 1} </code></pre>
2
2014-10-31T10:52:45Z
[ "python", "performance", "numpy" ]
Fastest way to convert a Numpy array into a sparse dictionary?
877,578
<p>I'm interested in converting a numpy array into a sparse dictionary as quickly as possible. Let me elaborate:</p> <p>Given the array:</p> <pre><code>numpy.array([12,0,0,0,3,0,0,1]) </code></pre> <p>I wish to produce the dictionary:</p> <pre><code>{0:12, 4:3, 7:1} </code></pre> <p>As you can see, we are simply converting the sequence type into an explicit mapping from indices that are nonzero to their values.</p> <p>In order to make this a bit more interesting, I offer the following test harness to try out alternatives:</p> <pre><code>from timeit import Timer if __name__ == "__main__": s = "import numpy; from itertools import izip; from numpy import nonzero, flatnonzero; vector = numpy.random.poisson(0.1, size=10000);" ms = [ "f = flatnonzero(vector); dict( zip( f, vector[f] ) )" , "f = flatnonzero(vector); dict( izip( f, vector[f] ) )" , "f = nonzero(vector); dict( izip( f[0], vector[f] ) )" , "n = vector &gt; 0; i = numpy.arange(len(vector))[n]; v = vector[n]; dict(izip(i,v))" , "i = flatnonzero(vector); v = vector[vector &gt; 0]; dict(izip(i,v))" , "dict( zip( flatnonzero(vector), vector[flatnonzero(vector)] ) )" , "dict( zip( flatnonzero(vector), vector[nonzero(vector)] ) )" , "dict( (i, x) for i,x in enumerate(vector) if x &gt; 0);" ] for m in ms: print " %.2fs" % Timer(m, s).timeit(1000), m </code></pre> <p>I'm using a poisson distribution to simulate the sort of arrays I am interested in converting.</p> <p>Here are my results so far:</p> <pre><code> 0.78s f = flatnonzero(vector); dict( zip( f, vector[f] ) ) 0.73s f = flatnonzero(vector); dict( izip( f, vector[f] ) ) 0.71s f = nonzero(vector); dict( izip( f[0], vector[f] ) ) 0.67s n = vector &gt; 0; i = numpy.arange(len(vector))[n]; v = vector[n]; dict(izip(i,v)) 0.81s i = flatnonzero(vector); v = vector[vector &gt; 0]; dict(izip(i,v)) 1.01s dict( zip( flatnonzero(vector), vector[flatnonzero(vector)] ) ) 1.03s dict( zip( flatnonzero(vector), vector[nonzero(vector)] ) ) 4.90s dict( (i, x) for i,x in enumerate(vector) if x &gt; 0); </code></pre> <p>As you can see, the fastest solution I have found is</p> <pre><code>n = vector &gt; 0; i = numpy.arange(len(vector))[n] v = vector[n] dict(izip(i,v)) </code></pre> <p>Any faster way?</p> <p>Edit: The step</p> <pre><code>i = numpy.arange(len(vector))[n] </code></pre> <p>Seems particularly clumsy- generating an entire array before selecting only some elements, particularly when we know it might only be around 1/10 of the elements getting selected. I think this might still be improved. </p>
4
2009-05-18T12:52:21Z
26,682,853
<p>The following seems to be a significant improvement:</p> <pre><code>i = np.flatnonzero(vector) dict.fromkeys(i.tolist(), vector[i].tolist()) </code></pre> <p>Timing:</p> <pre><code>import numpy as np from itertools import izip vector = np.random.poisson(0.1, size=10000) %timeit f = np.flatnonzero(vector); dict( izip( f, vector[f] ) ) # 1000 loops, best of 3: 951 µs per loop %timeit f = np.flatnonzero(vector); dict.fromkeys(f.tolist(), vector[f].tolist()) # 1000 loops, best of 3: 419 µs per loop </code></pre> <p>I also tried <code>scipy.sparse.dok_matrix</code> and <code>pandas.DataFrame.to_dict</code> but in my testing they were slower than the original.</p>
0
2014-10-31T20:24:31Z
[ "python", "performance", "numpy" ]
How should I return interesting values from a with-statement?
877,709
<p>Is there a better way than using globals to get interesting values from a context manager?</p> <pre><code>@contextmanager def transaction(): global successCount global errorCount try: yield except: storage.store.rollback() errorCount += 1 else: storage.store.commit() successCount += 1 </code></pre> <p>Other possibilities:</p> <ul> <li><h3>singletons</h3> <p>sort of globals...</p></li> <li><h3>tuple as an argument to the context manager</h3> <p>makes the function more specific to a problem /less reusable</p></li> <li><h3>instance that holds the specific attributes as an argument to the context manager</h3> <p>same problems as the tuple, but more legible</p></li> <li><h3>raise an exception at the end of the context manager holding the values.</h3> <p>really bad idea</p></li> </ul>
2
2009-05-18T13:20:15Z
877,747
<p>See <a href="http://docs.python.org/reference/datamodel.html#context-managers" rel="nofollow">http://docs.python.org/reference/datamodel.html#context-managers</a></p> <p>Create a class which holds the success and error counts, and which implements the <code>__enter__</code> and <code>__exit__</code> methods.</p>
6
2009-05-18T13:31:38Z
[ "python", "with-statement", "contextmanager" ]
How should I return interesting values from a with-statement?
877,709
<p>Is there a better way than using globals to get interesting values from a context manager?</p> <pre><code>@contextmanager def transaction(): global successCount global errorCount try: yield except: storage.store.rollback() errorCount += 1 else: storage.store.commit() successCount += 1 </code></pre> <p>Other possibilities:</p> <ul> <li><h3>singletons</h3> <p>sort of globals...</p></li> <li><h3>tuple as an argument to the context manager</h3> <p>makes the function more specific to a problem /less reusable</p></li> <li><h3>instance that holds the specific attributes as an argument to the context manager</h3> <p>same problems as the tuple, but more legible</p></li> <li><h3>raise an exception at the end of the context manager holding the values.</h3> <p>really bad idea</p></li> </ul>
2
2009-05-18T13:20:15Z
877,837
<p>I still think you should be creating a class to hold you error/success counts, as I said in you <a href="http://stackoverflow.com/questions/877440/try-except-except-how-to-avoid-repeating-code">last question</a>. I'm guessing you have your own class, so just add something like this to it:</p> <pre><code>class transaction: def __init__(self): self.errorCount = 0 self.successCount = 0 def __exit__(self, type, value, traceback): if type: storage.store.rollback() self.errorCount += 1 else: storage.store.commit() self.successCount += 1 </code></pre> <p>(<code>type</code> is None if there are no exceptions once invoking the <code>contextmanager</code>)</p> <p>And then you probably are already using this somewhere, which will invoke the <code>contextmanager</code> and run your <code>__exit__()</code> code. <strong>Edit:</strong> As Eli commented, only create a new transaction instance when you want to reset the coutners.</p> <pre><code>t = transaction() for q in queries: with t: t.execute(q) </code></pre>
2
2009-05-18T13:49:53Z
[ "python", "with-statement", "contextmanager" ]
How should I return interesting values from a with-statement?
877,709
<p>Is there a better way than using globals to get interesting values from a context manager?</p> <pre><code>@contextmanager def transaction(): global successCount global errorCount try: yield except: storage.store.rollback() errorCount += 1 else: storage.store.commit() successCount += 1 </code></pre> <p>Other possibilities:</p> <ul> <li><h3>singletons</h3> <p>sort of globals...</p></li> <li><h3>tuple as an argument to the context manager</h3> <p>makes the function more specific to a problem /less reusable</p></li> <li><h3>instance that holds the specific attributes as an argument to the context manager</h3> <p>same problems as the tuple, but more legible</p></li> <li><h3>raise an exception at the end of the context manager holding the values.</h3> <p>really bad idea</p></li> </ul>
2
2009-05-18T13:20:15Z
877,999
<p>"tuple as an argument to the context manager</p> <p>makes the function more specific to a problem /less reusable"</p> <p>False.</p> <p>This makes the context manager retain state.</p> <p>If you don't implement anything more than this, it will be reusable.</p> <p>However, you can't actually use a tuple because it's immutable. You need some mutable collection. Dictionaries and class definitions come to mind.</p> <p>Consequently, the recommended implementation is</p> <p>"instance that holds the specific attributes as an argument to the context manager"</p> <p>A simple class definition with two attributes is all you need. However, your transaction status is stateful and you need to retain state somewhere.</p> <pre><code>class Counters(dict): SUCCEED= 0 FAIL= 1 def __init__( self ): self[ self.SUCCEED ]= 0 self[ self.FAIL ]= 0 def increment( self, status ): self[status] += 1 class Transaction(object): def __init__( self, worker, counters ): self.worker= worker self.counters= counters def __enter__( self ): self.counters.status= None def process( self, *args, **kw ): status= self.worker.execute( *args, **kw ) self.counters.increment( status ) def __exit__( self ): pass counts= Counters() for q in queryList: with Transaction(execQuery,counts) as t: t.process( q ) print counts </code></pre>
-1
2009-05-18T14:21:02Z
[ "python", "with-statement", "contextmanager" ]
Resumable File Upload
878,143
<p>I am in the design phase of a file upload service that allows users to upload very large zip files to our server as well as updates our database with the data. Since the files are large (About 300mb) we want to allow the user to limit the amount of bandwidth they want to use for uploading. They should also be able to pause and resume the transfer, and it should recover from a system reboot. The user also needs to be authenticated in our MSSQL database to ensure that they have permission to upload the file and make changes to our database. </p> <p>My question is, what is the best technology to do this? We would like to minimize the amount of development required, but the only thing that I can think of now that would allow us to do this would be to create a client and server app from scratch in something like python, java or c#. Is there an existing technology available that will allow us to do this? </p>
5
2009-05-18T14:56:04Z
878,154
<p>What's wrong with FTP? The protocol supports reusability and there are lots and lots of clients.</p>
4
2009-05-18T14:58:31Z
[ "c#", "java", "python", "design" ]
Resumable File Upload
878,143
<p>I am in the design phase of a file upload service that allows users to upload very large zip files to our server as well as updates our database with the data. Since the files are large (About 300mb) we want to allow the user to limit the amount of bandwidth they want to use for uploading. They should also be able to pause and resume the transfer, and it should recover from a system reboot. The user also needs to be authenticated in our MSSQL database to ensure that they have permission to upload the file and make changes to our database. </p> <p>My question is, what is the best technology to do this? We would like to minimize the amount of development required, but the only thing that I can think of now that would allow us to do this would be to create a client and server app from scratch in something like python, java or c#. Is there an existing technology available that will allow us to do this? </p>
5
2009-05-18T14:56:04Z
878,160
<p>On client side, flash; On server side, whatever (it wouldn't make any difference).</p> <p>No existing technologies (except for using FTP or something).</p>
0
2009-05-18T14:59:35Z
[ "c#", "java", "python", "design" ]
Resumable File Upload
878,143
<p>I am in the design phase of a file upload service that allows users to upload very large zip files to our server as well as updates our database with the data. Since the files are large (About 300mb) we want to allow the user to limit the amount of bandwidth they want to use for uploading. They should also be able to pause and resume the transfer, and it should recover from a system reboot. The user also needs to be authenticated in our MSSQL database to ensure that they have permission to upload the file and make changes to our database. </p> <p>My question is, what is the best technology to do this? We would like to minimize the amount of development required, but the only thing that I can think of now that would allow us to do this would be to create a client and server app from scratch in something like python, java or c#. Is there an existing technology available that will allow us to do this? </p>
5
2009-05-18T14:56:04Z
878,250
<p>There are quite a few upload controls for this you should be able to Google. There are a few on this <a href="http://thin-slice-upload.qarchive.org/" rel="nofollow">download page</a>.</p> <p>Another work around is to have your clients install a Firefox FTP plugin or write a Firefox plugin yourself but FTP is by far the easiest way to boot.</p>
4
2009-05-18T15:16:20Z
[ "c#", "java", "python", "design" ]
Resumable File Upload
878,143
<p>I am in the design phase of a file upload service that allows users to upload very large zip files to our server as well as updates our database with the data. Since the files are large (About 300mb) we want to allow the user to limit the amount of bandwidth they want to use for uploading. They should also be able to pause and resume the transfer, and it should recover from a system reboot. The user also needs to be authenticated in our MSSQL database to ensure that they have permission to upload the file and make changes to our database. </p> <p>My question is, what is the best technology to do this? We would like to minimize the amount of development required, but the only thing that I can think of now that would allow us to do this would be to create a client and server app from scratch in something like python, java or c#. Is there an existing technology available that will allow us to do this? </p>
5
2009-05-18T14:56:04Z
7,661,871
<p>I found 2 more possibilities</p> <ul> <li><p><strong>Microsoft Background Intelligent Transfer Service (BITS)</strong>:</p> <p><strong>Has</strong>: up and download, large files, encrypted (vis https), resumable (even auto resuming as long as the user is logged in), manual pause and resume, authentication (via https again), wrapper for .NET, foreground or background priority, ...</p> <p><strong>Not</strong>: bandwidth throttling, file verification (only filesize), compression</p></li> <li><p><strong>rsync</strong>:</p> <p><strong>Has</strong>: unidirectional transfer, large files, resume of partial uploads (and pause via stop), verification, encryption (via ssh, stunnel), compression, usable c library (librsync by Martin Pool [<a href="http://sourceforge.net/projects/librsync/" rel="nofollow">1</a>],[<a href="http://librsync.sourcefrog.net/" rel="nofollow">2</a>])</p> <p><strong>Not</strong>: good windows compability (only via cygwin or cwrsync), commercially usable (GPL)</p></li> </ul> <p>Anybody found something else in C#?</p>
0
2011-10-05T13:16:44Z
[ "c#", "java", "python", "design" ]
Resumable File Upload
878,143
<p>I am in the design phase of a file upload service that allows users to upload very large zip files to our server as well as updates our database with the data. Since the files are large (About 300mb) we want to allow the user to limit the amount of bandwidth they want to use for uploading. They should also be able to pause and resume the transfer, and it should recover from a system reboot. The user also needs to be authenticated in our MSSQL database to ensure that they have permission to upload the file and make changes to our database. </p> <p>My question is, what is the best technology to do this? We would like to minimize the amount of development required, but the only thing that I can think of now that would allow us to do this would be to create a client and server app from scratch in something like python, java or c#. Is there an existing technology available that will allow us to do this? </p>
5
2009-05-18T14:56:04Z
18,015,229
<p>There's an example of using HTML5 to create a resumable large file upload, might be helpful.</p> <p><a href="http://net.tutsplus.com/tutorials/javascript-ajax/how-to-create-a-resumable-video-uploade-in-node-js/" rel="nofollow">http://net.tutsplus.com/tutorials/javascript-ajax/how-to-create-a-resumable-video-uploade-in-node-js/</a></p>
0
2013-08-02T10:58:38Z
[ "c#", "java", "python", "design" ]
Resumable File Upload
878,143
<p>I am in the design phase of a file upload service that allows users to upload very large zip files to our server as well as updates our database with the data. Since the files are large (About 300mb) we want to allow the user to limit the amount of bandwidth they want to use for uploading. They should also be able to pause and resume the transfer, and it should recover from a system reboot. The user also needs to be authenticated in our MSSQL database to ensure that they have permission to upload the file and make changes to our database. </p> <p>My question is, what is the best technology to do this? We would like to minimize the amount of development required, but the only thing that I can think of now that would allow us to do this would be to create a client and server app from scratch in something like python, java or c#. Is there an existing technology available that will allow us to do this? </p>
5
2009-05-18T14:56:04Z
30,990,243
<p>I'm surprised no one has mentioned torrent files. They can also be packaged into a script that then triggers something to execute.</p>
0
2015-06-22T21:35:53Z
[ "c#", "java", "python", "design" ]
PyImport_Import vs import
878,439
<p>I've tried to replace </p> <pre><code>PyRun_SimpleString("import Pootle"); </code></pre> <p>with</p> <pre><code>PyObject *obj = PyString_FromString("Pootle"); PyImport_Import(obj); Py_DECREF(obj); </code></pre> <p>after initialising the module Pootle in some C code. The first seems to make the name <code>Pootle</code> available to subsequent <code>PyRun_SimpleString</code> calls, but the second doesn't.</p> <p>Could someone please explain the difference to me? Is there a way to do what the first does with C API calls?</p> <p>Thanks</p>
1
2009-05-18T15:56:27Z
878,790
<p>All the <code>PyImport_Import</code> call does is return a reference to the module -- it doesn't make such a reference available to other parts of the program. So, if you want <code>PyRun_SimpleString</code> to see your new imported module, you need to add it manually.</p> <p><code>PyRun_SimpleString</code> works automatically in the <code>__main__</code> module namespace. Without paying a lot of attention to error checking (be wary of NULL returns!), this is a general outline: </p> <pre><code>PyObject *main = PyImport_AddModule("__main__"); PyObject *obj = PyString_FromString("Pootle"); PyObject *pootle = PyImport_Import(obj); PyObject_SetAttrString(main, "Pootle", pootle); Py_DECREF(obj); Py_XDECREF(pootle); </code></pre>
3
2009-05-18T17:11:32Z
[ "python", "c", "import" ]
What is the Python equivalent to JDBC DatabaseMetaData?
878,737
<p>What is the Python equivalent to <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/sql/DatabaseMetaData.html" rel="nofollow">DatabaseMetaData</a></p>
3
2009-05-18T17:03:24Z
878,858
<p>If your willing to use ODBC for data access then you could use pyodbc, <a href="http://code.google.com/p/pyodbc/wiki/Features" rel="nofollow">http://code.google.com/p/pyodbc/wiki/Features</a>. Pyodbc allows you to call functions like SQLTables, which is equivalent to the JDBC getTables function. The JDBC and ODBC functions to get to metadata are extremely similar.</p>
0
2009-05-18T17:28:03Z
[ "python", "jdbc", "database-metadata" ]
What is the Python equivalent to JDBC DatabaseMetaData?
878,737
<p>What is the Python equivalent to <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/sql/DatabaseMetaData.html" rel="nofollow">DatabaseMetaData</a></p>
3
2009-05-18T17:03:24Z
879,008
<p>This is not a python-specific answer; in fact I don't know if Python data drivers have this sort of thing. But maybe this info will help. </p> <p>The ANSI SQL-92 and SQL-99 Standard requires the <a href="http://en.wikipedia.org/wiki/Information%5FSchema">INFORMATION_SCHEMA schema</a>, which stores information regarding the tables in a catalog. </p> <p>The metadata you seek can be retrieved with a query on views in that schema. </p> <p>for example:</p> <pre><code>select column_name, is_nullable, data_type, character_maximum_length as maxlen from information_schema.columns where table_name = 'Products' </code></pre> <p>Not all databases implement that part of the standard. Oracle, for example, does not. </p> <p>Fortunately, there are also database-specific tables that store that kind of info. </p> <p>While Microsoft SQL Server supports the Information_Schema thing, there are also SQL Server-specific tables that give more metadata information. These are <code>[CatalogName].dbo.sysobjects</code> and <code>[CatalogName].dbo.sysolumns</code>. Similar queries on these tables will give you the metadata you seek. Example:</p> <pre><code>select * from [CatalogName].dbo.syscolumns where id = (Select id from [CatalogName].dbo.sysobjects where name = 'Products') </code></pre> <p>In Oracle, the ALL_TAB_COLUMNS table can give you the information: </p> <pre><code>select column_name, data_type, data_length, data_precision, data_scale from ALL_TAB_COLUMNS where table_name = 'EMP'; </code></pre> <p>Whether you query the standard views or the db-specific views, you don't need ODBC to do these queries - you can use whatever db connection you have available for operational data, subject to security approvals of course.</p>
6
2009-05-18T17:59:08Z
[ "python", "jdbc", "database-metadata" ]
Why return NotImplemented instead of raising NotImplementedError
878,943
<p>Python has a singleton called <a href="https://docs.python.org/2/library/constants.html#NotImplemented"><code>NotImplemented</code></a>. </p> <p>Why would someone want to ever return <code>NotImplemented</code> instead of raising the <a href="https://docs.python.org/2/library/exceptions.html#exceptions.NotImplementedError"><code>NotImplementedError</code></a> exception? Won't it just make it harder to find bugs, such as code that executes invalid methods?</p>
134
2009-05-18T17:43:40Z
878,985
<p>My guess would be performance. In a situation like rich comparisons, where you could be doing lots of operations in a short time, setting up and handling lots of exceptions could take a lot longer than simply returning a <code>NotImplemented</code> value.</p>
9
2009-05-18T17:54:03Z
[ "python" ]
Why return NotImplemented instead of raising NotImplementedError
878,943
<p>Python has a singleton called <a href="https://docs.python.org/2/library/constants.html#NotImplemented"><code>NotImplemented</code></a>. </p> <p>Why would someone want to ever return <code>NotImplemented</code> instead of raising the <a href="https://docs.python.org/2/library/exceptions.html#exceptions.NotImplementedError"><code>NotImplementedError</code></a> exception? Won't it just make it harder to find bugs, such as code that executes invalid methods?</p>
134
2009-05-18T17:43:40Z
879,003
<p>There are functions that raise Exceptions and functions that do not, <code>return NotImplemented</code> could be for the latter.... it really depends on the programmer/design. That's why they are both there for use.</p>
-2
2009-05-18T17:58:00Z
[ "python" ]
Why return NotImplemented instead of raising NotImplementedError
878,943
<p>Python has a singleton called <a href="https://docs.python.org/2/library/constants.html#NotImplemented"><code>NotImplemented</code></a>. </p> <p>Why would someone want to ever return <code>NotImplemented</code> instead of raising the <a href="https://docs.python.org/2/library/exceptions.html#exceptions.NotImplementedError"><code>NotImplementedError</code></a> exception? Won't it just make it harder to find bugs, such as code that executes invalid methods?</p>
134
2009-05-18T17:43:40Z
879,005
<p>It's because <code>__lt__()</code> and related comparison methods are quite commonly used indirectly in list sorts and such. Sometimes the algorithm will choose to try another way or pick a default winner. Raising an exception would break out of the sort unless caught, whereas <code>NotImplemented</code> doesn't get raised and can be used in further tests.</p> <p><a href="http://jcalderone.livejournal.com/32837.html">http://jcalderone.livejournal.com/32837.html</a></p> <p>To summarise that link:</p> <blockquote> <p>"<code>NotImplemented</code> signals to the runtime that it should ask someone else to satisfy the operation. In the expression <code>a == b</code>, if <code>a.__eq__(b)</code> returns <code>NotImplemented</code>, then Python tries <code>b.__eq__(a)</code>. If <code>b</code> knows enough to return <code>True</code> or <code>False</code>, then the expression can succeed. If it doesn't, then the runtime will fall back to the built-in behavior (which is based on identity for <code>==</code> and <code>!=</code>)."</p> </blockquote>
149
2009-05-18T17:58:32Z
[ "python" ]
Windows cmd encoding change causes Python crash
878,972
<p>First I change Windows CMD encoding to utf-8 and run Python interpreter:</p> <pre><code>chcp 65001 python </code></pre> <p>Then I try to print a unicode sting inside it and when i do this Python crashes in a peculiar way (I just get a cmd prompt in the same window). </p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; print u'ëèæîð'.encode(sys.stdin.encoding) </code></pre> <p>Any ideas why it happens and how to make it work?</p> <p><b>UPD</b>: <code>sys.stdin.encoding</code> returns <code>'cp65001'</code></p> <p><b>UPD2</b>: It just came to me that the issue might be connected with the fact that utf-8 uses <a href="http://en.wikipedia.org/wiki/Multi-byte_character_set" rel="nofollow">multi-byte character set</a> (kcwu made a good point on that). I tried running the whole example with 'windows-1250' and got 'ëeaî?'. Windows-1250 uses single-character set so it worked for those characters it understands. However I still have no idea how to make 'utf-8' work here.</p> <p><b>UPD3</b>: Oh, I found out it is a <a href="http://bugs.python.org/issue1602" rel="nofollow">known Python bug</a>. I guess what happens is that Python copies the cmd encoding as 'cp65001 to sys.stdin.encoding and tries to apply it to all the input. Since it fails to understand 'cp65001' it crashes on any input that contains non-ascii characters.</p>
38
2009-05-18T17:52:10Z
879,058
<p>This is because "code page" of cmd is different to "mbcs" of system. Although you changed the "code page", python (actually, windows) still think your "mbcs" doesn't change.</p>
2
2009-05-18T18:12:57Z
[ "python", "windows", "unicode", "encoding", "cmd" ]
Windows cmd encoding change causes Python crash
878,972
<p>First I change Windows CMD encoding to utf-8 and run Python interpreter:</p> <pre><code>chcp 65001 python </code></pre> <p>Then I try to print a unicode sting inside it and when i do this Python crashes in a peculiar way (I just get a cmd prompt in the same window). </p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; print u'ëèæîð'.encode(sys.stdin.encoding) </code></pre> <p>Any ideas why it happens and how to make it work?</p> <p><b>UPD</b>: <code>sys.stdin.encoding</code> returns <code>'cp65001'</code></p> <p><b>UPD2</b>: It just came to me that the issue might be connected with the fact that utf-8 uses <a href="http://en.wikipedia.org/wiki/Multi-byte_character_set" rel="nofollow">multi-byte character set</a> (kcwu made a good point on that). I tried running the whole example with 'windows-1250' and got 'ëeaî?'. Windows-1250 uses single-character set so it worked for those characters it understands. However I still have no idea how to make 'utf-8' work here.</p> <p><b>UPD3</b>: Oh, I found out it is a <a href="http://bugs.python.org/issue1602" rel="nofollow">known Python bug</a>. I guess what happens is that Python copies the cmd encoding as 'cp65001 to sys.stdin.encoding and tries to apply it to all the input. Since it fails to understand 'cp65001' it crashes on any input that contains non-ascii characters.</p>
38
2009-05-18T17:52:10Z
879,087
<p>Do you want Python to encode to UTF-8?</p> <pre><code>&gt;&gt;&gt;print u'ëèæîð'.encode('utf-8') ëèæîð </code></pre> <p>Python will not recognize cp65001 as UTF-8. </p>
1
2009-05-18T18:21:09Z
[ "python", "windows", "unicode", "encoding", "cmd" ]
Windows cmd encoding change causes Python crash
878,972
<p>First I change Windows CMD encoding to utf-8 and run Python interpreter:</p> <pre><code>chcp 65001 python </code></pre> <p>Then I try to print a unicode sting inside it and when i do this Python crashes in a peculiar way (I just get a cmd prompt in the same window). </p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; print u'ëèæîð'.encode(sys.stdin.encoding) </code></pre> <p>Any ideas why it happens and how to make it work?</p> <p><b>UPD</b>: <code>sys.stdin.encoding</code> returns <code>'cp65001'</code></p> <p><b>UPD2</b>: It just came to me that the issue might be connected with the fact that utf-8 uses <a href="http://en.wikipedia.org/wiki/Multi-byte_character_set" rel="nofollow">multi-byte character set</a> (kcwu made a good point on that). I tried running the whole example with 'windows-1250' and got 'ëeaî?'. Windows-1250 uses single-character set so it worked for those characters it understands. However I still have no idea how to make 'utf-8' work here.</p> <p><b>UPD3</b>: Oh, I found out it is a <a href="http://bugs.python.org/issue1602" rel="nofollow">known Python bug</a>. I guess what happens is that Python copies the cmd encoding as 'cp65001 to sys.stdin.encoding and tries to apply it to all the input. Since it fails to understand 'cp65001' it crashes on any input that contains non-ascii characters.</p>
38
2009-05-18T17:52:10Z
879,125
<p>A few comments: you probably misspelled <code>encodig</code> and <code>.code</code>. Here is my run of your example.</p> <pre><code>C:\&gt;chcp 65001 Active code page: 65001 C:\&gt;\python25\python ... &gt;&gt;&gt; import sys &gt;&gt;&gt; sys.stdin.encoding 'cp65001' &gt;&gt;&gt; s=u'\u0065\u0066' &gt;&gt;&gt; s u'ef' &gt;&gt;&gt; s.encode(sys.stdin.encoding) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; LookupError: unknown encoding: cp65001 &gt;&gt;&gt; </code></pre> <p>The conclusion - <code>cp65001</code> is not a known encoding for python. Try 'UTF-16' or something similar.</p>
1
2009-05-18T18:29:59Z
[ "python", "windows", "unicode", "encoding", "cmd" ]
Windows cmd encoding change causes Python crash
878,972
<p>First I change Windows CMD encoding to utf-8 and run Python interpreter:</p> <pre><code>chcp 65001 python </code></pre> <p>Then I try to print a unicode sting inside it and when i do this Python crashes in a peculiar way (I just get a cmd prompt in the same window). </p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; print u'ëèæîð'.encode(sys.stdin.encoding) </code></pre> <p>Any ideas why it happens and how to make it work?</p> <p><b>UPD</b>: <code>sys.stdin.encoding</code> returns <code>'cp65001'</code></p> <p><b>UPD2</b>: It just came to me that the issue might be connected with the fact that utf-8 uses <a href="http://en.wikipedia.org/wiki/Multi-byte_character_set" rel="nofollow">multi-byte character set</a> (kcwu made a good point on that). I tried running the whole example with 'windows-1250' and got 'ëeaî?'. Windows-1250 uses single-character set so it worked for those characters it understands. However I still have no idea how to make 'utf-8' work here.</p> <p><b>UPD3</b>: Oh, I found out it is a <a href="http://bugs.python.org/issue1602" rel="nofollow">known Python bug</a>. I guess what happens is that Python copies the cmd encoding as 'cp65001 to sys.stdin.encoding and tries to apply it to all the input. Since it fails to understand 'cp65001' it crashes on any input that contains non-ascii characters.</p>
38
2009-05-18T17:52:10Z
1,432,462
<p>I had this annoying issue, too, and I hated not being able to run my unicode-aware scripts same in MS Windows as in linux. So, I managed to come up with a workaround.</p> <p>Take this script (say, <code>uniconsole.py</code> in your site-packages or whatever):</p> <pre><code>import sys, os if sys.platform == "win32": class UniStream(object): __slots__= ("fileno", "softspace",) def __init__(self, fileobject): self.fileno = fileobject.fileno() self.softspace = False def write(self, text): os.write(self.fileno, text.encode("utf_8") if isinstance(text, unicode) else text) sys.stdout = UniStream(sys.stdout) sys.stderr = UniStream(sys.stderr) </code></pre> <p>This seems to work around the python bug (or win32 unicode console bug, whatever). Then I added in all related scripts:</p> <pre><code>try: import uniconsole except ImportError: sys.exc_clear() # could be just pass, of course else: del uniconsole # reduce pollution, not needed anymore </code></pre> <p>Finally, I just run my scripts as needed in a console where <code>chcp 65001</code> is run and the font is <code>Lucida Console</code>. (How I wish that <code>DejaVu Sans Mono</code> could be used instead… but hacking the registry and selecting it as a console font reverts to a bitmap font.)</p> <p>This is a quick-and-dirty <code>stdout</code> and <code>stderr</code> replacement, and also does not handle any <code>raw_input</code> related bugs (obviously, since it doesn't touch <code>sys.stdin</code> at all). And, by the way, I've added the <code>cp65001</code> alias for <code>utf_8</code> in the <code>encodings\aliases.py</code> file of the standard lib.</p>
2
2009-09-16T11:42:40Z
[ "python", "windows", "unicode", "encoding", "cmd" ]
Windows cmd encoding change causes Python crash
878,972
<p>First I change Windows CMD encoding to utf-8 and run Python interpreter:</p> <pre><code>chcp 65001 python </code></pre> <p>Then I try to print a unicode sting inside it and when i do this Python crashes in a peculiar way (I just get a cmd prompt in the same window). </p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; print u'ëèæîð'.encode(sys.stdin.encoding) </code></pre> <p>Any ideas why it happens and how to make it work?</p> <p><b>UPD</b>: <code>sys.stdin.encoding</code> returns <code>'cp65001'</code></p> <p><b>UPD2</b>: It just came to me that the issue might be connected with the fact that utf-8 uses <a href="http://en.wikipedia.org/wiki/Multi-byte_character_set" rel="nofollow">multi-byte character set</a> (kcwu made a good point on that). I tried running the whole example with 'windows-1250' and got 'ëeaî?'. Windows-1250 uses single-character set so it worked for those characters it understands. However I still have no idea how to make 'utf-8' work here.</p> <p><b>UPD3</b>: Oh, I found out it is a <a href="http://bugs.python.org/issue1602" rel="nofollow">known Python bug</a>. I guess what happens is that Python copies the cmd encoding as 'cp65001 to sys.stdin.encoding and tries to apply it to all the input. Since it fails to understand 'cp65001' it crashes on any input that contains non-ascii characters.</p>
38
2009-05-18T17:52:10Z
3,259,271
<p>Here's how to alias <code>cp65001</code> to UTF-8 without changing <code>encodings\aliases.py</code>:</p> <pre><code>import codecs codecs.register(lambda name: codecs.lookup('utf-8') if name == 'cp65001' else None) </code></pre> <p>(IMHO, don't pay any attention to the silliness about <code>cp65001</code> not being identical to UTF-8 at <a href="http://bugs.python.org/issue6058#msg97731">http://bugs.python.org/issue6058#msg97731</a> . It's intended to be the same, even if Microsoft's codec has some minor bugs.)</p> <p>Here is some code (written for Tahoe-LAFS, tahoe-lafs.org) that makes console output work <em>regardless</em> of the <code>chcp</code> code page, and also reads Unicode command-line arguments. Credit to <a href="http://www.siao2.com/2008/03/18/8306597.aspx">Michael Kaplan</a> for the idea behind this solution. If stdout or stderr are redirected, it will output UTF-8. If you want a Byte Order Mark, you'll need to write it explicitly.</p> <p>[Edit: This version uses <code>WriteConsoleW</code> instead of the <code>_O_U8TEXT</code> flag in the MSVC runtime library, which is buggy. <code>WriteConsoleW</code> is also buggy relative to the MS documentation, but less so.]</p> <pre><code>import sys if sys.platform == "win32": import codecs from ctypes import WINFUNCTYPE, windll, POINTER, byref, c_int from ctypes.wintypes import BOOL, HANDLE, DWORD, LPWSTR, LPCWSTR, LPVOID original_stderr = sys.stderr # If any exception occurs in this code, we'll probably try to print it on stderr, # which makes for frustrating debugging if stderr is directed to our wrapper. # So be paranoid about catching errors and reporting them to original_stderr, # so that we can at least see them. def _complain(message): print &gt;&gt;original_stderr, message if isinstance(message, str) else repr(message) # Work around &lt;http://bugs.python.org/issue6058&gt;. codecs.register(lambda name: codecs.lookup('utf-8') if name == 'cp65001' else None) # Make Unicode console output work independently of the current code page. # This also fixes &lt;http://bugs.python.org/issue1602&gt;. # Credit to Michael Kaplan &lt;http://www.siao2.com/2010/04/07/9989346.aspx&gt; # and TZOmegaTZIOY # &lt;http://stackoverflow.com/questions/878972/windows-cmd-encoding-change-causes-python-crash/1432462#1432462&gt;. try: # &lt;http://msdn.microsoft.com/en-us/library/ms683231(VS.85).aspx&gt; # HANDLE WINAPI GetStdHandle(DWORD nStdHandle); # returns INVALID_HANDLE_VALUE, NULL, or a valid handle # # &lt;http://msdn.microsoft.com/en-us/library/aa364960(VS.85).aspx&gt; # DWORD WINAPI GetFileType(DWORD hFile); # # &lt;http://msdn.microsoft.com/en-us/library/ms683167(VS.85).aspx&gt; # BOOL WINAPI GetConsoleMode(HANDLE hConsole, LPDWORD lpMode); GetStdHandle = WINFUNCTYPE(HANDLE, DWORD)(("GetStdHandle", windll.kernel32)) STD_OUTPUT_HANDLE = DWORD(-11) STD_ERROR_HANDLE = DWORD(-12) GetFileType = WINFUNCTYPE(DWORD, DWORD)(("GetFileType", windll.kernel32)) FILE_TYPE_CHAR = 0x0002 FILE_TYPE_REMOTE = 0x8000 GetConsoleMode = WINFUNCTYPE(BOOL, HANDLE, POINTER(DWORD))(("GetConsoleMode", windll.kernel32)) INVALID_HANDLE_VALUE = DWORD(-1).value def not_a_console(handle): if handle == INVALID_HANDLE_VALUE or handle is None: return True return ((GetFileType(handle) &amp; ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR or GetConsoleMode(handle, byref(DWORD())) == 0) old_stdout_fileno = None old_stderr_fileno = None if hasattr(sys.stdout, 'fileno'): old_stdout_fileno = sys.stdout.fileno() if hasattr(sys.stderr, 'fileno'): old_stderr_fileno = sys.stderr.fileno() STDOUT_FILENO = 1 STDERR_FILENO = 2 real_stdout = (old_stdout_fileno == STDOUT_FILENO) real_stderr = (old_stderr_fileno == STDERR_FILENO) if real_stdout: hStdout = GetStdHandle(STD_OUTPUT_HANDLE) if not_a_console(hStdout): real_stdout = False if real_stderr: hStderr = GetStdHandle(STD_ERROR_HANDLE) if not_a_console(hStderr): real_stderr = False if real_stdout or real_stderr: # BOOL WINAPI WriteConsoleW(HANDLE hOutput, LPWSTR lpBuffer, DWORD nChars, # LPDWORD lpCharsWritten, LPVOID lpReserved); WriteConsoleW = WINFUNCTYPE(BOOL, HANDLE, LPWSTR, DWORD, POINTER(DWORD), LPVOID)(("WriteConsoleW", windll.kernel32)) class UnicodeOutput: def __init__(self, hConsole, stream, fileno, name): self._hConsole = hConsole self._stream = stream self._fileno = fileno self.closed = False self.softspace = False self.mode = 'w' self.encoding = 'utf-8' self.name = name self.flush() def isatty(self): return False def close(self): # don't really close the handle, that would only cause problems self.closed = True def fileno(self): return self._fileno def flush(self): if self._hConsole is None: try: self._stream.flush() except Exception as e: _complain("%s.flush: %r from %r" % (self.name, e, self._stream)) raise def write(self, text): try: if self._hConsole is None: if isinstance(text, unicode): text = text.encode('utf-8') self._stream.write(text) else: if not isinstance(text, unicode): text = str(text).decode('utf-8') remaining = len(text) while remaining: n = DWORD(0) # There is a shorter-than-documented limitation on the # length of the string passed to WriteConsoleW (see # &lt;http://tahoe-lafs.org/trac/tahoe-lafs/ticket/1232&gt;. retval = WriteConsoleW(self._hConsole, text, min(remaining, 10000), byref(n), None) if retval == 0 or n.value == 0: raise IOError("WriteConsoleW returned %r, n.value = %r" % (retval, n.value)) remaining -= n.value if not remaining: break text = text[n.value:] except Exception as e: _complain("%s.write: %r" % (self.name, e)) raise def writelines(self, lines): try: for line in lines: self.write(line) except Exception as e: _complain("%s.writelines: %r" % (self.name, e)) raise if real_stdout: sys.stdout = UnicodeOutput(hStdout, None, STDOUT_FILENO, '&lt;Unicode console stdout&gt;') else: sys.stdout = UnicodeOutput(None, sys.stdout, old_stdout_fileno, '&lt;Unicode redirected stdout&gt;') if real_stderr: sys.stderr = UnicodeOutput(hStderr, None, STDERR_FILENO, '&lt;Unicode console stderr&gt;') else: sys.stderr = UnicodeOutput(None, sys.stderr, old_stderr_fileno, '&lt;Unicode redirected stderr&gt;') except Exception as e: _complain("exception %r while fixing up sys.stdout and sys.stderr" % (e,)) # While we're at it, let's unmangle the command-line arguments: # This works around &lt;http://bugs.python.org/issue2128&gt;. GetCommandLineW = WINFUNCTYPE(LPWSTR)(("GetCommandLineW", windll.kernel32)) CommandLineToArgvW = WINFUNCTYPE(POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(("CommandLineToArgvW", windll.shell32)) argc = c_int(0) argv_unicode = CommandLineToArgvW(GetCommandLineW(), byref(argc)) argv = [argv_unicode[i].encode('utf-8') for i in xrange(0, argc.value)] if not hasattr(sys, 'frozen'): # If this is an executable produced by py2exe or bbfreeze, then it will # have been invoked directly. Otherwise, unicode_argv[0] is the Python # interpreter, so skip that. argv = argv[1:] # Also skip option arguments to the Python interpreter. while len(argv) &gt; 0: arg = argv[0] if not arg.startswith(u"-") or arg == u"-": break argv = argv[1:] if arg == u'-m': # sys.argv[0] should really be the absolute path of the module source, # but never mind break if arg == u'-c': argv[0] = u'-c' break # if you like: sys.argv = argv </code></pre> <p>Finally, it <em>is</em> possible to grant ΤΖΩΤΖΙΟΥ's wish to use DejaVu Sans Mono, which I agree is an excellent font, for the console.</p> <p>You can find information on the font requirements and how to add new fonts for the windows console in the <a href="https://support.microsoft.com/en-us/kb/247815">'Necessary criteria for fonts to be available in a command window' Microsoft KB</a></p> <p>But basically, on Vista (probably also Win7):</p> <ul> <li>under <code>HKEY_LOCAL_MACHINE_SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console\TrueTypeFont</code>, set <code>"0"</code> to <code>"DejaVu Sans Mono"</code>;</li> <li>for each of the subkeys under <code>HKEY_CURRENT_USER\Console</code>, set <code>"FaceName"</code> to <code>"DejaVu Sans Mono"</code>.</li> </ul> <p>On XP, check the thread <a href="http://help.lockergnome.com/windows/Changing-Command-Prompt-fonts--ftopict551879.html">'Changing Command Prompt fonts?' in LockerGnome forums</a>.</p>
67
2010-07-15T19:35:10Z
[ "python", "windows", "unicode", "encoding", "cmd" ]
Windows cmd encoding change causes Python crash
878,972
<p>First I change Windows CMD encoding to utf-8 and run Python interpreter:</p> <pre><code>chcp 65001 python </code></pre> <p>Then I try to print a unicode sting inside it and when i do this Python crashes in a peculiar way (I just get a cmd prompt in the same window). </p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; print u'ëèæîð'.encode(sys.stdin.encoding) </code></pre> <p>Any ideas why it happens and how to make it work?</p> <p><b>UPD</b>: <code>sys.stdin.encoding</code> returns <code>'cp65001'</code></p> <p><b>UPD2</b>: It just came to me that the issue might be connected with the fact that utf-8 uses <a href="http://en.wikipedia.org/wiki/Multi-byte_character_set" rel="nofollow">multi-byte character set</a> (kcwu made a good point on that). I tried running the whole example with 'windows-1250' and got 'ëeaî?'. Windows-1250 uses single-character set so it worked for those characters it understands. However I still have no idea how to make 'utf-8' work here.</p> <p><b>UPD3</b>: Oh, I found out it is a <a href="http://bugs.python.org/issue1602" rel="nofollow">known Python bug</a>. I guess what happens is that Python copies the cmd encoding as 'cp65001 to sys.stdin.encoding and tries to apply it to all the input. Since it fails to understand 'cp65001' it crashes on any input that contains non-ascii characters.</p>
38
2009-05-18T17:52:10Z
12,834,315
<p>Set <strong>PYTHONIOENCODING</strong> system variable:</p> <pre><code>&gt; chcp 65001 &gt; set PYTHONIOENCODING=utf-8 &gt; python example.py Encoding is utf-8 </code></pre> <p>Source of example.py is simple:</p> <pre><code>import sys print "Encoding is", sys.stdin.encoding </code></pre>
24
2012-10-11T07:26:37Z
[ "python", "windows", "unicode", "encoding", "cmd" ]
How to install python-dateutil on Windows?
879,156
<p>I'm trying to convert some date/times to UTC, which I thought would be dead simple in Python - batteries included, right? Well, it would be simple except that Python (2.6) doesn't include any tzinfo classes. No problem, a quick search turns up <a href="http://pypi.python.org/pypi/python-dateutil">python-dateutil</a> which should do exactly what I need.</p> <p>The problem is that I need to install it on Windows. I was able to upack the .tar.gz2 distribution using 7-zip, but now I'm left with a collection of files and no guidance on how to proceed. When I try to run setup.py I get the error "No module named setuptools".</p>
43
2009-05-18T18:38:53Z
879,204
<p>Looks like the setup.py uses easy_install (i.e. <code>setuptools</code>). Just install the <a href="http://pypi.python.org/pypi/setuptools/0.6c9">setuptools</a> package and you will be all set.</p> <p>To install setuptools in Python 2.6, see the answer to <a href="http://stackoverflow.com/questions/309412/how-to-setup-setuptools-for-python-26-on-windows">this question</a>.</p>
6
2009-05-18T18:49:41Z
[ "python", "install", "python-dateutil" ]
How to install python-dateutil on Windows?
879,156
<p>I'm trying to convert some date/times to UTC, which I thought would be dead simple in Python - batteries included, right? Well, it would be simple except that Python (2.6) doesn't include any tzinfo classes. No problem, a quick search turns up <a href="http://pypi.python.org/pypi/python-dateutil">python-dateutil</a> which should do exactly what I need.</p> <p>The problem is that I need to install it on Windows. I was able to upack the .tar.gz2 distribution using 7-zip, but now I'm left with a collection of files and no guidance on how to proceed. When I try to run setup.py I get the error "No module named setuptools".</p>
43
2009-05-18T18:38:53Z
879,879
<p>Why didn't someone tell me I was being a total noob? All I had to do was copy the <code>dateutil</code> directory to someplace in my Python path, and it was good to go.</p>
17
2009-05-18T21:15:02Z
[ "python", "install", "python-dateutil" ]
How to install python-dateutil on Windows?
879,156
<p>I'm trying to convert some date/times to UTC, which I thought would be dead simple in Python - batteries included, right? Well, it would be simple except that Python (2.6) doesn't include any tzinfo classes. No problem, a quick search turns up <a href="http://pypi.python.org/pypi/python-dateutil">python-dateutil</a> which should do exactly what I need.</p> <p>The problem is that I need to install it on Windows. I was able to upack the .tar.gz2 distribution using 7-zip, but now I'm left with a collection of files and no guidance on how to proceed. When I try to run setup.py I get the error "No module named setuptools".</p>
43
2009-05-18T18:38:53Z
2,717,096
<p>Using <code>setup</code> from <code>distutils.core</code> instead of <code>setuptools</code> in setup.py worked for me, too:</p> <pre><code>#from setuptools import setup from distutils.core import setup </code></pre>
2
2010-04-26T21:38:36Z
[ "python", "install", "python-dateutil" ]
How to install python-dateutil on Windows?
879,156
<p>I'm trying to convert some date/times to UTC, which I thought would be dead simple in Python - batteries included, right? Well, it would be simple except that Python (2.6) doesn't include any tzinfo classes. No problem, a quick search turns up <a href="http://pypi.python.org/pypi/python-dateutil">python-dateutil</a> which should do exactly what I need.</p> <p>The problem is that I need to install it on Windows. I was able to upack the .tar.gz2 distribution using 7-zip, but now I'm left with a collection of files and no guidance on how to proceed. When I try to run setup.py I get the error "No module named setuptools".</p>
43
2009-05-18T18:38:53Z
7,186,957
<p>If dateutil is missing install it via:</p> <pre><code>pip install python-dateutil </code></pre> <p>Or on Ubuntu:</p> <pre><code>sudo apt-get install python-dateutil </code></pre>
54
2011-08-25T08:05:27Z
[ "python", "install", "python-dateutil" ]
How to install python-dateutil on Windows?
879,156
<p>I'm trying to convert some date/times to UTC, which I thought would be dead simple in Python - batteries included, right? Well, it would be simple except that Python (2.6) doesn't include any tzinfo classes. No problem, a quick search turns up <a href="http://pypi.python.org/pypi/python-dateutil">python-dateutil</a> which should do exactly what I need.</p> <p>The problem is that I need to install it on Windows. I was able to upack the .tar.gz2 distribution using 7-zip, but now I'm left with a collection of files and no guidance on how to proceed. When I try to run setup.py I get the error "No module named setuptools".</p>
43
2009-05-18T18:38:53Z
19,030,443
<p>Install from the "Unofficial Windows Binaries for Python Extension Packages"</p> <p><a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#python-dateutil">http://www.lfd.uci.edu/~gohlke/pythonlibs/#python-dateutil</a></p> <p>Pretty much has every package you would need.</p>
5
2013-09-26T14:02:29Z
[ "python", "install", "python-dateutil" ]
How to install python-dateutil on Windows?
879,156
<p>I'm trying to convert some date/times to UTC, which I thought would be dead simple in Python - batteries included, right? Well, it would be simple except that Python (2.6) doesn't include any tzinfo classes. No problem, a quick search turns up <a href="http://pypi.python.org/pypi/python-dateutil">python-dateutil</a> which should do exactly what I need.</p> <p>The problem is that I need to install it on Windows. I was able to upack the .tar.gz2 distribution using 7-zip, but now I'm left with a collection of files and no guidance on how to proceed. When I try to run setup.py I get the error "No module named setuptools".</p>
43
2009-05-18T18:38:53Z
21,032,978
<p>Just run command prompt as administrator and type this in.</p> <pre><code>easy_install python-dateutil </code></pre>
0
2014-01-09T22:58:42Z
[ "python", "install", "python-dateutil" ]
How to install python-dateutil on Windows?
879,156
<p>I'm trying to convert some date/times to UTC, which I thought would be dead simple in Python - batteries included, right? Well, it would be simple except that Python (2.6) doesn't include any tzinfo classes. No problem, a quick search turns up <a href="http://pypi.python.org/pypi/python-dateutil">python-dateutil</a> which should do exactly what I need.</p> <p>The problem is that I need to install it on Windows. I was able to upack the .tar.gz2 distribution using 7-zip, but now I'm left with a collection of files and no guidance on how to proceed. When I try to run setup.py I get the error "No module named setuptools".</p>
43
2009-05-18T18:38:53Z
26,626,787
<p>You could also change your PYTHONPATH:</p> <pre><code>$ python -c 'import dateutil' Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; ImportError: No module named dateutil $ $ PYTHONPATH="/usr/lib/python2.6/site-packages/python_dateutil-1.5-py2.6.egg":"${PYTHONPATH}" $ export PYTHONPATH $ python -c 'import dateutil' $ </code></pre> <p>Where <code>/usr/lib/python2.6/site-packages/python_dateutil-1.5-py2.6.egg</code> is the place <strong>dateutil</strong> was installed in my box (<em>centos</em> using <code>sudo yum install python-dateutil15</code>)</p>
0
2014-10-29T09:32:38Z
[ "python", "install", "python-dateutil" ]
How to install python-dateutil on Windows?
879,156
<p>I'm trying to convert some date/times to UTC, which I thought would be dead simple in Python - batteries included, right? Well, it would be simple except that Python (2.6) doesn't include any tzinfo classes. No problem, a quick search turns up <a href="http://pypi.python.org/pypi/python-dateutil">python-dateutil</a> which should do exactly what I need.</p> <p>The problem is that I need to install it on Windows. I was able to upack the .tar.gz2 distribution using 7-zip, but now I'm left with a collection of files and no guidance on how to proceed. When I try to run setup.py I get the error "No module named setuptools".</p>
43
2009-05-18T18:38:53Z
29,878,438
<p>First confirm that you have in C:/python##/Lib/Site-packages/ a folder dateutil, perhaps you download it, you should already have pip,matplotlib, six##,,confirm you have installed dateutil by--- go to the cmd, cd /python, you should have a folder /Scripts. cd to Scripts, then type --pip install python-dateutil -- ----This applies to windows 7 Ultimate 32bit, Python 3.4------</p>
0
2015-04-26T13:46:30Z
[ "python", "install", "python-dateutil" ]
How to install python-dateutil on Windows?
879,156
<p>I'm trying to convert some date/times to UTC, which I thought would be dead simple in Python - batteries included, right? Well, it would be simple except that Python (2.6) doesn't include any tzinfo classes. No problem, a quick search turns up <a href="http://pypi.python.org/pypi/python-dateutil">python-dateutil</a> which should do exactly what I need.</p> <p>The problem is that I need to install it on Windows. I was able to upack the .tar.gz2 distribution using 7-zip, but now I'm left with a collection of files and no guidance on how to proceed. When I try to run setup.py I get the error "No module named setuptools".</p>
43
2009-05-18T18:38:53Z
32,178,715
<p>If you are offline and have untared the package, you can use command prompt. </p> <p>Navigate to the untared folder and run:</p> <pre><code>python setup.py install </code></pre>
1
2015-08-24T09:24:24Z
[ "python", "install", "python-dateutil" ]
How to install python-dateutil on Windows?
879,156
<p>I'm trying to convert some date/times to UTC, which I thought would be dead simple in Python - batteries included, right? Well, it would be simple except that Python (2.6) doesn't include any tzinfo classes. No problem, a quick search turns up <a href="http://pypi.python.org/pypi/python-dateutil">python-dateutil</a> which should do exactly what I need.</p> <p>The problem is that I need to install it on Windows. I was able to upack the .tar.gz2 distribution using 7-zip, but now I'm left with a collection of files and no guidance on how to proceed. When I try to run setup.py I get the error "No module named setuptools".</p>
43
2009-05-18T18:38:53Z
34,170,126
<p>It is a little tricky for people who is not used to command prompt. All you have to do is open the directory where python is installed (C:\Python27 by default) and open the command prompt there (shift + right click and select open command window here) and then type :</p> <p><strong>python -m pip install python-dateutil</strong></p> <p>Hope that helps.</p>
3
2015-12-09T03:12:43Z
[ "python", "install", "python-dateutil" ]
How to ignore deprecation warnings in Python
879,173
<p>I keep getting this :</p> <pre><code>DeprecationWarning: integer argument expected, got float </code></pre> <p>How do I make this message go away? Is there a way to avoid warnings in Python?</p>
73
2009-05-18T18:42:44Z
879,202
<p>Pass the correct arguments? :P</p> <p>On the more serious note, you can pass the argument -Wi::DeprecationWarning on the command line to the interpreter to ignore the deprecation warnings.</p>
6
2009-05-18T18:49:35Z
[ "python", "warnings", "deprecated", "ignore" ]
How to ignore deprecation warnings in Python
879,173
<p>I keep getting this :</p> <pre><code>DeprecationWarning: integer argument expected, got float </code></pre> <p>How do I make this message go away? Is there a way to avoid warnings in Python?</p>
73
2009-05-18T18:42:44Z
879,203
<p>Convert the argument to int. It's as simple as</p> <pre><code>int(argument) </code></pre>
5
2009-05-18T18:49:38Z
[ "python", "warnings", "deprecated", "ignore" ]
How to ignore deprecation warnings in Python
879,173
<p>I keep getting this :</p> <pre><code>DeprecationWarning: integer argument expected, got float </code></pre> <p>How do I make this message go away? Is there a way to avoid warnings in Python?</p>
73
2009-05-18T18:42:44Z
879,208
<p>I <a href="http://www.google.nl/search?q=python+silence+Deprecationwarning">Googled</a> and <a href="https://docs.python.org/3/library/warnings.html">found</a>:</p> <pre><code> #!/usr/bin/env python -W ignore::DeprecationWarning </code></pre> <p>If you're on Windows: pass <code>-W ignore::DeprecationWarning</code> as an argument to Python.</p> <p>(But resolving the issue may be a better course of action... casting to <a href="http://docs.python.org/3.0/library/functions.html#int">int</a> is not hard.)</p> <p><strong>Edit:</strong> user <a href="https://stackoverflow.com/users/341255/shahensha">shahensha</a> pointed out that the link this answer original pointed to was broken. Changed the link to just point to the documentation. Note that as for version 2.7 and 3.2 deprecation warnings are ignored by default.</p>
71
2009-05-18T18:50:07Z
[ "python", "warnings", "deprecated", "ignore" ]
How to ignore deprecation warnings in Python
879,173
<p>I keep getting this :</p> <pre><code>DeprecationWarning: integer argument expected, got float </code></pre> <p>How do I make this message go away? Is there a way to avoid warnings in Python?</p>
73
2009-05-18T18:42:44Z
879,226
<p>Not to beat you up about it but you are being warned that what you are doing will likely stop working when you next upgrade python. Convert to int and be done with it.</p> <p>BTW. You can also write your own warnings handler. Just assign a function that does nothing. <a href="http://stackoverflow.com/questions/858916/how-to-redirect-python-warnings-to-a-custom-stream">http://stackoverflow.com/questions/858916/how-to-redirect-python-warnings-to-a-custom-stream</a></p>
2
2009-05-18T18:55:05Z
[ "python", "warnings", "deprecated", "ignore" ]
How to ignore deprecation warnings in Python
879,173
<p>I keep getting this :</p> <pre><code>DeprecationWarning: integer argument expected, got float </code></pre> <p>How do I make this message go away? Is there a way to avoid warnings in Python?</p>
73
2009-05-18T18:42:44Z
879,249
<p>You should just fix your code but just in case,</p> <pre><code>import warnings warnings.filterwarnings("ignore", category=DeprecationWarning) </code></pre>
83
2009-05-18T19:01:48Z
[ "python", "warnings", "deprecated", "ignore" ]
How to ignore deprecation warnings in Python
879,173
<p>I keep getting this :</p> <pre><code>DeprecationWarning: integer argument expected, got float </code></pre> <p>How do I make this message go away? Is there a way to avoid warnings in Python?</p>
73
2009-05-18T18:42:44Z
1,640,777
<p>I had these:</p> <blockquote> <p>/home/eddyp/virtualenv/lib/python2.6/site-packages/Twisted-8.2.0-py2.6-linux-x86_64.egg/twisted/persisted/sob.py:12: DeprecationWarning: the md5 module is deprecated; use hashlib instead<br /> import os, md5, sys</p> <p>/home/eddyp/virtualenv/lib/python2.6/site-packages/Twisted-8.2.0-py2.6-linux-x86_64.egg/twisted/python/filepath.py:12: DeprecationWarning: the sha module is deprecated; use the hashlib module instead import sha</p> </blockquote> <p>Fixed it with:</p> <pre><code>import warnings with warnings.catch_warnings(): warnings.filterwarnings("ignore",category=DeprecationWarning) import md5, sha yourcode() </code></pre> <p>Now you still get all the other DeprecationWarnings, but not the ones caused by import md5, sha</p>
108
2009-10-28T23:24:01Z
[ "python", "warnings", "deprecated", "ignore" ]
How to ignore deprecation warnings in Python
879,173
<p>I keep getting this :</p> <pre><code>DeprecationWarning: integer argument expected, got float </code></pre> <p>How do I make this message go away? Is there a way to avoid warnings in Python?</p>
73
2009-05-18T18:42:44Z
2,381,422
<p>I found the cleanest way to do this (especially on windows) is by adding the following to C:\Python26\Lib\site-packages\sitecustomize.py:</p> <pre><code>import warnings warnings.filterwarnings("ignore", category=DeprecationWarning) </code></pre> <p>Note that I had to create this file. Of course, change the path to python if yours is different.</p>
19
2010-03-04T17:35:36Z
[ "python", "warnings", "deprecated", "ignore" ]
Serializing a Python Object to XML (Apple .plist)
879,212
<p>I need to read and serialize objects from and to XML, Apple's .plist format in particular. What's the most intelligent way to do it in Python? Are there any ready-made solutions?</p>
3
2009-05-18T18:51:32Z
879,222
<p>Check out <a href="http://docs.python.org/dev/library/plistlib.html" rel="nofollow">plistlib</a>.</p>
7
2009-05-18T18:54:30Z
[ "python", "xml", "plist" ]
Serializing a Python Object to XML (Apple .plist)
879,212
<p>I need to read and serialize objects from and to XML, Apple's .plist format in particular. What's the most intelligent way to do it in Python? Are there any ready-made solutions?</p>
3
2009-05-18T18:51:32Z
1,261,238
<p>Assuming you are on a Mac, you can use PyObjC.</p> <p>Here is an example of reading from a plist, from <a href="http://mwpdf.shownets.net:8080/MacIT%20Conference/IT831%5Fnkersten%5Fcadams.pdf" rel="nofollow">Using Python For System Administration</a>, slide 27.</p> <pre><code>from Cocoa import NSDictionary myfile = "/Library/Preferences/com.apple.SoftwareUpdate.plist" mydict = NSDictionary.dictionaryWithContentsOfFile_(myfile) print mydict["LastSuccessfulDate"] # returns: 2009-08-11 08:38:01 -0600 </code></pre> <p>And an example of writing to a plist (that I wrote):</p> <pre><code>#!/usr/bin/env python from Cocoa import NSDictionary, NSString myfile = "~/test.plist" myfile = NSString.stringByExpandingTildeInPath(myfile) mydict = {"Nice Number" : 47, "Universal Sum" : 42} mydict["Vector"] = (10, 20, 30) mydict["Complex"] = [47, "i^2"] mydict["Truth"] = True NSDictionary.dictionaryWithDictionary_(mydict).writeToFile_atomically_(myfile, True) </code></pre> <p>When I then run <code>defaults read ~/test</code> in bash, I get:</p> <pre><code>{ Complex = ( 47, "i^2" ); "Nice Number" = 47; Truth = 1; "Universal Sum" = 42; Vector = ( 10, 20, 30 ); } </code></pre> <p>And the file looks very nice when opened in Property List Editor.app.</p>
2
2009-08-11T15:45:50Z
[ "python", "xml", "plist" ]
Python learning environment
879,218
<p>I'm looking to get up to speed on Python, is it worth working locally via the ActivePython interface, then progressing to a website that supports one of the standard frameworks (Django or Pylons) OR utilize the Google Apps environment? I want to stay as interactive as possible - making feedback/learning easier.</p>
3
2009-05-18T18:53:42Z
879,227
<p>Not sure what you mean.</p> <p>For development</p> <p>First choice: idle -- you already have it.</p> <p>Second choice: Komodo Edit -- very easy to use, but not as directly interactive as idle.</p> <p>For deploying applications, that depends on your application. If you're building desktop applications or web applications, you still use similar tools. I prefer using Komodo Edit for big things (either desktop or web) because it's a nice IDE.</p> <p>What are you asking about? Development tools or final deployment of a finished product?</p>
2
2009-05-18T18:55:32Z
[ "python" ]
Python learning environment
879,218
<p>I'm looking to get up to speed on Python, is it worth working locally via the ActivePython interface, then progressing to a website that supports one of the standard frameworks (Django or Pylons) OR utilize the Google Apps environment? I want to stay as interactive as possible - making feedback/learning easier.</p>
3
2009-05-18T18:53:42Z
879,231
<p>I would just start locally. Django and Pylons add another layer of complexity to the edit/feedback loop.</p> <p>Unless your primary focus is to make python websites, just stick with an editor and the console.</p>
2
2009-05-18T18:56:08Z
[ "python" ]
Python learning environment
879,218
<p>I'm looking to get up to speed on Python, is it worth working locally via the ActivePython interface, then progressing to a website that supports one of the standard frameworks (Django or Pylons) OR utilize the Google Apps environment? I want to stay as interactive as possible - making feedback/learning easier.</p>
3
2009-05-18T18:53:42Z
879,236
<p>Go with the Python interpreter. Take one of the tutorials that many people on SO <a href="http://stackoverflow.com/search?q=python%2Btutorial">recommend</a> and you're on your way. Once you're comfortable with the language, have a look at a framework like Django, but not sooner.</p>
6
2009-05-18T18:57:24Z
[ "python" ]
Python learning environment
879,218
<p>I'm looking to get up to speed on Python, is it worth working locally via the ActivePython interface, then progressing to a website that supports one of the standard frameworks (Django or Pylons) OR utilize the Google Apps environment? I want to stay as interactive as possible - making feedback/learning easier.</p>
3
2009-05-18T18:53:42Z
879,240
<p>I learned using the <a href="http://docs.python.org/tutorial/" rel="nofollow">docs</a> and IDLE (with shell). Go to Django well after you fully understand Python.</p>
2
2009-05-18T18:57:41Z
[ "python" ]
Python learning environment
879,218
<p>I'm looking to get up to speed on Python, is it worth working locally via the ActivePython interface, then progressing to a website that supports one of the standard frameworks (Django or Pylons) OR utilize the Google Apps environment? I want to stay as interactive as possible - making feedback/learning easier.</p>
3
2009-05-18T18:53:42Z
879,830
<p>ipython and your favorite text editor. spend an hour with these screencasts and you'll be comfy with it in no time.</p> <p><a href="http://showmedo.com/videotutorials/series?name=CnluURUTV" rel="nofollow">http://showmedo.com/videotutorials/series?name=CnluURUTV</a></p>
1
2009-05-18T21:04:48Z
[ "python" ]
logging with filters
879,732
<p>I'm using Logging (import logging) to log messages.</p> <p>Within 1 single module, I am logging messages at the debug level (my_logger.debug('msg')); </p> <p>Some of these debug messages come from function_a() and others from function_b(); I'd like to be able to enable/disable logging based on whether they come from a or from b; </p> <p>I'm guessing that I have to use Logging's filtering mechanism. </p> <p>Can someone please show me how the code below would need to be instrumented to do what I want? thanks.</p> <pre><code>import logging logger= logging.getLogger( "module_name" ) def function_a( ... ): logger.debug( "a message" ) def function_b( ... ): logger.debug( "another message" ) if __name__ == "__main__": logging.basicConfig( stream=sys.stderr, level=logging.DEBUG ) #don't want function_a()'s noise -&gt; .... #somehow filter-out function_a's logging function_a() #don't want function_b()'s noise -&gt; .... #somehow filter-out function_b's logging function_b() </code></pre> <p>If I scaled this simple example to more modules and more funcs per module, I'd be concerned about lots of loggers; </p> <p>Can I keep it down to 1 logger per module? Note that the log messages are "structured", i.e. if the function(s) logging it are doing some parsing work, they all contain a prefix logger.debug("parsing: xxx") - can I somehow with a single line just shut-off all "parsing" messages (regardless of the module/function emitting the message?)</p>
16
2009-05-18T20:43:48Z
879,765
<p>Do not use global. It's an accident waiting to happen.</p> <p>You can give your loggers any "."-separated names that are meaningful to you.</p> <p>You can control them as a hierarchy. If you have loggers named <code>a.b.c</code> and <code>a.b.d</code>, you can check the logging level for <code>a.b</code> and alter both loggers.</p> <p>You can have any number of loggers -- they're inexpensive.</p> <p>The most common design pattern is one logger per module. See <a href="http://stackoverflow.com/questions/401277/naming-python-loggers">http://stackoverflow.com/questions/401277/naming-python-loggers</a></p> <p>Do this.</p> <pre><code>import logging logger= logging.getLogger( "module_name" ) logger_a = logger.getLogger( "module_name.function_a" ) logger_b = logger.getLogger( "module_name.function_b" ) def function_a( ... ): logger_a.debug( "a message" ) def functio_b( ... ): logger_b.debug( "another message" ) if __name__ == "__main__": logging.basicConfig( stream=sys.stderr, level=logging.DEBUG ) logger_a.setLevel( logging.DEBUG ) logger_b.setLevel( logging.WARN ) ... etc ... </code></pre>
12
2009-05-18T20:49:26Z
[ "python", "logging" ]
logging with filters
879,732
<p>I'm using Logging (import logging) to log messages.</p> <p>Within 1 single module, I am logging messages at the debug level (my_logger.debug('msg')); </p> <p>Some of these debug messages come from function_a() and others from function_b(); I'd like to be able to enable/disable logging based on whether they come from a or from b; </p> <p>I'm guessing that I have to use Logging's filtering mechanism. </p> <p>Can someone please show me how the code below would need to be instrumented to do what I want? thanks.</p> <pre><code>import logging logger= logging.getLogger( "module_name" ) def function_a( ... ): logger.debug( "a message" ) def function_b( ... ): logger.debug( "another message" ) if __name__ == "__main__": logging.basicConfig( stream=sys.stderr, level=logging.DEBUG ) #don't want function_a()'s noise -&gt; .... #somehow filter-out function_a's logging function_a() #don't want function_b()'s noise -&gt; .... #somehow filter-out function_b's logging function_b() </code></pre> <p>If I scaled this simple example to more modules and more funcs per module, I'd be concerned about lots of loggers; </p> <p>Can I keep it down to 1 logger per module? Note that the log messages are "structured", i.e. if the function(s) logging it are doing some parsing work, they all contain a prefix logger.debug("parsing: xxx") - can I somehow with a single line just shut-off all "parsing" messages (regardless of the module/function emitting the message?)</p>
16
2009-05-18T20:43:48Z
879,937
<p>Just implement a subclass of <code>logging.Filter</code>: <a href="http://docs.python.org/library/logging.html#filter-objects">http://docs.python.org/library/logging.html#filter-objects</a>. It will have one method, <code>filter(record)</code>, that examines the log record and returns True to log it or False to discard it. Then you can install the filter on either a <code>Logger</code> or a <code>Handler</code> by calling its <code>addFilter(filter)</code> method.</p> <p>Example:</p> <pre><code>class NoParsingFilter(logging.Filter): def filter(self, record): return not record.getMessage().startswith('parsing') logger.addFilter(NoParsingFilter()) </code></pre> <p>Or something like that, anyway.</p>
25
2009-05-18T21:27:07Z
[ "python", "logging" ]
How do you know when looking at the list of attributes and methods listed in a dir which are attributes and which are methods?
880,160
<p>I am working through trying to learn to program in Python and am focused on getting a better handle on how to use Standard and other modules. The dir function seems really powerful in the interpreter but I wonder if I am missing something because of my lack of OOP background. Using S.Lotts book I decided to use his Die class to learn more about syntax and use of classes and instances. </p> <p>Here is the original code:</p> <pre><code>class Die(object): ''' simulate a six-sided die ''' def roll(self): self.value=random.randrange(1,7) return self.value def getValue(self): return self.value </code></pre> <p>I was looking at that and after creating some instances I wondered if the word value was a keyword somehow and what the use of the word object in the class statement did and so I decided to find out by changing the class definition to the following:</p> <pre><code>class Die(): ''' simulate a six-sided die ''' def roll(self): self.ban=random.randrange(1,7) return self.ban def getValue(self): return self.ban </code></pre> <p>That change showed me that I got the same behavior from my instances but the following methods/attributes were missing from the instances when I did dir:</p> <pre><code>'__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', _repr__', '__setattr__', '__str__', '__weakref__' </code></pre> <p>I also figured out that when I did a dir on an instance I had an additional keyword-<b>ban</b> which I finally figured out was an attribute of my instance. This helped me understand that I could use <b>d1.ban</b> to access the value of my instance. The only reason I could figure out that this was an attribute was I typed <b>d1.happy</b> and got an <b>AttributeError</b> I figured out that <b>d1.GetValue</b> was a method attached to Die because that is what the interpreter told me. </p> <p>So when I am trying to use some complicated but helpful module like BeautifulSoup how can I know which of the things that are listed are attributes of my instance or methods of my instance after typing <b>dir(instance)</b>. I would need to know this because this poking around has taught me that with attributes I am calling the result of a method and with methods I am invoking a function on my instance.</p> <p>This question is probably too wordy but it sure did help me better understand the difference between attributes and methods. Specifically, when I look at the result of calling dir on an instance of my Die class I see this</p> <pre><code>['__doc__', '__module__', 'ban', 'getValue', 'roll'] </code></pre> <p>So it would seem useful to know by looking at that list which are attributes and which are methods without having to resort to trial and error or result to typing in <b>hasattr(myInstance,suspectedAttributeName)</b>.</p> <p>After posting the question I tried </p> <pre><code>for each in dir(d1): print hasattr(d1,each) </code></pre> <p>which tells me strictly speaking that all methods are attributes. but I can't call a method without the <b>()</b> so it seems to me that the hasattr() is misleading.</p>
4
2009-05-18T22:42:38Z
880,218
<blockquote> <p>which tells me strictly speaking that all methods are attributes. but I can't call a method without the () so it seems to me that the hasattr() is misleading.</p> </blockquote> <p>Why is it misleading? If <code>obj.ban()</code> is a method, then <code>obj.ban</code> is the corresponding attribute. You can have code like this:</p> <pre><code>print obj.getValue() </code></pre> <p>or</p> <pre><code>get = obj.getValue print get() </code></pre> <p>If you want to get a list of methods on an object, you can try this function. It's not perfect, since it will also trigger for callable attributes that aren't methods, but for 99% of cases should be good enough:</p> <pre><code>def methods(obj): attrs = (getattr(obj, n) for n in dir(obj)) return [a for a in attrs if a.hasattr("__call__")] </code></pre>
2
2009-05-18T23:07:30Z
[ "python", "attributes", "methods", "python-datamodel" ]
How do you know when looking at the list of attributes and methods listed in a dir which are attributes and which are methods?
880,160
<p>I am working through trying to learn to program in Python and am focused on getting a better handle on how to use Standard and other modules. The dir function seems really powerful in the interpreter but I wonder if I am missing something because of my lack of OOP background. Using S.Lotts book I decided to use his Die class to learn more about syntax and use of classes and instances. </p> <p>Here is the original code:</p> <pre><code>class Die(object): ''' simulate a six-sided die ''' def roll(self): self.value=random.randrange(1,7) return self.value def getValue(self): return self.value </code></pre> <p>I was looking at that and after creating some instances I wondered if the word value was a keyword somehow and what the use of the word object in the class statement did and so I decided to find out by changing the class definition to the following:</p> <pre><code>class Die(): ''' simulate a six-sided die ''' def roll(self): self.ban=random.randrange(1,7) return self.ban def getValue(self): return self.ban </code></pre> <p>That change showed me that I got the same behavior from my instances but the following methods/attributes were missing from the instances when I did dir:</p> <pre><code>'__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', _repr__', '__setattr__', '__str__', '__weakref__' </code></pre> <p>I also figured out that when I did a dir on an instance I had an additional keyword-<b>ban</b> which I finally figured out was an attribute of my instance. This helped me understand that I could use <b>d1.ban</b> to access the value of my instance. The only reason I could figure out that this was an attribute was I typed <b>d1.happy</b> and got an <b>AttributeError</b> I figured out that <b>d1.GetValue</b> was a method attached to Die because that is what the interpreter told me. </p> <p>So when I am trying to use some complicated but helpful module like BeautifulSoup how can I know which of the things that are listed are attributes of my instance or methods of my instance after typing <b>dir(instance)</b>. I would need to know this because this poking around has taught me that with attributes I am calling the result of a method and with methods I am invoking a function on my instance.</p> <p>This question is probably too wordy but it sure did help me better understand the difference between attributes and methods. Specifically, when I look at the result of calling dir on an instance of my Die class I see this</p> <pre><code>['__doc__', '__module__', 'ban', 'getValue', 'roll'] </code></pre> <p>So it would seem useful to know by looking at that list which are attributes and which are methods without having to resort to trial and error or result to typing in <b>hasattr(myInstance,suspectedAttributeName)</b>.</p> <p>After posting the question I tried </p> <pre><code>for each in dir(d1): print hasattr(d1,each) </code></pre> <p>which tells me strictly speaking that all methods are attributes. but I can't call a method without the <b>()</b> so it seems to me that the hasattr() is misleading.</p>
4
2009-05-18T22:42:38Z
880,222
<p>Ideally, when using a complicated library like BeautifulSoup, you should consult its documentation to see what methods each class provides. However, in the rare case where you don't have easily accessible documentation, you can check for the presence of methods using the following. </p> <p>All methods, which themselves are objects, implement the <code>__call__</code> method and can be checked using the callable() method which returns <code>True</code>, if the value being checked has the <code>__call__</code> method. </p> <p>The following code should work.</p> <pre><code>x = Die() x.roll() for attribute in dir(x) : print attribute, callable(getattr(x, attribute)) </code></pre> <p>The above code would return true for all the methods and false for all non callable attributes (such as data members like ban). However, this method also returns <code>True</code> for any callable objects (like inner classes). you can also check if the type of the attribute is <code>instancemethod</code></p>
1
2009-05-18T23:08:30Z
[ "python", "attributes", "methods", "python-datamodel" ]
How do you know when looking at the list of attributes and methods listed in a dir which are attributes and which are methods?
880,160
<p>I am working through trying to learn to program in Python and am focused on getting a better handle on how to use Standard and other modules. The dir function seems really powerful in the interpreter but I wonder if I am missing something because of my lack of OOP background. Using S.Lotts book I decided to use his Die class to learn more about syntax and use of classes and instances. </p> <p>Here is the original code:</p> <pre><code>class Die(object): ''' simulate a six-sided die ''' def roll(self): self.value=random.randrange(1,7) return self.value def getValue(self): return self.value </code></pre> <p>I was looking at that and after creating some instances I wondered if the word value was a keyword somehow and what the use of the word object in the class statement did and so I decided to find out by changing the class definition to the following:</p> <pre><code>class Die(): ''' simulate a six-sided die ''' def roll(self): self.ban=random.randrange(1,7) return self.ban def getValue(self): return self.ban </code></pre> <p>That change showed me that I got the same behavior from my instances but the following methods/attributes were missing from the instances when I did dir:</p> <pre><code>'__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', _repr__', '__setattr__', '__str__', '__weakref__' </code></pre> <p>I also figured out that when I did a dir on an instance I had an additional keyword-<b>ban</b> which I finally figured out was an attribute of my instance. This helped me understand that I could use <b>d1.ban</b> to access the value of my instance. The only reason I could figure out that this was an attribute was I typed <b>d1.happy</b> and got an <b>AttributeError</b> I figured out that <b>d1.GetValue</b> was a method attached to Die because that is what the interpreter told me. </p> <p>So when I am trying to use some complicated but helpful module like BeautifulSoup how can I know which of the things that are listed are attributes of my instance or methods of my instance after typing <b>dir(instance)</b>. I would need to know this because this poking around has taught me that with attributes I am calling the result of a method and with methods I am invoking a function on my instance.</p> <p>This question is probably too wordy but it sure did help me better understand the difference between attributes and methods. Specifically, when I look at the result of calling dir on an instance of my Die class I see this</p> <pre><code>['__doc__', '__module__', 'ban', 'getValue', 'roll'] </code></pre> <p>So it would seem useful to know by looking at that list which are attributes and which are methods without having to resort to trial and error or result to typing in <b>hasattr(myInstance,suspectedAttributeName)</b>.</p> <p>After posting the question I tried </p> <pre><code>for each in dir(d1): print hasattr(d1,each) </code></pre> <p>which tells me strictly speaking that all methods are attributes. but I can't call a method without the <b>()</b> so it seems to me that the hasattr() is misleading.</p>
4
2009-05-18T22:42:38Z
880,224
<p>There is a built in method called callable. You can apply it to any object and it will return True/False depending on if it can be called. e.g.</p> <pre><code>&gt;&gt;&gt; def foo(): ... print "This is the only function now" ... &gt;&gt;&gt; localDictionary = dir() &gt;&gt;&gt; for item in localDictionary: ... print repr(item) + "is callable: " + str(callable(locals()[item])) '__builtins__'is callable: False '__doc__'is callable: False '__name__'is callable: False 'foo'is callable: True </code></pre> <p>Note the locals() call will return a dictionary containing everything defined in your current scope. I did this because the items out of the dictionary are just strings, and we need to run callable on the actual object.</p>
1
2009-05-18T23:09:17Z
[ "python", "attributes", "methods", "python-datamodel" ]
How do you know when looking at the list of attributes and methods listed in a dir which are attributes and which are methods?
880,160
<p>I am working through trying to learn to program in Python and am focused on getting a better handle on how to use Standard and other modules. The dir function seems really powerful in the interpreter but I wonder if I am missing something because of my lack of OOP background. Using S.Lotts book I decided to use his Die class to learn more about syntax and use of classes and instances. </p> <p>Here is the original code:</p> <pre><code>class Die(object): ''' simulate a six-sided die ''' def roll(self): self.value=random.randrange(1,7) return self.value def getValue(self): return self.value </code></pre> <p>I was looking at that and after creating some instances I wondered if the word value was a keyword somehow and what the use of the word object in the class statement did and so I decided to find out by changing the class definition to the following:</p> <pre><code>class Die(): ''' simulate a six-sided die ''' def roll(self): self.ban=random.randrange(1,7) return self.ban def getValue(self): return self.ban </code></pre> <p>That change showed me that I got the same behavior from my instances but the following methods/attributes were missing from the instances when I did dir:</p> <pre><code>'__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', _repr__', '__setattr__', '__str__', '__weakref__' </code></pre> <p>I also figured out that when I did a dir on an instance I had an additional keyword-<b>ban</b> which I finally figured out was an attribute of my instance. This helped me understand that I could use <b>d1.ban</b> to access the value of my instance. The only reason I could figure out that this was an attribute was I typed <b>d1.happy</b> and got an <b>AttributeError</b> I figured out that <b>d1.GetValue</b> was a method attached to Die because that is what the interpreter told me. </p> <p>So when I am trying to use some complicated but helpful module like BeautifulSoup how can I know which of the things that are listed are attributes of my instance or methods of my instance after typing <b>dir(instance)</b>. I would need to know this because this poking around has taught me that with attributes I am calling the result of a method and with methods I am invoking a function on my instance.</p> <p>This question is probably too wordy but it sure did help me better understand the difference between attributes and methods. Specifically, when I look at the result of calling dir on an instance of my Die class I see this</p> <pre><code>['__doc__', '__module__', 'ban', 'getValue', 'roll'] </code></pre> <p>So it would seem useful to know by looking at that list which are attributes and which are methods without having to resort to trial and error or result to typing in <b>hasattr(myInstance,suspectedAttributeName)</b>.</p> <p>After posting the question I tried </p> <pre><code>for each in dir(d1): print hasattr(d1,each) </code></pre> <p>which tells me strictly speaking that all methods are attributes. but I can't call a method without the <b>()</b> so it seems to me that the hasattr() is misleading.</p>
4
2009-05-18T22:42:38Z
880,240
<p>Instead of: "<code>print hasattr(d1,each)</code>", try: "<code>print each, type(getattr(d1,each))</code>". You should find the results informative. </p> <p>Also, in place of <code>dir()</code> try <code>help()</code>, which I think you're really looking for.</p>
7
2009-05-18T23:16:17Z
[ "python", "attributes", "methods", "python-datamodel" ]
How do you know when looking at the list of attributes and methods listed in a dir which are attributes and which are methods?
880,160
<p>I am working through trying to learn to program in Python and am focused on getting a better handle on how to use Standard and other modules. The dir function seems really powerful in the interpreter but I wonder if I am missing something because of my lack of OOP background. Using S.Lotts book I decided to use his Die class to learn more about syntax and use of classes and instances. </p> <p>Here is the original code:</p> <pre><code>class Die(object): ''' simulate a six-sided die ''' def roll(self): self.value=random.randrange(1,7) return self.value def getValue(self): return self.value </code></pre> <p>I was looking at that and after creating some instances I wondered if the word value was a keyword somehow and what the use of the word object in the class statement did and so I decided to find out by changing the class definition to the following:</p> <pre><code>class Die(): ''' simulate a six-sided die ''' def roll(self): self.ban=random.randrange(1,7) return self.ban def getValue(self): return self.ban </code></pre> <p>That change showed me that I got the same behavior from my instances but the following methods/attributes were missing from the instances when I did dir:</p> <pre><code>'__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', _repr__', '__setattr__', '__str__', '__weakref__' </code></pre> <p>I also figured out that when I did a dir on an instance I had an additional keyword-<b>ban</b> which I finally figured out was an attribute of my instance. This helped me understand that I could use <b>d1.ban</b> to access the value of my instance. The only reason I could figure out that this was an attribute was I typed <b>d1.happy</b> and got an <b>AttributeError</b> I figured out that <b>d1.GetValue</b> was a method attached to Die because that is what the interpreter told me. </p> <p>So when I am trying to use some complicated but helpful module like BeautifulSoup how can I know which of the things that are listed are attributes of my instance or methods of my instance after typing <b>dir(instance)</b>. I would need to know this because this poking around has taught me that with attributes I am calling the result of a method and with methods I am invoking a function on my instance.</p> <p>This question is probably too wordy but it sure did help me better understand the difference between attributes and methods. Specifically, when I look at the result of calling dir on an instance of my Die class I see this</p> <pre><code>['__doc__', '__module__', 'ban', 'getValue', 'roll'] </code></pre> <p>So it would seem useful to know by looking at that list which are attributes and which are methods without having to resort to trial and error or result to typing in <b>hasattr(myInstance,suspectedAttributeName)</b>.</p> <p>After posting the question I tried </p> <pre><code>for each in dir(d1): print hasattr(d1,each) </code></pre> <p>which tells me strictly speaking that all methods are attributes. but I can't call a method without the <b>()</b> so it seems to me that the hasattr() is misleading.</p>
4
2009-05-18T22:42:38Z
880,969
<p>Consider using the standard library's <code>inspect</code> module -- it's often the handiest approach to introspection, packaging up substantial chunks of functionality (you could implement that from scratch, but reusing well-tested, well-designed code is a good thing). See <a href="http://docs.python.org/library/inspect.html" rel="nofollow">http://docs.python.org/library/inspect.html</a> for all the details, but for example <code>inspect.getmembers(foo, inspect.ismethod)</code> is an excellent way to get all methods of foo (you'll get <code>(name, value)</code> pairs sorted by name).</p>
4
2009-05-19T04:25:07Z
[ "python", "attributes", "methods", "python-datamodel" ]
How do you know when looking at the list of attributes and methods listed in a dir which are attributes and which are methods?
880,160
<p>I am working through trying to learn to program in Python and am focused on getting a better handle on how to use Standard and other modules. The dir function seems really powerful in the interpreter but I wonder if I am missing something because of my lack of OOP background. Using S.Lotts book I decided to use his Die class to learn more about syntax and use of classes and instances. </p> <p>Here is the original code:</p> <pre><code>class Die(object): ''' simulate a six-sided die ''' def roll(self): self.value=random.randrange(1,7) return self.value def getValue(self): return self.value </code></pre> <p>I was looking at that and after creating some instances I wondered if the word value was a keyword somehow and what the use of the word object in the class statement did and so I decided to find out by changing the class definition to the following:</p> <pre><code>class Die(): ''' simulate a six-sided die ''' def roll(self): self.ban=random.randrange(1,7) return self.ban def getValue(self): return self.ban </code></pre> <p>That change showed me that I got the same behavior from my instances but the following methods/attributes were missing from the instances when I did dir:</p> <pre><code>'__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', _repr__', '__setattr__', '__str__', '__weakref__' </code></pre> <p>I also figured out that when I did a dir on an instance I had an additional keyword-<b>ban</b> which I finally figured out was an attribute of my instance. This helped me understand that I could use <b>d1.ban</b> to access the value of my instance. The only reason I could figure out that this was an attribute was I typed <b>d1.happy</b> and got an <b>AttributeError</b> I figured out that <b>d1.GetValue</b> was a method attached to Die because that is what the interpreter told me. </p> <p>So when I am trying to use some complicated but helpful module like BeautifulSoup how can I know which of the things that are listed are attributes of my instance or methods of my instance after typing <b>dir(instance)</b>. I would need to know this because this poking around has taught me that with attributes I am calling the result of a method and with methods I am invoking a function on my instance.</p> <p>This question is probably too wordy but it sure did help me better understand the difference between attributes and methods. Specifically, when I look at the result of calling dir on an instance of my Die class I see this</p> <pre><code>['__doc__', '__module__', 'ban', 'getValue', 'roll'] </code></pre> <p>So it would seem useful to know by looking at that list which are attributes and which are methods without having to resort to trial and error or result to typing in <b>hasattr(myInstance,suspectedAttributeName)</b>.</p> <p>After posting the question I tried </p> <pre><code>for each in dir(d1): print hasattr(d1,each) </code></pre> <p>which tells me strictly speaking that all methods are attributes. but I can't call a method without the <b>()</b> so it seems to me that the hasattr() is misleading.</p>
4
2009-05-18T22:42:38Z
884,385
<p>This <code>info</code> module inspired from Dive into Python serves the purpose. </p> <pre><code>def info(obj, spacing=20, collapse=1, variables=False): '''Print methods and their doc Strings Takes any object''' if variables: methodList = [method for method in dir(obj)] else: methodList = [method for method in dir(obj) if callable(getattr(obj,method))] #print methodList print '\n'.join(['%s %s' % (method.ljust(spacing), " ".join(str(getattr(obj,method).__doc__).split())) for method in methodList]) if __name__=='__main__': info(list) </code></pre>
2
2009-05-19T18:40:25Z
[ "python", "attributes", "methods", "python-datamodel" ]
How to strip html/javascript from text input in django
880,188
<p>What is the easiest way to strip all html/javascript from a string?</p>
51
2009-05-18T22:53:47Z
880,212
<p>The <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#striptags">striptags</a> template filter.</p> <pre><code>{{ value|striptags }} </code></pre>
34
2009-05-18T23:04:13Z
[ "python", "django" ]
How to strip html/javascript from text input in django
880,188
<p>What is the easiest way to strip all html/javascript from a string?</p>
51
2009-05-18T22:53:47Z
880,238
<p>If you want to strip tags in the python, you can use:</p> <pre><code>from django.utils.html import strip_tags strip_tags(string_value) </code></pre> <p>EDIT: If you are using strip_tags, than you should update your django. Because security researchers found a way in order to bypass strip_tags . Further information : <a href="http://www.mehmetince.net/django-strip_tags-bypass-vulnerability-exploit/">http://www.mehmetince.net/django-strip_tags-bypass-vulnerability-exploit/</a></p>
112
2009-05-18T23:15:37Z
[ "python", "django" ]
How to strip html/javascript from text input in django
880,188
<p>What is the easiest way to strip all html/javascript from a string?</p>
51
2009-05-18T22:53:47Z
6,649,408
<p>nice snippet, if you want to hold some tags and strip the rest:</p> <p><a href="http://djangosnippets.org/snippets/295/" rel="nofollow">http://djangosnippets.org/snippets/295/</a></p>
-2
2011-07-11T11:27:48Z
[ "python", "django" ]
Can modules have properties the same way that objects can?
880,530
<p>With python properties, I can make it such that </p> <pre><code>obj.y </code></pre> <p>calls a function rather than just returning a value.</p> <p>Is there a way to do this with modules? I have a case where I want</p> <pre><code>module.y </code></pre> <p>to call a function, rather than just returning the value stored there.</p>
54
2009-05-19T01:03:31Z
880,550
<p>Only instances of new-style classes can have properties. You can make Python believe such an instance is a module by stashing it in <code>sys.modules[thename] = theinstance</code>. So, for example, your m.py module file could be:</p> <pre><code>import sys class _M(object): def __init__(self): self.c = 0 def afunction(self): self.c += 1 return self.c y = property(afunction) sys.modules[__name__] = _M() </code></pre> <p><sub><strong>Edited</strong>: removed an implicit dependency on globals (had nothing to do with the point of the example but did confuse things by making the original code fail!).</sub></p>
43
2009-05-19T01:09:42Z
[ "python", "properties", "python-module" ]
Can modules have properties the same way that objects can?
880,530
<p>With python properties, I can make it such that </p> <pre><code>obj.y </code></pre> <p>calls a function rather than just returning a value.</p> <p>Is there a way to do this with modules? I have a case where I want</p> <pre><code>module.y </code></pre> <p>to call a function, rather than just returning the value stored there.</p>
54
2009-05-19T01:03:31Z
880,751
<p>I would do this in order to properly inherit all the attributes of a module, and be correctly identified by isinstance()</p> <pre><code>import types class MyModule(types.ModuleType): @property def y(self): return 5 &gt;&gt;&gt; a=MyModule("test") &gt;&gt;&gt; a &lt;module 'test' (built-in)&gt; &gt;&gt;&gt; a.y 5 </code></pre> <p>And then you can insert this into sys.modules</p>
34
2009-05-19T02:40:12Z
[ "python", "properties", "python-module" ]
Can modules have properties the same way that objects can?
880,530
<p>With python properties, I can make it such that </p> <pre><code>obj.y </code></pre> <p>calls a function rather than just returning a value.</p> <p>Is there a way to do this with modules? I have a case where I want</p> <pre><code>module.y </code></pre> <p>to call a function, rather than just returning the value stored there.</p>
54
2009-05-19T01:03:31Z
34,829,743
<p>A typical use case is: enriching a (huge) existing module with some (few) dynamic attributes - without turning all module stuff into a class layout. Unfortunately a most simple module class patch like <code>sys.modules[__name__].__class__ = MyPropertyModule</code> fails with <code>TypeError: __class__ assignment: only for heap types</code>. So module creation needs to be rewired.</p> <p>This approach does it without Python import hooks, just by having some prolog on top of the module code:</p> <pre><code>""" Module property example """ if '_orgmod' not in globals(): # constant prolog for having module properties print "PropertyModule stub", __name__ import sys, types class PropertyModule(types.ModuleType): def __str__(self): return "&lt;PropertyModule %r from %r&gt;" % (self.__name__, self.__file__) modnew = PropertyModule(__name__, __doc__) modnew.__file__ = __file__ modnew._orgmod = modnew.__orgmod__ = sys.modules[__name__] sys.modules[__name__] = modnew exec sys._getframe().f_code in modnew.__dict__ del modnew._orgmod else: # normal module code (usually vast) .. print "module init start" a = 7 def f(): return "function f: %s" % (a * 3) # defines 'dynval' as dynamic module property __orgmod__.PropertyModule.dynval = property(lambda self:f()) print "module init end." </code></pre> <p>Note: Something like <code>from testmodule import dynval</code> will produce a frozen copy of course.</p>
0
2016-01-16T17:13:19Z
[ "python", "properties", "python-module" ]
cxxTestgen.py throw a syntax error
880,639
<p>I've follow the tutorial on <a href="http://cxxtest.com/index.php?title=Visual_Studio_integration" rel="nofollow">cxxtest Visual Studio Integration</a> and I've looked on google but found nothing.</p> <p>When I try to lunch a basic test with cxxtest and visual studio I get this error :</p> <pre><code>1&gt;Generating main code for test suite 1&gt; File "C:/cxxtest/cxxtestgen.py", line 60 1&gt; print usageString() 1&gt; ^ 1&gt;SyntaxError: invalid syntax </code></pre> <p>I am at the step 7 of the tutorial and all my setting are set exactly as they are on the tutorial.</p> <p>this is the basic test script :</p> <pre><code>#include &lt;cxxtest/TestSuite.h&gt; class MyTestSuite : public CxxTest::TestSuite { public: void testAddition( void ) { TS_ASSERT( 1 + 1 &gt; 1 ); TS_ASSERT_EQUALS( 1 + 1, 2 ); } }; </code></pre> <p>Edit : I am using Python 3.0, could it be the problem?</p>
0
2009-05-19T01:50:55Z
880,666
<p>Try running the <code>cxxtestgen.py</code> on command line. Does it print the usage page?</p>
0
2009-05-19T01:58:42Z
[ "c++", "python", "visual-studio", "unit-testing" ]
cxxTestgen.py throw a syntax error
880,639
<p>I've follow the tutorial on <a href="http://cxxtest.com/index.php?title=Visual_Studio_integration" rel="nofollow">cxxtest Visual Studio Integration</a> and I've looked on google but found nothing.</p> <p>When I try to lunch a basic test with cxxtest and visual studio I get this error :</p> <pre><code>1&gt;Generating main code for test suite 1&gt; File "C:/cxxtest/cxxtestgen.py", line 60 1&gt; print usageString() 1&gt; ^ 1&gt;SyntaxError: invalid syntax </code></pre> <p>I am at the step 7 of the tutorial and all my setting are set exactly as they are on the tutorial.</p> <p>this is the basic test script :</p> <pre><code>#include &lt;cxxtest/TestSuite.h&gt; class MyTestSuite : public CxxTest::TestSuite { public: void testAddition( void ) { TS_ASSERT( 1 + 1 &gt; 1 ); TS_ASSERT_EQUALS( 1 + 1, 2 ); } }; </code></pre> <p>Edit : I am using Python 3.0, could it be the problem?</p>
0
2009-05-19T01:50:55Z
880,857
<p>You appear to be using Python 3.0 on a body of code which is not ready for python 3.0 - your best bet is to downgrade to python 2.6 until cxxtestgen.py works with python 3.0.</p> <p>See <a href="http://docs.python.org/3.0/whatsnew/3.0.html#print-is-a-function" rel="nofollow">http://docs.python.org/3.0/whatsnew/3.0.html#print-is-a-function</a> for details</p>
3
2009-05-19T03:38:35Z
[ "c++", "python", "visual-studio", "unit-testing" ]
cxxTestgen.py throw a syntax error
880,639
<p>I've follow the tutorial on <a href="http://cxxtest.com/index.php?title=Visual_Studio_integration" rel="nofollow">cxxtest Visual Studio Integration</a> and I've looked on google but found nothing.</p> <p>When I try to lunch a basic test with cxxtest and visual studio I get this error :</p> <pre><code>1&gt;Generating main code for test suite 1&gt; File "C:/cxxtest/cxxtestgen.py", line 60 1&gt; print usageString() 1&gt; ^ 1&gt;SyntaxError: invalid syntax </code></pre> <p>I am at the step 7 of the tutorial and all my setting are set exactly as they are on the tutorial.</p> <p>this is the basic test script :</p> <pre><code>#include &lt;cxxtest/TestSuite.h&gt; class MyTestSuite : public CxxTest::TestSuite { public: void testAddition( void ) { TS_ASSERT( 1 + 1 &gt; 1 ); TS_ASSERT_EQUALS( 1 + 1, 2 ); } }; </code></pre> <p>Edit : I am using Python 3.0, could it be the problem?</p>
0
2009-05-19T01:50:55Z
8,950,829
<p>The previous comments correctly note that CxxTest 3.x did not support Python 3.x. However, CxxTest 4.0 has recently been released, and it supports Python 3.1 and 3.2.</p> <p>See the CxxTest Home Page: <a href="http://cxxtest.com" rel="nofollow">cxxtest website</a></p>
1
2012-01-21T05:07:48Z
[ "c++", "python", "visual-studio", "unit-testing" ]
Should I implement the mixed use of BeautifulSoup and REGEXs or rely solely on BS
880,687
<p>I have some data I need to extract from a collection of html files. I am not sure if the data resides in a div element, a table element or a combined element (where the div tag is an element of a table. I have seen all three cases. My files are large-as big as 2 mb and I have tens of thousands of them. So far I have looked at the td elements in the tables and looked at the lonely div elements. It seems to me that the longest time is taking the file to be <b>souped</b>, upwards of 30 seconds. I played around with creating a regular expression to find the data I am looking for and then looking for the next close tag-table,tr,td,or div to determine what type of structure my text is contained in. finding the matching open tag, snipping that section and then wrapping it all in open and close HTML tags</p> <pre><code> stuff &lt;div&gt; stuff mytext stuff &lt;/div&gt; </code></pre> <p>so I create a string that looks like:</p> <pre><code>s='&lt;div&gt;stuffmyTextstuff&lt;/div&gt;' </code></pre> <p>I then wrap the string</p> <pre><code> def stringWrapper(s): newString='&lt;HTML&gt;'+s+'&lt;/HTML&gt;' return newString </code></pre> <p>And then use BeautifulSoup</p> <pre><code>littleSoup=BeautifulSoup(newString) </code></pre> <p>I can then access the power of BeautifulSoup to do what I want with newString.</p> <p>This is running much faster than the alternative which is first test all the cell contents of all of the tables until I find my text and if I can't find it there test all the div contents.</p> <p>Am I missing something here? </p>
0
2009-05-19T02:06:57Z
880,698
<p>Have you tried <code>lxml</code>? BeautifulSoup is good but not super-fast, and I believe <code>lxml</code> can offer the same quality but often better performance.</p>
3
2009-05-19T02:11:37Z
[ "python", "regex", "beautifulsoup" ]
Should I implement the mixed use of BeautifulSoup and REGEXs or rely solely on BS
880,687
<p>I have some data I need to extract from a collection of html files. I am not sure if the data resides in a div element, a table element or a combined element (where the div tag is an element of a table. I have seen all three cases. My files are large-as big as 2 mb and I have tens of thousands of them. So far I have looked at the td elements in the tables and looked at the lonely div elements. It seems to me that the longest time is taking the file to be <b>souped</b>, upwards of 30 seconds. I played around with creating a regular expression to find the data I am looking for and then looking for the next close tag-table,tr,td,or div to determine what type of structure my text is contained in. finding the matching open tag, snipping that section and then wrapping it all in open and close HTML tags</p> <pre><code> stuff &lt;div&gt; stuff mytext stuff &lt;/div&gt; </code></pre> <p>so I create a string that looks like:</p> <pre><code>s='&lt;div&gt;stuffmyTextstuff&lt;/div&gt;' </code></pre> <p>I then wrap the string</p> <pre><code> def stringWrapper(s): newString='&lt;HTML&gt;'+s+'&lt;/HTML&gt;' return newString </code></pre> <p>And then use BeautifulSoup</p> <pre><code>littleSoup=BeautifulSoup(newString) </code></pre> <p>I can then access the power of BeautifulSoup to do what I want with newString.</p> <p>This is running much faster than the alternative which is first test all the cell contents of all of the tables until I find my text and if I can't find it there test all the div contents.</p> <p>Am I missing something here? </p>
0
2009-05-19T02:06:57Z
880,758
<p>BeautifulSoup uses regex internally (it's what separates it from other XML parsers) so you'll likely find yourself just repeating what it does. If you want a faster option then use try/catch to attempt an lxml or etree parse first then try BeautifulSoup and/or tidylib to parse broken HTML if the parser fails.</p> <p>It seems for what you are doing you really want to be using XPath or XSLT to find and retrieve your data, lxml can do both.</p> <p>Finally, given the size of your files you should probably parse using a path or file handle so the source can be read incrementally rather than held in memory for the parse.</p>
3
2009-05-19T02:42:28Z
[ "python", "regex", "beautifulsoup" ]
Should I implement the mixed use of BeautifulSoup and REGEXs or rely solely on BS
880,687
<p>I have some data I need to extract from a collection of html files. I am not sure if the data resides in a div element, a table element or a combined element (where the div tag is an element of a table. I have seen all three cases. My files are large-as big as 2 mb and I have tens of thousands of them. So far I have looked at the td elements in the tables and looked at the lonely div elements. It seems to me that the longest time is taking the file to be <b>souped</b>, upwards of 30 seconds. I played around with creating a regular expression to find the data I am looking for and then looking for the next close tag-table,tr,td,or div to determine what type of structure my text is contained in. finding the matching open tag, snipping that section and then wrapping it all in open and close HTML tags</p> <pre><code> stuff &lt;div&gt; stuff mytext stuff &lt;/div&gt; </code></pre> <p>so I create a string that looks like:</p> <pre><code>s='&lt;div&gt;stuffmyTextstuff&lt;/div&gt;' </code></pre> <p>I then wrap the string</p> <pre><code> def stringWrapper(s): newString='&lt;HTML&gt;'+s+'&lt;/HTML&gt;' return newString </code></pre> <p>And then use BeautifulSoup</p> <pre><code>littleSoup=BeautifulSoup(newString) </code></pre> <p>I can then access the power of BeautifulSoup to do what I want with newString.</p> <p>This is running much faster than the alternative which is first test all the cell contents of all of the tables until I find my text and if I can't find it there test all the div contents.</p> <p>Am I missing something here? </p>
0
2009-05-19T02:06:57Z
880,763
<p>I don't quite understand what you are trying to do. But I do know that you don't need to enclose your div string with &lt; html> tags. BS will parse that just fine.</p>
1
2009-05-19T02:47:00Z
[ "python", "regex", "beautifulsoup" ]
Should I implement the mixed use of BeautifulSoup and REGEXs or rely solely on BS
880,687
<p>I have some data I need to extract from a collection of html files. I am not sure if the data resides in a div element, a table element or a combined element (where the div tag is an element of a table. I have seen all three cases. My files are large-as big as 2 mb and I have tens of thousands of them. So far I have looked at the td elements in the tables and looked at the lonely div elements. It seems to me that the longest time is taking the file to be <b>souped</b>, upwards of 30 seconds. I played around with creating a regular expression to find the data I am looking for and then looking for the next close tag-table,tr,td,or div to determine what type of structure my text is contained in. finding the matching open tag, snipping that section and then wrapping it all in open and close HTML tags</p> <pre><code> stuff &lt;div&gt; stuff mytext stuff &lt;/div&gt; </code></pre> <p>so I create a string that looks like:</p> <pre><code>s='&lt;div&gt;stuffmyTextstuff&lt;/div&gt;' </code></pre> <p>I then wrap the string</p> <pre><code> def stringWrapper(s): newString='&lt;HTML&gt;'+s+'&lt;/HTML&gt;' return newString </code></pre> <p>And then use BeautifulSoup</p> <pre><code>littleSoup=BeautifulSoup(newString) </code></pre> <p>I can then access the power of BeautifulSoup to do what I want with newString.</p> <p>This is running much faster than the alternative which is first test all the cell contents of all of the tables until I find my text and if I can't find it there test all the div contents.</p> <p>Am I missing something here? </p>
0
2009-05-19T02:06:57Z
880,821
<p>I've found that even if lxml is faster than BeautifulSoup, for documents that size it's usually best to try to reduce the size to a few kB via regex (or direct stripping) and load that into BS, as you are doing now.</p>
1
2009-05-19T03:26:33Z
[ "python", "regex", "beautifulsoup" ]
Applications of Python
880,917
<p>What are some applications for Python that <strong>relative amateur programmers</strong> can get into? For example, Ruby has Rails for building web applications. What are some cool applications of Python?</p> <p>Thanks.</p>
2
2009-05-19T04:03:09Z
880,926
<p>You can build web applications in Python. See the <a href="http://www.djangoproject.com/" rel="nofollow">Django framework</a>.</p> <p>Besides that, <a href="http://www.python.org/about/apps/" rel="nofollow">here's</a> a nice list.</p> <p>Not particularly relevant, but interesting, is the fact that NASA uses Python.</p>
5
2009-05-19T04:06:24Z
[ "python" ]
Applications of Python
880,917
<p>What are some applications for Python that <strong>relative amateur programmers</strong> can get into? For example, Ruby has Rails for building web applications. What are some cool applications of Python?</p> <p>Thanks.</p>
2
2009-05-19T04:03:09Z
880,935
<p>"cool" is a state of mind. Hence cool applications depends on your definition of cool. A Ant colony simulation is cool, if you want to implement the theory.</p> <p>Python, with its own and 3rd party libraries (batteries) has been applied in possibly all domains of day to day programming. My advise is, decide on the cool app you want to write and then see, what Python has to offer in that domain. If you are sufficiently satisfied, you can start coding. Good Luck!</p>
5
2009-05-19T04:09:35Z
[ "python" ]
Applications of Python
880,917
<p>What are some applications for Python that <strong>relative amateur programmers</strong> can get into? For example, Ruby has Rails for building web applications. What are some cool applications of Python?</p> <p>Thanks.</p>
2
2009-05-19T04:03:09Z
880,938
<p>Python is a general purpose programming language much like Ruby. It can be used for systems programming, embedded programming, desktop programming, and web programming. In short, it has about as much potential for "cool" projects as any other general purpose language.</p>
0
2009-05-19T04:11:34Z
[ "python" ]
Applications of Python
880,917
<p>What are some applications for Python that <strong>relative amateur programmers</strong> can get into? For example, Ruby has Rails for building web applications. What are some cool applications of Python?</p> <p>Thanks.</p>
2
2009-05-19T04:03:09Z
880,940
<p>Google App Engine has excellent support for developing -- and especially for deploying -- web applications in Python (with several possible frameworks, of which Django may be the most suitable one for "relative amateurs"). Apart from web apps, Blender lets you use Python for 3D graphics, Poser for apps involving moving human-like figures, SPSS for statistics, scipy and many other tools included in Enthought's distribution support Python use in scientific programming and advanced visualization, etc, etc -- the sky's the limit.</p>
15
2009-05-19T04:11:47Z
[ "python" ]
Applications of Python
880,917
<p>What are some applications for Python that <strong>relative amateur programmers</strong> can get into? For example, Ruby has Rails for building web applications. What are some cool applications of Python?</p> <p>Thanks.</p>
2
2009-05-19T04:03:09Z
880,965
<p>I like:</p> <ul> <li><a href="http://www.djangoproject.com/" rel="nofollow">Django</a>, for web development</li> <li><a href="http://www.riverbankcomputing.co.uk/software/pyqt/intro" rel="nofollow">PyQt4</a> for GUI programming</li> <li><a href="http://www.pygame.org/news.html" rel="nofollow">pygame</a> for games, input management etc</li> <li><a href="http://www.pythonware.com/products/pil/" rel="nofollow">PIL</a> - python imaging library, it's not huge application, but really helpful and library imo</li> <li>also, <a href="http://www.blender.org/" rel="nofollow">Blender</a> is an application scriptable in Python, so if you'd be into some 3D graphics, here you got it.</li> </ul> <p>If you're making applications for windows and want to ship them easily, you can also look at stuff like <a href="http://www.py2exe.org/" rel="nofollow">py2exe</a>.</p>
0
2009-05-19T04:22:35Z
[ "python" ]
Applications of Python
880,917
<p>What are some applications for Python that <strong>relative amateur programmers</strong> can get into? For example, Ruby has Rails for building web applications. What are some cool applications of Python?</p> <p>Thanks.</p>
2
2009-05-19T04:03:09Z
880,974
<p>I wasn't a programming amateur at the time, but using <a href="http://pygame.org" rel="nofollow">pygame</a> was my first intro to Python.</p>
3
2009-05-19T04:27:59Z
[ "python" ]
Applications of Python
880,917
<p>What are some applications for Python that <strong>relative amateur programmers</strong> can get into? For example, Ruby has Rails for building web applications. What are some cool applications of Python?</p> <p>Thanks.</p>
2
2009-05-19T04:03:09Z
880,993
<p>One of the first bits of Python programming I ever did was to hack on the <a href="http://www.nicotine-plus.org/" rel="nofollow">nicotine</a> client for the Soulseek peer-to-peer network to add a '/g [query]' chat command to open the default browser and search Google.</p>
0
2009-05-19T04:42:25Z
[ "python" ]
Applications of Python
880,917
<p>What are some applications for Python that <strong>relative amateur programmers</strong> can get into? For example, Ruby has Rails for building web applications. What are some cool applications of Python?</p> <p>Thanks.</p>
2
2009-05-19T04:03:09Z
881,038
<p>Probably not the most general purpose example, but I learned Python when AutoDesk Maya adopted it as a secondary programming language to complement MEL (Maya Expression Language). By comparison, it was a god-sent.</p>
0
2009-05-19T05:04:39Z
[ "python" ]