title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
sequence
Capitalize a string
352,478
<p>Does anyone know of a really simple way of capitalizing just the first letter of a string, regardless of the capitalization of the rest of the string?</p> <p>For example:</p> <pre><code>asimpletest -&gt; Asimpletest aSimpleTest -&gt; ASimpleTest </code></pre> <p>I would like to be able to do all string lengths as well.</p>
25
2008-12-09T11:42:47Z
352,513
<p>@<a href="#352494">saua</a> is right, and </p> <pre><code>str = str[:1].upper() + str[1:] </code></pre> <p>will work for any string</p>
49
2008-12-09T11:52:33Z
[ "python", "string" ]
Capitalize a string
352,478
<p>Does anyone know of a really simple way of capitalizing just the first letter of a string, regardless of the capitalization of the rest of the string?</p> <p>For example:</p> <pre><code>asimpletest -&gt; Asimpletest aSimpleTest -&gt; ASimpleTest </code></pre> <p>I would like to be able to do all string lengths as well.</p>
25
2008-12-09T11:42:47Z
14,162,785
<p>What about <code>your_string.title()</code>?</p> <p>e.g. <code>"banana".title() -&gt; Banana</code></p>
9
2013-01-04T18:30:46Z
[ "python", "string" ]
Capitalize a string
352,478
<p>Does anyone know of a really simple way of capitalizing just the first letter of a string, regardless of the capitalization of the rest of the string?</p> <p>For example:</p> <pre><code>asimpletest -&gt; Asimpletest aSimpleTest -&gt; ASimpleTest </code></pre> <p>I would like to be able to do all string lengths as well.</p>
25
2008-12-09T11:42:47Z
15,279,448
<p>this actually gives you a capitalized word, instead of just capitalizing the first letter</p> <p>cApItAlIzE -> Capitalize</p> <pre><code>def capitalize(str): return str[:1].upper() + str[1:].lower()....... </code></pre>
3
2013-03-07T18:57:11Z
[ "python", "string" ]
Capitalize a string
352,478
<p>Does anyone know of a really simple way of capitalizing just the first letter of a string, regardless of the capitalization of the rest of the string?</p> <p>For example:</p> <pre><code>asimpletest -&gt; Asimpletest aSimpleTest -&gt; ASimpleTest </code></pre> <p>I would like to be able to do all string lengths as well.</p>
25
2008-12-09T11:42:47Z
16,212,385
<pre><code>&gt;&gt;&gt; b = "my name" &gt;&gt;&gt; b.capitalize() 'My name' &gt;&gt;&gt; b.title() 'My Name' </code></pre>
63
2013-04-25T10:29:58Z
[ "python", "string" ]
Capitalize a string
352,478
<p>Does anyone know of a really simple way of capitalizing just the first letter of a string, regardless of the capitalization of the rest of the string?</p> <p>For example:</p> <pre><code>asimpletest -&gt; Asimpletest aSimpleTest -&gt; ASimpleTest </code></pre> <p>I would like to be able to do all string lengths as well.</p>
25
2008-12-09T11:42:47Z
32,772,576
<pre><code>str = str[:].upper() </code></pre> <p>this is the easiest way to do it in my opinion</p>
-2
2015-09-24T23:33:33Z
[ "python", "string" ]
Capitalize a string
352,478
<p>Does anyone know of a really simple way of capitalizing just the first letter of a string, regardless of the capitalization of the rest of the string?</p> <p>For example:</p> <pre><code>asimpletest -&gt; Asimpletest aSimpleTest -&gt; ASimpleTest </code></pre> <p>I would like to be able to do all string lengths as well.</p>
25
2008-12-09T11:42:47Z
38,990,813
<p>for capitalize first word; </p> <pre><code>a="asimpletest" print a.capitalize() </code></pre> <p>for make all the string uppercase use the following tip;</p> <pre><code>print a.upper() </code></pre> <p>this is the easy one i think.</p>
0
2016-08-17T07:42:47Z
[ "python", "string" ]
Extending builtin classes in python
352,537
<p>How can I extend a builtin class in python? I would like to add a method to the str class.<br /> I've done some searching but all I'm finding is older posts, I'm hoping someone knows of something newer.</p>
17
2008-12-09T12:01:30Z
352,546
<p>Just subclass the type</p> <pre><code>&gt;&gt;&gt; class X(str): ... def myMethod( self ): ... return int(self) ... &gt;&gt;&gt; s=X("Hi Mom") &gt;&gt;&gt; s.lower() 'hi mom' &gt;&gt;&gt; s.myMethod() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 3, in myMethod ValueError: invalid literal for int() with base 10: 'Hi Mom' &gt;&gt;&gt; z=X("271828") &gt;&gt;&gt; z.lower() '271828' &gt;&gt;&gt; z.myMethod() 271828 </code></pre>
19
2008-12-09T12:08:35Z
[ "python" ]
Extending builtin classes in python
352,537
<p>How can I extend a builtin class in python? I would like to add a method to the str class.<br /> I've done some searching but all I'm finding is older posts, I'm hoping someone knows of something newer.</p>
17
2008-12-09T12:01:30Z
33,033,631
<p>One way could be to use the "class reopening" concept (natively existing in Ruby) that can be implemented in Python using a class decorator. An exemple is given in this page: <a href="http://www.ianbicking.org/blog/2007/08/opening-python-classes.html">http://www.ianbicking.org/blog/2007/08/opening-python-classes.html</a></p> <p>I quote:</p> <p>I think with class decorators you could do this:</p> <pre><code>@extend(SomeClassThatAlreadyExists) class SomeClassThatAlreadyExists: def some_method(self, blahblahblah): stuff </code></pre> <p>Implemented like this:</p> <pre><code>def extend(class_to_extend): def decorator(extending_class): class_to_extend.__dict__.update(extending_class.__dict__) return class_to_extend return decorator </code></pre>
5
2015-10-09T08:37:13Z
[ "python" ]
Extending builtin classes in python
352,537
<p>How can I extend a builtin class in python? I would like to add a method to the str class.<br /> I've done some searching but all I'm finding is older posts, I'm hoping someone knows of something newer.</p>
17
2008-12-09T12:01:30Z
39,709,092
<p>Assuming that you can not change builtin classes. To simulate a "class reopening" like Ruby in Python3 where <code>__dict__</code> is an mappingproxy object and not dict object :</p> <pre><code>def extend(class_to_extend): def decorator(extending_class): for k,v in extending_class.__dict__.items(): if k != '__dict__': setattr(class_to_extend,k,v) return class_to_extend return decorator class A(object): def hello(self): print('Hello!') A().hello() #=&gt; Hello! #reopen class A @extend(A): class A(object): def hello(self): print('New hello!') def bye(self): print('Bye bye') A().hello() #=&gt; New hello! A().bye() #=&gt; Bye bye </code></pre>
0
2016-09-26T17:39:31Z
[ "python" ]
Weighted random selection with and without replacement
352,670
<p>Recently I needed to do weighted random selection of elements from a list, both with and without replacement. While there are well known and good algorithms for unweighted selection, and some for weighted selection without replacement (such as modifications of the resevoir algorithm), I couldn't find any good algorithms for weighted selection with replacement. I also wanted to avoid the resevoir method, as I was selecting a significant fraction of the list, which is small enough to hold in memory.</p> <p>Does anyone have any suggestions on the best approach in this situation? I have my own solutions, but I'm hoping to find something more efficient, simpler, or both.</p>
43
2008-12-09T13:15:00Z
352,735
<p>I'd recommend you start by looking at section 3.4.2 of Donald Knuth's <a href="http://rads.stackoverflow.com/amzn/click/0201896842" rel="nofollow">Seminumerical Algorithms</a>. </p> <p>If your arrays are large, there are more efficient algorithms in chapter 3 of <a href="http://rads.stackoverflow.com/amzn/click/0198522029" rel="nofollow">Principles of Random Variate Generation</a> by John Dagpunar. If your arrays are not terribly large or you're not concerned with squeezing out as much efficiency as possible, the simpler algorithms in Knuth are probably fine.</p>
4
2008-12-09T13:43:46Z
[ "python", "algorithm", "random", "random-sample" ]
Weighted random selection with and without replacement
352,670
<p>Recently I needed to do weighted random selection of elements from a list, both with and without replacement. While there are well known and good algorithms for unweighted selection, and some for weighted selection without replacement (such as modifications of the resevoir algorithm), I couldn't find any good algorithms for weighted selection with replacement. I also wanted to avoid the resevoir method, as I was selecting a significant fraction of the list, which is small enough to hold in memory.</p> <p>Does anyone have any suggestions on the best approach in this situation? I have my own solutions, but I'm hoping to find something more efficient, simpler, or both.</p>
43
2008-12-09T13:15:00Z
353,510
<p>Here's what I came up with for weighted selection without replacement:</p> <pre><code>def WeightedSelectionWithoutReplacement(l, n): """Selects without replacement n random elements from a list of (weight, item) tuples.""" l = sorted((random.random() * x[0], x[1]) for x in l) return l[-n:] </code></pre> <p>This is O(m log m) on the number of items in the list to be selected from. I'm fairly certain this will weight items correctly, though I haven't verified it in any formal sense.</p> <p>Here's what I came up with for weighted selection with replacement:</p> <pre><code>def WeightedSelectionWithReplacement(l, n): """Selects with replacement n random elements from a list of (weight, item) tuples.""" cuml = [] total_weight = 0.0 for weight, item in l: total_weight += weight cuml.append((total_weight, item)) return [cuml[bisect.bisect(cuml, random.random()*total_weight)] for x in range(n)] </code></pre> <p>This is O(m + n log m), where m is the number of items in the input list, and n is the number of items to be selected.</p>
4
2008-12-09T17:06:26Z
[ "python", "algorithm", "random", "random-sample" ]
Weighted random selection with and without replacement
352,670
<p>Recently I needed to do weighted random selection of elements from a list, both with and without replacement. While there are well known and good algorithms for unweighted selection, and some for weighted selection without replacement (such as modifications of the resevoir algorithm), I couldn't find any good algorithms for weighted selection with replacement. I also wanted to avoid the resevoir method, as I was selecting a significant fraction of the list, which is small enough to hold in memory.</p> <p>Does anyone have any suggestions on the best approach in this situation? I have my own solutions, but I'm hoping to find something more efficient, simpler, or both.</p>
43
2008-12-09T13:15:00Z
353,576
<p>One of the fastest ways to make many with replacement samples from an unchanging list is the alias method. The core intuition is that we can create a set of equal-sized bins for the weighted list that can be indexed very efficiently through bit operations, to avoid a binary search. It will turn out that, done correctly, we will need to only store two items from the original list per bin, and thus can represent the split with a single percentage.</p> <p>Let's us take the example of five equally weighted choices, <code>(a:1, b:1, c:1, d:1, e:1)</code></p> <p>To create the alias lookup:</p> <ol> <li><p>Normalize the weights such that they sum to <code>1.0</code>. <code>(a:0.2 b:0.2 c:0.2 d:0.2 e:0.2)</code> This is the probability of choosing each weight.</p></li> <li><p>Find the smallest power of 2 greater than or equal to the number of variables, and create this number of partitions, <code>|p|</code>. Each partition represents a probability mass of <code>1/|p|</code>. In this case, we create <code>8</code> partitions, each able to contain <code>0.125</code>.</p></li> <li><p>Take the variable with the least remaining weight, and place as much of it's mass as possible in an empty partition. In this example, we see that <code>a</code> fills the first partition. <code>(p1{a|null,1.0},p2,p3,p4,p5,p6,p7,p8)</code> with <code>(a:0.075, b:0.2 c:0.2 d:0.2 e:0.2)</code></p></li> <li><p>If the partition is not filled, take the variable with the most weight, and fill the partition with that variable. </p></li> </ol> <p>Repeat steps 3 and 4, until none of the weight from the original partition need be assigned to the list.</p> <p>For example, if we run another iteration of 3 and 4, we see </p> <p><code>(p1{a|null,1.0},p2{a|b,0.6},p3,p4,p5,p6,p7,p8)</code> with <code>(a:0, b:0.15 c:0.2 d:0.2 e:0.2)</code> left to be assigned</p> <p>At runtime:</p> <ol> <li><p>Get a <code>U(0,1)</code> random number, say binary <code>0.001100000</code></p></li> <li><p>bitshift it <code>lg2(p)</code>, finding the index partition. Thus, we shift it by <code>3</code>, yielding <code>001.1</code>, or position 1, and thus partition 2.</p></li> <li><p>If the partition is split, use the decimal portion of the shifted random number to decide the split. In this case, the value is <code>0.5</code>, and <code>0.5 &lt; 0.6</code>, so return <code>a</code>.</p></li> </ol> <p><a href="http://prxq.wordpress.com/2006/04/17/the-alias-method/">Here is some code and another explanation</a>, but unfortunately it doesn't use the bitshifting technique, nor have I actually verified it.</p>
31
2008-12-09T17:27:01Z
[ "python", "algorithm", "random", "random-sample" ]
Weighted random selection with and without replacement
352,670
<p>Recently I needed to do weighted random selection of elements from a list, both with and without replacement. While there are well known and good algorithms for unweighted selection, and some for weighted selection without replacement (such as modifications of the resevoir algorithm), I couldn't find any good algorithms for weighted selection with replacement. I also wanted to avoid the resevoir method, as I was selecting a significant fraction of the list, which is small enough to hold in memory.</p> <p>Does anyone have any suggestions on the best approach in this situation? I have my own solutions, but I'm hoping to find something more efficient, simpler, or both.</p>
43
2008-12-09T13:15:00Z
9,827,070
<p>The following is a description of random weighted selection of an element of a set (or multiset, if repeats are allowed), both with and without replacement in O(n) space and O(log n) time.</p> <p>It consists of implementing a binary search tree, sorted by the elements to be selected, where each <em>node</em> of the tree contains:</p> <ol> <li>the element itself (<em>element</em>)</li> <li>the un-normalized weight of the element (<em>elementweight</em>), and</li> <li>the sum of all the un-normalized weights of the left-child node and all of its children (<em>leftbranchweight</em>).</li> <li>the sum of all the un-normalized weights of the right-child node and all of its chilren (<em>rightbranchweight</em>).</li> </ol> <p>Then we randomly select an element from the BST by descending down the tree. A rough description of the algorithm follows. The algorithm is given a <em>node</em> of the tree. Then the values of <em>leftbranchweight</em>, <em>rightbranchweight</em>, and <em>elementweight</em> of <em>node</em> is summed, and the weights are divided by this sum, resulting in the values <em>leftbranchprobability</em>, <em>rightbranchprobability</em>, and <em>elementprobability</em>, respectively. Then a random number between 0 and 1 (<em>randomnumber</em>) is obtained.</p> <ul> <li>if the number is less than <em>elementprobability</em>, <ul> <li>remove the element from the BST as normal, updating <em>leftbranchweight</em> and <em>rightbranchweight</em> of all the necessary nodes, and return the element.</li> </ul></li> <li>else if the number is less than (<em>elementprobability</em> + <em>leftbranchweight</em>) <ul> <li>recurse on <em>leftchild</em> (run the algorithm using <em>leftchild</em> as <em>node</em>)</li> </ul></li> <li>else <ul> <li>recurse on <em>rightchild</em></li> </ul></li> </ul> <p>When we finally find, using these weights, which element is to be returned, we either simply return it (with replacement) or we remove it and update relevant weights in the tree (without replacement).</p> <p>DISCLAIMER: The algorithm is rough, and a treatise on the proper implementation of a BST is not attempted here; rather, it is hoped that this answer will help those who <em>really</em> need fast weighted selection without replacement (like I do).</p>
3
2012-03-22T17:07:26Z
[ "python", "algorithm", "random", "random-sample" ]
Weighted random selection with and without replacement
352,670
<p>Recently I needed to do weighted random selection of elements from a list, both with and without replacement. While there are well known and good algorithms for unweighted selection, and some for weighted selection without replacement (such as modifications of the resevoir algorithm), I couldn't find any good algorithms for weighted selection with replacement. I also wanted to avoid the resevoir method, as I was selecting a significant fraction of the list, which is small enough to hold in memory.</p> <p>Does anyone have any suggestions on the best approach in this situation? I have my own solutions, but I'm hoping to find something more efficient, simpler, or both.</p>
43
2008-12-09T13:15:00Z
20,548,895
<p>A simple approach that hasn't been mentioned here is one proposed in <a href="http://www.sciencedirect.com/science/article/pii/S002001900500298X" rel="nofollow">Efraimidis and Spirakis</a>. In python you could select m items from n >= m weighted items with strictly positive weights stored in weights, returning the selected indices, with:</p> <pre><code>import heapq import math import random def WeightedSelectionWithoutReplacement(weights, m): elt = [(math.log(random.random()) / weights[i], i) for i in range(len(weights))] return [x[1] for x in heapq.nlargest(m, elt)] </code></pre> <p>This is very similar in structure to the first approach proposed by Nick Johnson. Unfortunately, that approach is biased in selecting the elements (see the comments on the method). Efraimidis and Spirakis proved that their approach is equivalent to random sampling without replacement in the linked paper.</p>
4
2013-12-12T16:30:12Z
[ "python", "algorithm", "random", "random-sample" ]
Weighted random selection with and without replacement
352,670
<p>Recently I needed to do weighted random selection of elements from a list, both with and without replacement. While there are well known and good algorithms for unweighted selection, and some for weighted selection without replacement (such as modifications of the resevoir algorithm), I couldn't find any good algorithms for weighted selection with replacement. I also wanted to avoid the resevoir method, as I was selecting a significant fraction of the list, which is small enough to hold in memory.</p> <p>Does anyone have any suggestions on the best approach in this situation? I have my own solutions, but I'm hoping to find something more efficient, simpler, or both.</p>
43
2008-12-09T13:15:00Z
29,722,230
<p>It is possible to do Weighted Random Selection with replacement in O(1) time, after first creating an additional O(N)-sized data structure in O(N) time. The algorithm is based on the <a href="http://en.wikipedia.org/wiki/Alias_method" rel="nofollow">Alias Method</a> developed by Walker and Vose, which is well described <a href="http://www.keithschwarz.com/darts-dice-coins/" rel="nofollow">here</a>. </p> <p>The essential idea is that each bin in a histogram would be chosen with probability 1/N by a uniform RNG. So we will walk through it, and for any underpopulated bin which would would receive excess hits, assign the excess to an overpopulated bin. For each bin, we store the percentage of hits which belong to it, and the partner bin for the excess. This version tracks small and large bins in place, removing the need for an additional stack. It uses the index of the partner (stored in <code>bucket[1]</code>) as an indicator that they have already been processed.</p> <p>Here is a minimal python implementation, based on <a href="https://gist.github.com/ashelly/cc0cd6916235a04df49a" rel="nofollow">the C implementation here</a></p> <pre><code>def prep(weights): data_sz = len(weights) factor = data_sz/float(sum(weights)) data = [[w*factor, i] for i,w in enumerate(weights)] big=0 while big&lt;data_sz and data[big][0]&lt;=1.0: big+=1 for small,bucket in enumerate(data): if bucket[1] is not small: continue excess = 1.0 - bucket[0] while excess &gt; 0: if big==data_sz: break bucket[1] = big bucket = data[big] bucket[0] -= excess excess = 1.0 - bucket[0] if (excess &gt;= 0): big+=1 while big&lt;data_sz and data[big][0]&lt;=1: big+=1 return data def sample(data): r=random.random()*len(data) idx = int(r) return data[idx][1] if r-idx &gt; data[idx][0] else idx </code></pre> <p>Example usage:</p> <pre><code>TRIALS=1000 weights = [20,1.5,9.8,10,15,10,15.5,10,8,.2]; samples = [0]*len(weights) data = prep(weights) for _ in range(int(sum(weights)*TRIALS)): samples[sample(data)]+=1 result = [float(s)/TRIALS for s in samples] err = [a-b for a,b in zip(result,weights)] print(result) print([round(e,5) for e in err]) print(sum([e*e for e in err])) </code></pre>
2
2015-04-18T20:07:58Z
[ "python", "algorithm", "random", "random-sample" ]
Weighted random selection with and without replacement
352,670
<p>Recently I needed to do weighted random selection of elements from a list, both with and without replacement. While there are well known and good algorithms for unweighted selection, and some for weighted selection without replacement (such as modifications of the resevoir algorithm), I couldn't find any good algorithms for weighted selection with replacement. I also wanted to avoid the resevoir method, as I was selecting a significant fraction of the list, which is small enough to hold in memory.</p> <p>Does anyone have any suggestions on the best approach in this situation? I have my own solutions, but I'm hoping to find something more efficient, simpler, or both.</p>
43
2008-12-09T13:15:00Z
40,071,790
<p>Suppose you want to sample 3 elements without replacement from the list ['white','blue','black','yellow','green'] with a prob. distribution [0.1, 0.2, 0.4, 0.1, 0.2]. Using numpy.random module it is as easy as this:</p> <pre><code> import numpy.random as rnd sampling_size = 3 domain = ['white','blue','black','yellow','green'] probs = [.1, .2, .4, .1, .2] sample = rnd.choice(domain, size=sampling_size, replace=False, p=probs) # in short: rnd.choice(domain, sampling_size, False, probs) print(sample) # Possible output: ['white' 'black' 'blue'] </code></pre> <p>Setting the <code>replace</code> flag to <code>True</code>, you have a sampling with replacement.</p> <p>More info here: <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.choice.html#numpy.random.choice" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.choice.html#numpy.random.choice</a></p>
0
2016-10-16T15:07:49Z
[ "python", "algorithm", "random", "random-sample" ]
How to add file extensions based on file type on Linux/Unix?
352,837
<p>This is a question regarding Unix shell scripting (any shell), but any other "standard" scripting language solution would also be appreciated:</p> <p>I have a directory full of files where the filenames are hash values like this:</p> <pre><code>fd73d0cf8ee68073dce270cf7e770b97 fec8047a9186fdcc98fdbfc0ea6075ee </code></pre> <p>These files have different original file types such as png, zip, doc, pdf etc.</p> <p>Can anybody provide a script that would rename the files so they get their appropriate file extension, probably based on the output of the <code>file</code> command?</p> <h2>Answer:</h2> <p><a href="http://stackoverflow.com/questions/352837/how-to-add-file-extensions-based-on-file-type-on-linuxunix#352973">J.F. Sebastian's</a> script will work for both ouput of the filenames as well as the actual renaming.</p>
11
2008-12-09T14:10:18Z
352,846
<p>You can use</p> <pre><code>file -i filename </code></pre> <p>to get a MIME-type. You could potentially lookup the type in a list and then append an extension. You can find a <a href="http://www.iana.org/assignments/media-types/media-types.xhtml" rel="nofollow">list of MIME-types</a> and <a href="http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types" rel="nofollow">example file extensions</a> on the net.</p>
12
2008-12-09T14:13:59Z
[ "python", "linux", "bash", "unix", "shell" ]
How to add file extensions based on file type on Linux/Unix?
352,837
<p>This is a question regarding Unix shell scripting (any shell), but any other "standard" scripting language solution would also be appreciated:</p> <p>I have a directory full of files where the filenames are hash values like this:</p> <pre><code>fd73d0cf8ee68073dce270cf7e770b97 fec8047a9186fdcc98fdbfc0ea6075ee </code></pre> <p>These files have different original file types such as png, zip, doc, pdf etc.</p> <p>Can anybody provide a script that would rename the files so they get their appropriate file extension, probably based on the output of the <code>file</code> command?</p> <h2>Answer:</h2> <p><a href="http://stackoverflow.com/questions/352837/how-to-add-file-extensions-based-on-file-type-on-linuxunix#352973">J.F. Sebastian's</a> script will work for both ouput of the filenames as well as the actual renaming.</p>
11
2008-12-09T14:10:18Z
352,919
<p>Following csl's response:</p> <blockquote> <p>You can use</p> <pre><code>file -i filename </code></pre> <p>to get a MIME-type. You could potentially lookup the type in a list and then append an extension. You can find list of MIME-types and suggested file extensions on the net.</p> </blockquote> <p>I'd suggest you write a script that takes the output of <code>file -i filename</code>, and returns an extension (split on spaces, find the '/', look up that term in a table file) in your language of choice - a few lines at most. Then you can do something like:</p> <pre><code>ls | while read f; do mv "$f" "$f".`file -i "$f" | get_extension.py`; done </code></pre> <p>in bash, or throw that in a bash script. Or make the get_extension script bigger, but that makes it less useful next time you want the relevant extension.</p> <p>Edit: change from <code>for f in *</code> to <code>ls | while read f</code> because the latter handles filenames with spaces in (a particular nightmare on Windows).</p>
7
2008-12-09T14:33:48Z
[ "python", "linux", "bash", "unix", "shell" ]
How to add file extensions based on file type on Linux/Unix?
352,837
<p>This is a question regarding Unix shell scripting (any shell), but any other "standard" scripting language solution would also be appreciated:</p> <p>I have a directory full of files where the filenames are hash values like this:</p> <pre><code>fd73d0cf8ee68073dce270cf7e770b97 fec8047a9186fdcc98fdbfc0ea6075ee </code></pre> <p>These files have different original file types such as png, zip, doc, pdf etc.</p> <p>Can anybody provide a script that would rename the files so they get their appropriate file extension, probably based on the output of the <code>file</code> command?</p> <h2>Answer:</h2> <p><a href="http://stackoverflow.com/questions/352837/how-to-add-file-extensions-based-on-file-type-on-linuxunix#352973">J.F. Sebastian's</a> script will work for both ouput of the filenames as well as the actual renaming.</p>
11
2008-12-09T14:10:18Z
352,973
<p>Here's mimetypes' version:</p> <pre><code>#!/usr/bin/env python """It is a `filename -&gt; filename.ext` filter. `ext` is mime-based. """ import fileinput import mimetypes import os import sys from subprocess import Popen, PIPE if len(sys.argv) &gt; 1 and sys.argv[1] == '--rename': do_rename = True del sys.argv[1] else: do_rename = False for filename in (line.rstrip() for line in fileinput.input()): output, _ = Popen(['file', '-bi', filename], stdout=PIPE).communicate() mime = output.split(';', 1)[0].lower().strip() ext = mimetypes.guess_extension(mime, strict=False) if ext is None: ext = os.path.extsep + 'undefined' filename_ext = filename + ext print filename_ext if do_rename: os.rename(filename, filename_ext) </code></pre> <p>Example:</p> <pre> $ ls *.file? | python add-ext.py --rename avi.file.avi djvu.file.undefined doc.file.dot gif.file.gif html.file.html ico.file.obj jpg.file.jpe m3u.file.ksh mp3.file.mp3 mpg.file.m1v pdf.file.pdf pdf.file2.pdf pdf.file3.pdf png.file.png tar.bz2.file.undefined </pre> <p><hr /></p> <p>Following @Phil H's response that follows @csl' response:</p> <pre><code>#!/usr/bin/env python """It is a `filename -&gt; filename.ext` filter. `ext` is mime-based. """ # Mapping of mime-types to extensions is taken form here: # http://as3corelib.googlecode.com/svn/trunk/src/com/adobe/net/MimeTypeMap.as mime2exts_list = [ ["application/andrew-inset","ez"], ["application/atom+xml","atom"], ["application/mac-binhex40","hqx"], ["application/mac-compactpro","cpt"], ["application/mathml+xml","mathml"], ["application/msword","doc"], ["application/octet-stream","bin","dms","lha","lzh","exe","class","so","dll","dmg"], ["application/oda","oda"], ["application/ogg","ogg"], ["application/pdf","pdf"], ["application/postscript","ai","eps","ps"], ["application/rdf+xml","rdf"], ["application/smil","smi","smil"], ["application/srgs","gram"], ["application/srgs+xml","grxml"], ["application/vnd.adobe.apollo-application-installer-package+zip","air"], ["application/vnd.mif","mif"], ["application/vnd.mozilla.xul+xml","xul"], ["application/vnd.ms-excel","xls"], ["application/vnd.ms-powerpoint","ppt"], ["application/vnd.rn-realmedia","rm"], ["application/vnd.wap.wbxml","wbxml"], ["application/vnd.wap.wmlc","wmlc"], ["application/vnd.wap.wmlscriptc","wmlsc"], ["application/voicexml+xml","vxml"], ["application/x-bcpio","bcpio"], ["application/x-cdlink","vcd"], ["application/x-chess-pgn","pgn"], ["application/x-cpio","cpio"], ["application/x-csh","csh"], ["application/x-director","dcr","dir","dxr"], ["application/x-dvi","dvi"], ["application/x-futuresplash","spl"], ["application/x-gtar","gtar"], ["application/x-hdf","hdf"], ["application/x-javascript","js"], ["application/x-koan","skp","skd","skt","skm"], ["application/x-latex","latex"], ["application/x-netcdf","nc","cdf"], ["application/x-sh","sh"], ["application/x-shar","shar"], ["application/x-shockwave-flash","swf"], ["application/x-stuffit","sit"], ["application/x-sv4cpio","sv4cpio"], ["application/x-sv4crc","sv4crc"], ["application/x-tar","tar"], ["application/x-tcl","tcl"], ["application/x-tex","tex"], ["application/x-texinfo","texinfo","texi"], ["application/x-troff","t","tr","roff"], ["application/x-troff-man","man"], ["application/x-troff-me","me"], ["application/x-troff-ms","ms"], ["application/x-ustar","ustar"], ["application/x-wais-source","src"], ["application/xhtml+xml","xhtml","xht"], ["application/xml","xml","xsl"], ["application/xml-dtd","dtd"], ["application/xslt+xml","xslt"], ["application/zip","zip"], ["audio/basic","au","snd"], ["audio/midi","mid","midi","kar"], ["audio/mpeg","mp3","mpga","mp2"], ["audio/x-aiff","aif","aiff","aifc"], ["audio/x-mpegurl","m3u"], ["audio/x-pn-realaudio","ram","ra"], ["audio/x-wav","wav"], ["chemical/x-pdb","pdb"], ["chemical/x-xyz","xyz"], ["image/bmp","bmp"], ["image/cgm","cgm"], ["image/gif","gif"], ["image/ief","ief"], ["image/jpeg","jpg","jpeg","jpe"], ["image/png","png"], ["image/svg+xml","svg"], ["image/tiff","tiff","tif"], ["image/vnd.djvu","djvu","djv"], ["image/vnd.wap.wbmp","wbmp"], ["image/x-cmu-raster","ras"], ["image/x-icon","ico"], ["image/x-portable-anymap","pnm"], ["image/x-portable-bitmap","pbm"], ["image/x-portable-graymap","pgm"], ["image/x-portable-pixmap","ppm"], ["image/x-rgb","rgb"], ["image/x-xbitmap","xbm"], ["image/x-xpixmap","xpm"], ["image/x-xwindowdump","xwd"], ["model/iges","igs","iges"], ["model/mesh","msh","mesh","silo"], ["model/vrml","wrl","vrml"], ["text/calendar","ics","ifb"], ["text/css","css"], ["text/html","html","htm"], ["text/plain","txt","asc"], ["text/richtext","rtx"], ["text/rtf","rtf"], ["text/sgml","sgml","sgm"], ["text/tab-separated-values","tsv"], ["text/vnd.wap.wml","wml"], ["text/vnd.wap.wmlscript","wmls"], ["text/x-setext","etx"], ["video/mpeg","mpg","mpeg","mpe"], ["video/quicktime","mov","qt"], ["video/vnd.mpegurl","m4u","mxu"], ["video/x-flv","flv"], ["video/x-msvideo","avi"], ["video/x-sgi-movie","movie"], ["x-conference/x-cooltalk","ice"]] #NOTE: take only the first extension mime2ext = dict(x[:2] for x in mime2exts_list) if __name__ == '__main__': import fileinput, os.path from subprocess import Popen, PIPE for filename in (line.rstrip() for line in fileinput.input()): output, _ = Popen(['file', '-bi', filename], stdout=PIPE).communicate() mime = output.split(';', 1)[0].lower().strip() print filename + os.path.extsep + mime2ext.get(mime, 'undefined') </code></pre> <p><hr /></p> <p>Here's a snippet for old python's versions (not tested):</p> <pre><code>#NOTE: take only the first extension mime2ext = {} for x in mime2exts_list: mime2ext[x[0]] = x[1] if __name__ == '__main__': import os import sys # this version supports only stdin (part of fileinput.input() functionality) lines = sys.stdin.read().split('\n') for line in lines: filename = line.rstrip() output = os.popen('file -bi ' + filename).read() mime = output.split(';')[0].lower().strip() try: ext = mime2ext[mime] except KeyError: ext = 'undefined' print filename + '.' + ext </code></pre> <p>It should work on Python 2.3.5 (I guess).</p>
9
2008-12-09T14:47:24Z
[ "python", "linux", "bash", "unix", "shell" ]
How to add file extensions based on file type on Linux/Unix?
352,837
<p>This is a question regarding Unix shell scripting (any shell), but any other "standard" scripting language solution would also be appreciated:</p> <p>I have a directory full of files where the filenames are hash values like this:</p> <pre><code>fd73d0cf8ee68073dce270cf7e770b97 fec8047a9186fdcc98fdbfc0ea6075ee </code></pre> <p>These files have different original file types such as png, zip, doc, pdf etc.</p> <p>Can anybody provide a script that would rename the files so they get their appropriate file extension, probably based on the output of the <code>file</code> command?</p> <h2>Answer:</h2> <p><a href="http://stackoverflow.com/questions/352837/how-to-add-file-extensions-based-on-file-type-on-linuxunix#352973">J.F. Sebastian's</a> script will work for both ouput of the filenames as well as the actual renaming.</p>
11
2008-12-09T14:10:18Z
352,985
<p>Of course, it should be added that deciding on a MIME type just based on file(1) output can be very inaccurate/vague (what's "data" ?) or even completely incorrect...</p>
2
2008-12-09T14:51:21Z
[ "python", "linux", "bash", "unix", "shell" ]
How to add file extensions based on file type on Linux/Unix?
352,837
<p>This is a question regarding Unix shell scripting (any shell), but any other "standard" scripting language solution would also be appreciated:</p> <p>I have a directory full of files where the filenames are hash values like this:</p> <pre><code>fd73d0cf8ee68073dce270cf7e770b97 fec8047a9186fdcc98fdbfc0ea6075ee </code></pre> <p>These files have different original file types such as png, zip, doc, pdf etc.</p> <p>Can anybody provide a script that would rename the files so they get their appropriate file extension, probably based on the output of the <code>file</code> command?</p> <h2>Answer:</h2> <p><a href="http://stackoverflow.com/questions/352837/how-to-add-file-extensions-based-on-file-type-on-linuxunix#352973">J.F. Sebastian's</a> script will work for both ouput of the filenames as well as the actual renaming.</p>
11
2008-12-09T14:10:18Z
2,352,986
<p>Agreeing with Keltia, and elaborating some on his answer:</p> <p>Take care -- some filetypes may be problematic. <a href="http://www.linuxquestions.org/questions/showthread.php?p=3843206#post3843206" rel="nofollow">JPEG2000</a>, for example.<br> And others might return too much info given the "file" command without any option tags. The way to <a href="http://www.linuxquestions.org/questions/showthread.php?p=3880220#post3880220" rel="nofollow">avoid</a> this is to use "file -b" for a brief return of information.<br><br>BZT</p>
0
2010-02-28T22:40:36Z
[ "python", "linux", "bash", "unix", "shell" ]
Making Python default to another version installed on a shared host
353,148
<p>I am on a shared host and can not change the symbolic link to Python2.4, it defaults to 2.3. I tried creating a sym link in the director I would be working on to 2.4, but it seems the the 'global' python interpreter under /usr/bin/python take presedence unless I run it as ./python. What alternative ways are there to override this behaviour?</p>
1
2008-12-09T15:35:15Z
353,159
<p>Create a symlink and prepend the path to your PATH variable:</p> <pre><code>ln -s /usr/bin/python2.4 $HOME/bin/python export PATH="$HOME/bin:$PATH" </code></pre>
2
2008-12-09T15:37:31Z
[ "python", "linux" ]
Making Python default to another version installed on a shared host
353,148
<p>I am on a shared host and can not change the symbolic link to Python2.4, it defaults to 2.3. I tried creating a sym link in the director I would be working on to 2.4, but it seems the the 'global' python interpreter under /usr/bin/python take presedence unless I run it as ./python. What alternative ways are there to override this behaviour?</p>
1
2008-12-09T15:35:15Z
353,200
<p>If you're working from the shell, you can create a symbolic link as suggested and update your path in the .profile. This is described in a previous post.</p> <p>In case these are CGI/whatever scripts that you only run on your shared host, you can alter the shebang line at the top of your scripts that tell the system what interpreter to run the script with.</p> <p>I.e. change</p> <pre><code>#!/usr/bin/env python </code></pre> <p>to</p> <pre><code>#!/whatever/the/path/to/your/version/python </code></pre>
3
2008-12-09T15:47:16Z
[ "python", "linux" ]
How to work with very long strings in Python?
353,152
<p>I'm tackling project euler's <a href="http://projecteuler.net/index.php?section=problems&amp;id=220" rel="nofollow">problem 220</a> (looked easy, in comparison to some of the others - thought I'd try a higher numbered one for a change!)</p> <p>So far I have:</p> <pre><code>D = "Fa" def iterate(D,num): for i in range (0,num): D = D.replace("a","A") D = D.replace("b","B") D = D.replace("A","aRbFR") D = D.replace("B","LFaLb") return D instructions = iterate("Fa",50) print instructions </code></pre> <p>Now, this works fine for low values, but when you put it to repeat higher then you just get a "Memory error". Can anyone suggest a way to overcome this? I really want a string/file that contains instructions for the next step.</p>
5
2008-12-09T15:35:58Z
353,220
<p>If you think about how many "a" and "b" characters there are in D(0), D(1), etc, you'll see that the string gets very long very quickly. Calculate how many characters there are in D(50), and then maybe think again about where you would store that much data. I make it 4.5*10^15 characters, which is 4500 TB at one byte per char.</p> <p>Come to think of it, you don't have to calculate - the problem tells you there are 10^12 steps at least, which is a terabyte of data at one byte per character, or quarter of that if you use tricks to get down to 2 bits per character. I think this would cause problems with the one-minute time limit on any kind of storage medium I have access to :-)</p>
2
2008-12-09T15:51:50Z
[ "python" ]
How to work with very long strings in Python?
353,152
<p>I'm tackling project euler's <a href="http://projecteuler.net/index.php?section=problems&amp;id=220" rel="nofollow">problem 220</a> (looked easy, in comparison to some of the others - thought I'd try a higher numbered one for a change!)</p> <p>So far I have:</p> <pre><code>D = "Fa" def iterate(D,num): for i in range (0,num): D = D.replace("a","A") D = D.replace("b","B") D = D.replace("A","aRbFR") D = D.replace("B","LFaLb") return D instructions = iterate("Fa",50) print instructions </code></pre> <p>Now, this works fine for low values, but when you put it to repeat higher then you just get a "Memory error". Can anyone suggest a way to overcome this? I really want a string/file that contains instructions for the next step.</p>
5
2008-12-09T15:35:58Z
353,242
<p>Since you can't materialize the string, you must generate it. If you yield the individual characters instead of returning the whole string, you might get it to work.</p> <pre><code>def repl220( string ): for c in string: if c == 'a': yield "aRbFR" elif c == 'b': yield "LFaLb" else yield c </code></pre> <p>Something like that will do replacement without creating a new string.</p> <p>Now, of course, you need to call it recursively, and to the appropriate depth. So, each yield isn't just a yield, it's something a bit more complex.</p> <p>Trying not to solve this for you, so I'll leave it at that.</p>
1
2008-12-09T15:56:53Z
[ "python" ]
How to work with very long strings in Python?
353,152
<p>I'm tackling project euler's <a href="http://projecteuler.net/index.php?section=problems&amp;id=220" rel="nofollow">problem 220</a> (looked easy, in comparison to some of the others - thought I'd try a higher numbered one for a change!)</p> <p>So far I have:</p> <pre><code>D = "Fa" def iterate(D,num): for i in range (0,num): D = D.replace("a","A") D = D.replace("b","B") D = D.replace("A","aRbFR") D = D.replace("B","LFaLb") return D instructions = iterate("Fa",50) print instructions </code></pre> <p>Now, this works fine for low values, but when you put it to repeat higher then you just get a "Memory error". Can anyone suggest a way to overcome this? I really want a string/file that contains instructions for the next step.</p>
5
2008-12-09T15:35:58Z
353,243
<p>The trick is in noticing which patterns emerge as you run the string through each iteration. Try evaluating <code>iterate(D,n)</code> for n between 1 and 10 and see if you can spot them. Also feed the string through a function that calculates the end position and the number of steps, and look for patterns there too.</p> <p>You can then use this knowledge to simplify the algorithm to something that doesn't use these strings at all.</p>
3
2008-12-09T15:57:07Z
[ "python" ]
How to work with very long strings in Python?
353,152
<p>I'm tackling project euler's <a href="http://projecteuler.net/index.php?section=problems&amp;id=220" rel="nofollow">problem 220</a> (looked easy, in comparison to some of the others - thought I'd try a higher numbered one for a change!)</p> <p>So far I have:</p> <pre><code>D = "Fa" def iterate(D,num): for i in range (0,num): D = D.replace("a","A") D = D.replace("b","B") D = D.replace("A","aRbFR") D = D.replace("B","LFaLb") return D instructions = iterate("Fa",50) print instructions </code></pre> <p>Now, this works fine for low values, but when you put it to repeat higher then you just get a "Memory error". Can anyone suggest a way to overcome this? I really want a string/file that contains instructions for the next step.</p>
5
2008-12-09T15:35:58Z
353,419
<p>You could treat D as a byte stream file.</p> <p>Something like:-</p> seedfile = open('D1.txt', 'w'); seedfile.write("Fa"); seedfile.close(); n = 0 while (n <p>warning totally untested</p>
0
2008-12-09T16:40:18Z
[ "python" ]
How to work with very long strings in Python?
353,152
<p>I'm tackling project euler's <a href="http://projecteuler.net/index.php?section=problems&amp;id=220" rel="nofollow">problem 220</a> (looked easy, in comparison to some of the others - thought I'd try a higher numbered one for a change!)</p> <p>So far I have:</p> <pre><code>D = "Fa" def iterate(D,num): for i in range (0,num): D = D.replace("a","A") D = D.replace("b","B") D = D.replace("A","aRbFR") D = D.replace("B","LFaLb") return D instructions = iterate("Fa",50) print instructions </code></pre> <p>Now, this works fine for low values, but when you put it to repeat higher then you just get a "Memory error". Can anyone suggest a way to overcome this? I really want a string/file that contains instructions for the next step.</p>
5
2008-12-09T15:35:58Z
353,608
<p>Python strings are not going to be the answer to this one. Strings are stored as immutable arrays, so each one of those replacements creates an entirely new string in memory. Not to mention, the set of instructions after 10^12 steps will be at least 1TB in size if you store them as characters (and that's with some minor compressions).</p> <p>Ideally, there should be a way to mathematically (hint, there is) generate the answer on the fly, so that you never need to store the sequence. </p> <p>Just use the string as a guide to determine a method which creates your path. </p>
2
2008-12-09T17:42:22Z
[ "python" ]
How to work with very long strings in Python?
353,152
<p>I'm tackling project euler's <a href="http://projecteuler.net/index.php?section=problems&amp;id=220" rel="nofollow">problem 220</a> (looked easy, in comparison to some of the others - thought I'd try a higher numbered one for a change!)</p> <p>So far I have:</p> <pre><code>D = "Fa" def iterate(D,num): for i in range (0,num): D = D.replace("a","A") D = D.replace("b","B") D = D.replace("A","aRbFR") D = D.replace("B","LFaLb") return D instructions = iterate("Fa",50) print instructions </code></pre> <p>Now, this works fine for low values, but when you put it to repeat higher then you just get a "Memory error". Can anyone suggest a way to overcome this? I really want a string/file that contains instructions for the next step.</p>
5
2008-12-09T15:35:58Z
8,056,397
<p>Just as a word of warning be careful when using the replace() function. If your strings are very large (in my case ~ 5e6 chars) the replace function would return a subset of the string (around ~ 4e6 chars) without throwing any errors.</p>
1
2011-11-08T20:02:58Z
[ "python" ]
How to blend drawn circles with pygame
353,297
<p>I am trying to create an application like the one here:</p> <p><a href="http://www.eigenfaces.com/" rel="nofollow">http://www.eigenfaces.com/</a></p> <p>Basically lots of overlapping circles drawn with pygame. I cannot figure out how the blend the circles to make them translucent. That is to have overlapping colors show through. My code so far is this:</p> <pre><code>import sys, random, time import pygame from pygame.locals import * from pygame import draw rand = random.randint pygame.init( ) W = 320 H = 320 size = (W, H) screen = pygame.display.set_mode(size) run = True while 1: for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE : run = not run else: sys.exit() if run: xc = rand(1, W) yc = rand(1, H) rc = rand(1, 25) red = rand(1, 255) grn = rand(1, 255) blu = rand(1, 255) draw.circle(screen, (red, grn, blu, 200), (xc, yc), rc, 0) pygame.display.flip() </code></pre>
3
2008-12-09T16:09:12Z
353,719
<p>I got it to work by drawing to a surface that is not the display and combining the set colorkey and set alpha functions.</p> <pre><code>import pygame from pygame.locals import * TRANSPARENT = (255,0,255) pygame.init() screen = pygame.display.set_mode((500,500)) surf1 = pygame.Surface((200,200)) surf1.fill(TRANSPARENT) surf1.set_colorkey(TRANSPARENT) pygame.draw.circle(surf1, (0,0,200,100),(100,100), 100) surf2 = pygame.Surface((200,200)) surf2.fill(TRANSPARENT) surf2.set_colorkey(TRANSPARENT) pygame.draw.circle(surf2, (200,0,0,100),(100,100), 100) surf1.set_alpha(100) surf2.set_alpha(100) while True: screen.fill((255,255,255)) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() screen.blit(surf1, (100,100,100,100)) screen.blit(surf2, (200,200,100,100)) pygame.display.flip() </code></pre> <p>P.S There's also the blend flags that you can put in the blit() arguments: <a href="http://www.pygame.org/docs/ref/surface.html#Surface.blit">Pygame.org - Surface.blit</a></p>
6
2008-12-09T18:17:24Z
[ "python", "pygame" ]
How to blend drawn circles with pygame
353,297
<p>I am trying to create an application like the one here:</p> <p><a href="http://www.eigenfaces.com/" rel="nofollow">http://www.eigenfaces.com/</a></p> <p>Basically lots of overlapping circles drawn with pygame. I cannot figure out how the blend the circles to make them translucent. That is to have overlapping colors show through. My code so far is this:</p> <pre><code>import sys, random, time import pygame from pygame.locals import * from pygame import draw rand = random.randint pygame.init( ) W = 320 H = 320 size = (W, H) screen = pygame.display.set_mode(size) run = True while 1: for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE : run = not run else: sys.exit() if run: xc = rand(1, W) yc = rand(1, H) rc = rand(1, 25) red = rand(1, 255) grn = rand(1, 255) blu = rand(1, 255) draw.circle(screen, (red, grn, blu, 200), (xc, yc), rc, 0) pygame.display.flip() </code></pre>
3
2008-12-09T16:09:12Z
354,494
<p>I am Dave. Creator of the images at eigenfaces.com. Good luck with your experiments. I posted the code here:</p> <p><a href="http://www.eigenfaces.com/" rel="nofollow">http://www.eigenfaces.com/</a></p> <p>Let me know if it's of use.</p> <p>By the way.. I have also experimented with movies... Here is about 20 frames with about 1000 generations each:</p> <p><a href="http://www.eigenfaces.com/img/morphs/anim-100x20.gif" rel="nofollow">http://www.eigenfaces.com/img/morphs/anim-100x20.gif</a></p>
3
2008-12-09T22:32:49Z
[ "python", "pygame" ]
Cleaner way to query on a dynamic number of columns in Django?
353,489
<p>In my case, I have a number of column names coming from a form. I want to filter to make sure they're all true. Here's how I currently do it:</p> <pre><code>for op in self.cleaned_data['options']: cars = cars.filter((op, True)) </code></pre> <p>Now it <em>works</em> but there are are a possible ~40 columns to be tested and it therefore doesn't appear very efficient to keep querying.</p> <p>Is there a way I can condense this into one filter query?</p>
0
2008-12-09T17:00:26Z
353,602
<p>Build the query as a dictionary and use the ** operator to unpack the options as keyword arguments to the filter method.</p> <pre><code>op_kwargs = {} for op in self.cleaned_data['options']: op_kwargs[op] = True cars = CarModel.objects.filter(**op_kwargs) </code></pre> <p>This is covered in the <a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-all-objects" rel="nofollow">django documentation</a> and has been covered on <a href="http://stackoverflow.com/questions/310732/in-django-how-does-one-filter-a-queryset-with-dynamic-field-lookups">SO</a> as well.</p>
9
2008-12-09T17:37:46Z
[ "python", "django" ]
Cleaner way to query on a dynamic number of columns in Django?
353,489
<p>In my case, I have a number of column names coming from a form. I want to filter to make sure they're all true. Here's how I currently do it:</p> <pre><code>for op in self.cleaned_data['options']: cars = cars.filter((op, True)) </code></pre> <p>Now it <em>works</em> but there are are a possible ~40 columns to be tested and it therefore doesn't appear very efficient to keep querying.</p> <p>Is there a way I can condense this into one filter query?</p>
0
2008-12-09T17:00:26Z
354,215
<p>Django's query sets are lazy, so what you're currently doing is actually pretty efficient. The database won't be hit until you try to access one of the fields in the QuerySet... assuming, that is, that you didn't edit out some code, and it is effectively like this:</p> <pre><code>cars = CarModel.objects.all() for op in self.cleaned_data['options']: cars = cars.filter((op, True)) </code></pre> <p>More information <a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#id3" rel="nofollow">here</a>.</p>
3
2008-12-09T20:57:51Z
[ "python", "django" ]
Beginner: Trying to understand how apps interact in Django
353,571
<p>I just got done working through the Django tutorials for the second time, and am understanding things much more clearly now. However, I'm still unclear how apps inside a site interact with one another.</p> <p>For example, lets say I'm writing a blog application (a rather popular activity, apparently). Blog posts and comments tend to go together, and yet they are distinct enough that they should be built into separate apps, as is the general philosophy of Djano development.</p> <p>Consider the following example. In reality I would not actually write the comment app myself, as good code for that already exists on the web, but this is for demonstration/practice purposes:</p> <p><strong>mysite/blog/models.py</strong></p> <pre><code>from django.db import models class post(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=200) content = models.TextField() </code></pre> <p><strong>mysite/comments/models.py</strong></p> <pre><code>from django.db import models from mysite.blog.models import post class comment(models.Model): id = models.AutoField() post = models.ForeignKey(post) author = models.CharField(max_length=200) text = models.TextField() </code></pre> <p>Is what I wrote above, importing a model from another app and setting it as a foreign key, how Django apps interact? Or is there a different/better method for the apps that comprise a site to interact?</p> <p><strong>Update</strong><br> Per the recommendation in one response, I'm reading the documentation for contrib.contenttypes. If I'm reading this correctly, I could rewrite my example comment app like this: </p> <pre><code>from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contentypes import generic class comment(models.Model): id = models.AutoField() author = models.CharField(max_length=200) text = models.TextField() content_type = models.ForeignKey(ContentType) content_object = generic.GenericForeignKey(content_type, id) </code></pre> <p>Would this be correct?</p>
23
2008-12-09T17:25:23Z
353,615
<p>Your code seems correct. I would keep the post and the comment in a <strong>blog</strong> app though. I am not saying this is <em>the</em> Django way, but those models are close enough to be in the same app.</p> <h3>How To Divide The Project</h3> <p>I would seperate an app if;</p> <ul> <li>I plan to design it resuable. (and try loose coupling)</li> <li>(for big projects) It consists of a major section of the project.</li> </ul> <p>On the other hand; having many tiny apps (such as an app with a single model and two views) is hard to read and maintain IMHO.</p> <h3>How Apps Should Interact</h3> <p>This depends on the type of project and the type of the app again. For example if an app is implicitly dependent on another (ie not generic) importing and using references from the other app is acceptable. In this case the second app might be installed alone, but the first one needs the presence of the second.</p> <p>If you want to make an app highly reusable and generic, such as a commenting app, you might need to integrate some setup mechanism. Maybe some new settings or additional URL configuration, or a special directive/method on your models... <code>django.contrib.admin</code> is a good example for this.</p> <p>Apps shouldn't interact if it is not necessary though. Designing apps to avoid unnecessary coupling is very useful. It improves your app's flexibility and makes it more maintainable (but possibly with a higher cost in integrating).</p>
2
2008-12-09T17:45:34Z
[ "python", "django", "django-models", "django-apps" ]
Beginner: Trying to understand how apps interact in Django
353,571
<p>I just got done working through the Django tutorials for the second time, and am understanding things much more clearly now. However, I'm still unclear how apps inside a site interact with one another.</p> <p>For example, lets say I'm writing a blog application (a rather popular activity, apparently). Blog posts and comments tend to go together, and yet they are distinct enough that they should be built into separate apps, as is the general philosophy of Djano development.</p> <p>Consider the following example. In reality I would not actually write the comment app myself, as good code for that already exists on the web, but this is for demonstration/practice purposes:</p> <p><strong>mysite/blog/models.py</strong></p> <pre><code>from django.db import models class post(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=200) content = models.TextField() </code></pre> <p><strong>mysite/comments/models.py</strong></p> <pre><code>from django.db import models from mysite.blog.models import post class comment(models.Model): id = models.AutoField() post = models.ForeignKey(post) author = models.CharField(max_length=200) text = models.TextField() </code></pre> <p>Is what I wrote above, importing a model from another app and setting it as a foreign key, how Django apps interact? Or is there a different/better method for the apps that comprise a site to interact?</p> <p><strong>Update</strong><br> Per the recommendation in one response, I'm reading the documentation for contrib.contenttypes. If I'm reading this correctly, I could rewrite my example comment app like this: </p> <pre><code>from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contentypes import generic class comment(models.Model): id = models.AutoField() author = models.CharField(max_length=200) text = models.TextField() content_type = models.ForeignKey(ContentType) content_object = generic.GenericForeignKey(content_type, id) </code></pre> <p>Would this be correct?</p>
23
2008-12-09T17:25:23Z
353,667
<p>Take a look at django's built-in <a href="http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#ref-contrib-contenttypes">contenttypes framework</a>:</p> <p><code>django.contrib.contenttypes</code></p> <p>It allows you develop your applications as stand-alone units. This is what the django developers used to allow django's built-in <a href="http://docs.djangoproject.com/en/dev/ref/contrib/comments/#ref-contrib-comments-index">comment framework</a> to attach a comment to any model in your project.</p> <p>For instance, if you have some content object that you want to "attach" to other content objects of different types, like allowing each user to leave a "favorite" star on a blog post, image, or user profile, you can create a <code>Favorite</code> model with a <a href="http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#generic-relations">generic relation field</a> like so:</p> <pre><code>from django.db import models from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic class Favorite(models.Model): user = models.ForeignKey(User) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') </code></pre> <p>In this way you can add a <code>Favorite</code> star from any user to any model in your project. If you want to add API access via the recipient model class you can either add a <a href="http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#reverse-generic-relations">reverse generic relation field</a> on the recipient model (although this would be "coupling" the two models, which you said you wanted to avoid), or do the lookup through the <code>Favorite</code> model with the <code>content_type</code> and <code>object_id</code> of the recipient instance, see the <a href="http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#reverse-generic-relations">official docs</a> for an example. </p>
20
2008-12-09T18:01:25Z
[ "python", "django", "django-models", "django-apps" ]
Beginner: Trying to understand how apps interact in Django
353,571
<p>I just got done working through the Django tutorials for the second time, and am understanding things much more clearly now. However, I'm still unclear how apps inside a site interact with one another.</p> <p>For example, lets say I'm writing a blog application (a rather popular activity, apparently). Blog posts and comments tend to go together, and yet they are distinct enough that they should be built into separate apps, as is the general philosophy of Djano development.</p> <p>Consider the following example. In reality I would not actually write the comment app myself, as good code for that already exists on the web, but this is for demonstration/practice purposes:</p> <p><strong>mysite/blog/models.py</strong></p> <pre><code>from django.db import models class post(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=200) content = models.TextField() </code></pre> <p><strong>mysite/comments/models.py</strong></p> <pre><code>from django.db import models from mysite.blog.models import post class comment(models.Model): id = models.AutoField() post = models.ForeignKey(post) author = models.CharField(max_length=200) text = models.TextField() </code></pre> <p>Is what I wrote above, importing a model from another app and setting it as a foreign key, how Django apps interact? Or is there a different/better method for the apps that comprise a site to interact?</p> <p><strong>Update</strong><br> Per the recommendation in one response, I'm reading the documentation for contrib.contenttypes. If I'm reading this correctly, I could rewrite my example comment app like this: </p> <pre><code>from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contentypes import generic class comment(models.Model): id = models.AutoField() author = models.CharField(max_length=200) text = models.TextField() content_type = models.ForeignKey(ContentType) content_object = generic.GenericForeignKey(content_type, id) </code></pre> <p>Would this be correct?</p>
23
2008-12-09T17:25:23Z
353,686
<p>"Is what I wrote above, importing a model from another app and setting it as a foreign key, how Django apps interact?"</p> <p>Yep. Works for me.</p> <p>We have about 10 applications that borrow back and forth among themselves.</p> <p>This leads to a kind of dependency in our unit test script.</p> <p>It looks like this.</p> <ul> <li><p>"ownership". We have a simple data ownership application that defines some core ownership concepts that other applications depend on. There are a few simple tables here.</p></li> <li><p>"thing". [Not the real name]. Our thing application has data elements owned by different user groups. There are actually several complex tables the model for this app. It depends on "ownership".</p></li> <li><p>"tables". [Not the real name]. Some of our users create fairly complex off-line models (probably with spreadsheets) and upload the results of that modeling in "tables". This has a cluster of fairly complex tables. It depends on "ownership".</p></li> <li><p>"result". [Not the real name]. Our results are based on things which have owners. The results are based on things and tables, and are responses to customer requests. This isn't too complex, perhaps only two or three core tables. It depends on "things" and "table". No, it doesn't completely stand-alone. However, it is subject to more change than the other things on which it depends. That's why it's separate.</p></li> <li><p>"processing". We schedule and monitor big batch jobs. This is in this application. It's really generic, and can be used in a variety of ways. It completely stands alone.</p></li> <li><p>"welcome". We have a "welcome" app that presents a bunch of mostly static pages. This doesn't have too many tables. But it's on it's second incarnation because the first was too complex. It completely stands alone.</p></li> </ul> <p>The only relationship among the dependent apps is some table names. As long as we preserve those tables (and their keys) we can rearrange other apps as we see fit.</p>
3
2008-12-09T18:06:38Z
[ "python", "django", "django-models", "django-apps" ]
Beginner: Trying to understand how apps interact in Django
353,571
<p>I just got done working through the Django tutorials for the second time, and am understanding things much more clearly now. However, I'm still unclear how apps inside a site interact with one another.</p> <p>For example, lets say I'm writing a blog application (a rather popular activity, apparently). Blog posts and comments tend to go together, and yet they are distinct enough that they should be built into separate apps, as is the general philosophy of Djano development.</p> <p>Consider the following example. In reality I would not actually write the comment app myself, as good code for that already exists on the web, but this is for demonstration/practice purposes:</p> <p><strong>mysite/blog/models.py</strong></p> <pre><code>from django.db import models class post(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=200) content = models.TextField() </code></pre> <p><strong>mysite/comments/models.py</strong></p> <pre><code>from django.db import models from mysite.blog.models import post class comment(models.Model): id = models.AutoField() post = models.ForeignKey(post) author = models.CharField(max_length=200) text = models.TextField() </code></pre> <p>Is what I wrote above, importing a model from another app and setting it as a foreign key, how Django apps interact? Or is there a different/better method for the apps that comprise a site to interact?</p> <p><strong>Update</strong><br> Per the recommendation in one response, I'm reading the documentation for contrib.contenttypes. If I'm reading this correctly, I could rewrite my example comment app like this: </p> <pre><code>from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contentypes import generic class comment(models.Model): id = models.AutoField() author = models.CharField(max_length=200) text = models.TextField() content_type = models.ForeignKey(ContentType) content_object = generic.GenericForeignKey(content_type, id) </code></pre> <p>Would this be correct?</p>
23
2008-12-09T17:25:23Z
353,761
<p>There's nothing wrong (imho) with making some app dependent on another. After all, apps are just operations on a set of models. you just have to always be aware of which app depends on which app (I guess you could call that a dependency map).</p> <p>You can achieve loose coupling with the contenttypes framework. It allows an app to be truely portable/pluggable yet still integrated with other applications.</p> <p>I wrote a comments app (yea, I re-invented the wheel), that can be integrated into any other application, with a few lines in the template of the page where comments should be posted (using custom tags).</p> <p>Say you want a model "thread" to be pluggable into any other model. The idea is to create e generic foreign key (see django documentation on that), and write a small function that takes any object and returns a "thread" corresponding to it (or creates one if necessary), and write a custom template tag that uses that functionality, e.g. <code>{% get_thread for arbitrary_object as thread %}</code>. All posts are related to a thread, which is related to the object, which can be of any type.</p> <p>You can think of the "thread" object as a kind of a proxy, so instead of having a post be related to a certain "article" or a "blog post", it's just related to a thread, which is abstract in a sense, what <em>is</em> is a thread? It's just a collection of posts. The thread then allows itself to be related to any object regardless of its type. (although it does more than that, it could hold extra information such as allowing/disallowing anon. posts, closing/opening comments on the page, etc ..)</p> <p><strong>EDIT</strong></p> <p>Here's how you can create a generic foreign key with the content types framework:</p> <pre><code>from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType class Thread( models.Model ): object_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() object = generic.GenericForeignKey('object_type', 'object_id') </code></pre> <p>You can make it more "transparent" by exploiting the implicit "common" interface that django assumes all objects implement ..</p> <pre><code> #inside the Thread class: def __unicode__(self): return unicode(self.object) def get_absolute_url(self): return self.object.get_absolute_url() </code></pre>
3
2008-12-09T18:35:09Z
[ "python", "django", "django-models", "django-apps" ]
How do I check if a string is a number (float) in Python?
354,038
<p>What is the best possible way to check if a string can be represented as a number in Python? </p> <p>The function I currently have right now is:</p> <pre><code>def is_number(s): try: float(s) return True except ValueError: return False </code></pre> <p>Which, not only is ugly and slow, seems clunky. However I haven't found a better method because calling <code>float</code> in the main function is even worse. </p>
872
2008-12-09T20:03:42Z
354,073
<p>In case you are looking for parsing (positive, unsigned) integers instead of floats, you can use the <a href="https://docs.python.org/2/library/stdtypes.html#str.isdigit"><code>isdigit()</code></a> function for string objects.</p> <pre><code>&gt;&gt;&gt; a = "03523" &gt;&gt;&gt; a.isdigit() True &gt;&gt;&gt; b = "963spam" &gt;&gt;&gt; b.isdigit() False </code></pre> <p><a href="https://docs.python.org/2/library/stdtypes.html#string-methods">String Methods - <code>isdigit()</code></a></p> <p>There's also something on Unicode strings, which I'm not too familiar with <a href="https://docs.python.org/2/library/stdtypes.html#unicode.isnumeric">Unicode - Is decimal/decimal</a></p>
1,069
2008-12-09T20:15:18Z
[ "python", "casting", "floating-point", "type-conversion" ]
How do I check if a string is a number (float) in Python?
354,038
<p>What is the best possible way to check if a string can be represented as a number in Python? </p> <p>The function I currently have right now is:</p> <pre><code>def is_number(s): try: float(s) return True except ValueError: return False </code></pre> <p>Which, not only is ugly and slow, seems clunky. However I haven't found a better method because calling <code>float</code> in the main function is even worse. </p>
872
2008-12-09T20:03:42Z
354,130
<blockquote> <p>Which, not only is ugly and slow</p> </blockquote> <p>I'd dispute both.</p> <p>A regex or other string parsing would be uglier and slower. </p> <p>I'm not sure that anything much could be faster than the above. It calls the function and returns. Try/Catch doesn't introduce much overhead because the most common exception is caught without an extensive search of stack frames.</p> <p>The issue is that any numeric conversion function has two kinds of results</p> <ul> <li>A number, if the number is valid</li> <li>A status code (e.g., via errno) or exception to show that no valid number could be parsed.</li> </ul> <p>C (as an example) hacks around this a number of ways. Python lays it out clearly and explicitly.</p> <p>I think your code for doing this is perfect.</p>
429
2008-12-09T20:30:48Z
[ "python", "casting", "floating-point", "type-conversion" ]
How do I check if a string is a number (float) in Python?
354,038
<p>What is the best possible way to check if a string can be represented as a number in Python? </p> <p>The function I currently have right now is:</p> <pre><code>def is_number(s): try: float(s) return True except ValueError: return False </code></pre> <p>Which, not only is ugly and slow, seems clunky. However I haven't found a better method because calling <code>float</code> in the main function is even worse. </p>
872
2008-12-09T20:03:42Z
354,134
<p>Casting to float and catching ValueError is probably the fastest way, since float() is specifically meant for just that. Anything else that requires string parsing (regex, etc) will likely be slower due to the fact that it's not tuned for this operation. My $0.02.</p>
9
2008-12-09T20:31:49Z
[ "python", "casting", "floating-point", "type-conversion" ]
How do I check if a string is a number (float) in Python?
354,038
<p>What is the best possible way to check if a string can be represented as a number in Python? </p> <p>The function I currently have right now is:</p> <pre><code>def is_number(s): try: float(s) return True except ValueError: return False </code></pre> <p>Which, not only is ugly and slow, seems clunky. However I haven't found a better method because calling <code>float</code> in the main function is even worse. </p>
872
2008-12-09T20:03:42Z
355,489
<p>If you want to know if the <em>entire</em> string can be represented as a number you'll want to use a regexp (or maybe convert the float back to a string and compare it to the source string, but I'm guessing that's not very fast).</p>
1
2008-12-10T09:15:25Z
[ "python", "casting", "floating-point", "type-conversion" ]
How do I check if a string is a number (float) in Python?
354,038
<p>What is the best possible way to check if a string can be represented as a number in Python? </p> <p>The function I currently have right now is:</p> <pre><code>def is_number(s): try: float(s) return True except ValueError: return False </code></pre> <p>Which, not only is ugly and slow, seems clunky. However I haven't found a better method because calling <code>float</code> in the main function is even worse. </p>
872
2008-12-09T20:03:42Z
358,415
<p>Your code looks fine to me.</p> <p>Perhaps you think the code is "clunky" because of using exceptions? Note that Python programmers tend to use exceptions liberally when it improves code readability, thanks to its low performance penalty.</p>
4
2008-12-11T04:03:03Z
[ "python", "casting", "floating-point", "type-conversion" ]
How do I check if a string is a number (float) in Python?
354,038
<p>What is the best possible way to check if a string can be represented as a number in Python? </p> <p>The function I currently have right now is:</p> <pre><code>def is_number(s): try: float(s) return True except ValueError: return False </code></pre> <p>Which, not only is ugly and slow, seems clunky. However I haven't found a better method because calling <code>float</code> in the main function is even worse. </p>
872
2008-12-09T20:03:42Z
358,479
<blockquote> <p>Which, not only is ugly and slow, seems clunky.</p> </blockquote> <p>It may take some getting used to, but this is the pythonic way of doing it. As has been already pointed out, the alternatives are worse. But there is one other advantage of doing things this way: polymorphism.</p> <p>The central idea behind duck typing is that "if it walks and talks like a duck, then it's a duck." What if you decide that you need to subclass string so that you can change how you determine if something can be converted into a float? Or what if you decide to test some other object entirely? You can do these things without having to change the above code.</p> <p>Other languages solve these problems by using interfaces. I'll save the analysis of which solution is better for another thread. The point, though, is that python is decidedly on the duck typing side of the equation, and you're probably going to have to get used to syntax like this if you plan on doing much programming in Python (but that doesn't mean you have to like it of course).</p> <p>One other thing you might want to take into consideration: Python is pretty fast in throwing and catching exceptions compared to a lot of other languages (30x faster than .Net for instance). Heck, the language itself even throws exceptions to communicate non-exceptional, normal program conditions (every time you use a for loop). Thus, I wouldn't worry too much about the performance aspects of this code until you notice a significant problem.</p>
33
2008-12-11T04:56:26Z
[ "python", "casting", "floating-point", "type-conversion" ]
How do I check if a string is a number (float) in Python?
354,038
<p>What is the best possible way to check if a string can be represented as a number in Python? </p> <p>The function I currently have right now is:</p> <pre><code>def is_number(s): try: float(s) return True except ValueError: return False </code></pre> <p>Which, not only is ugly and slow, seems clunky. However I haven't found a better method because calling <code>float</code> in the main function is even worse. </p>
872
2008-12-09T20:03:42Z
1,139,186
<p>Here's my simple way of doing it. Let's say that I'm looping through some strings and I want to add them to an array if they turn out to be numbers.</p> <pre><code>try: myvar.append( float(string_to_check) ) except: continue </code></pre> <p>Replace the myvar.apppend with whatever operation you want to do with the string if it turns out to be a number. The idea is to try to use a float() operation and use the returned error to determine whether or not the string is a number.</p>
1
2009-07-16T17:45:12Z
[ "python", "casting", "floating-point", "type-conversion" ]
How do I check if a string is a number (float) in Python?
354,038
<p>What is the best possible way to check if a string can be represented as a number in Python? </p> <p>The function I currently have right now is:</p> <pre><code>def is_number(s): try: float(s) return True except ValueError: return False </code></pre> <p>Which, not only is ugly and slow, seems clunky. However I haven't found a better method because calling <code>float</code> in the main function is even worse. </p>
872
2008-12-09T20:03:42Z
3,335,060
<p>Updated after Alfe pointed out you don't need to check for float separately as complex handles both:</p> <pre><code>def is_number(s): try: complex(s) # for int, long, float and complex except ValueError: return False return True </code></pre> <hr> <p>Previously said: Is some rare cases you might also need to check for complex numbers (e.g. 1+2i), which can not be represented by a float:</p> <pre><code>def is_number(s): try: float(s) # for int, long and float except ValueError: try: complex(s) # for complex except ValueError: return False return True </code></pre>
27
2010-07-26T13:10:15Z
[ "python", "casting", "floating-point", "type-conversion" ]
How do I check if a string is a number (float) in Python?
354,038
<p>What is the best possible way to check if a string can be represented as a number in Python? </p> <p>The function I currently have right now is:</p> <pre><code>def is_number(s): try: float(s) return True except ValueError: return False </code></pre> <p>Which, not only is ugly and slow, seems clunky. However I haven't found a better method because calling <code>float</code> in the main function is even worse. </p>
872
2008-12-09T20:03:42Z
3,618,897
<p>There is one exception that you may want to take into account: the string 'NaN'</p> <p>If you want is_number to return FALSE for 'NaN' this code will not work as Python converts it to its representation of a number that is not a number (talk about identity issues):</p> <pre><code>&gt;&gt;&gt; float('NaN') nan </code></pre> <p>Otherwise, I should actually thank you for the piece of code I now use extensively. :)</p> <p>G.</p>
50
2010-09-01T14:06:08Z
[ "python", "casting", "floating-point", "type-conversion" ]
How do I check if a string is a number (float) in Python?
354,038
<p>What is the best possible way to check if a string can be represented as a number in Python? </p> <p>The function I currently have right now is:</p> <pre><code>def is_number(s): try: float(s) return True except ValueError: return False </code></pre> <p>Which, not only is ugly and slow, seems clunky. However I haven't found a better method because calling <code>float</code> in the main function is even worse. </p>
872
2008-12-09T20:03:42Z
3,912,515
<p>I did some speed test. Lets say that if the string is <strong>likely</strong> to be a number the <em>try/except</em> strategy is the fastest possible.If the string is <strong>not likely</strong> to be a number <strong>and</strong> you are interested in <strong>Integer</strong> check, it worths to do some test (isdigit plus heading '-'). If you are interested to check float number, you have to use the <em>try/except</em> code whitout escape.</p>
4
2010-10-12T07:43:19Z
[ "python", "casting", "floating-point", "type-conversion" ]
How do I check if a string is a number (float) in Python?
354,038
<p>What is the best possible way to check if a string can be represented as a number in Python? </p> <p>The function I currently have right now is:</p> <pre><code>def is_number(s): try: float(s) return True except ValueError: return False </code></pre> <p>Which, not only is ugly and slow, seems clunky. However I haven't found a better method because calling <code>float</code> in the main function is even worse. </p>
872
2008-12-09T20:03:42Z
9,337,733
<h2>Just Mimic C#</h2> <p><strong>In C# there are two different functions that handle parsing of scalar values:</strong></p> <ul> <li>Float.Parse()</li> <li>Float.TryParse()</li> </ul> <p><strong>float.parse():</strong></p> <pre><code>def parse(string): try: return float(string) except Exception: throw TypeError </code></pre> <p><em>Note: If you're wondering why I changed the exception to a TypeError, <a href="http://docs.python.org/library/exceptions.html">here's the documentation</a>.</em></p> <p><strong>float.try_parse():</strong></p> <pre><code>def try_parse(string, fail=None): try: return float(string) except Exception: return fail; </code></pre> <p><em>Note: You don't want to return the boolean 'False' because that's still a value type. None is better because it indicates failure. Of course, if you want something different you can change the fail parameter to whatever you want.</em></p> <p>To extend float to include the 'parse()' and 'try_parse()' you'll need to monkeypatch the 'float' class to add these methods.</p> <p>If you want respect pre-existing functions the code should be something like:</p> <pre><code>def monkey_patch(): if(!hasattr(float, 'parse')): float.parse = parse if(!hasattr(float, 'try_parse')): float.try_parse = try_parse </code></pre> <p><em>SideNote: I personally prefer to call it Monkey Punching because it feels like I'm abusing the language when I do this but YMMV.</em></p> <p><strong>Usage:</strong></p> <pre><code>float.parse('giggity') // throws TypeException float.parse('54.3') // returns the scalar value 54.3 float.tryParse('twank') // returns None float.tryParse('32.2') // returns the scalar value 32.2 </code></pre> <p><em>And the great Sage Pythonas said to the Holy See Sharpisus, "Anything you can do I can do better; I can do anything better than you."</em></p>
12
2012-02-18T01:35:32Z
[ "python", "casting", "floating-point", "type-conversion" ]
How do I check if a string is a number (float) in Python?
354,038
<p>What is the best possible way to check if a string can be represented as a number in Python? </p> <p>The function I currently have right now is:</p> <pre><code>def is_number(s): try: float(s) return True except ValueError: return False </code></pre> <p>Which, not only is ugly and slow, seems clunky. However I haven't found a better method because calling <code>float</code> in the main function is even worse. </p>
872
2008-12-09T20:03:42Z
9,842,626
<p>So to put it all together, checking for Nan, infinity and complex numbers (it would seem they are specified with j, not i, i.e. 1+2j) it results in:</p> <pre><code>def is_number(s): try: n=str(float(s)) if n == "nan" or n=="inf" or n=="-inf" : return False except ValueError: try: complex(s) # for complex except ValueError: return False return True </code></pre>
6
2012-03-23T16:10:09Z
[ "python", "casting", "floating-point", "type-conversion" ]
How do I check if a string is a number (float) in Python?
354,038
<p>What is the best possible way to check if a string can be represented as a number in Python? </p> <p>The function I currently have right now is:</p> <pre><code>def is_number(s): try: float(s) return True except ValueError: return False </code></pre> <p>Which, not only is ugly and slow, seems clunky. However I haven't found a better method because calling <code>float</code> in the main function is even worse. </p>
872
2008-12-09T20:03:42Z
10,762,002
<p>how about this:</p> <pre><code>'3.14'.replace('.','',1).isdigit() </code></pre> <p>which will return true only if there is one or no '.' in the string of digits.</p> <pre><code>'3.14.5'.replace('.','',1).isdigit() </code></pre> <p>will return false</p> <p>edit: just saw another comment ... adding a <code>.replace(badstuff,'',maxnum_badstuff)</code> for other cases can be done. if you are passing salt and not arbitrary condiments (ref:<a href="http://xkcd.com/974/">xkcd#974</a>) this will do fine :P</p>
33
2012-05-25T22:22:32Z
[ "python", "casting", "floating-point", "type-conversion" ]
How do I check if a string is a number (float) in Python?
354,038
<p>What is the best possible way to check if a string can be represented as a number in Python? </p> <p>The function I currently have right now is:</p> <pre><code>def is_number(s): try: float(s) return True except ValueError: return False </code></pre> <p>Which, not only is ugly and slow, seems clunky. However I haven't found a better method because calling <code>float</code> in the main function is even worse. </p>
872
2008-12-09T20:03:42Z
14,352,314
<p>I wanted to see which method is fastest, and turns out catching an exception is the fastest.</p> <pre><code>import time import re check_regexp = re.compile("^\d*\.?\d*$") check_replace = lambda x: x.replace('.','',1).isdigit() numbers = [str(float(x) / 100) for x in xrange(10000000)] def is_number(s): try: float(s) return True except ValueError: return False start = time.time() b = [is_number(x) for x in numbers] print time.time() - start # returns 4.10500001907 start = time.time() b = [check_regexp.match(x) for x in numbers] print time.time() - start # returns 5.41799998283 start = time.time() b = [check_replace(x) for x in numbers] print time.time() - start # returns 4.5110001564 </code></pre>
5
2013-01-16T06:09:37Z
[ "python", "casting", "floating-point", "type-conversion" ]
How do I check if a string is a number (float) in Python?
354,038
<p>What is the best possible way to check if a string can be represented as a number in Python? </p> <p>The function I currently have right now is:</p> <pre><code>def is_number(s): try: float(s) return True except ValueError: return False </code></pre> <p>Which, not only is ugly and slow, seems clunky. However I haven't found a better method because calling <code>float</code> in the main function is even worse. </p>
872
2008-12-09T20:03:42Z
15,205,926
<p>You can use Unicode strings, they have a method to do just what you want:</p> <pre><code>&gt;&gt;&gt; s = u"345" &gt;&gt;&gt; s.isnumeric() True </code></pre> <p>Or:</p> <pre><code>&gt;&gt;&gt; s = "345" &gt;&gt;&gt; u = unicode(s) &gt;&gt;&gt; u.isnumeric() True </code></pre> <p><a href="http://www.tutorialspoint.com/python/string_isnumeric.htm">http://www.tutorialspoint.com/python/string_isnumeric.htm</a></p> <p><a href="http://docs.python.org/2/howto/unicode.html">http://docs.python.org/2/howto/unicode.html</a></p>
9
2013-03-04T16:12:38Z
[ "python", "casting", "floating-point", "type-conversion" ]
How do I check if a string is a number (float) in Python?
354,038
<p>What is the best possible way to check if a string can be represented as a number in Python? </p> <p>The function I currently have right now is:</p> <pre><code>def is_number(s): try: float(s) return True except ValueError: return False </code></pre> <p>Which, not only is ugly and slow, seems clunky. However I haven't found a better method because calling <code>float</code> in the main function is even worse. </p>
872
2008-12-09T20:03:42Z
16,743,970
<p>You can generalize the exception technique in a useful way by returning more useful values than True and False. For example this function puts quotes round strings but leaves numbers alone. Which is just what I needed for a quick and dirty filter to make some variable definitions for R. </p> <pre><code>import sys def fix_quotes(s): try: float(s) return s except ValueError: return '"{0}"'.format(s) for line in sys.stdin: input = line.split() print input[0], '&lt;- c(', ','.join(fix_quotes(c) for c in input[1:]), ')' </code></pre>
0
2013-05-24T21:36:36Z
[ "python", "casting", "floating-point", "type-conversion" ]
How do I check if a string is a number (float) in Python?
354,038
<p>What is the best possible way to check if a string can be represented as a number in Python? </p> <p>The function I currently have right now is:</p> <pre><code>def is_number(s): try: float(s) return True except ValueError: return False </code></pre> <p>Which, not only is ugly and slow, seems clunky. However I haven't found a better method because calling <code>float</code> in the main function is even worse. </p>
872
2008-12-09T20:03:42Z
17,926,244
<p>RyanN suggests</p> <blockquote> <p>If you want to return False for a NaN and Inf, change line to x = float(s); return (x == x) and (x - 1 != x). This should return True for all floats except Inf and NaN</p> </blockquote> <p>But this doesn't quite work, because for sufficiently large floats, <code>x-1 == x</code> returns true. For example, <code>2.0**54 - 1 == 2.0**54</code></p>
3
2013-07-29T14:08:23Z
[ "python", "casting", "floating-point", "type-conversion" ]
How do I check if a string is a number (float) in Python?
354,038
<p>What is the best possible way to check if a string can be represented as a number in Python? </p> <p>The function I currently have right now is:</p> <pre><code>def is_number(s): try: float(s) return True except ValueError: return False </code></pre> <p>Which, not only is ugly and slow, seems clunky. However I haven't found a better method because calling <code>float</code> in the main function is even worse. </p>
872
2008-12-09T20:03:42Z
23,639,915
<p>I did some <a href="http://nbviewer.ipython.org/github/rasbt/One-Python-benchmark-per-day/blob/master/ipython_nbs/day6_string_is_number.ipynb?create=1" rel="nofollow">benchmarks</a> comparing the different approaches</p> <pre><code>def is_number_tryexcept(s): """ Returns True is string is a number. """ try: float(s) return True except ValueError: return False import re def is_number_regex(s): """ Returns True is string is a number. """ if re.match("^\d+?\.\d+?$", s) is None: return s.isdigit() return True def is_number_repl_isdigit(s): """ Returns True is string is a number. """ return s.replace('.','',1).isdigit() </code></pre> <p>If the string is not a number, the except-block is quite slow. But more importantly, the try-except method is the only approach that handles scientific notations correctly.</p> <pre><code>funcs = [ is_number_tryexcept, is_number_regex, is_number_repl_isdigit ] a_float = '.1234' print('Float notation ".1234" is not supported by:') for f in funcs: if not f(a_float): print('\t -', f.__name__) </code></pre> <p>Float notation ".1234" is not supported by:<br> - is_number_regex </p> <pre><code>scientific1 = '1.000000e+50' scientific2 = '1e50' print('Scientific notation "1.000000e+50" is not supported by:') for f in funcs: if not f(scientific1): print('\t -', f.__name__) print('Scientific notation "1e50" is not supported by:') for f in funcs: if not f(scientific2): print('\t -', f.__name__) </code></pre> <p>Scientific notation "1.000000e+50" is not supported by:<br> - is_number_regex<br> - is_number_repl_isdigit<br> Scientific notation "1e50" is not supported by:<br> - is_number_regex<br> - is_number_repl_isdigit </p> <h2>EDIT: The benchmark results</h2> <pre><code>import timeit test_cases = ['1.12345', '1.12.345', 'abc12345', '12345'] times_n = {f.__name__:[] for f in funcs} for t in test_cases: for f in funcs: f = f.__name__ times_n[f].append(min(timeit.Timer('%s(t)' %f, 'from __main__ import %s, t' %f) .repeat(repeat=3, number=1000000))) </code></pre> <p>where the following functions were tested</p> <pre><code>from re import match as re_match from re import compile as re_compile def is_number_tryexcept(s): """ Returns True is string is a number. """ try: float(s) return True except ValueError: return False def is_number_regex(s): """ Returns True is string is a number. """ if re_match("^\d+?\.\d+?$", s) is None: return s.isdigit() return True comp = re_compile("^\d+?\.\d+?$") def compiled_regex(s): """ Returns True is string is a number. """ if comp.match(s) is None: return s.isdigit() return True def is_number_repl_isdigit(s): """ Returns True is string is a number. """ return s.replace('.','',1).isdigit() </code></pre> <p><a href="http://i.stack.imgur.com/DFoK6.png" rel="nofollow"><img src="http://i.stack.imgur.com/DFoK6.png" alt="enter image description here"></a></p>
3
2014-05-13T19:28:03Z
[ "python", "casting", "floating-point", "type-conversion" ]
How do I check if a string is a number (float) in Python?
354,038
<p>What is the best possible way to check if a string can be represented as a number in Python? </p> <p>The function I currently have right now is:</p> <pre><code>def is_number(s): try: float(s) return True except ValueError: return False </code></pre> <p>Which, not only is ugly and slow, seems clunky. However I haven't found a better method because calling <code>float</code> in the main function is even worse. </p>
872
2008-12-09T20:03:42Z
24,559,671
<p>I needed to determine if a string cast into basic types (float,int,str,bool). After not finding anything on the internet I created this:</p> <pre><code>def str_to_type (s): """ Get possible cast type for a string Parameters ---------- s : string Returns ------- float,int,str,bool : type Depending on what it can be cast to """ try: f = float(s) if "." not in s: return int return float except ValueError: value = s.upper() if value == "TRUE" or value == "FALSE": return bool return type(s) </code></pre> <p>Example</p> <pre><code>str_to_type("true") # bool str_to_type("6.0") # float str_to_type("6") # int str_to_type("6abc") # str str_to_type(u"6abc") # unicode </code></pre> <p>You can capture the type and use it </p> <pre><code>s = "6.0" type_ = str_to_type(s) # float f = type_(s) </code></pre>
1
2014-07-03T17:12:27Z
[ "python", "casting", "floating-point", "type-conversion" ]
How do I check if a string is a number (float) in Python?
354,038
<p>What is the best possible way to check if a string can be represented as a number in Python? </p> <p>The function I currently have right now is:</p> <pre><code>def is_number(s): try: float(s) return True except ValueError: return False </code></pre> <p>Which, not only is ugly and slow, seems clunky. However I haven't found a better method because calling <code>float</code> in the main function is even worse. </p>
872
2008-12-09T20:03:42Z
25,299,619
<p>For strings of non-numbers, <code>try: except:</code> is actually slower than regular expressions. For strings of valid numbers, regex is slower. So, the appropriate method depends on your input. </p> <p>If you find that you are in a performance bind, you can use a new third-party module called <a href="https://pypi.python.org/pypi/fastnumbers" rel="nofollow">fastnumbers</a> that provides a function called <a href="http://pythonhosted.org//fastnumbers/checks.html#isfloat" rel="nofollow">isfloat</a>. Full disclosure, I am the author. I have included its results in the timings below.</p> <hr> <pre><code>from __future__ import print_function import timeit prep_base = '''\ x = 'invalid' y = '5402' z = '4.754e3' ''' prep_try_method = '''\ def is_number_try(val): try: float(val) return True except ValueError: return False ''' prep_re_method = '''\ import re float_match = re.compile(r'[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?$').match def is_number_re(val): return bool(float_match(val)) ''' fn_method = '''\ from fastnumbers import isfloat ''' print('Try with non-number strings', timeit.timeit('is_number_try(x)', prep_base + prep_try_method), 'seconds') print('Try with integer strings', timeit.timeit('is_number_try(y)', prep_base + prep_try_method), 'seconds') print('Try with float strings', timeit.timeit('is_number_try(z)', prep_base + prep_try_method), 'seconds') print() print('Regex with non-number strings', timeit.timeit('is_number_re(x)', prep_base + prep_re_method), 'seconds') print('Regex with integer strings', timeit.timeit('is_number_re(y)', prep_base + prep_re_method), 'seconds') print('Regex with float strings', timeit.timeit('is_number_re(z)', prep_base + prep_re_method), 'seconds') print() print('fastnumbers with non-number strings', timeit.timeit('isfloat(x)', prep_base + 'from fastnumbers import isfloat'), 'seconds') print('fastnumbers with integer strings', timeit.timeit('isfloat(y)', prep_base + 'from fastnumbers import isfloat'), 'seconds') print('fastnumbers with float strings', timeit.timeit('isfloat(z)', prep_base + 'from fastnumbers import isfloat'), 'seconds') print() </code></pre> <hr> <pre><code>Try with non-number strings 2.39108395576 seconds Try with integer strings 0.375686168671 seconds Try with float strings 0.369210958481 seconds Regex with non-number strings 0.748660802841 seconds Regex with integer strings 1.02021503448 seconds Regex with float strings 1.08564686775 seconds fastnumbers with non-number strings 0.174362897873 seconds fastnumbers with integer strings 0.179651021957 seconds fastnumbers with float strings 0.20222902298 seconds </code></pre> <p>As you can see</p> <ul> <li><code>try: except:</code> was fast for numeric input but very slow for an invalid input</li> <li>regex is very efficient when the input is invalid</li> <li><code>fastnumbers</code> wins in both cases</li> </ul>
11
2014-08-14T03:34:08Z
[ "python", "casting", "floating-point", "type-conversion" ]
How do I check if a string is a number (float) in Python?
354,038
<p>What is the best possible way to check if a string can be represented as a number in Python? </p> <p>The function I currently have right now is:</p> <pre><code>def is_number(s): try: float(s) return True except ValueError: return False </code></pre> <p>Which, not only is ugly and slow, seems clunky. However I haven't found a better method because calling <code>float</code> in the main function is even worse. </p>
872
2008-12-09T20:03:42Z
26,336,546
<p>Lets say you have digits in string. str = "100949" and you would like to check if it has only numbers</p> <pre><code>if str.isdigit(): returns TRUE or FALSE </code></pre> <p><a href="http://docs.python.org/2/library/stdtypes.html#str.isdigit">isdigit docs</a></p> <p>otherwise your method works great to find the occurrence of a digit in a string. </p>
8
2014-10-13T09:17:53Z
[ "python", "casting", "floating-point", "type-conversion" ]
How do I check if a string is a number (float) in Python?
354,038
<p>What is the best possible way to check if a string can be represented as a number in Python? </p> <p>The function I currently have right now is:</p> <pre><code>def is_number(s): try: float(s) return True except ValueError: return False </code></pre> <p>Which, not only is ugly and slow, seems clunky. However I haven't found a better method because calling <code>float</code> in the main function is even worse. </p>
872
2008-12-09T20:03:42Z
26,829,047
<p>I was working on a problem that led me to this thread, namely how to convert a collection of data to strings and numbers in the most intuitive way. I realized after reading the original code that what I needed was different in two ways:</p> <p>1 - I wanted an integer result if the string represented an integer</p> <p>2 - I wanted a number or a string result to stick into a data structure</p> <p>so I adapted the original code to produce this derivative:</p> <pre><code>def string_or_number(s): try: z = int(s) return z except ValueError: try: z = float(s) return z except ValueError: return s </code></pre>
0
2014-11-09T14:06:38Z
[ "python", "casting", "floating-point", "type-conversion" ]
How do I check if a string is a number (float) in Python?
354,038
<p>What is the best possible way to check if a string can be represented as a number in Python? </p> <p>The function I currently have right now is:</p> <pre><code>def is_number(s): try: float(s) return True except ValueError: return False </code></pre> <p>Which, not only is ugly and slow, seems clunky. However I haven't found a better method because calling <code>float</code> in the main function is even worse. </p>
872
2008-12-09T20:03:42Z
30,549,042
<p>Try this.</p> <pre><code> def is_number(var): try: if var == int(var): return True except Exception: return False </code></pre>
1
2015-05-30T17:12:56Z
[ "python", "casting", "floating-point", "type-conversion" ]
How do I check if a string is a number (float) in Python?
354,038
<p>What is the best possible way to check if a string can be represented as a number in Python? </p> <p>The function I currently have right now is:</p> <pre><code>def is_number(s): try: float(s) return True except ValueError: return False </code></pre> <p>Which, not only is ugly and slow, seems clunky. However I haven't found a better method because calling <code>float</code> in the main function is even worse. </p>
872
2008-12-09T20:03:42Z
32,167,108
<p>You may use regex.</p> <pre><code>number = raw_input("Enter a number: ") if re.match(r'^\d+$', number): print "It's integer" print int(number) elif re.match(r'^\d+\.\d+$', number): print "It's float" print float(number) else: print("Please enter a number") </code></pre>
0
2015-08-23T13:22:38Z
[ "python", "casting", "floating-point", "type-conversion" ]
How do I check if a string is a number (float) in Python?
354,038
<p>What is the best possible way to check if a string can be represented as a number in Python? </p> <p>The function I currently have right now is:</p> <pre><code>def is_number(s): try: float(s) return True except ValueError: return False </code></pre> <p>Which, not only is ugly and slow, seems clunky. However I haven't found a better method because calling <code>float</code> in the main function is even worse. </p>
872
2008-12-09T20:03:42Z
32,453,110
<p>For <code>int</code> use this:</p> <pre><code>&gt;&gt;&gt; "1221323".isdigit() True </code></pre> <p>But for <code>float</code> we need some tricks ;-). Every float number has one point...</p> <pre><code>&gt;&gt;&gt; "12.34".isdigit() False &gt;&gt;&gt; "12.34".replace('.','',1).isdigit() True &gt;&gt;&gt; "12.3.4".replace('.','',1).isdigit() False </code></pre> <p>Also for negative numbers just add <code>lstrip()</code>:</p> <pre><code>&gt;&gt;&gt; '-12'.lstrip('-') '12' </code></pre> <p>And now we get a universal way:</p> <pre><code>&gt;&gt;&gt; '-12.34'.lstrip('-').replace('.','',1).isdigit() True &gt;&gt;&gt; '.-234'.lstrip('-').replace('.','',1).isdigit() False </code></pre>
10
2015-09-08T08:42:14Z
[ "python", "casting", "floating-point", "type-conversion" ]
How do I check if a string is a number (float) in Python?
354,038
<p>What is the best possible way to check if a string can be represented as a number in Python? </p> <p>The function I currently have right now is:</p> <pre><code>def is_number(s): try: float(s) return True except ValueError: return False </code></pre> <p>Which, not only is ugly and slow, seems clunky. However I haven't found a better method because calling <code>float</code> in the main function is even worse. </p>
872
2008-12-09T20:03:42Z
34,615,173
<p>I know this is particularly old but I would add an answer I believe covers the information missing from the highest voted answer that could be very valuable to any who find this:</p> <p>For each of the following methods connect them with a count if you need any input to be accepted. (Assuming we are using vocal definitions of integers rather than 0-255, etc.)</p> <p><code>x.isdigit()</code> works well for checking if x is an integer.</p> <p><code>x.replace('-','').isdigit()</code> works well for checking if x is a negative.(Check - in first position)</p> <p><code>x.replace('.','').isdigit()</code> works well for checking if x is a decimal.</p> <p><code>x.replace(':','').isdigit()</code> works well for checking if x is a ratio.</p> <p><code>x.replace('/','').isdigit()</code> works well for checking if x is a fraction.</p>
7
2016-01-05T15:21:27Z
[ "python", "casting", "floating-point", "type-conversion" ]
How do I check if a string is a number (float) in Python?
354,038
<p>What is the best possible way to check if a string can be represented as a number in Python? </p> <p>The function I currently have right now is:</p> <pre><code>def is_number(s): try: float(s) return True except ValueError: return False </code></pre> <p>Which, not only is ugly and slow, seems clunky. However I haven't found a better method because calling <code>float</code> in the main function is even worse. </p>
872
2008-12-09T20:03:42Z
39,523,992
<p>To check if the input value is a <code>float</code>, you can compare the type of the input to a <code>float</code></p> <pre><code>def isFloat(s): realFloat = 0.1 if type(s) == type(realFloat): return True else: return False </code></pre> <p><strong>Returns:</strong></p> <pre><code>False # s = 5 True # s = 1.2345 </code></pre> <p>The original post would actually return <code>True</code> for <code>s = 5</code> since it is a number (integer) and you can cast an <code>int</code> to a <code>float</code> without a <code>ValueError</code>. If you are trying to verify that it is an actual <code>float</code> instead of just a number, you would need to account for that case.</p>
1
2016-09-16T05:00:12Z
[ "python", "casting", "floating-point", "type-conversion" ]
How do I check if a string is a number (float) in Python?
354,038
<p>What is the best possible way to check if a string can be represented as a number in Python? </p> <p>The function I currently have right now is:</p> <pre><code>def is_number(s): try: float(s) return True except ValueError: return False </code></pre> <p>Which, not only is ugly and slow, seems clunky. However I haven't found a better method because calling <code>float</code> in the main function is even worse. </p>
872
2008-12-09T20:03:42Z
40,064,255
<p>I also used the function you mentioned, but soon I notice that strings as "Nan", "Inf" and it's variation are considered as number. So I propose you improved version of your function, that will return false on those type of input and will not fail "1e3" variants:</p> <pre><code>def is_float(text): try: float(text) # check for nan/infinity etc. if text.isalpha(): return False return True except ValueError: return False </code></pre>
0
2016-10-15T21:11:09Z
[ "python", "casting", "floating-point", "type-conversion" ]
How to configure vim to not put comments at the beginning of lines while editing python files
354,097
<p>When I add a # in insert mode on an empty line in Vim while editing python files, vim moves the # to the beginning of the line, but I would like the # to be inserted at the tab level where I entered it.</p> <p>For example, when writing this in vim</p> <pre><code>for i in range(10): # </code></pre> <p>the # does not stay there where I entered it.</p> <p>It is moved like so, by vim.</p> <pre><code>for i in range(10): # </code></pre> <p>Does anyone know of a configuration item in vim that would change this?</p> <p>If it helps, I am using Ubuntu 8.10.</p>
40
2008-12-09T20:21:40Z
354,271
<p>My Vim configuration doesn't do that. You might try the python.vim script available from this link: <a href="http://www.vim.org/scripts/script.php?script_id=790" rel="nofollow">http://www.vim.org/scripts/script.php?script_id=790</a></p>
1
2008-12-09T21:18:38Z
[ "python", "vim" ]
How to configure vim to not put comments at the beginning of lines while editing python files
354,097
<p>When I add a # in insert mode on an empty line in Vim while editing python files, vim moves the # to the beginning of the line, but I would like the # to be inserted at the tab level where I entered it.</p> <p>For example, when writing this in vim</p> <pre><code>for i in range(10): # </code></pre> <p>the # does not stay there where I entered it.</p> <p>It is moved like so, by vim.</p> <pre><code>for i in range(10): # </code></pre> <p>Does anyone know of a configuration item in vim that would change this?</p> <p>If it helps, I am using Ubuntu 8.10.</p>
40
2008-12-09T20:21:40Z
354,422
<p>I found an answer here <a href="http://vim.wikia.com/wiki/Restoring_indent_after_typing_hash">http://vim.wikia.com/wiki/Restoring_indent_after_typing_hash</a></p> <p>It seems that the vim smartindent option is the cause of the problem. The referenced page above describes work-a-rounds but after reading the help in smartindent in vim itself (:help smartindent), I decided to try cindent instead of smartindent.</p> <p>I replaced </p> <pre><code>set smartindent </code></pre> <p>with </p> <pre><code>set cindent </code></pre> <p>in my .vimrc file</p> <p>and so far it is working perfectly.</p> <p>This changed also fixed the behavior of '&lt;&lt;' and '>>' for indenting visual blocks that include python comments.</p> <p>There are more configuration options for and information on indentation in the vim help for smartindent and cindent (:help smartindent and :help cindent).</p>
26
2008-12-09T22:07:18Z
[ "python", "vim" ]
How to configure vim to not put comments at the beginning of lines while editing python files
354,097
<p>When I add a # in insert mode on an empty line in Vim while editing python files, vim moves the # to the beginning of the line, but I would like the # to be inserted at the tab level where I entered it.</p> <p>For example, when writing this in vim</p> <pre><code>for i in range(10): # </code></pre> <p>the # does not stay there where I entered it.</p> <p>It is moved like so, by vim.</p> <pre><code>for i in range(10): # </code></pre> <p>Does anyone know of a configuration item in vim that would change this?</p> <p>If it helps, I am using Ubuntu 8.10.</p>
40
2008-12-09T20:21:40Z
385,388
<p>It's caused by the 'smartindent' feature. If you have <code>:set smartindent</code> in your .vimrc you need to remove it.</p>
2
2008-12-22T02:13:59Z
[ "python", "vim" ]
How to configure vim to not put comments at the beginning of lines while editing python files
354,097
<p>When I add a # in insert mode on an empty line in Vim while editing python files, vim moves the # to the beginning of the line, but I would like the # to be inserted at the tab level where I entered it.</p> <p>For example, when writing this in vim</p> <pre><code>for i in range(10): # </code></pre> <p>the # does not stay there where I entered it.</p> <p>It is moved like so, by vim.</p> <pre><code>for i in range(10): # </code></pre> <p>Does anyone know of a configuration item in vim that would change this?</p> <p>If it helps, I am using Ubuntu 8.10.</p>
40
2008-12-09T20:21:40Z
385,724
<p>I have the following lines in my .vimrc, seems to be installed by default with my Ubuntu 8.10</p> <pre><code>set smartindent inoremap # X^H# set autoindent </code></pre> <p>And I don't observe the problem. Maybe you can try this. (Note that ^H should be entered by Ctrl-V Ctrl-H)</p>
8
2008-12-22T07:27:50Z
[ "python", "vim" ]
How to configure vim to not put comments at the beginning of lines while editing python files
354,097
<p>When I add a # in insert mode on an empty line in Vim while editing python files, vim moves the # to the beginning of the line, but I would like the # to be inserted at the tab level where I entered it.</p> <p>For example, when writing this in vim</p> <pre><code>for i in range(10): # </code></pre> <p>the # does not stay there where I entered it.</p> <p>It is moved like so, by vim.</p> <pre><code>for i in range(10): # </code></pre> <p>Does anyone know of a configuration item in vim that would change this?</p> <p>If it helps, I am using Ubuntu 8.10.</p>
40
2008-12-09T20:21:40Z
777,385
<p>@PolyThinker Though I see that response a lot to this question, in my opinion it's not a good solution. The editor still thinks it should be indented all the way to left - check this by pushing == on a line that starts with a hash, or pushing = while a block of code with comments in it is highlighted to reindent.</p> <p>I would strongly recommend <code>filetype indent on</code>, and remove the <code>set smartindent</code> and <code>set autoindent</code> (or <code>set cindent</code>) lines from your vimrc. Someone else (appparently David Bustos) was kind enough to write a full indentation parser for us; it's located at $VIMDIRECTORY/indent/python.vim.</p> <p>(Paul's <code>cindent</code> solution probably works for python, but <code>filetype indent on</code> is much more generally useful.)</p>
15
2009-04-22T14:07:40Z
[ "python", "vim" ]
How to configure vim to not put comments at the beginning of lines while editing python files
354,097
<p>When I add a # in insert mode on an empty line in Vim while editing python files, vim moves the # to the beginning of the line, but I would like the # to be inserted at the tab level where I entered it.</p> <p>For example, when writing this in vim</p> <pre><code>for i in range(10): # </code></pre> <p>the # does not stay there where I entered it.</p> <p>It is moved like so, by vim.</p> <pre><code>for i in range(10): # </code></pre> <p>Does anyone know of a configuration item in vim that would change this?</p> <p>If it helps, I am using Ubuntu 8.10.</p>
40
2008-12-09T20:21:40Z
23,683,246
<p>My solution to the unindenting of #:</p> <p>If you use cindent, recognize that it is designed for C and C++ coding. Here, a # means you are creating a #DEFINE or #MACRO(), so the behavior is correct. But for other languages where # is a comment, it is irritating.</p> <p>The following worked for me:</p> <pre><code>" cindent enable specific indenting for C code " set cin nocin set cin " cinkeys The default cinkeys causes leading # to unindent to column 0. " To prevent this, remove the 0# from the definition. " set cinkeys=0{,0},0),:,0#,!^F,o,O,e - default set cinkeys=0{,0},0),:,!^F,o,O,e </code></pre>
2
2014-05-15T15:57:17Z
[ "python", "vim" ]
How to configure vim to not put comments at the beginning of lines while editing python files
354,097
<p>When I add a # in insert mode on an empty line in Vim while editing python files, vim moves the # to the beginning of the line, but I would like the # to be inserted at the tab level where I entered it.</p> <p>For example, when writing this in vim</p> <pre><code>for i in range(10): # </code></pre> <p>the # does not stay there where I entered it.</p> <p>It is moved like so, by vim.</p> <pre><code>for i in range(10): # </code></pre> <p>Does anyone know of a configuration item in vim that would change this?</p> <p>If it helps, I am using Ubuntu 8.10.</p>
40
2008-12-09T20:21:40Z
24,045,070
<p>I removed <code>set smartindent</code> from <code>~/.vimrc</code> but it still didn't disable smartindent. When I opened a .py file and ran <code>:set smartindent?</code> it displayed <code>smartindent</code>.</p> <p>Turns out that further down in the <code>~/.vimrc</code> was this line:</p> <pre><code>autocmd BufRead *.py set smartindent cinwords=if,elif,else,for,while,try,except,finally,def,class ^^^^^^^^^^^ </code></pre> <p>Once I deleted "smartindent" from that line, then smartindent was finally disabled and my comments were indented properly again.</p>
0
2014-06-04T18:38:23Z
[ "python", "vim" ]
Are there statistical studies that indicates that Python is "more productive"?
354,124
<p>If I do a google search with the string "python productive" the first results is a page <a href="http://www.ferg.org/projects/python_java_side-by-side.html">http://www.ferg.org/projects/python_java_side-by-side.html</a> claiming that "python is more productive of Java". Many Python programmers that I have talked with claim that Python is "more productive", and most of them report the arguments listed in the above cited article.</p> <p>The article could be summarized in these stametements:</p> <ol> <li>Python allow you write terser code </li> <li>A more terser is written in lesser time </li> <li><strong>Then</strong> Python is more productive</li> </ol> <p>But the article does not reports any statisticals evidences that support the hypothesis that a more terse code could be developed (not written) in lesser time.</p> <p>Do you know if there any article that reports statistical evidences that Python is more productive of something else?</p> <h2>Update:</h2> <p>I'm not interested in adovacy arguments. Please do not tell why something <em>should</em> be more productive of something else. I'm interested in studies that measures that the use of something is related or not related to the productivity.</p> <p>I'm interested in statisticals evidences. If you claim that the productivity depends from many other factors then there should be a statistical study that proves that the language choiche is not statistically correlated to the productivity.</p>
44
2008-12-09T20:29:40Z
354,149
<p>I think it really is going to depend on the programmer and what you want to do. It's subjective. Someone who is a Java God will outperform someone who is only good at python. Any study that tries to blanketly state that will be far too broad in what it tries to accomplish.</p>
1
2008-12-09T20:37:31Z
[ "python", "productivity" ]
Are there statistical studies that indicates that Python is "more productive"?
354,124
<p>If I do a google search with the string "python productive" the first results is a page <a href="http://www.ferg.org/projects/python_java_side-by-side.html">http://www.ferg.org/projects/python_java_side-by-side.html</a> claiming that "python is more productive of Java". Many Python programmers that I have talked with claim that Python is "more productive", and most of them report the arguments listed in the above cited article.</p> <p>The article could be summarized in these stametements:</p> <ol> <li>Python allow you write terser code </li> <li>A more terser is written in lesser time </li> <li><strong>Then</strong> Python is more productive</li> </ol> <p>But the article does not reports any statisticals evidences that support the hypothesis that a more terse code could be developed (not written) in lesser time.</p> <p>Do you know if there any article that reports statistical evidences that Python is more productive of something else?</p> <h2>Update:</h2> <p>I'm not interested in adovacy arguments. Please do not tell why something <em>should</em> be more productive of something else. I'm interested in studies that measures that the use of something is related or not related to the productivity.</p> <p>I'm interested in statisticals evidences. If you claim that the productivity depends from many other factors then there should be a statistical study that proves that the language choiche is not statistically correlated to the productivity.</p>
44
2008-12-09T20:29:40Z
354,158
<p>General claims about productivity do not necessarily make sense. A good software engineer (or project manager) knows what language to pick based on the nature of the project, the requirements of the customer, and the skills of his team.</p> <p>There is generally no "one language to rule them all", though there are clearly languages that are better for certain domains. I would not write distributed enterprise applications or device drivers in perl, or games in prolog, but there are great uses for them.</p> <p>Productivity also depends on tool support (e.g., are there good Python IDEs?), on skills, and on the possibility for practitioners to mess up. I am generally wary of functional programming in the hands of the average programmer. </p> <p>If Python automates or simplifies tasks that Java developers building the same applications would frequently have to do, then yes, it may be more productive, but any evidence you get would still be anecdotal.</p>
3
2008-12-09T20:41:24Z
[ "python", "productivity" ]
Are there statistical studies that indicates that Python is "more productive"?
354,124
<p>If I do a google search with the string "python productive" the first results is a page <a href="http://www.ferg.org/projects/python_java_side-by-side.html">http://www.ferg.org/projects/python_java_side-by-side.html</a> claiming that "python is more productive of Java". Many Python programmers that I have talked with claim that Python is "more productive", and most of them report the arguments listed in the above cited article.</p> <p>The article could be summarized in these stametements:</p> <ol> <li>Python allow you write terser code </li> <li>A more terser is written in lesser time </li> <li><strong>Then</strong> Python is more productive</li> </ol> <p>But the article does not reports any statisticals evidences that support the hypothesis that a more terse code could be developed (not written) in lesser time.</p> <p>Do you know if there any article that reports statistical evidences that Python is more productive of something else?</p> <h2>Update:</h2> <p>I'm not interested in adovacy arguments. Please do not tell why something <em>should</em> be more productive of something else. I'm interested in studies that measures that the use of something is related or not related to the productivity.</p> <p>I'm interested in statisticals evidences. If you claim that the productivity depends from many other factors then there should be a statistical study that proves that the language choiche is not statistically correlated to the productivity.</p>
44
2008-12-09T20:29:40Z
354,219
<p>I think the point about IDEs is a particularly strong one. For example, is there a Python IDE on par with Eclipse, offering the same refactoring capabilities? Conversely, does an IDE with strong refactoring capabilities promote less intelligent up-front design?</p> <p>This just highlights the difficulty (or, rather the futility) of declaring one language more/less productive than another.</p>
0
2008-12-09T20:58:28Z
[ "python", "productivity" ]
Are there statistical studies that indicates that Python is "more productive"?
354,124
<p>If I do a google search with the string "python productive" the first results is a page <a href="http://www.ferg.org/projects/python_java_side-by-side.html">http://www.ferg.org/projects/python_java_side-by-side.html</a> claiming that "python is more productive of Java". Many Python programmers that I have talked with claim that Python is "more productive", and most of them report the arguments listed in the above cited article.</p> <p>The article could be summarized in these stametements:</p> <ol> <li>Python allow you write terser code </li> <li>A more terser is written in lesser time </li> <li><strong>Then</strong> Python is more productive</li> </ol> <p>But the article does not reports any statisticals evidences that support the hypothesis that a more terse code could be developed (not written) in lesser time.</p> <p>Do you know if there any article that reports statistical evidences that Python is more productive of something else?</p> <h2>Update:</h2> <p>I'm not interested in adovacy arguments. Please do not tell why something <em>should</em> be more productive of something else. I'm interested in studies that measures that the use of something is related or not related to the productivity.</p> <p>I'm interested in statisticals evidences. If you claim that the productivity depends from many other factors then there should be a statistical study that proves that the language choiche is not statistically correlated to the productivity.</p>
44
2008-12-09T20:29:40Z
354,230
<p>You can't measure it, but if you're experienced with Java, and then you learn python and try to do stuff with it, you will realize it by yourself. </p> <p>It's one of those things that can't be quantified, and frankly even if there was a statistical study, I wouldn't be convinced by it. You can bring a Java guru and a python newbie and give them a task that is better done with java (maybe because there's a specific library or even built-in functionality for it), and <em>maybe</em> in that case the Java guru will be "more productive" than the python newbie.</p> <p>Some people mention IDEs, in my opinion, you can be productive with python even without an IDE, specially without a beast like Eclipse. You don't have cheked exceptions in python, so you don't need a tool to help you deal with that. Because everything in python is dynamic, you don't have "virtual" methods (although you can mimic them if you really want), so you don't need a tool to help you deal with writing stubs and whatnot. etc. Many things in Java that require an IDE are simply not applicable to python. The only useful thing an IDE in python would do is auto-complete and maybe an interactive shell in the same editor window.</p> <p>OK, here's the thing about the "terse" argument: Java has so much clutter overhead, i.e. public static void main! System.stdout.writeln (or what the hell was it?), remind me again how do you get input from the user? Yea, there's no specific way, you <em>always</em> end up writing a wrapper class around it!! Remind me again how do you read a file? which library do you have to import? oh, go read the API docs and browse through tons of stream readers and writers, while in python, it's just <code>open('filename')</code>. You can run through all lines of a text file by simply: <code>for line in open('filename'):</code>.</p> <p>In Java there's so much overhead of words it just clutters your mind and diverts your attention from your main task. This overhead is a real hindrance, there's only about 7 items you could hold in your short term memory, <code>for line in file</code> fills one item; how many items do you need to fill if you use Java IOStream classes for that task? How many slots do you have left for thing related to the actual task you're doing?</p>
4
2008-12-09T21:05:00Z
[ "python", "productivity" ]
Are there statistical studies that indicates that Python is "more productive"?
354,124
<p>If I do a google search with the string "python productive" the first results is a page <a href="http://www.ferg.org/projects/python_java_side-by-side.html">http://www.ferg.org/projects/python_java_side-by-side.html</a> claiming that "python is more productive of Java". Many Python programmers that I have talked with claim that Python is "more productive", and most of them report the arguments listed in the above cited article.</p> <p>The article could be summarized in these stametements:</p> <ol> <li>Python allow you write terser code </li> <li>A more terser is written in lesser time </li> <li><strong>Then</strong> Python is more productive</li> </ol> <p>But the article does not reports any statisticals evidences that support the hypothesis that a more terse code could be developed (not written) in lesser time.</p> <p>Do you know if there any article that reports statistical evidences that Python is more productive of something else?</p> <h2>Update:</h2> <p>I'm not interested in adovacy arguments. Please do not tell why something <em>should</em> be more productive of something else. I'm interested in studies that measures that the use of something is related or not related to the productivity.</p> <p>I'm interested in statisticals evidences. If you claim that the productivity depends from many other factors then there should be a statistical study that proves that the language choiche is not statistically correlated to the productivity.</p>
44
2008-12-09T20:29:40Z
354,240
<p>Well, the very same google search points also a link to an <a href="http://www.artima.com/intv/speed.html" rel="nofollow">interview to GvR</a>, where he explain the reasons for the productivity gain. He lists, in particular:</p> <ul> <li>terser language, hence less typing</li> <li>built-in data types</li> <li>duck typing</li> <li>rich set of standard libraries</li> </ul> <p>About the first point, some further data comes from Code Complete, where Python has an index of 6 equivalent lines of C code , while Java and C++ are on 2.5.</p> <p>Whatever those numbers mean, something I personally like very much with python is the idea of pythonicity. Once you get it, the language is very coherent, and rarely you get the feeling that it gets in your way. This helps really a lot in focusing on the problem, instead of the implementation, and therefore achieving an higher development speed.</p>
0
2008-12-09T21:06:46Z
[ "python", "productivity" ]
Are there statistical studies that indicates that Python is "more productive"?
354,124
<p>If I do a google search with the string "python productive" the first results is a page <a href="http://www.ferg.org/projects/python_java_side-by-side.html">http://www.ferg.org/projects/python_java_side-by-side.html</a> claiming that "python is more productive of Java". Many Python programmers that I have talked with claim that Python is "more productive", and most of them report the arguments listed in the above cited article.</p> <p>The article could be summarized in these stametements:</p> <ol> <li>Python allow you write terser code </li> <li>A more terser is written in lesser time </li> <li><strong>Then</strong> Python is more productive</li> </ol> <p>But the article does not reports any statisticals evidences that support the hypothesis that a more terse code could be developed (not written) in lesser time.</p> <p>Do you know if there any article that reports statistical evidences that Python is more productive of something else?</p> <h2>Update:</h2> <p>I'm not interested in adovacy arguments. Please do not tell why something <em>should</em> be more productive of something else. I'm interested in studies that measures that the use of something is related or not related to the productivity.</p> <p>I'm interested in statisticals evidences. If you claim that the productivity depends from many other factors then there should be a statistical study that proves that the language choiche is not statistically correlated to the productivity.</p>
44
2008-12-09T20:29:40Z
354,249
<p>All evidence is anecdotal.</p> <p>You can't ever find published studies that show the general superiority of one language over another because there are too many confounds:</p> <ul> <li>Individual programmers differ greatly in ability</li> <li>Some tasks are more amenable to a given language/library than others (what constitues representative set of tasks?)</li> <li>Different languages have different core libraries</li> <li>Different languages have different tool chains</li> <li>Interaction of two or more of the above (e.g. familiarity of programmer X with tools Y)</li> <li>etc. the list goes on and on and on</li> </ul> <p>Even though you can design experiments to control for some of these, the variability still requires a huge amount of statistical power to get any meaningful result, and no one ever does studies where like 1000 programmers do the exact same task in different languages, so there's never anything definitive.</p> <p>The upshot is, each of us knows what the best languages/tools are, and so we can advocate them without fear of being shot down by a published study. :)</p>
16
2008-12-09T21:09:45Z
[ "python", "productivity" ]
Are there statistical studies that indicates that Python is "more productive"?
354,124
<p>If I do a google search with the string "python productive" the first results is a page <a href="http://www.ferg.org/projects/python_java_side-by-side.html">http://www.ferg.org/projects/python_java_side-by-side.html</a> claiming that "python is more productive of Java". Many Python programmers that I have talked with claim that Python is "more productive", and most of them report the arguments listed in the above cited article.</p> <p>The article could be summarized in these stametements:</p> <ol> <li>Python allow you write terser code </li> <li>A more terser is written in lesser time </li> <li><strong>Then</strong> Python is more productive</li> </ol> <p>But the article does not reports any statisticals evidences that support the hypothesis that a more terse code could be developed (not written) in lesser time.</p> <p>Do you know if there any article that reports statistical evidences that Python is more productive of something else?</p> <h2>Update:</h2> <p>I'm not interested in adovacy arguments. Please do not tell why something <em>should</em> be more productive of something else. I'm interested in studies that measures that the use of something is related or not related to the productivity.</p> <p>I'm interested in statisticals evidences. If you claim that the productivity depends from many other factors then there should be a statistical study that proves that the language choiche is not statistically correlated to the productivity.</p>
44
2008-12-09T20:29:40Z
354,250
<p>Yes, there's an excellent paper by Lutz Prechelt on this subject:</p> <p><a href="http://page.mi.fu-berlin.de/prechelt/Biblio//jccpprt_computer2000.pdf">An Empirical Comparison of Seven Programming Languages</a></p> <p>Of course, this paper doesn’t “prove” the superiority of any particular language. But it probably comes as close as any scientific study <em>can</em> come to the truth. On the other hand, the data of this study is very dated, and in the fast-developing world of software engineering this actually plays an important role since both the languages and the tools have vastly improved over time.</p>
19
2008-12-09T21:09:52Z
[ "python", "productivity" ]
Are there statistical studies that indicates that Python is "more productive"?
354,124
<p>If I do a google search with the string "python productive" the first results is a page <a href="http://www.ferg.org/projects/python_java_side-by-side.html">http://www.ferg.org/projects/python_java_side-by-side.html</a> claiming that "python is more productive of Java". Many Python programmers that I have talked with claim that Python is "more productive", and most of them report the arguments listed in the above cited article.</p> <p>The article could be summarized in these stametements:</p> <ol> <li>Python allow you write terser code </li> <li>A more terser is written in lesser time </li> <li><strong>Then</strong> Python is more productive</li> </ol> <p>But the article does not reports any statisticals evidences that support the hypothesis that a more terse code could be developed (not written) in lesser time.</p> <p>Do you know if there any article that reports statistical evidences that Python is more productive of something else?</p> <h2>Update:</h2> <p>I'm not interested in adovacy arguments. Please do not tell why something <em>should</em> be more productive of something else. I'm interested in studies that measures that the use of something is related or not related to the productivity.</p> <p>I'm interested in statisticals evidences. If you claim that the productivity depends from many other factors then there should be a statistical study that proves that the language choiche is not statistically correlated to the productivity.</p>
44
2008-12-09T20:29:40Z
354,290
<p>I think there are cases where one or the other may be more productive, but the question I always ask is how would this language perform on a mixed team involving people who were not good at programming and would cause more problems than they solve, people who think they know everything and like to write tricky code using all the neat language features available, family oriented programmers who just want to go home at 5:00, etc.</p> <p>I keep hearing these phrases like "if the programmer wants to shoot himself in the foot, let him", as though the speaker has never been on a team.</p> <p>When on a project team like the one I just described, I would not consider a language that allowed me to "Shoot myself in the foot" if it also meant that any of my teammates could also shoot me in the foot.</p> <p>The thing is, by definition most projects will either fail or, eventually, be maintained by a team of widely varying talents--so as far as I'm concerned, I have to assume that of all non-trivial projects.</p>
-1
2008-12-09T21:25:56Z
[ "python", "productivity" ]
Are there statistical studies that indicates that Python is "more productive"?
354,124
<p>If I do a google search with the string "python productive" the first results is a page <a href="http://www.ferg.org/projects/python_java_side-by-side.html">http://www.ferg.org/projects/python_java_side-by-side.html</a> claiming that "python is more productive of Java". Many Python programmers that I have talked with claim that Python is "more productive", and most of them report the arguments listed in the above cited article.</p> <p>The article could be summarized in these stametements:</p> <ol> <li>Python allow you write terser code </li> <li>A more terser is written in lesser time </li> <li><strong>Then</strong> Python is more productive</li> </ol> <p>But the article does not reports any statisticals evidences that support the hypothesis that a more terse code could be developed (not written) in lesser time.</p> <p>Do you know if there any article that reports statistical evidences that Python is more productive of something else?</p> <h2>Update:</h2> <p>I'm not interested in adovacy arguments. Please do not tell why something <em>should</em> be more productive of something else. I'm interested in studies that measures that the use of something is related or not related to the productivity.</p> <p>I'm interested in statisticals evidences. If you claim that the productivity depends from many other factors then there should be a statistical study that proves that the language choiche is not statistically correlated to the productivity.</p>
44
2008-12-09T20:29:40Z
354,361
<p>Yes, and there are also statistical studies that prove that dogs are more productive than cats. Both are equally valid. ;-)</p> <p>by popular demand, here are a couple of "studies" - take them with a block of salt!</p> <ol> <li><a href="http://page.mi.fu-berlin.de/prechelt/Biblio/jccpprt_computer2000.pdf" rel="nofollow">An empirical comparison of C, C++, Java, Perl, Python, Rexx, and Tcl</a> PDF warning!</li> <li><a href="http://www.connellybarnes.com/documents/language_productivity.pdf" rel="nofollow">Programming Language Productivity</a> PDF warning! Note that these statistics are for a "string processing problem", so one might expect the winner to be...Perl of course!</li> </ol> <p>and <a href="http://blog.codinghorror.com/are-all-programming-languages-the-same/" rel="nofollow">Jeff Atwood's musings</a> are interesting as well</p> <p>the issues of programmer productivity are far more complex than what language is being used. Productivity among programmers can vary wildly, and is affected by the problem domain plus many other factors. Thus no "study" can ever be "definitive". See <a href="http://www.usc.edu/dept/ATRIUM/Papers/Software_Productivity.html" rel="nofollow">Understanding Software Productivity</a> and <a href="http://forums.construx.com/blogs/stevemcc/archive/2008/03/27/productivity-variations-among-software-developers-and-teams-the-origin-of-quot-10x-quot.aspx" rel="nofollow">Productivity Variations Among Software Developers and Teams</a> for additional information.</p> <p>Finally, <strong>the right tool for the right job</strong> is still the rule. No exceptions.</p>
28
2008-12-09T21:50:45Z
[ "python", "productivity" ]
Are there statistical studies that indicates that Python is "more productive"?
354,124
<p>If I do a google search with the string "python productive" the first results is a page <a href="http://www.ferg.org/projects/python_java_side-by-side.html">http://www.ferg.org/projects/python_java_side-by-side.html</a> claiming that "python is more productive of Java". Many Python programmers that I have talked with claim that Python is "more productive", and most of them report the arguments listed in the above cited article.</p> <p>The article could be summarized in these stametements:</p> <ol> <li>Python allow you write terser code </li> <li>A more terser is written in lesser time </li> <li><strong>Then</strong> Python is more productive</li> </ol> <p>But the article does not reports any statisticals evidences that support the hypothesis that a more terse code could be developed (not written) in lesser time.</p> <p>Do you know if there any article that reports statistical evidences that Python is more productive of something else?</p> <h2>Update:</h2> <p>I'm not interested in adovacy arguments. Please do not tell why something <em>should</em> be more productive of something else. I'm interested in studies that measures that the use of something is related or not related to the productivity.</p> <p>I'm interested in statisticals evidences. If you claim that the productivity depends from many other factors then there should be a statistical study that proves that the language choiche is not statistically correlated to the productivity.</p>
44
2008-12-09T20:29:40Z
361,425
<p>It's a poorly-conceived question, and as such can't be meaningfully answered. If you came to me with a project proposal and asked me what language would be the most productive, the <em>last thing in the world</em> I would look at was a "scientific" comparison of how random programmers did implementing an algorithm in different languages.</p> <p>I'd ask:</p> <ul> <li>What does the software have to do?</li> <li>What technical constraints are there on the software?</li> <li>Who will develop the software?</li> <li>What methodology will they use?</li> <li>How will the software be supported?</li> <li>Who will maintain the software?</li> </ul> <p>At some stage of the game, I'd rely on "non-scientific" or "anecdotal" evidence to guide my decision-making. I don't need a scientific study to tell me that I shouldn't be developing device drivers in a scripting language. Nor do I need one to tell me that a team of C++ programmers is probably going to be able to implement a small project in C++ faster than they'd be able to in Python.</p> <p>If at any point in this process, I reached for a study that demonstrated that some developers implemented a specific algorithm in Python twice as fast as other developers implemented it in Java, you'd fire me and get someone else to run the project, if you had any brains.</p>
2
2008-12-11T23:29:19Z
[ "python", "productivity" ]
Are there statistical studies that indicates that Python is "more productive"?
354,124
<p>If I do a google search with the string "python productive" the first results is a page <a href="http://www.ferg.org/projects/python_java_side-by-side.html">http://www.ferg.org/projects/python_java_side-by-side.html</a> claiming that "python is more productive of Java". Many Python programmers that I have talked with claim that Python is "more productive", and most of them report the arguments listed in the above cited article.</p> <p>The article could be summarized in these stametements:</p> <ol> <li>Python allow you write terser code </li> <li>A more terser is written in lesser time </li> <li><strong>Then</strong> Python is more productive</li> </ol> <p>But the article does not reports any statisticals evidences that support the hypothesis that a more terse code could be developed (not written) in lesser time.</p> <p>Do you know if there any article that reports statistical evidences that Python is more productive of something else?</p> <h2>Update:</h2> <p>I'm not interested in adovacy arguments. Please do not tell why something <em>should</em> be more productive of something else. I'm interested in studies that measures that the use of something is related or not related to the productivity.</p> <p>I'm interested in statisticals evidences. If you claim that the productivity depends from many other factors then there should be a statistical study that proves that the language choiche is not statistically correlated to the productivity.</p>
44
2008-12-09T20:29:40Z
24,998,191
<p>Another issue to consider is the size of the codebase:</p> <p><a href="http://dustyvolumes.com/archives/506" rel="nofollow">http://dustyvolumes.com/archives/506</a></p> <blockquote> <p>More interestingly, this seems to have been one of the first papers to note that productivity rates decline as the size of the program increases. Jones details that programs of less than 2 KLOC usually take about 1 programmer month/KLOC, whereas programs of over 512 KLOC take 10 programmer months/KLOC.</p> </blockquote> <p>Note how dramatic is the performance decline. All other things equal, we should strongly prefer shorter programs, and Python or other "terse" languages result fewer lines of code (again, ceteris paribus).</p> <p>The big and seemingly unexplored questions here is what's behind this decline: are those are plain KLOCs that are the reason, or a "denser" logic of such software irrespective of PL (and then amortized cost of the big program would depend little on PL), or maybe particular PL constructs actually allow easier/cheaper expression of what programmers wants to build (and then a big program in a "terse" PL is cheaper and more maintainable)?</p>
0
2014-07-28T15:03:36Z
[ "python", "productivity" ]
Are there statistical studies that indicates that Python is "more productive"?
354,124
<p>If I do a google search with the string "python productive" the first results is a page <a href="http://www.ferg.org/projects/python_java_side-by-side.html">http://www.ferg.org/projects/python_java_side-by-side.html</a> claiming that "python is more productive of Java". Many Python programmers that I have talked with claim that Python is "more productive", and most of them report the arguments listed in the above cited article.</p> <p>The article could be summarized in these stametements:</p> <ol> <li>Python allow you write terser code </li> <li>A more terser is written in lesser time </li> <li><strong>Then</strong> Python is more productive</li> </ol> <p>But the article does not reports any statisticals evidences that support the hypothesis that a more terse code could be developed (not written) in lesser time.</p> <p>Do you know if there any article that reports statistical evidences that Python is more productive of something else?</p> <h2>Update:</h2> <p>I'm not interested in adovacy arguments. Please do not tell why something <em>should</em> be more productive of something else. I'm interested in studies that measures that the use of something is related or not related to the productivity.</p> <p>I'm interested in statisticals evidences. If you claim that the productivity depends from many other factors then there should be a statistical study that proves that the language choiche is not statistically correlated to the productivity.</p>
44
2008-12-09T20:29:40Z
29,518,256
<h1>Plat_Forms</h1> <p>You may also want to have a look at <a href="https://www.plat-forms.org" rel="nofollow">Plat_Forms</a>.</p> <p>Plat_Forms was a fairly well-controlled, scientifically evaluated web development contest (teams of 3 worked for 2 days) comparing Java, PHP, Perl, and Ruby. Python is <em>not</em> included, but the conclusions can still tell you something. They are:</p> <ul> <li>Team performance is good if the team knows their platform well. It is not good if not.</li> <li>Ruby-on-Rails was successful because the character of that platform fit well with the character of the contest (rapid development, rather than detailed, long-term, continued development).</li> </ul> <p>(There are plenty of interesting details beyond this. For instance, have a look at the (long!) <a href="http://www.mi.fu-berlin.de/w/SE/OurPublications#PF07resultsTR" rel="nofollow">2007 Plat_Forms Technical Report</a> (without Ruby).)</p> <p>For your question, I would say the take-home message of the above could be:</p> <p><strong>Yes, Python will be more productive if [the conditions are right].</strong></p>
0
2015-04-08T14:57:11Z
[ "python", "productivity" ]
Are there statistical studies that indicates that Python is "more productive"?
354,124
<p>If I do a google search with the string "python productive" the first results is a page <a href="http://www.ferg.org/projects/python_java_side-by-side.html">http://www.ferg.org/projects/python_java_side-by-side.html</a> claiming that "python is more productive of Java". Many Python programmers that I have talked with claim that Python is "more productive", and most of them report the arguments listed in the above cited article.</p> <p>The article could be summarized in these stametements:</p> <ol> <li>Python allow you write terser code </li> <li>A more terser is written in lesser time </li> <li><strong>Then</strong> Python is more productive</li> </ol> <p>But the article does not reports any statisticals evidences that support the hypothesis that a more terse code could be developed (not written) in lesser time.</p> <p>Do you know if there any article that reports statistical evidences that Python is more productive of something else?</p> <h2>Update:</h2> <p>I'm not interested in adovacy arguments. Please do not tell why something <em>should</em> be more productive of something else. I'm interested in studies that measures that the use of something is related or not related to the productivity.</p> <p>I'm interested in statisticals evidences. If you claim that the productivity depends from many other factors then there should be a statistical study that proves that the language choiche is not statistically correlated to the productivity.</p>
44
2008-12-09T20:29:40Z
40,007,599
<p>There's a great new paper on this: <a href="https://arxiv.org/pdf/1409.0252.pdf" rel="nofollow">https://arxiv.org/pdf/1409.0252.pdf</a></p> <p><a href="https://i.stack.imgur.com/AW6Io.png" rel="nofollow"><img src="https://i.stack.imgur.com/AW6Io.png" alt="enter image description here"></a></p> <p>Key finding: </p> <blockquote> <p>Figure 6 shows the corresponding language relationship graph; remember that arrows point to the more concise languages, thickness denotes larger effects, and horizontal distances are roughly proportional to average differences. Languages are clearly divided into two groups: functional and scripting languages tend to provide the most concise code, whereas procedural and object-oriented languages are significantly more verbose. The absolute difference between the two groups is major; for instance, Java programs are on average 2.2–2.9 times longer than programs in functional and scripting languages.</p> </blockquote> <p>What's important from my viewpoint is that this study is highly rigorous, studying over 7,000 programs implementing the same 745 tasks, so there's little if any variation by feature or scope among the programs.</p>
0
2016-10-12T20:17:08Z
[ "python", "productivity" ]
Adding a SOAP header to a SOAPpy request
354,370
<p>Does anyone know how to do this? I need to add a header of the form:</p> <p> value1 value2 </p>
0
2008-12-09T21:52:26Z
493,527
<p>As the question is phrased, it's hard to guess what the intention (or even the intended semantics) is. For setting headers, try the following:</p> <pre><code>import SOAPpy headers = SOAPpy.Types.headerType() headers.value1 = value2 </code></pre> <p>or</p> <pre><code>[...] headers.foo = value1 headers.bar = value2 </code></pre>
4
2009-01-29T21:29:56Z
[ "python", "soappy" ]
How is ** implemented in Python?
354,421
<p>I'm wondering where I find the source to show how the operator ** is implemented in Python. Can someone point me in the right direction? </p>
9
2008-12-09T22:07:10Z
354,433
<p>It's the power to operator</p> <p><a href="http://www.python.org/doc/2.5.2/ref/power.html" rel="nofollow">python.org doc - Power operator</a></p> <p>Edit: Oh, dang, the code, right. Hope the link still helps. Sloppy read from my part</p>
1
2008-12-09T22:10:08Z
[ "python" ]
How is ** implemented in Python?
354,421
<p>I'm wondering where I find the source to show how the operator ** is implemented in Python. Can someone point me in the right direction? </p>
9
2008-12-09T22:07:10Z
354,622
<p>There are two different implementations one for int (long in 3.0) objects and another one for float objects. </p> <p>The float pow is the float_pow(PyObject *v, PyObject *w, PyObject *z) function defined in Objects/floatobject.c file of the Python source code. This functions calls pow() from C stdlib's math.h</p> <p>The int pow has its own implementation, is the function int_pow(PyIntObject *v, PyIntObject *w, PyIntObject *z) defined in Objects/intobject.c (longobject.c for 3.0) of the Python source code.</p>
1
2008-12-09T23:32:22Z
[ "python" ]
How is ** implemented in Python?
354,421
<p>I'm wondering where I find the source to show how the operator ** is implemented in Python. Can someone point me in the right direction? </p>
9
2008-12-09T22:07:10Z
354,626
<p>The python grammar definition (from which the parser is generated using <a href="http://www.python.org/dev/peps/pep-0269/">pgen</a>), look for 'power': <a href="http://svn.python.org/view/python/trunk/Grammar/Grammar?rev=65872&amp;view=markup">Gramar/Gramar</a></p> <p>The python ast, look for 'ast_for_power': <a href="http://svn.python.org/view/python/trunk/Python/ast.c?rev=67590&amp;view=markup">Python/ast.c</a></p> <p>The python eval loop, look for 'BINARY_POWER': <a href="http://svn.python.org/view/python/trunk/Python/ceval.c?rev=67666&amp;view=markup">Python/ceval.c</a></p> <p>Which calls PyNumber_Power (implemented in <a href="http://svn.python.org/view/python/trunk/Objects/abstract.c?rev=66043&amp;view=markup">Objects/abstract.c</a>):</p> <pre><code>PyObject * PyNumber_Power(PyObject *v, PyObject *w, PyObject *z) { return ternary_op(v, w, z, NB_SLOT(nb_power), "** or pow()"); } </code></pre> <p>Essentially, invoke the <strong>pow</strong> slot. For long objects (the only default integer type in 3.0) this is implemented in the long_pow function <a href="http://svn.python.org/view/python/trunk/Objects/longobject.c?rev=65518&amp;view=markup">Objects/longobject.c</a>, for int objects (in the 2.x branches) it is implemented in the int_pow function <a href="http://svn.python.org/view/python/trunk/Objects/intobject.c?rev=64753&amp;view=markup">Object/intobject.c</a></p> <p>If you dig into long_pow, you can see that after vetting the arguments and doing a bit of set up, the heart of the exponentiation can be see here:</p> <pre><code>if (Py_SIZE(b) &lt;= FIVEARY_CUTOFF) { /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */ /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */ for (i = Py_SIZE(b) - 1; i &gt;= 0; --i) { digit bi = b-&gt;ob_digit[i]; for (j = 1 &lt;&lt; (PyLong_SHIFT-1); j != 0; j &gt;&gt;= 1) { MULT(z, z, z) if (bi &amp; j) MULT(z, a, z) } } } else { /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */ Py_INCREF(z); /* still holds 1L */ table[0] = z; for (i = 1; i &lt; 32; ++i) MULT(table[i-1], a, table[i]) for (i = Py_SIZE(b) - 1; i &gt;= 0; --i) { const digit bi = b-&gt;ob_digit[i]; for (j = PyLong_SHIFT - 5; j &gt;= 0; j -= 5) { const int index = (bi &gt;&gt; j) &amp; 0x1f; for (k = 0; k &lt; 5; ++k) MULT(z, z, z) if (index) MULT(z, table[index], z) } } } </code></pre> <p>Which uses algorithms discussed in <a href="http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf">Chapter 14.6</a> of the <a href="http://www.cacr.math.uwaterloo.ca/hac/">Handbook of Applied Cryptography</a> which describes efficient exponentiation algorithms for arbitrary precision arithmetic.</p>
23
2008-12-09T23:33:18Z
[ "python" ]
How is ** implemented in Python?
354,421
<p>I'm wondering where I find the source to show how the operator ** is implemented in Python. Can someone point me in the right direction? </p>
9
2008-12-09T22:07:10Z
354,649
<p>I think caseysrandomthoughts are asking about asterisks at functions definition.</p> <p>You could find answer at this Python doc page: <a href="http://docs.python.org/tutorial/controlflow.html#more-on-defining-functions" rel="nofollow">http://docs.python.org/tutorial/controlflow.html#more-on-defining-functions</a></p> <p>When a final formal parameter of the form **name is present, it receives a dictionary containing all keyword arguments except for those corresponding to a formal parameter.</p> <p>I've sow description of this stuff somewhere else at python doc but I can't to remember.</p>
1
2008-12-09T23:47:28Z
[ "python" ]
How can I get the number of records that reference a particular foreign key in Django?
354,755
<p>I'm working on a blog application in Django. Naturally, I have models set up such that there are Posts and Comments, and a particular Post may have many Comments; thus, Post is a ForeignKey in the Comments model.</p> <p>Given a Post object, is there an easy way (ideally, through a method call) to find out how many Comments belong to the Post?</p>
2
2008-12-10T00:43:29Z
354,765
<pre><code>Comments.objects.filter(post=post).count() </code></pre> <p>or:</p> <pre><code>post.comment_set.count() </code></pre>
6
2008-12-10T00:49:16Z
[ "python", "django", "django-models" ]
How can I get the number of records that reference a particular foreign key in Django?
354,755
<p>I'm working on a blog application in Django. Naturally, I have models set up such that there are Posts and Comments, and a particular Post may have many Comments; thus, Post is a ForeignKey in the Comments model.</p> <p>Given a Post object, is there an easy way (ideally, through a method call) to find out how many Comments belong to the Post?</p>
2
2008-12-10T00:43:29Z
355,537
<p>You can add field CommentCount to you Post model, and update it in pre_save, pre_delete signals. It's a hard for the db to calculate comments count at every view call and number of queries will be grow.</p>
0
2008-12-10T09:47:32Z
[ "python", "django", "django-models" ]
How do you return multiple values in Python?
354,883
<p>The canonical way to return multiple values in languages that support it is often <a href="http://stackoverflow.com/questions/38508/whats-the-best-way-to-return-multiple-values-from-a-function-in-python">tupling</a>. </p> <h3>Option: Using a tuple</h3> <p>Consider this trivial example:</p> <pre><code>def f(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return (y0,y1,y2) </code></pre> <p>However, this quickly gets problematic as the number of values returned increases. What if you want to return four or five values? Sure, you could keep tupling them, but it gets easy to forget which value is where. It's also rather ugly to unpack them wherever you want to receive them.</p> <h3>Option: Using a dictionary</h3> <p>The next logical step seems to be to introduce some sort of 'record notation'. In python, the obvious way to do this is by means of a <code>dict</code>. </p> <p>Consider the following:</p> <pre><code>def g(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return {'y0':y0, 'y1':y1 ,'y2':y2 } </code></pre> <p>(edit- Just to be clear, y0, y1 and y2 are just meant as abstract identifiers. As pointed out, in practice you'd use meaningful identifiers)</p> <p>Now, we have a mechanism whereby we can project out a particular member of the returned object. For example, </p> <pre><code>result['y0'] </code></pre> <h3>Option: Using a class</h3> <p>However, there is another option. We could instead return a specialized structure. I've framed this in the context of Python, but I'm sure it applies to other languages as well. Indeed, if you were working in C this might very well be your only option. Here goes:</p> <pre><code>class ReturnValue(object): def __init__(self, y0, y1, y2): self.y0 = y0 self.y1 = y1 self.y2 = y2 def g(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return ReturnValue(y0, y1, y2) </code></pre> <p>In python the previous two are perhaps very similar in terms of plumbing- After all <code>{ y0, y1, y2 }</code> just end up being entries in the internal <code>__dict__</code> of the <code>ReturnValue</code>.</p> <p>There is one additional feature provided by Python though for tiny objects, the <code>__slots__</code> attribute. The class could be expressed as:</p> <pre><code>class ReturnValue(object): __slots__ = ["y0", "y1", "y2"] def __init__(self, y0, y1, y2): self.y0 = y0 self.y1 = y1 self.y2 = y2 </code></pre> <p>From the <a href="http://www.network-theory.co.uk/docs/pylang/__slots__.html">Python Reference Manual</a>:</p> <blockquote> <p>The <code>__slots__</code> declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because <code>__dict__</code> is not created for each instance.</p> </blockquote> <h3>Option: Using a list</h3> <p>Another suggestion which I'd overlooked comes from Bill the Lizard:</p> <pre><code>def h(x): result = [x + 1] result.append(x * 3) result.append(y0 ** y3) return result </code></pre> <p>This is my least favorite method though. I suppose I'm tainted by exposure to Haskell, but the idea of mixed-type lists has always felt uncomfortable to me. In this particular example the list is -not- mixed type, but it conceivably could be. A list used in this way really doesn't gain anything with respect to the tuple as far as I can tell. The only real difference between lists and tuples in Python is that lists are <a href="http://docs.python.org/library/stdtypes.html#typesseq-mutable">mutable</a>, wheras tuples are not. I personally tend to carry over the conventions from functional programming: use lists for any number of elements of the same type, and tuples for a fixed number of elements of predetermined types.</p> <h1>Question</h1> <p>After the lengthy preamble, comes the inevitable question. Which method (do you think) is best?</p> <p>I've typically found myself going the dictionary route because it involves less set-up work. From a types perspective however, you might be better off going the class route, since that may help you avoid confusing what a dictionary represents. On the other hand, there are some in the Python community that feel <a href="http://www.canonical.org/~kragen/isinstance/">implied interfaces should be preferred to explicit interfaces</a>, at which point the type of the object really isn't relevant, since you're basically relying on the convention that the same attribute will always have the same meaning. </p> <p>So, how do -you- return multiple values in Python?</p>
435
2008-12-10T01:55:50Z
354,892
<p>I prefer</p> <pre><code>def g(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return {'y0':y0, 'y1':y1 ,'y2':y2 } </code></pre> <p>it seems everything else is just extra code to do the same thing.</p>
9
2008-12-10T02:00:49Z
[ "python", "coding-style", "return", "return-value" ]
How do you return multiple values in Python?
354,883
<p>The canonical way to return multiple values in languages that support it is often <a href="http://stackoverflow.com/questions/38508/whats-the-best-way-to-return-multiple-values-from-a-function-in-python">tupling</a>. </p> <h3>Option: Using a tuple</h3> <p>Consider this trivial example:</p> <pre><code>def f(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return (y0,y1,y2) </code></pre> <p>However, this quickly gets problematic as the number of values returned increases. What if you want to return four or five values? Sure, you could keep tupling them, but it gets easy to forget which value is where. It's also rather ugly to unpack them wherever you want to receive them.</p> <h3>Option: Using a dictionary</h3> <p>The next logical step seems to be to introduce some sort of 'record notation'. In python, the obvious way to do this is by means of a <code>dict</code>. </p> <p>Consider the following:</p> <pre><code>def g(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return {'y0':y0, 'y1':y1 ,'y2':y2 } </code></pre> <p>(edit- Just to be clear, y0, y1 and y2 are just meant as abstract identifiers. As pointed out, in practice you'd use meaningful identifiers)</p> <p>Now, we have a mechanism whereby we can project out a particular member of the returned object. For example, </p> <pre><code>result['y0'] </code></pre> <h3>Option: Using a class</h3> <p>However, there is another option. We could instead return a specialized structure. I've framed this in the context of Python, but I'm sure it applies to other languages as well. Indeed, if you were working in C this might very well be your only option. Here goes:</p> <pre><code>class ReturnValue(object): def __init__(self, y0, y1, y2): self.y0 = y0 self.y1 = y1 self.y2 = y2 def g(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return ReturnValue(y0, y1, y2) </code></pre> <p>In python the previous two are perhaps very similar in terms of plumbing- After all <code>{ y0, y1, y2 }</code> just end up being entries in the internal <code>__dict__</code> of the <code>ReturnValue</code>.</p> <p>There is one additional feature provided by Python though for tiny objects, the <code>__slots__</code> attribute. The class could be expressed as:</p> <pre><code>class ReturnValue(object): __slots__ = ["y0", "y1", "y2"] def __init__(self, y0, y1, y2): self.y0 = y0 self.y1 = y1 self.y2 = y2 </code></pre> <p>From the <a href="http://www.network-theory.co.uk/docs/pylang/__slots__.html">Python Reference Manual</a>:</p> <blockquote> <p>The <code>__slots__</code> declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because <code>__dict__</code> is not created for each instance.</p> </blockquote> <h3>Option: Using a list</h3> <p>Another suggestion which I'd overlooked comes from Bill the Lizard:</p> <pre><code>def h(x): result = [x + 1] result.append(x * 3) result.append(y0 ** y3) return result </code></pre> <p>This is my least favorite method though. I suppose I'm tainted by exposure to Haskell, but the idea of mixed-type lists has always felt uncomfortable to me. In this particular example the list is -not- mixed type, but it conceivably could be. A list used in this way really doesn't gain anything with respect to the tuple as far as I can tell. The only real difference between lists and tuples in Python is that lists are <a href="http://docs.python.org/library/stdtypes.html#typesseq-mutable">mutable</a>, wheras tuples are not. I personally tend to carry over the conventions from functional programming: use lists for any number of elements of the same type, and tuples for a fixed number of elements of predetermined types.</p> <h1>Question</h1> <p>After the lengthy preamble, comes the inevitable question. Which method (do you think) is best?</p> <p>I've typically found myself going the dictionary route because it involves less set-up work. From a types perspective however, you might be better off going the class route, since that may help you avoid confusing what a dictionary represents. On the other hand, there are some in the Python community that feel <a href="http://www.canonical.org/~kragen/isinstance/">implied interfaces should be preferred to explicit interfaces</a>, at which point the type of the object really isn't relevant, since you're basically relying on the convention that the same attribute will always have the same meaning. </p> <p>So, how do -you- return multiple values in Python?</p>
435
2008-12-10T01:55:50Z
354,896
<p>In languages like Python, I would usually use a dictionary as it involves less overhead than creating a new class.</p> <p>However, if I find myself constantly returning the same set of variables, then that probably involves a new class that I'll factor out.</p>
1
2008-12-10T02:02:37Z
[ "python", "coding-style", "return", "return-value" ]
How do you return multiple values in Python?
354,883
<p>The canonical way to return multiple values in languages that support it is often <a href="http://stackoverflow.com/questions/38508/whats-the-best-way-to-return-multiple-values-from-a-function-in-python">tupling</a>. </p> <h3>Option: Using a tuple</h3> <p>Consider this trivial example:</p> <pre><code>def f(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return (y0,y1,y2) </code></pre> <p>However, this quickly gets problematic as the number of values returned increases. What if you want to return four or five values? Sure, you could keep tupling them, but it gets easy to forget which value is where. It's also rather ugly to unpack them wherever you want to receive them.</p> <h3>Option: Using a dictionary</h3> <p>The next logical step seems to be to introduce some sort of 'record notation'. In python, the obvious way to do this is by means of a <code>dict</code>. </p> <p>Consider the following:</p> <pre><code>def g(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return {'y0':y0, 'y1':y1 ,'y2':y2 } </code></pre> <p>(edit- Just to be clear, y0, y1 and y2 are just meant as abstract identifiers. As pointed out, in practice you'd use meaningful identifiers)</p> <p>Now, we have a mechanism whereby we can project out a particular member of the returned object. For example, </p> <pre><code>result['y0'] </code></pre> <h3>Option: Using a class</h3> <p>However, there is another option. We could instead return a specialized structure. I've framed this in the context of Python, but I'm sure it applies to other languages as well. Indeed, if you were working in C this might very well be your only option. Here goes:</p> <pre><code>class ReturnValue(object): def __init__(self, y0, y1, y2): self.y0 = y0 self.y1 = y1 self.y2 = y2 def g(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return ReturnValue(y0, y1, y2) </code></pre> <p>In python the previous two are perhaps very similar in terms of plumbing- After all <code>{ y0, y1, y2 }</code> just end up being entries in the internal <code>__dict__</code> of the <code>ReturnValue</code>.</p> <p>There is one additional feature provided by Python though for tiny objects, the <code>__slots__</code> attribute. The class could be expressed as:</p> <pre><code>class ReturnValue(object): __slots__ = ["y0", "y1", "y2"] def __init__(self, y0, y1, y2): self.y0 = y0 self.y1 = y1 self.y2 = y2 </code></pre> <p>From the <a href="http://www.network-theory.co.uk/docs/pylang/__slots__.html">Python Reference Manual</a>:</p> <blockquote> <p>The <code>__slots__</code> declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because <code>__dict__</code> is not created for each instance.</p> </blockquote> <h3>Option: Using a list</h3> <p>Another suggestion which I'd overlooked comes from Bill the Lizard:</p> <pre><code>def h(x): result = [x + 1] result.append(x * 3) result.append(y0 ** y3) return result </code></pre> <p>This is my least favorite method though. I suppose I'm tainted by exposure to Haskell, but the idea of mixed-type lists has always felt uncomfortable to me. In this particular example the list is -not- mixed type, but it conceivably could be. A list used in this way really doesn't gain anything with respect to the tuple as far as I can tell. The only real difference between lists and tuples in Python is that lists are <a href="http://docs.python.org/library/stdtypes.html#typesseq-mutable">mutable</a>, wheras tuples are not. I personally tend to carry over the conventions from functional programming: use lists for any number of elements of the same type, and tuples for a fixed number of elements of predetermined types.</p> <h1>Question</h1> <p>After the lengthy preamble, comes the inevitable question. Which method (do you think) is best?</p> <p>I've typically found myself going the dictionary route because it involves less set-up work. From a types perspective however, you might be better off going the class route, since that may help you avoid confusing what a dictionary represents. On the other hand, there are some in the Python community that feel <a href="http://www.canonical.org/~kragen/isinstance/">implied interfaces should be preferred to explicit interfaces</a>, at which point the type of the object really isn't relevant, since you're basically relying on the convention that the same attribute will always have the same meaning. </p> <p>So, how do -you- return multiple values in Python?</p>
435
2008-12-10T01:55:50Z
354,918
<p>Generally, the "specialized structure" actually IS a sensible current state of an object, with its own methods.</p> <pre><code>class Some3SpaceThing(object): def __init__(self,x): self.g(x) def g(self,x): self.y0 = x + 1 self.y1 = x * 3 self.y2 = y0 ** y3 r = Some3SpaceThing( x ) r.y0 r.y1 r.y2 </code></pre> <p>I like to find names for anonymous structures where possible. Meaningful names make things more clear.</p>
7
2008-12-10T02:15:34Z
[ "python", "coding-style", "return", "return-value" ]
How do you return multiple values in Python?
354,883
<p>The canonical way to return multiple values in languages that support it is often <a href="http://stackoverflow.com/questions/38508/whats-the-best-way-to-return-multiple-values-from-a-function-in-python">tupling</a>. </p> <h3>Option: Using a tuple</h3> <p>Consider this trivial example:</p> <pre><code>def f(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return (y0,y1,y2) </code></pre> <p>However, this quickly gets problematic as the number of values returned increases. What if you want to return four or five values? Sure, you could keep tupling them, but it gets easy to forget which value is where. It's also rather ugly to unpack them wherever you want to receive them.</p> <h3>Option: Using a dictionary</h3> <p>The next logical step seems to be to introduce some sort of 'record notation'. In python, the obvious way to do this is by means of a <code>dict</code>. </p> <p>Consider the following:</p> <pre><code>def g(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return {'y0':y0, 'y1':y1 ,'y2':y2 } </code></pre> <p>(edit- Just to be clear, y0, y1 and y2 are just meant as abstract identifiers. As pointed out, in practice you'd use meaningful identifiers)</p> <p>Now, we have a mechanism whereby we can project out a particular member of the returned object. For example, </p> <pre><code>result['y0'] </code></pre> <h3>Option: Using a class</h3> <p>However, there is another option. We could instead return a specialized structure. I've framed this in the context of Python, but I'm sure it applies to other languages as well. Indeed, if you were working in C this might very well be your only option. Here goes:</p> <pre><code>class ReturnValue(object): def __init__(self, y0, y1, y2): self.y0 = y0 self.y1 = y1 self.y2 = y2 def g(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return ReturnValue(y0, y1, y2) </code></pre> <p>In python the previous two are perhaps very similar in terms of plumbing- After all <code>{ y0, y1, y2 }</code> just end up being entries in the internal <code>__dict__</code> of the <code>ReturnValue</code>.</p> <p>There is one additional feature provided by Python though for tiny objects, the <code>__slots__</code> attribute. The class could be expressed as:</p> <pre><code>class ReturnValue(object): __slots__ = ["y0", "y1", "y2"] def __init__(self, y0, y1, y2): self.y0 = y0 self.y1 = y1 self.y2 = y2 </code></pre> <p>From the <a href="http://www.network-theory.co.uk/docs/pylang/__slots__.html">Python Reference Manual</a>:</p> <blockquote> <p>The <code>__slots__</code> declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because <code>__dict__</code> is not created for each instance.</p> </blockquote> <h3>Option: Using a list</h3> <p>Another suggestion which I'd overlooked comes from Bill the Lizard:</p> <pre><code>def h(x): result = [x + 1] result.append(x * 3) result.append(y0 ** y3) return result </code></pre> <p>This is my least favorite method though. I suppose I'm tainted by exposure to Haskell, but the idea of mixed-type lists has always felt uncomfortable to me. In this particular example the list is -not- mixed type, but it conceivably could be. A list used in this way really doesn't gain anything with respect to the tuple as far as I can tell. The only real difference between lists and tuples in Python is that lists are <a href="http://docs.python.org/library/stdtypes.html#typesseq-mutable">mutable</a>, wheras tuples are not. I personally tend to carry over the conventions from functional programming: use lists for any number of elements of the same type, and tuples for a fixed number of elements of predetermined types.</p> <h1>Question</h1> <p>After the lengthy preamble, comes the inevitable question. Which method (do you think) is best?</p> <p>I've typically found myself going the dictionary route because it involves less set-up work. From a types perspective however, you might be better off going the class route, since that may help you avoid confusing what a dictionary represents. On the other hand, there are some in the Python community that feel <a href="http://www.canonical.org/~kragen/isinstance/">implied interfaces should be preferred to explicit interfaces</a>, at which point the type of the object really isn't relevant, since you're basically relying on the convention that the same attribute will always have the same meaning. </p> <p>So, how do -you- return multiple values in Python?</p>
435
2008-12-10T01:55:50Z
354,929
<p>For small projects I find it easiest to work with tuples. When that gets too hard to manage (and not before) I start grouping things into logical structures, however I think your suggested use of dictionaries and ReturnValue objects is wrong (or too simplistic).</p> <p>Returning a dictionary with keys y0, y1, y2 etc doesn't offer any advantage over tuples. Returning a ReturnValue instance with properties .y0 .y1 .y2 etc doesn't offer any advantage over tuples either. You need to start naming things if you want to get anywhere, and you can do that using tuples anyway:</p> <pre><code>def getImageData(filename): [snip] return size, (format, version, compression), (width,height) size, type, dimensions = getImageData(x) </code></pre> <p>IMHO, the only good technique beyond tuples is to return real objects with proper methods and properties, like you get from <code>re.match()</code> or <code>open(file)</code>.</p>
84
2008-12-10T02:22:28Z
[ "python", "coding-style", "return", "return-value" ]
How do you return multiple values in Python?
354,883
<p>The canonical way to return multiple values in languages that support it is often <a href="http://stackoverflow.com/questions/38508/whats-the-best-way-to-return-multiple-values-from-a-function-in-python">tupling</a>. </p> <h3>Option: Using a tuple</h3> <p>Consider this trivial example:</p> <pre><code>def f(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return (y0,y1,y2) </code></pre> <p>However, this quickly gets problematic as the number of values returned increases. What if you want to return four or five values? Sure, you could keep tupling them, but it gets easy to forget which value is where. It's also rather ugly to unpack them wherever you want to receive them.</p> <h3>Option: Using a dictionary</h3> <p>The next logical step seems to be to introduce some sort of 'record notation'. In python, the obvious way to do this is by means of a <code>dict</code>. </p> <p>Consider the following:</p> <pre><code>def g(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return {'y0':y0, 'y1':y1 ,'y2':y2 } </code></pre> <p>(edit- Just to be clear, y0, y1 and y2 are just meant as abstract identifiers. As pointed out, in practice you'd use meaningful identifiers)</p> <p>Now, we have a mechanism whereby we can project out a particular member of the returned object. For example, </p> <pre><code>result['y0'] </code></pre> <h3>Option: Using a class</h3> <p>However, there is another option. We could instead return a specialized structure. I've framed this in the context of Python, but I'm sure it applies to other languages as well. Indeed, if you were working in C this might very well be your only option. Here goes:</p> <pre><code>class ReturnValue(object): def __init__(self, y0, y1, y2): self.y0 = y0 self.y1 = y1 self.y2 = y2 def g(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return ReturnValue(y0, y1, y2) </code></pre> <p>In python the previous two are perhaps very similar in terms of plumbing- After all <code>{ y0, y1, y2 }</code> just end up being entries in the internal <code>__dict__</code> of the <code>ReturnValue</code>.</p> <p>There is one additional feature provided by Python though for tiny objects, the <code>__slots__</code> attribute. The class could be expressed as:</p> <pre><code>class ReturnValue(object): __slots__ = ["y0", "y1", "y2"] def __init__(self, y0, y1, y2): self.y0 = y0 self.y1 = y1 self.y2 = y2 </code></pre> <p>From the <a href="http://www.network-theory.co.uk/docs/pylang/__slots__.html">Python Reference Manual</a>:</p> <blockquote> <p>The <code>__slots__</code> declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because <code>__dict__</code> is not created for each instance.</p> </blockquote> <h3>Option: Using a list</h3> <p>Another suggestion which I'd overlooked comes from Bill the Lizard:</p> <pre><code>def h(x): result = [x + 1] result.append(x * 3) result.append(y0 ** y3) return result </code></pre> <p>This is my least favorite method though. I suppose I'm tainted by exposure to Haskell, but the idea of mixed-type lists has always felt uncomfortable to me. In this particular example the list is -not- mixed type, but it conceivably could be. A list used in this way really doesn't gain anything with respect to the tuple as far as I can tell. The only real difference between lists and tuples in Python is that lists are <a href="http://docs.python.org/library/stdtypes.html#typesseq-mutable">mutable</a>, wheras tuples are not. I personally tend to carry over the conventions from functional programming: use lists for any number of elements of the same type, and tuples for a fixed number of elements of predetermined types.</p> <h1>Question</h1> <p>After the lengthy preamble, comes the inevitable question. Which method (do you think) is best?</p> <p>I've typically found myself going the dictionary route because it involves less set-up work. From a types perspective however, you might be better off going the class route, since that may help you avoid confusing what a dictionary represents. On the other hand, there are some in the Python community that feel <a href="http://www.canonical.org/~kragen/isinstance/">implied interfaces should be preferred to explicit interfaces</a>, at which point the type of the object really isn't relevant, since you're basically relying on the convention that the same attribute will always have the same meaning. </p> <p>So, how do -you- return multiple values in Python?</p>
435
2008-12-10T01:55:50Z
354,955
<p>I prefer to use tuples whenever a tuple feels "natural"; coordinates are a typical example, where the separate objects can stand on their own, e.g. in one-axis only scaling calculations.</p> <p>I use dictionaries as a return value only when the grouped objects aren't always the same. Think optional email headers.</p> <p>For the rest of the cases, where the grouped objects have inherent meaning inside the group or a fully-fledged object with its own methods is needed, I use a class.</p>
14
2008-12-10T02:40:43Z
[ "python", "coding-style", "return", "return-value" ]
How do you return multiple values in Python?
354,883
<p>The canonical way to return multiple values in languages that support it is often <a href="http://stackoverflow.com/questions/38508/whats-the-best-way-to-return-multiple-values-from-a-function-in-python">tupling</a>. </p> <h3>Option: Using a tuple</h3> <p>Consider this trivial example:</p> <pre><code>def f(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return (y0,y1,y2) </code></pre> <p>However, this quickly gets problematic as the number of values returned increases. What if you want to return four or five values? Sure, you could keep tupling them, but it gets easy to forget which value is where. It's also rather ugly to unpack them wherever you want to receive them.</p> <h3>Option: Using a dictionary</h3> <p>The next logical step seems to be to introduce some sort of 'record notation'. In python, the obvious way to do this is by means of a <code>dict</code>. </p> <p>Consider the following:</p> <pre><code>def g(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return {'y0':y0, 'y1':y1 ,'y2':y2 } </code></pre> <p>(edit- Just to be clear, y0, y1 and y2 are just meant as abstract identifiers. As pointed out, in practice you'd use meaningful identifiers)</p> <p>Now, we have a mechanism whereby we can project out a particular member of the returned object. For example, </p> <pre><code>result['y0'] </code></pre> <h3>Option: Using a class</h3> <p>However, there is another option. We could instead return a specialized structure. I've framed this in the context of Python, but I'm sure it applies to other languages as well. Indeed, if you were working in C this might very well be your only option. Here goes:</p> <pre><code>class ReturnValue(object): def __init__(self, y0, y1, y2): self.y0 = y0 self.y1 = y1 self.y2 = y2 def g(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return ReturnValue(y0, y1, y2) </code></pre> <p>In python the previous two are perhaps very similar in terms of plumbing- After all <code>{ y0, y1, y2 }</code> just end up being entries in the internal <code>__dict__</code> of the <code>ReturnValue</code>.</p> <p>There is one additional feature provided by Python though for tiny objects, the <code>__slots__</code> attribute. The class could be expressed as:</p> <pre><code>class ReturnValue(object): __slots__ = ["y0", "y1", "y2"] def __init__(self, y0, y1, y2): self.y0 = y0 self.y1 = y1 self.y2 = y2 </code></pre> <p>From the <a href="http://www.network-theory.co.uk/docs/pylang/__slots__.html">Python Reference Manual</a>:</p> <blockquote> <p>The <code>__slots__</code> declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because <code>__dict__</code> is not created for each instance.</p> </blockquote> <h3>Option: Using a list</h3> <p>Another suggestion which I'd overlooked comes from Bill the Lizard:</p> <pre><code>def h(x): result = [x + 1] result.append(x * 3) result.append(y0 ** y3) return result </code></pre> <p>This is my least favorite method though. I suppose I'm tainted by exposure to Haskell, but the idea of mixed-type lists has always felt uncomfortable to me. In this particular example the list is -not- mixed type, but it conceivably could be. A list used in this way really doesn't gain anything with respect to the tuple as far as I can tell. The only real difference between lists and tuples in Python is that lists are <a href="http://docs.python.org/library/stdtypes.html#typesseq-mutable">mutable</a>, wheras tuples are not. I personally tend to carry over the conventions from functional programming: use lists for any number of elements of the same type, and tuples for a fixed number of elements of predetermined types.</p> <h1>Question</h1> <p>After the lengthy preamble, comes the inevitable question. Which method (do you think) is best?</p> <p>I've typically found myself going the dictionary route because it involves less set-up work. From a types perspective however, you might be better off going the class route, since that may help you avoid confusing what a dictionary represents. On the other hand, there are some in the Python community that feel <a href="http://www.canonical.org/~kragen/isinstance/">implied interfaces should be preferred to explicit interfaces</a>, at which point the type of the object really isn't relevant, since you're basically relying on the convention that the same attribute will always have the same meaning. </p> <p>So, how do -you- return multiple values in Python?</p>
435
2008-12-10T01:55:50Z
354,958
<p>I vote for the dictionary.</p> <p>I find that if I make a function that returns anything more than 2-3 variables I'll fold them up in a dictionary. Otherwise I tend to forget the order and content of what I'm returning.</p> <p>Also, introducing a 'special' structure makes your code more difficult to follow. (Someone else will have to search through the code to find out what it is)</p> <p>If your concerned about type look up, use descriptive dictionary keys, for example, 'x-values list'.</p> <pre><code>def g(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return {'y0':y0, 'y1':y1 ,'y2':y2 } </code></pre>
33
2008-12-10T02:42:05Z
[ "python", "coding-style", "return", "return-value" ]
How do you return multiple values in Python?
354,883
<p>The canonical way to return multiple values in languages that support it is often <a href="http://stackoverflow.com/questions/38508/whats-the-best-way-to-return-multiple-values-from-a-function-in-python">tupling</a>. </p> <h3>Option: Using a tuple</h3> <p>Consider this trivial example:</p> <pre><code>def f(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return (y0,y1,y2) </code></pre> <p>However, this quickly gets problematic as the number of values returned increases. What if you want to return four or five values? Sure, you could keep tupling them, but it gets easy to forget which value is where. It's also rather ugly to unpack them wherever you want to receive them.</p> <h3>Option: Using a dictionary</h3> <p>The next logical step seems to be to introduce some sort of 'record notation'. In python, the obvious way to do this is by means of a <code>dict</code>. </p> <p>Consider the following:</p> <pre><code>def g(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return {'y0':y0, 'y1':y1 ,'y2':y2 } </code></pre> <p>(edit- Just to be clear, y0, y1 and y2 are just meant as abstract identifiers. As pointed out, in practice you'd use meaningful identifiers)</p> <p>Now, we have a mechanism whereby we can project out a particular member of the returned object. For example, </p> <pre><code>result['y0'] </code></pre> <h3>Option: Using a class</h3> <p>However, there is another option. We could instead return a specialized structure. I've framed this in the context of Python, but I'm sure it applies to other languages as well. Indeed, if you were working in C this might very well be your only option. Here goes:</p> <pre><code>class ReturnValue(object): def __init__(self, y0, y1, y2): self.y0 = y0 self.y1 = y1 self.y2 = y2 def g(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return ReturnValue(y0, y1, y2) </code></pre> <p>In python the previous two are perhaps very similar in terms of plumbing- After all <code>{ y0, y1, y2 }</code> just end up being entries in the internal <code>__dict__</code> of the <code>ReturnValue</code>.</p> <p>There is one additional feature provided by Python though for tiny objects, the <code>__slots__</code> attribute. The class could be expressed as:</p> <pre><code>class ReturnValue(object): __slots__ = ["y0", "y1", "y2"] def __init__(self, y0, y1, y2): self.y0 = y0 self.y1 = y1 self.y2 = y2 </code></pre> <p>From the <a href="http://www.network-theory.co.uk/docs/pylang/__slots__.html">Python Reference Manual</a>:</p> <blockquote> <p>The <code>__slots__</code> declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because <code>__dict__</code> is not created for each instance.</p> </blockquote> <h3>Option: Using a list</h3> <p>Another suggestion which I'd overlooked comes from Bill the Lizard:</p> <pre><code>def h(x): result = [x + 1] result.append(x * 3) result.append(y0 ** y3) return result </code></pre> <p>This is my least favorite method though. I suppose I'm tainted by exposure to Haskell, but the idea of mixed-type lists has always felt uncomfortable to me. In this particular example the list is -not- mixed type, but it conceivably could be. A list used in this way really doesn't gain anything with respect to the tuple as far as I can tell. The only real difference between lists and tuples in Python is that lists are <a href="http://docs.python.org/library/stdtypes.html#typesseq-mutable">mutable</a>, wheras tuples are not. I personally tend to carry over the conventions from functional programming: use lists for any number of elements of the same type, and tuples for a fixed number of elements of predetermined types.</p> <h1>Question</h1> <p>After the lengthy preamble, comes the inevitable question. Which method (do you think) is best?</p> <p>I've typically found myself going the dictionary route because it involves less set-up work. From a types perspective however, you might be better off going the class route, since that may help you avoid confusing what a dictionary represents. On the other hand, there are some in the Python community that feel <a href="http://www.canonical.org/~kragen/isinstance/">implied interfaces should be preferred to explicit interfaces</a>, at which point the type of the object really isn't relevant, since you're basically relying on the convention that the same attribute will always have the same meaning. </p> <p>So, how do -you- return multiple values in Python?</p>
435
2008-12-10T01:55:50Z
355,036
<p>+1 on S.Lott's suggestion of a named container class.</p> <p>For python 2.6 and up, a <a href="http://docs.python.org/library/collections.html#collections.namedtuple">named tuple</a> provides a useful way of easily creating these container classes, and the results are "lightweight and require no more memory than regular tuples".</p>
9
2008-12-10T03:51:47Z
[ "python", "coding-style", "return", "return-value" ]
How do you return multiple values in Python?
354,883
<p>The canonical way to return multiple values in languages that support it is often <a href="http://stackoverflow.com/questions/38508/whats-the-best-way-to-return-multiple-values-from-a-function-in-python">tupling</a>. </p> <h3>Option: Using a tuple</h3> <p>Consider this trivial example:</p> <pre><code>def f(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return (y0,y1,y2) </code></pre> <p>However, this quickly gets problematic as the number of values returned increases. What if you want to return four or five values? Sure, you could keep tupling them, but it gets easy to forget which value is where. It's also rather ugly to unpack them wherever you want to receive them.</p> <h3>Option: Using a dictionary</h3> <p>The next logical step seems to be to introduce some sort of 'record notation'. In python, the obvious way to do this is by means of a <code>dict</code>. </p> <p>Consider the following:</p> <pre><code>def g(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return {'y0':y0, 'y1':y1 ,'y2':y2 } </code></pre> <p>(edit- Just to be clear, y0, y1 and y2 are just meant as abstract identifiers. As pointed out, in practice you'd use meaningful identifiers)</p> <p>Now, we have a mechanism whereby we can project out a particular member of the returned object. For example, </p> <pre><code>result['y0'] </code></pre> <h3>Option: Using a class</h3> <p>However, there is another option. We could instead return a specialized structure. I've framed this in the context of Python, but I'm sure it applies to other languages as well. Indeed, if you were working in C this might very well be your only option. Here goes:</p> <pre><code>class ReturnValue(object): def __init__(self, y0, y1, y2): self.y0 = y0 self.y1 = y1 self.y2 = y2 def g(x): y0 = x + 1 y1 = x * 3 y2 = y0 ** y3 return ReturnValue(y0, y1, y2) </code></pre> <p>In python the previous two are perhaps very similar in terms of plumbing- After all <code>{ y0, y1, y2 }</code> just end up being entries in the internal <code>__dict__</code> of the <code>ReturnValue</code>.</p> <p>There is one additional feature provided by Python though for tiny objects, the <code>__slots__</code> attribute. The class could be expressed as:</p> <pre><code>class ReturnValue(object): __slots__ = ["y0", "y1", "y2"] def __init__(self, y0, y1, y2): self.y0 = y0 self.y1 = y1 self.y2 = y2 </code></pre> <p>From the <a href="http://www.network-theory.co.uk/docs/pylang/__slots__.html">Python Reference Manual</a>:</p> <blockquote> <p>The <code>__slots__</code> declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because <code>__dict__</code> is not created for each instance.</p> </blockquote> <h3>Option: Using a list</h3> <p>Another suggestion which I'd overlooked comes from Bill the Lizard:</p> <pre><code>def h(x): result = [x + 1] result.append(x * 3) result.append(y0 ** y3) return result </code></pre> <p>This is my least favorite method though. I suppose I'm tainted by exposure to Haskell, but the idea of mixed-type lists has always felt uncomfortable to me. In this particular example the list is -not- mixed type, but it conceivably could be. A list used in this way really doesn't gain anything with respect to the tuple as far as I can tell. The only real difference between lists and tuples in Python is that lists are <a href="http://docs.python.org/library/stdtypes.html#typesseq-mutable">mutable</a>, wheras tuples are not. I personally tend to carry over the conventions from functional programming: use lists for any number of elements of the same type, and tuples for a fixed number of elements of predetermined types.</p> <h1>Question</h1> <p>After the lengthy preamble, comes the inevitable question. Which method (do you think) is best?</p> <p>I've typically found myself going the dictionary route because it involves less set-up work. From a types perspective however, you might be better off going the class route, since that may help you avoid confusing what a dictionary represents. On the other hand, there are some in the Python community that feel <a href="http://www.canonical.org/~kragen/isinstance/">implied interfaces should be preferred to explicit interfaces</a>, at which point the type of the object really isn't relevant, since you're basically relying on the convention that the same attribute will always have the same meaning. </p> <p>So, how do -you- return multiple values in Python?</p>
435
2008-12-10T01:55:50Z
356,695
<p><a href="http://docs.python.org/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields">Named tuples</a> were added in 2.6 for this purpose. Also see <a href="http://docs.python.org/library/os.html#os.stat">os.stat</a> for a similar builtin example.</p> <pre><code>&gt;&gt;&gt; import collections &gt;&gt;&gt; point = collections.namedtuple('Point', ['x', 'y']) &gt;&gt;&gt; p = point(1, y=2) &gt;&gt;&gt; p.x, p.y 1 2 &gt;&gt;&gt; p[0], p[1] 1 2 </code></pre>
278
2008-12-10T16:36:01Z
[ "python", "coding-style", "return", "return-value" ]