title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Various Python datetime issues
513,291
<p>I have two methods that I'm using as custom tags in a template engine:</p> <pre><code># Renders a &lt;select&gt; form field def select_field(options, selected_item, field_name): options = [(str(v),str(v)) for v in options] html = ['&lt;select name="%s"&gt;' % field_name] for k,v in options: tmp = '...
2
2009-02-04T20:54:50Z
513,416
<p>To add to my previous answer, some comments on making the selected option selected. </p> <p>First, your HTML generation code would be more robust if rather than splitting the start and end of the HTML tags...</p> <pre><code>html = ['&lt;select name="%s"&gt;' % field_name] for k,v in options: tmp = '&lt;option ...
1
2009-02-04T21:22:05Z
[ "python", "datetime" ]
Newline characters in non ASCII encoded files
513,675
<p>I'm using Python 2.6 to read latin2 encoded file with windows line endings ('\r\n').</p> <pre><code>import codecs file = codecs.open('stackoverflow_secrets.txt', encoding='latin2', mode='rt') line = file.readline() print(repr(line)) </code></pre> <p>outputs : <code>u'login: yabcok\n'</code></p> <pre><code>file =...
1
2009-02-04T22:28:09Z
513,820
<p>Are you sure that your examples are correct? The <a href="http://docs.python.org/library/codecs.html#module-codecs" rel="nofollow">documentation</a> of the codecs module says: </p> <blockquote> <p>Note: Files are always opened in binary mode, even if no binary mode was specified. This is done to avoid data loss d...
4
2009-02-04T23:13:09Z
[ "python", "encoding", "file" ]
Newline characters in non ASCII encoded files
513,675
<p>I'm using Python 2.6 to read latin2 encoded file with windows line endings ('\r\n').</p> <pre><code>import codecs file = codecs.open('stackoverflow_secrets.txt', encoding='latin2', mode='rt') line = file.readline() print(repr(line)) </code></pre> <p>outputs : <code>u'login: yabcok\n'</code></p> <pre><code>file =...
1
2009-02-04T22:28:09Z
514,168
<blockquote> <p>mode='rt'</p> </blockquote> <p>'rt' isn't a real mode as such - that will do the same as 'r'. </p> <blockquote> <p>Why text mode is not the default?</p> </blockquote> <p>See Torsten's answer.</p> <p>Also, if you are using anything but Windows, text mode files behave identically to binary files a...
1
2009-02-05T01:23:09Z
[ "python", "encoding", "file" ]
Delete file from zipfile with the ZipFile Module
513,788
<p>The only way i came up for deleting a file from a zipfile was to create a temporary zipfile without the file to be deleted and then rename it to the original filename.</p> <p>In python 2.4 the ZipInfo class had an attribute <code>file_offset</code>, so it was possible to create a second zip file and copy the data t...
22
2009-02-04T23:00:26Z
513,889
<p>The following snippet worked for me (deletes all *.exe files from a Zip archive):</p> <pre><code>zin = zipfile.ZipFile ('archive.zip', 'r') zout = zipfile.ZipFile ('archve_new.zip', 'w') for item in zin.infolist(): buffer = zin.read(item.filename) if (item.filename[-4:] != '.exe'): zout.writestr(ite...
28
2009-02-04T23:31:37Z
[ "python", "zip" ]
How to distribute script using gdata-python-client?
513,806
<p>I've written several scripts that make use of the gdata API, and they all (obviously) have my API key and client ID in plain-text. How am I supposed to distribute these?</p>
3
2009-02-04T23:06:11Z
513,829
<p>Move the variables into a separate module and replace your values with dummy values. Make sure you trap for an invalid key and provide instructions on how to obtain a key and where to place it. In your code you can just import the values from that module.</p> <pre><code>import gdata_api_key print gdata_api_key.ke...
3
2009-02-04T23:16:32Z
[ "python", "gdata-api" ]
How to distribute script using gdata-python-client?
513,806
<p>I've written several scripts that make use of the gdata API, and they all (obviously) have my API key and client ID in plain-text. How am I supposed to distribute these?</p>
3
2009-02-04T23:06:11Z
513,838
<p>If we assume that you want clients to use their own keys I'd recommend putting them in a configuration file which defaults to an (invalid) sentinel value.</p> <p>If on the other hand you want the script to use your key the best you can do is obfuscate it. After all, if your program can read it then an attacker (wit...
0
2009-02-04T23:18:05Z
[ "python", "gdata-api" ]
Python: List vs Dict for look up table
513,882
<p>I have about 10million values that I need to put in some type of look up table, so I was wondering which would be more efficient a <i>list</i> or <i>dict</i>?</p> <p>I know you can do something like this for both:</p> <pre><code>if something in dict_of_stuff: pass </code></pre> <p>and</p> <pre><code>if somet...
79
2009-02-04T23:28:41Z
513,886
<p>if data are unique set() will be the most efficient, but of two - dict (which also requires uniqueness, oops :)</p>
6
2009-02-04T23:30:48Z
[ "python", "performance" ]
Python: List vs Dict for look up table
513,882
<p>I have about 10million values that I need to put in some type of look up table, so I was wondering which would be more efficient a <i>list</i> or <i>dict</i>?</p> <p>I know you can do something like this for both:</p> <pre><code>if something in dict_of_stuff: pass </code></pre> <p>and</p> <pre><code>if somet...
79
2009-02-04T23:28:41Z
513,890
<p>A dict is a hash table, so it is really fast to find the keys. So between dict and list, dict would be faster. But if you don't have a value to associate, it is even better to use a set. It is a hash table, without the "table" part.</p> <p><hr /></p> <p>EDIT: for your new question, YES, a set would be better. Just...
28
2009-02-04T23:31:41Z
[ "python", "performance" ]
Python: List vs Dict for look up table
513,882
<p>I have about 10million values that I need to put in some type of look up table, so I was wondering which would be more efficient a <i>list</i> or <i>dict</i>?</p> <p>I know you can do something like this for both:</p> <pre><code>if something in dict_of_stuff: pass </code></pre> <p>and</p> <pre><code>if somet...
79
2009-02-04T23:28:41Z
513,903
<p>You want a dict. </p> <p>For (unsorted) lists in Python, the "in" operation requires O(n) time---not good when you have a large amount of data. A dict, on the other hand, is a hash table, so you can expect O(1) lookup time. </p> <p>As others have noted, you might choose a set (a special type of dict) instead, i...
4
2009-02-04T23:37:45Z
[ "python", "performance" ]
Python: List vs Dict for look up table
513,882
<p>I have about 10million values that I need to put in some type of look up table, so I was wondering which would be more efficient a <i>list</i> or <i>dict</i>?</p> <p>I know you can do something like this for both:</p> <pre><code>if something in dict_of_stuff: pass </code></pre> <p>and</p> <pre><code>if somet...
79
2009-02-04T23:28:41Z
513,906
<h1>Speed</h1> <p>Lookups in lists are O(n), lookups in dictionaries are amortized O(1), with regard to the number of items in the data structure. If you don't need to associate values, use sets.</p> <h1>Memory</h1> <p>Both dictionaries and sets use hashing and they use much more memory than only for object storage....
109
2009-02-04T23:38:36Z
[ "python", "performance" ]
Python: List vs Dict for look up table
513,882
<p>I have about 10million values that I need to put in some type of look up table, so I was wondering which would be more efficient a <i>list</i> or <i>dict</i>?</p> <p>I know you can do something like this for both:</p> <pre><code>if something in dict_of_stuff: pass </code></pre> <p>and</p> <pre><code>if somet...
79
2009-02-04T23:28:41Z
578,885
<p>You don't actually need to store 10 million values in the table, so it's not a big deal either way.</p> <p>Hint: think about how large your result can be after the first sum of squares operation. The largest possible result will be much smaller than 10 million...</p>
1
2009-02-23T19:03:30Z
[ "python", "performance" ]
Python: List vs Dict for look up table
513,882
<p>I have about 10million values that I need to put in some type of look up table, so I was wondering which would be more efficient a <i>list</i> or <i>dict</i>?</p> <p>I know you can do something like this for both:</p> <pre><code>if something in dict_of_stuff: pass </code></pre> <p>and</p> <pre><code>if somet...
79
2009-02-04T23:28:41Z
578,968
<p><a href="http://docs.python.org/library/sets.html"><code>set()</code></a> is exactly what you want. O(1) lookups, and smaller than a dict.</p>
17
2009-02-23T19:24:39Z
[ "python", "performance" ]
Python: List vs Dict for look up table
513,882
<p>I have about 10million values that I need to put in some type of look up table, so I was wondering which would be more efficient a <i>list</i> or <i>dict</i>?</p> <p>I know you can do something like this for both:</p> <pre><code>if something in dict_of_stuff: pass </code></pre> <p>and</p> <pre><code>if somet...
79
2009-02-04T23:28:41Z
11,241,481
<p>I did some benchmarking and it turns out that dict is faster than both list and set for large data sets, running python 2.7.3 on an i7 CPU on linux:</p> <ul> <li><p><code>python -mtimeit -s 'd=range(10**7)' '5*10**6 in d'</code></p> <p>10 loops, best of 3: 64.2 msec per loop</p></li> <li><p><code>python -mtimeit -...
12
2012-06-28T09:16:06Z
[ "python", "performance" ]
How to split a string by using [] in Python
514,029
<p>So from this string:</p> <p>"name[id]"</p> <p>I need this:</p> <p>"id"</p> <p>I used str.split ('[]'), but it didn't work. Does it only take a single delimiter?</p>
2
2009-02-05T00:37:27Z
514,045
<p>Use a regular expression:</p> <pre><code>import re s = "name[id]" re.find(r"\[(.*?)\]", s).group(1) # = 'id' </code></pre> <p><code>str.split()</code> takes a string on which to split input. For instance:</p> <pre><code>"i,split,on commas".split(',') # = ['i', 'split', 'on commas'] </code></pre> <p>The <code>r...
13
2009-02-05T00:42:05Z
[ "python", "string" ]
How to split a string by using [] in Python
514,029
<p>So from this string:</p> <p>"name[id]"</p> <p>I need this:</p> <p>"id"</p> <p>I used str.split ('[]'), but it didn't work. Does it only take a single delimiter?</p>
2
2009-02-05T00:37:27Z
514,047
<p>Either</p> <pre><code>"name[id]".split('[')[1][:-1] == "id" </code></pre> <p>or</p> <pre><code>"name[id]".split('[')[1].split(']')[0] == "id" </code></pre> <p>or</p> <pre><code>re.search(r'\[(.*?)\]',"name[id]").group(1) == "id" </code></pre> <p>or</p> <pre><code>re.split(r'[\[\]]',"name[id]")[1] == "id" </co...
7
2009-02-05T00:42:15Z
[ "python", "string" ]
How to split a string by using [] in Python
514,029
<p>So from this string:</p> <p>"name[id]"</p> <p>I need this:</p> <p>"id"</p> <p>I used str.split ('[]'), but it didn't work. Does it only take a single delimiter?</p>
2
2009-02-05T00:37:27Z
514,049
<p>str.split uses the entire parameter to split a string. Try:</p> <pre><code>str.split("[")[1].split("]")[0] </code></pre>
-1
2009-02-05T00:43:14Z
[ "python", "string" ]
How to split a string by using [] in Python
514,029
<p>So from this string:</p> <p>"name[id]"</p> <p>I need this:</p> <p>"id"</p> <p>I used str.split ('[]'), but it didn't work. Does it only take a single delimiter?</p>
2
2009-02-05T00:37:27Z
514,054
<p>Yes, the delimiter is the whole string argument passed to split. So your example would only split a string like 'name[]id[]'.</p> <p>Try eg. something like:</p> <pre><code>'name[id]'.split('[', 1)[-1].split(']', 1)[0] 'name[id]'.split('[', 1)[-1].rstrip(']') </code></pre>
3
2009-02-05T00:43:43Z
[ "python", "string" ]
How to split a string by using [] in Python
514,029
<p>So from this string:</p> <p>"name[id]"</p> <p>I need this:</p> <p>"id"</p> <p>I used str.split ('[]'), but it didn't work. Does it only take a single delimiter?</p>
2
2009-02-05T00:37:27Z
514,096
<p>I'm not a fan of regex, but in cases like it often provides the best solution.</p> <p>Triptych already recommended this, but I'd like to point out that the ?P&lt;> group assignment can be used to assign a match to a dictionary key:</p> <pre><code>&gt;&gt;&gt; m = re.match(r'.*\[(?P&lt;id&gt;\w+)\]', 'name[id]') &g...
2
2009-02-05T00:58:34Z
[ "python", "string" ]
How to split a string by using [] in Python
514,029
<p>So from this string:</p> <p>"name[id]"</p> <p>I need this:</p> <p>"id"</p> <p>I used str.split ('[]'), but it didn't work. Does it only take a single delimiter?</p>
2
2009-02-05T00:37:27Z
514,141
<p>You don't actually need regular expressions for this. The .index() function and string slicing will work fine.</p> <p>Say we have:</p> <pre><code>&gt;&gt;&gt; s = 'name[id]' </code></pre> <p>Then:</p> <pre><code>&gt;&gt;&gt; s[s.index('[')+1:s.index(']')] 'id' </code></pre> <p>To me, this is easy to read: "sta...
1
2009-02-05T01:10:52Z
[ "python", "string" ]
How to split a string by using [] in Python
514,029
<p>So from this string:</p> <p>"name[id]"</p> <p>I need this:</p> <p>"id"</p> <p>I used str.split ('[]'), but it didn't work. Does it only take a single delimiter?</p>
2
2009-02-05T00:37:27Z
514,318
<pre><code>def between_brackets(text): return text.partition('[')[2].partition(']')[0] </code></pre> <p>This will also work even if your string does not contain a <code>[…]</code> construct, and it assumes an implied <code>]</code> at the end in the case you have only a <code>[</code> somewhere in the string.</p...
1
2009-02-05T02:37:45Z
[ "python", "string" ]
How to split a string by using [] in Python
514,029
<p>So from this string:</p> <p>"name[id]"</p> <p>I need this:</p> <p>"id"</p> <p>I used str.split ('[]'), but it didn't work. Does it only take a single delimiter?</p>
2
2009-02-05T00:37:27Z
2,739,117
<p>I'm new to python and this is an old question, but maybe this?</p> <p><code>str.split('[')[1].strip(']')</code></p>
0
2010-04-29T16:40:45Z
[ "python", "string" ]
Elegant ways to return multiple values from a function
514,038
<p>It seems like in most mainstream programming languages, <strong>returning multiple values from a function</strong> is an extremely awkward thing. </p> <p>The typical solutions are to make either a <strong>struct</strong> or a plain old data <strong>class</strong> and return that, or to pass at least some of the par...
27
2009-02-05T00:39:48Z
514,053
<p>i thinks python's is the most natural way, when I had to do same thing in php the only was to wrap return into an array. it does have similar unpacking though.</p>
3
2009-02-05T00:43:33Z
[ "python", "function", "language-agnostic", "language-design", "syntactic-sugar" ]
Elegant ways to return multiple values from a function
514,038
<p>It seems like in most mainstream programming languages, <strong>returning multiple values from a function</strong> is an extremely awkward thing. </p> <p>The typical solutions are to make either a <strong>struct</strong> or a plain old data <strong>class</strong> and return that, or to pass at least some of the par...
27
2009-02-05T00:39:48Z
514,069
<p>Often in php I'll use a referenced input:</p> <pre><code>public function Validates(&amp;$errors=array()) { if($failstest) { $errors[] = "It failed"; return false; } else { return true; } } </code></pre> <p>That gives me the error messages I want without polluting the bool return, so I ca...
1
2009-02-05T00:48:04Z
[ "python", "function", "language-agnostic", "language-design", "syntactic-sugar" ]
Elegant ways to return multiple values from a function
514,038
<p>It seems like in most mainstream programming languages, <strong>returning multiple values from a function</strong> is an extremely awkward thing. </p> <p>The typical solutions are to make either a <strong>struct</strong> or a plain old data <strong>class</strong> and return that, or to pass at least some of the par...
27
2009-02-05T00:39:48Z
514,071
<p>Pretty much all ML-influenced functional langues (which is most of them) also have great tuple support that makes this sort of thing trivial.</p> <p>For C++ I like boost::tuple plus boost::tie (or std::tr1 if you have it)</p> <pre><code>typedef boost::tuple&lt;double,double,double&gt; XYZ; XYZ foo(); double x,y,...
24
2009-02-05T00:48:27Z
[ "python", "function", "language-agnostic", "language-design", "syntactic-sugar" ]
Elegant ways to return multiple values from a function
514,038
<p>It seems like in most mainstream programming languages, <strong>returning multiple values from a function</strong> is an extremely awkward thing. </p> <p>The typical solutions are to make either a <strong>struct</strong> or a plain old data <strong>class</strong> and return that, or to pass at least some of the par...
27
2009-02-05T00:39:48Z
514,093
<p>If a function returns multiple values, that is a sign you might be witnessing the <a href="http://www.martinfowler.com/bliki/DataClump.html" rel="nofollow">"Data Clump" code smell</a>. Often data clumps are primitive values that nobody thinks to turn into an object, but interesting stuff happens as you begin to look...
5
2009-02-05T00:57:53Z
[ "python", "function", "language-agnostic", "language-design", "syntactic-sugar" ]
Elegant ways to return multiple values from a function
514,038
<p>It seems like in most mainstream programming languages, <strong>returning multiple values from a function</strong> is an extremely awkward thing. </p> <p>The typical solutions are to make either a <strong>struct</strong> or a plain old data <strong>class</strong> and return that, or to pass at least some of the par...
27
2009-02-05T00:39:48Z
514,114
<p>A few languages, notably Lisp and JavaScript, have a feature called destructuring assignment or destructuring bind. This is essentially tuple unpacking on steroids: rather than being limited to sequences like tuples, lists, or generators, you can unpack more complex object structures in an assignment statement. For ...
9
2009-02-05T01:05:05Z
[ "python", "function", "language-agnostic", "language-design", "syntactic-sugar" ]
Elegant ways to return multiple values from a function
514,038
<p>It seems like in most mainstream programming languages, <strong>returning multiple values from a function</strong> is an extremely awkward thing. </p> <p>The typical solutions are to make either a <strong>struct</strong> or a plain old data <strong>class</strong> and return that, or to pass at least some of the par...
27
2009-02-05T00:39:48Z
514,133
<p>Nobody seems to have mentioned Perl yet.</p> <pre><code>sub myfunc { return 1, 2; } my($val1, $val2) = myfunc(); </code></pre>
4
2009-02-05T01:09:13Z
[ "python", "function", "language-agnostic", "language-design", "syntactic-sugar" ]
Elegant ways to return multiple values from a function
514,038
<p>It seems like in most mainstream programming languages, <strong>returning multiple values from a function</strong> is an extremely awkward thing. </p> <p>The typical solutions are to make either a <strong>struct</strong> or a plain old data <strong>class</strong> and return that, or to pass at least some of the par...
27
2009-02-05T00:39:48Z
514,300
<p>PHP example:</p> <pre><code>function my_funct() { $x = "hello"; $y = "world"; return array($x, $y); } </code></pre> <p>Then, when run:</p> <pre><code>list($x, $y) = my_funct(); echo $x.' '.$y; // "hello world" </code></pre>
7
2009-02-05T02:31:32Z
[ "python", "function", "language-agnostic", "language-design", "syntactic-sugar" ]
Elegant ways to return multiple values from a function
514,038
<p>It seems like in most mainstream programming languages, <strong>returning multiple values from a function</strong> is an extremely awkward thing. </p> <p>The typical solutions are to make either a <strong>struct</strong> or a plain old data <strong>class</strong> and return that, or to pass at least some of the par...
27
2009-02-05T00:39:48Z
514,433
<p>In <code>C++</code> you can pass a container into the function so the function can fill it:</p> <pre><code>void getValues(std::vector&lt;int&gt;* result){ result-&gt;push_back(2); result-&gt;push_back(6); result-&gt;push_back(73); } </code></pre> <p>You could also have the function return a smart pointer (us...
0
2009-02-05T03:31:56Z
[ "python", "function", "language-agnostic", "language-design", "syntactic-sugar" ]
Elegant ways to return multiple values from a function
514,038
<p>It seems like in most mainstream programming languages, <strong>returning multiple values from a function</strong> is an extremely awkward thing. </p> <p>The typical solutions are to make either a <strong>struct</strong> or a plain old data <strong>class</strong> and return that, or to pass at least some of the par...
27
2009-02-05T00:39:48Z
514,509
<p>Even if you ignore the wonderful newer destructuring assignment <a href="http://stackoverflow.com/questions/514038/elegant-ways-to-return-multiple-values-from-a-function/514114#514114">Moss Collum mentioned</a>, JavaScript is pretty nice on returning multiple results.</p> <pre><code>function give7and5() { return ...
2
2009-02-05T04:02:06Z
[ "python", "function", "language-agnostic", "language-design", "syntactic-sugar" ]
Elegant ways to return multiple values from a function
514,038
<p>It seems like in most mainstream programming languages, <strong>returning multiple values from a function</strong> is an extremely awkward thing. </p> <p>The typical solutions are to make either a <strong>struct</strong> or a plain old data <strong>class</strong> and return that, or to pass at least some of the par...
27
2009-02-05T00:39:48Z
514,556
<p>As for Java, see Bruce Eckel's <a href="http://rads.stackoverflow.com/amzn/click/0131872486" rel="nofollow"><em>Thinking in Java</em></a> for a nice solution (pp. 621 ff).</p> <p>In essence, you can define a class equivalent to the following:</p> <pre><code>public class Pair&lt;T,U&gt; { public final T left; ...
4
2009-02-05T04:17:55Z
[ "python", "function", "language-agnostic", "language-design", "syntactic-sugar" ]
Elegant ways to return multiple values from a function
514,038
<p>It seems like in most mainstream programming languages, <strong>returning multiple values from a function</strong> is an extremely awkward thing. </p> <p>The typical solutions are to make either a <strong>struct</strong> or a plain old data <strong>class</strong> and return that, or to pass at least some of the par...
27
2009-02-05T00:39:48Z
514,679
<p>Both <a href="http://www.lua.org/" rel="nofollow">Lua</a> and CLU (by Barbara Liskov's group at MIT) have multiple return values for all functions---it is always the default. I believe the designers of Lua were inspired by CLU. I like having multiple values be the default for calls and returns; I think it is a ver...
1
2009-02-05T05:16:39Z
[ "python", "function", "language-agnostic", "language-design", "syntactic-sugar" ]
Elegant ways to return multiple values from a function
514,038
<p>It seems like in most mainstream programming languages, <strong>returning multiple values from a function</strong> is an extremely awkward thing. </p> <p>The typical solutions are to make either a <strong>struct</strong> or a plain old data <strong>class</strong> and return that, or to pass at least some of the par...
27
2009-02-05T00:39:48Z
3,163,927
<p>c#</p> <pre><code>public struct tStruct { int x; int y; string text; public tStruct(int nx, int ny, string stext) { this.x = nx; this.y = ny; this.text = stext; } } public tStruct YourFunction() { return new tStruct(50, 100, "hello world"); } public void Your...
0
2010-07-02T07:23:29Z
[ "python", "function", "language-agnostic", "language-design", "syntactic-sugar" ]
Elegant ways to return multiple values from a function
514,038
<p>It seems like in most mainstream programming languages, <strong>returning multiple values from a function</strong> is an extremely awkward thing. </p> <p>The typical solutions are to make either a <strong>struct</strong> or a plain old data <strong>class</strong> and return that, or to pass at least some of the par...
27
2009-02-05T00:39:48Z
4,869,624
<p>By the way, Scala can return multiple values as follows (pasted from an interpreter session):</p> <pre><code>scala&gt; def return2 = (1,2) return2: (Int, Int) scala&gt; val (a1,a2) = return2 a1: Int = 1 a2: Int = 2 </code></pre> <p>This is a special case of using <a href="http://www.nearinfinity.com/blogs/bryan_w...
0
2011-02-02T00:39:36Z
[ "python", "function", "language-agnostic", "language-design", "syntactic-sugar" ]
Elegant ways to return multiple values from a function
514,038
<p>It seems like in most mainstream programming languages, <strong>returning multiple values from a function</strong> is an extremely awkward thing. </p> <p>The typical solutions are to make either a <strong>struct</strong> or a plain old data <strong>class</strong> and return that, or to pass at least some of the par...
27
2009-02-05T00:39:48Z
10,018,424
<p>Here was my Ruby idea to return a special value that looks and acts like a scalar but actually has hidden attributes on it:</p> <p><a href="https://gist.github.com/2305169" rel="nofollow">https://gist.github.com/2305169</a></p>
0
2012-04-04T20:03:10Z
[ "python", "function", "language-agnostic", "language-design", "syntactic-sugar" ]
Extension methods in Python
514,068
<p>Does Python have extension methods like C#? Is it possible to call a method like:</p> <pre><code>MyRandomMethod() </code></pre> <p>on existing types like <code>int</code>?</p> <pre><code>myInt.MyRandomMethod() </code></pre>
23
2009-02-05T00:47:37Z
514,081
<p>not sure if that what you're asking but you can extend existing types and then call whatever you like on the new thing:</p> <pre><code>class int(int): def random_method(self): return 4 # guaranteed to be random v = int(5) # you'll have to instantiate...
7
2009-02-05T00:53:57Z
[ "python", "function", "extension-methods" ]
Extension methods in Python
514,068
<p>Does Python have extension methods like C#? Is it possible to call a method like:</p> <pre><code>MyRandomMethod() </code></pre> <p>on existing types like <code>int</code>?</p> <pre><code>myInt.MyRandomMethod() </code></pre>
23
2009-02-05T00:47:37Z
514,101
<p>You can add whatever methods you like on class objects defined in Python code (AKA monkey patching):</p> <pre><code>&gt;&gt;&gt; class A(object): &gt;&gt;&gt; pass &gt;&gt;&gt; def stuff(self): &gt;&gt;&gt; print self &gt;&gt;&gt; A.test = stuff &gt;&gt;&gt; A().test() </code></pre> <p>This does not wor...
32
2009-02-05T00:59:31Z
[ "python", "function", "extension-methods" ]
Extension methods in Python
514,068
<p>Does Python have extension methods like C#? Is it possible to call a method like:</p> <pre><code>MyRandomMethod() </code></pre> <p>on existing types like <code>int</code>?</p> <pre><code>myInt.MyRandomMethod() </code></pre>
23
2009-02-05T00:47:37Z
514,148
<p>Another option is to override the meta-class. This allows you to, among other things, specify functions that should exist in all classes.</p> <p>This article starts to discuss it:</p> <p><a href="http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html" rel="nofollow">http://www.onlamp.com/pub/a/python/2003...
0
2009-02-05T01:14:45Z
[ "python", "function", "extension-methods" ]
Extension methods in Python
514,068
<p>Does Python have extension methods like C#? Is it possible to call a method like:</p> <pre><code>MyRandomMethod() </code></pre> <p>on existing types like <code>int</code>?</p> <pre><code>myInt.MyRandomMethod() </code></pre>
23
2009-02-05T00:47:37Z
517,056
<p>I've had great luck with the method described here:</p> <p><a href="http://mail.python.org/pipermail/python-dev/2008-January/076194.html" rel="nofollow">http://mail.python.org/pipermail/python-dev/2008-January/076194.html</a></p> <p>I have no idea if it works on builtins though.</p>
1
2009-02-05T17:59:17Z
[ "python", "function", "extension-methods" ]
What's the bad magic number error?
514,371
<p>What's the "Bad magic number" ImportError in python, and how do I fix it?</p> <p>The only thing I can find online suggests this is caused by compiling a .py -> .pyc file and then trying to use it with the wrong version of python. In my case, however, the file seems to import fine some times but not others, and I'm ...
140
2009-02-05T02:59:47Z
514,395
<p>The magic number comes from UNIX-type systems where the first few bytes of a file held a marker indicating the file type.</p> <p>Python puts a similar marker into its <code>pyc</code> files when it creates them.</p> <p>Then the python interpreter makes sure this number is correct when loading it.</p> <p>Anything ...
174
2009-02-05T03:09:40Z
[ "python" ]
What's the bad magic number error?
514,371
<p>What's the "Bad magic number" ImportError in python, and how do I fix it?</p> <p>The only thing I can find online suggests this is caused by compiling a .py -> .pyc file and then trying to use it with the wrong version of python. In my case, however, the file seems to import fine some times but not others, and I'm ...
140
2009-02-05T02:59:47Z
2,905,435
<p>Deleting all .pyc files will fix "Bad Magic Number" error.</p> <pre><code>find . -name "*.pyc" -delete </code></pre>
28
2010-05-25T14:12:02Z
[ "python" ]
What's the bad magic number error?
514,371
<p>What's the "Bad magic number" ImportError in python, and how do I fix it?</p> <p>The only thing I can find online suggests this is caused by compiling a .py -> .pyc file and then trying to use it with the wrong version of python. In my case, however, the file seems to import fine some times but not others, and I'm ...
140
2009-02-05T02:59:47Z
2,905,486
<p>This is much more efficent than above.</p> <pre><code>find {directory-of-.pyc-files} -name "*.pyc" -print0 | xargs -0 rm -rf </code></pre> <p>where <code>{directory-of-.pyc-files}</code> is the directory that contains the compiled python files. </p>
0
2010-05-25T14:18:09Z
[ "python" ]
What's the bad magic number error?
514,371
<p>What's the "Bad magic number" ImportError in python, and how do I fix it?</p> <p>The only thing I can find online suggests this is caused by compiling a .py -> .pyc file and then trying to use it with the wrong version of python. In my case, however, the file seems to import fine some times but not others, and I'm ...
140
2009-02-05T02:59:47Z
4,854,784
<p>Loading a python3 generated *.pyc file with python2 also causes this error</p>
10
2011-01-31T18:52:09Z
[ "python" ]
What's the bad magic number error?
514,371
<p>What's the "Bad magic number" ImportError in python, and how do I fix it?</p> <p>The only thing I can find online suggests this is caused by compiling a .py -> .pyc file and then trying to use it with the wrong version of python. In my case, however, the file seems to import fine some times but not others, and I'm ...
140
2009-02-05T02:59:47Z
16,791,304
<p>Take the pyc file to a windows machine. Use any Hex editor to open this pyc file. I used freeware 'HexEdit'. Now read hex value of first two bytes. In my case, these were 03 f3.</p> <p>Open calc and convert its display mode to Programmer (Scientific in XP) to see Hex and Decimal conversion. Select "Hex" from Radio ...
5
2013-05-28T11:49:00Z
[ "python" ]
What's the bad magic number error?
514,371
<p>What's the "Bad magic number" ImportError in python, and how do I fix it?</p> <p>The only thing I can find online suggests this is caused by compiling a .py -> .pyc file and then trying to use it with the wrong version of python. In my case, however, the file seems to import fine some times but not others, and I'm ...
140
2009-02-05T02:59:47Z
24,394,381
<p>I had a strange case of Bad Magic Number error using a very old (1.5.2) implementation. I generated a .pyo file and that triggered the error. Bizarrely, the problem was solved by changing the name of the module. The offending name was sms.py. If I generated an sms.pyo from that module, Bad Magic Number error was the...
1
2014-06-24T19:06:29Z
[ "python" ]
What's the bad magic number error?
514,371
<p>What's the "Bad magic number" ImportError in python, and how do I fix it?</p> <p>The only thing I can find online suggests this is caused by compiling a .py -> .pyc file and then trying to use it with the wrong version of python. In my case, however, the file seems to import fine some times but not others, and I'm ...
140
2009-02-05T02:59:47Z
34,078,936
<p>In my case it was not <code>.pyc</code> but old binary <code>.mo</code> translation files after I renamed my own module, so inside this module folder I had to run</p> <pre><code>find . -name \*.po -execdir sh -c 'msgfmt "$0" -o `basename $0 .po`.mo' '{}' \; </code></pre> <p>(please do backup and try to fix <code>....
0
2015-12-04T00:35:50Z
[ "python" ]
What's the bad magic number error?
514,371
<p>What's the "Bad magic number" ImportError in python, and how do I fix it?</p> <p>The only thing I can find online suggests this is caused by compiling a .py -> .pyc file and then trying to use it with the wrong version of python. In my case, however, the file seems to import fine some times but not others, and I'm ...
140
2009-02-05T02:59:47Z
39,410,760
<p>Don't delete them!!! Until..........</p> <p>Find a version on your git, svn or copy folder that works. </p> <p>Delete them and then recover all .pyc. </p> <p>That's work for me. </p>
0
2016-09-09T11:39:53Z
[ "python" ]
Python: loop over consecutive characters?
514,448
<p>In Python (specifically Python 3.0 but I don't think it matters), how do I easily write a loop over a sequence of characters having consecutive character codes? I want to do something like this pseudocode:</p> <pre><code>for Ch from 'a' to 'z' inclusive: # f(Ch) </code></pre> <p>Example: how about a nice "pyth...
8
2009-02-05T03:41:31Z
514,466
<p>You have a constant in the string module called <code>ascii_lowercase</code>, try that out:</p> <pre><code>&gt;&gt;&gt; from string import ascii_lowercase </code></pre> <p>Then you can iterate over the characters in that string.</p> <pre><code>&gt;&gt;&gt; for i in ascii_lowercase : ... f(i) </code></pre> <p...
31
2009-02-05T03:47:46Z
[ "python", "algorithm", "python-3.x", "character" ]
Python: loop over consecutive characters?
514,448
<p>In Python (specifically Python 3.0 but I don't think it matters), how do I easily write a loop over a sequence of characters having consecutive character codes? I want to do something like this pseudocode:</p> <pre><code>for Ch from 'a' to 'z' inclusive: # f(Ch) </code></pre> <p>Example: how about a nice "pyth...
8
2009-02-05T03:41:31Z
514,517
<p>Iterating a constant with all the characters you need is very Pythonic. However if you don't want to import anything and are only working in Unicode, use the built-ins ord() and its inverse chr().</p> <pre><code>for code in range(ord('a'), ord('z') + 1): print chr(code) </code></pre>
8
2009-02-05T04:04:39Z
[ "python", "algorithm", "python-3.x", "character" ]
Python: loop over consecutive characters?
514,448
<p>In Python (specifically Python 3.0 but I don't think it matters), how do I easily write a loop over a sequence of characters having consecutive character codes? I want to do something like this pseudocode:</p> <pre><code>for Ch from 'a' to 'z' inclusive: # f(Ch) </code></pre> <p>Example: how about a nice "pyth...
8
2009-02-05T03:41:31Z
514,782
<p>I would write a function similar to Python's <code>range</code></p> <pre><code>def alpha_range(*args): if len(args) == 1: start, end, step = ord('a'), ord(args[0]), 1 elif len(args) == 2: start, end, step = ord(args[0]), ord(args[1]), 1 else: start, end, step = ord(args[0]), ord(args[1]), args[2] ...
0
2009-02-05T06:20:41Z
[ "python", "algorithm", "python-3.x", "character" ]
Python: loop over consecutive characters?
514,448
<p>In Python (specifically Python 3.0 but I don't think it matters), how do I easily write a loop over a sequence of characters having consecutive character codes? I want to do something like this pseudocode:</p> <pre><code>for Ch from 'a' to 'z' inclusive: # f(Ch) </code></pre> <p>Example: how about a nice "pyth...
8
2009-02-05T03:41:31Z
515,427
<p>You've got to leave the Pascal-isms behind and learn Python with a fresh perspective.</p> <pre><code>&gt;&gt;&gt; ascii_lowercase 'abcdefghijklmnopqrstuvwxyz' &gt;&gt;&gt; def pangram( source ): return all(c in source for c in ascii_lowercase) &gt;&gt;&gt; pangram('hi mom') False &gt;&gt;&gt; pangram(ascii_low...
6
2009-02-05T11:00:09Z
[ "python", "algorithm", "python-3.x", "character" ]
Python: loop over consecutive characters?
514,448
<p>In Python (specifically Python 3.0 but I don't think it matters), how do I easily write a loop over a sequence of characters having consecutive character codes? I want to do something like this pseudocode:</p> <pre><code>for Ch from 'a' to 'z' inclusive: # f(Ch) </code></pre> <p>Example: how about a nice "pyth...
8
2009-02-05T03:41:31Z
7,083,909
<p>A more abstract answer would be something like:</p> <pre><code>&gt;&gt;&gt; x="asdf" &gt;&gt;&gt; for i in range(len(x)): ... print x[i] </code></pre>
0
2011-08-16T19:32:44Z
[ "python", "algorithm", "python-3.x", "character" ]
Help building a regular expression in python using the re module
514,475
<p>im writing a simple propositional logic formula parser in python which uses regular expressions re module and the lex/yacc module for lexing/parsing. Originally my code could pick out implication as ->, but adding logical equivalence (&lt;->) caused issues with the compiled expressions</p> <pre><code>IMPLICATION = ...
1
2009-02-05T03:51:27Z
514,502
<p>I think you can solve this simply by reordering your checking to match equivalences first, and then implications. However, this seems to work :</p> <pre><code>&gt;&gt;&gt; IMPLICATION = re.compile(r'\s*[^\&lt;]\-\&gt;\s*') &gt;&gt;&gt; EQUIVALENCE = re.compile(r'\s*\&lt;\-\&gt;\s*') </code></pre>
0
2009-02-05T04:00:42Z
[ "python", "regex", "parsing" ]
Help building a regular expression in python using the re module
514,475
<p>im writing a simple propositional logic formula parser in python which uses regular expressions re module and the lex/yacc module for lexing/parsing. Originally my code could pick out implication as ->, but adding logical equivalence (&lt;->) caused issues with the compiled expressions</p> <pre><code>IMPLICATION = ...
1
2009-02-05T03:51:27Z
514,631
<p>As far as I can tell, your regular expressions are equivalent to the following:</p> <pre><code># This is bad, because IMPLICATION also will match every # string that EQUIVALENCE matches IMPLICATION = re.compile("-&gt;") EQUIVALENCE = re.compile("&lt;-&gt;") </code></pre> <p>As you've written it, you're also matchi...
4
2009-02-05T04:59:24Z
[ "python", "regex", "parsing" ]
Random name generator strategy - help me improve it
514,617
<p>I have a small project I am doing in Python using web.py. It's a name generator, using 4 "parts" of a name (<code>firstname, middlename, anothername, surname</code>). Each part of the name is a collection of entites in a MySQL databse (<code>name_part (id, part, type_id)</code>, and <code>name_part_type (id, descrip...
4
2009-02-05T04:51:24Z
514,629
<p>I think what you're after is:</p> <pre><code>select * from name_part where type_id=[something] order by used_count asc, rand() limit 1 </code></pre> <p>This will put the lesser used names at the top of the list and, if there's multiples with the same (lowest) used_count, they'll sort randomly.</p>
4
2009-02-05T04:57:45Z
[ "python", "mysql", "random", "web.py" ]
Random name generator strategy - help me improve it
514,617
<p>I have a small project I am doing in Python using web.py. It's a name generator, using 4 "parts" of a name (<code>firstname, middlename, anothername, surname</code>). Each part of the name is a collection of entites in a MySQL databse (<code>name_part (id, part, type_id)</code>, and <code>name_part_type (id, descrip...
4
2009-02-05T04:51:24Z
514,643
<p>I agree with your intuition that using a stored procedure is the right way to go, but then, I almost always try to implement database stuff in the database.</p> <p>In your proc, I would introduce some kind of logic like say, there's only a 30% chance that returning the result will actually increment the counter. Ju...
1
2009-02-05T05:05:00Z
[ "python", "mysql", "random", "web.py" ]
Translating Python Regexp to Shell
514,767
<p>I'm writing an Applescript playlist generator. Part of the process is to read the iTunes Library XML file to get a list of all of the genres in a user's library. This is the python implementation, which works as I'd like:</p> <pre><code> #!/usr/bin/env python # script to get all of the genres from itunes imp...
1
2009-02-05T06:10:39Z
514,919
<p>Why are you using regex to parse XML? Why not use a proper XML library? Python has some great utilities like ElementTree that make walking the DOM a lot easier, and it yields nice, friendly objects rather than untyped strings.</p> <p>Here are some ways of parsing XML using Applescript:</p> <p><a href="http://lis...
3
2009-02-05T07:30:52Z
[ "python", "applescript" ]
Translating Python Regexp to Shell
514,767
<p>I'm writing an Applescript playlist generator. Part of the process is to read the iTunes Library XML file to get a list of all of the genres in a user's library. This is the python implementation, which works as I'd like:</p> <pre><code> #!/usr/bin/env python # script to get all of the genres from itunes imp...
1
2009-02-05T06:10:39Z
515,599
<p>Is creating a standalone App the Solution ?</p> <p>Look at py2app:</p> <p>py2app, works like py2exe but targets Mac OS</p> <p><a href="http://stackoverflow.com/questions/2933/an-executable-python-app">See</a></p>
0
2009-02-05T11:58:02Z
[ "python", "applescript" ]
Translating Python Regexp to Shell
514,767
<p>I'm writing an Applescript playlist generator. Part of the process is to read the iTunes Library XML file to get a list of all of the genres in a user's library. This is the python implementation, which works as I'd like:</p> <pre><code> #!/usr/bin/env python # script to get all of the genres from itunes imp...
1
2009-02-05T06:10:39Z
525,605
<p>If you're already working in AppleScript, why not just ask iTunes directly?</p> <pre><code>tell application "iTunes" to get genre of every track of library playlist 1 </code></pre>
0
2009-02-08T12:13:07Z
[ "python", "applescript" ]
Web based wizard with Python
514,912
<p>What is a good/simple way to create, say a five page wizard, in Python, where the web server component composes the wizard page content mostly dynamically by fetching the data via calls to a XML-RPC back-end. I have experienced a bit with the XML-RPC Python module, but I don't know which Python module would be provi...
2
2009-02-05T07:27:05Z
515,077
<p>If we break down to the components you'll need, we get:</p> <ol> <li>HTTP server to receive the request from the clients browser.</li> <li>A URL router to look at the URL sent from client browser and call your function/method to handle that URL.</li> <li>An XML-RPC client library to fetch the data for that URL.</li...
3
2009-02-05T08:51:02Z
[ "python", "xml-rpc", "wizard" ]
How best to pass database objects to a turbogears WidgetList?
515,522
<p>I am trying to set up form widgets for adding some objects to the database but I'm getting stuck because it seems impossible to pass any arguments to Widgets contained within a WidgetList. To clarify that, here is my WidgetList:</p> <pre><code>class ClientFields(forms.WidgetsList): """Form to create a client"""...
1
2009-02-05T11:35:01Z
515,689
<p>A <a href="http://docs.turbogears.org/1.0/SimpleWidgetForm" rel="nofollow">page in the TurboGears documentation</a> may help.</p>
0
2009-02-05T12:26:02Z
[ "python", "turbogears" ]
Detect key press combination in Linux with Python?
515,801
<p>I'm trying to capture key presses so that when a given combination is pressed I trigger an event.</p> <p>I've searched around for tips on how to get started and the simplest code snippet I can find is in Python - I grabbed the code below for it from <a href="http://www.daniweb.com/forums/thread112975.html" rel="nof...
4
2009-02-05T13:03:36Z
515,835
<p>Tk does not seem to get it if you do not display the window. Try:</p> <pre><code>import Tkinter as tk def key(event): if event.keysym == 'Escape': root.destroy() print event.char root = tk.Tk() print "Press a key (Escape key to exit):" root.bind_all('&lt;Key&gt;', key) # don't show the tk window #...
3
2009-02-05T13:12:09Z
[ "python", "linux", "keylogger" ]
Detect key press combination in Linux with Python?
515,801
<p>I'm trying to capture key presses so that when a given combination is pressed I trigger an event.</p> <p>I've searched around for tips on how to get started and the simplest code snippet I can find is in Python - I grabbed the code below for it from <a href="http://www.daniweb.com/forums/thread112975.html" rel="nof...
4
2009-02-05T13:03:36Z
515,878
<p>What you're doing is reading <code>/dev/tty</code> in "raw" mode.</p> <p>Normal Linux input is "cooked" -- backspaces and line endings have been handled for you.</p> <p>To read a device like your keyboard in "raw" mode, you need to make direct Linux API calls to IOCTL.</p> <p>Look at <a href="http://code.activest...
1
2009-02-05T13:26:15Z
[ "python", "linux", "keylogger" ]
Detect key press combination in Linux with Python?
515,801
<p>I'm trying to capture key presses so that when a given combination is pressed I trigger an event.</p> <p>I've searched around for tips on how to get started and the simplest code snippet I can find is in Python - I grabbed the code below for it from <a href="http://www.daniweb.com/forums/thread112975.html" rel="nof...
4
2009-02-05T13:03:36Z
516,064
<p>Well, turns out there is a much simpler answer when using GNOME which doesn't involve any programming at all...</p> <p><a href="http://www.captain.at/howto-gnome-custom-hotkey-keyboard-shortcut.php" rel="nofollow">http://www.captain.at/howto-gnome-custom-hotkey-keyboard-shortcut.php</a></p> <p><a href="https://web...
1
2009-02-05T14:16:27Z
[ "python", "linux", "keylogger" ]
Detect key press combination in Linux with Python?
515,801
<p>I'm trying to capture key presses so that when a given combination is pressed I trigger an event.</p> <p>I've searched around for tips on how to get started and the simplest code snippet I can find is in Python - I grabbed the code below for it from <a href="http://www.daniweb.com/forums/thread112975.html" rel="nof...
4
2009-02-05T13:03:36Z
2,048,434
<p>Alternatively (a non-Python option) use <a href="http://www.nongnu.org/xbindkeys/xbindkeys.html" rel="nofollow">XBindKeys</a>.</p>
1
2010-01-12T11:14:22Z
[ "python", "linux", "keylogger" ]
Most pythonic way to extend a potentially incomplete list
516,039
<p>What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.</p> <p>An example transformation would be</p> <pre><code>['a','b'...
6
2009-02-05T14:11:32Z
516,070
<p>I think I'd do something pretty much like that, but with a few tidy ups:</p> <pre><code>for i in range(0,10): try: if choicesTxt[i] is None: choicesTxt[i] = "Choice %d"%i except IndexError: choicesTxt.append("Choice %d"%i) </code></pre> <p>Of which the only important two are to only catch <code>I...
3
2009-02-05T14:17:39Z
[ "python" ]
Most pythonic way to extend a potentially incomplete list
516,039
<p>What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.</p> <p>An example transformation would be</p> <pre><code>['a','b'...
6
2009-02-05T14:11:32Z
516,093
<p>I think you should treat resizing the array as a separate step. To do so, in the case the array is too short, call <code>choicesTxt=choicesTxt+[None]*(10-len(choicesTxt))</code>. The <code>None</code> choice reasignment can be done using list comprehensions.</p>
2
2009-02-05T14:22:01Z
[ "python" ]
Most pythonic way to extend a potentially incomplete list
516,039
<p>What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.</p> <p>An example transformation would be</p> <pre><code>['a','b'...
6
2009-02-05T14:11:32Z
516,094
<p>I would also recommend using xrange instead of range. The xrange function generates the numbers as needed. Range generates them in advance. For small sets it doesn't make much difference, but for large ranges the savings can be huge.</p>
0
2009-02-05T14:22:05Z
[ "python" ]
Most pythonic way to extend a potentially incomplete list
516,039
<p>What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.</p> <p>An example transformation would be</p> <pre><code>['a','b'...
6
2009-02-05T14:11:32Z
516,116
<p>What about that (seems to be a dict -- not a list -- when it's <em>incomplete</em>)</p> <pre><code>a = {1:'a', 2:None, 5:'e'} #test data [a[x] if x in a and a[x] is not None else 'Choice %d'%x for x in xrange(1,10)] </code></pre> <p>Edit once more: If it's really a list (not a dict):</p> <pre><code>b=['a',None,'b...
1
2009-02-05T14:28:08Z
[ "python" ]
Most pythonic way to extend a potentially incomplete list
516,039
<p>What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.</p> <p>An example transformation would be</p> <pre><code>['a','b'...
6
2009-02-05T14:11:32Z
516,121
<p>If you don't mind replacing anything that evaluates to False with "Choice %d", then <code>result</code> works for Python 2.4.</p> <p>If you do mind and have Python 2.5 and above then use <code>result2_5_plus</code> with the power of ternary <code>if</code>.</p> <p>If you don't like or can't use ternary if, then ta...
1
2009-02-05T14:29:56Z
[ "python" ]
Most pythonic way to extend a potentially incomplete list
516,039
<p>What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.</p> <p>An example transformation would be</p> <pre><code>['a','b'...
6
2009-02-05T14:11:32Z
516,129
<p>My initial reaction was to split the list extension and "filling in the blanks" into separate parts as so:</p> <pre><code>for i, v in enumerate(my_list): my_list[i] = v or "Choice %s" % (i+1) for j in range(len(my_list)+1, 10): my_list.append("Choice %s" % (j)) # maybe this is nicer for the extension? whi...
7
2009-02-05T14:31:59Z
[ "python" ]
Most pythonic way to extend a potentially incomplete list
516,039
<p>What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.</p> <p>An example transformation would be</p> <pre><code>['a','b'...
6
2009-02-05T14:11:32Z
516,138
<pre><code>&gt;&gt;&gt; in_list = ["a","b",None,"c"] &gt;&gt;&gt; new = ['choice ' + str(i + 1) if j is None else j for i, j in enumerate(in_list)] &gt;&gt;&gt; new.extend(('choice ' +str(i + 1) for i in range(len(new), 9))) &gt;&gt;&gt; new ['a', 'b', 'choice 3', 'c', 'choice 5', 'choice 6', 'choice 7', 'choice 8', 'c...
0
2009-02-05T14:36:01Z
[ "python" ]
Most pythonic way to extend a potentially incomplete list
516,039
<p>What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.</p> <p>An example transformation would be</p> <pre><code>['a','b'...
6
2009-02-05T14:11:32Z
516,144
<p>You could use map (dictionary) instead of list:</p> <pre><code>choices_map = {1:'Choice 1', 2:'Choice 2', 3:'Choice 12'} for key in xrange(1, 10): choices_map.setdefault(key, 'Choice %d'%key) </code></pre> <p>Then you have map filled with your data.<br /> If you want a list instead you can do: </p> <pre><co...
3
2009-02-05T14:36:36Z
[ "python" ]
Most pythonic way to extend a potentially incomplete list
516,039
<p>What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.</p> <p>An example transformation would be</p> <pre><code>['a','b'...
6
2009-02-05T14:11:32Z
516,170
<p>I'm a little unclear about why you're using range(1, 10); since you're using choicesTxt[i], that ends up skipping the None check for the first element in your list.</p> <p>Also, there are obviously easier ways to do this if you're creating a new list, but you're asking specifically to add to an existing list.</p> ...
1
2009-02-05T14:40:38Z
[ "python" ]
Most pythonic way to extend a potentially incomplete list
516,039
<p>What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.</p> <p>An example transformation would be</p> <pre><code>['a','b'...
6
2009-02-05T14:11:32Z
516,241
<p>I would do</p> <pre><code>for i, c in enumerate(choices): if c is None: choices[i] = 'Choice X' choices += ['Choice %d' % (i+1) for i in range(len(choices), 10)] </code></pre> <p>which only replaces actual <code>None</code> values (not anything that evaluates as false), and extends the list in a separ...
1
2009-02-05T15:01:08Z
[ "python" ]
Most pythonic way to extend a potentially incomplete list
516,039
<p>What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.</p> <p>An example transformation would be</p> <pre><code>['a','b'...
6
2009-02-05T14:11:32Z
516,266
<p>I find that when list comprehensions get long it's better to just use a standard for loop. Nearly the same as others but anyway:</p> <pre><code>&gt;&gt;&gt; in_list = ["a","b",None,"c"] &gt;&gt;&gt; full_list = in_list + ([None] * (10 - len(in_list))) &gt;&gt;&gt; for idx, value in enumerate(full_list): ... if ...
1
2009-02-05T15:07:41Z
[ "python" ]
Most pythonic way to extend a potentially incomplete list
516,039
<p>What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.</p> <p>An example transformation would be</p> <pre><code>['a','b'...
6
2009-02-05T14:11:32Z
516,279
<pre><code>choices[:] = ([{False: x, True: "Choice %d" % (i + 1)}[x is None] for i, x in enumerate(choices)] + ["Choice %d" % (i + 1) for i in xrange(len(choices), 9)]) </code></pre>
1
2009-02-05T15:10:46Z
[ "python" ]
Most pythonic way to extend a potentially incomplete list
516,039
<p>What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.</p> <p>An example transformation would be</p> <pre><code>['a','b'...
6
2009-02-05T14:11:32Z
516,349
<p>You could go simpler with a list comprehension:</p> <pre><code>extendedChoices = choices + ([None] * (10 - len(choices))) newChoices = ["Choice %d" % (i+1) if x is None else x for i, x in enumerate(extendedChoices)] </code></pre> <p>This appends <code>None</code> to your choices list until it has at least 10 i...
1
2009-02-05T15:25:20Z
[ "python" ]
Most pythonic way to extend a potentially incomplete list
516,039
<p>What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.</p> <p>An example transformation would be</p> <pre><code>['a','b'...
6
2009-02-05T14:11:32Z
516,491
<p>Unlike <code>zip</code>, Python's <code>map</code> automatically extends shorter sequences with <code>None</code>.</p> <pre><code>map(lambda a, b: b if a is None else a, choicesTxt, ['Choice %i' % n for n in range(1, 10)]) </code></pre> <p>You could simplify the lambda to</p> <pre><code>map(lambda a, b: a...
8
2009-02-05T15:54:23Z
[ "python" ]
Most pythonic way to extend a potentially incomplete list
516,039
<p>What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.</p> <p>An example transformation would be</p> <pre><code>['a','b'...
6
2009-02-05T14:11:32Z
516,554
<pre><code>def choice_n(index): return "Choice %d" % (index + 1) def add_choices(lst, length, default=choice_n): """ &gt;&gt;&gt; add_choices(['a', 'b', None, 'c'], 9) ['a', 'b', 'Choice 3', 'c', 'Choice 5', 'Choice 6', 'Choice 7', 'Choice 8', 'Choice 9'] """ for i, v in enumerate(lst): if v is None: ...
1
2009-02-05T16:05:20Z
[ "python" ]
Most pythonic way to extend a potentially incomplete list
516,039
<p>What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.</p> <p>An example transformation would be</p> <pre><code>['a','b'...
6
2009-02-05T14:11:32Z
516,671
<p>Simplest and most pythonic for me is:</p> <pre><code>repl = lambda i: "Choice %d" % (i + 1) # DRY print ([(x or repl(i)) for i, x in enumerate(aList)] + [repl(i) for i in xrange(len(aList), 9)]) </code></pre>
2
2009-02-05T16:30:29Z
[ "python" ]
Most pythonic way to extend a potentially incomplete list
516,039
<p>What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.</p> <p>An example transformation would be</p> <pre><code>['a','b'...
6
2009-02-05T14:11:32Z
516,673
<p>Well in one line:</p> <p><code><pre>[a or 'Choice %d' % i for a,i in map(None,["a","b",None,"c"],range(10))]</pre></code></p> <p>Though that will replace anything that evaluates to False (e.g. None, '', 0 etc) with "Choice n". Best to replace the <code>"a or 'Choice %d' % i"</code> with a function if yuo don't wa...
1
2009-02-05T16:30:53Z
[ "python" ]
Most pythonic way to extend a potentially incomplete list
516,039
<p>What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.</p> <p>An example transformation would be</p> <pre><code>['a','b'...
6
2009-02-05T14:11:32Z
3,684,238
<p>My two cents...</p> <pre><code>def extendchoices(clist): clist.extend( [None]*(9-len(clist)) ) for i in xrange(9): if clist[i] is None: clist[i] = "Choice %d"%(i+1) </code></pre>
0
2010-09-10T11:28:39Z
[ "python" ]
Most pythonic way to extend a potentially incomplete list
516,039
<p>What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.</p> <p>An example transformation would be</p> <pre><code>['a','b'...
6
2009-02-05T14:11:32Z
5,672,593
<p>If it's ok to replace any false value, eg '' or 0</p> <pre><code>&gt;&gt;&gt; mylist = ['a','b',None,'c'] &gt;&gt;&gt; map(lambda a,b:a or "Choice %s"%b, mylist, range(1,10)) ['a', 'b', 'Choice 3', 'c', 'Choice 5', 'Choice 6', 'Choice 7', 'Choice 8', 'Choice 9'] </code></pre> <p>If you really can only replace for ...
0
2011-04-15T05:05:27Z
[ "python" ]
Most pythonic way to extend a potentially incomplete list
516,039
<p>What I'm looking for is the best way to say, 'If this list is too short, lengthen it to 9 elements and add 'Choice 4', 'Choice 5', etc, as the additional elements. Also, replace any 'None' elements with 'Choice x'.' It is ok to replace "" and 0 too.</p> <p>An example transformation would be</p> <pre><code>['a','b'...
6
2009-02-05T14:11:32Z
37,236,045
<pre><code>&gt;&gt;&gt; my_list=['a','b',None,'c'] &gt;&gt;&gt; map (lambda x,y:x or 'Choice {}'.format(y+1),my_list,range(9)) ['a', 'b', 'Choice 3', 'c', 'Choice 5', 'Choice 6', 'Choice 7', 'Choice 8', 'Choice 9'] </code></pre>
0
2016-05-15T08:25:44Z
[ "python" ]
Is it possible to google search with the gdata API?
516,335
<p>I might be just thick (nothing new), but I can't seem to find anything related to an old-fashioned, vanilla google search in the gdata API docs. Anyone know if it's possible? (I know it probably is with a little tinkering, but I already have a Python web-scraping class created that does it for me, but I was wonderin...
1
2009-02-05T15:22:28Z
516,400
<p>AFAIK, the gdata API is just for the Google Doc's application (Google Spreadsheet etc). </p> <p>The search API does expose a REST interface for "Flash and other Non-Javascript Environments" though:</p> <p><a href="http://code.google.com/apis/ajaxsearch/documentation/#fonje" rel="nofollow">http://code.google.com/ap...
4
2009-02-05T15:35:12Z
[ "python", "gdata-api" ]
Python regex: Turn "ThisFileName.txt" into "This File Name.txt"
516,451
<p>I'm trying to add a space before every capital letter, except the first one.</p> <p>Here's what I have so far, and the output I'm getting:</p> <pre><code>&gt;&gt;&gt; tex = "ThisFileName.txt" &gt;&gt;&gt; re.sub('[A-Z].', ' ', tex) ' his ile ame.txt' </code></pre> <p>I want: 'This File Name.txt'</p> <p>(It'd ...
2
2009-02-05T15:46:33Z
516,486
<p>Key concept here is backreferences in regular expressions:</p> <pre><code>import re text = "ThisFileName.txt" print re.sub('([a-z])([A-Z])', r'\1 \2', text) # Prints: "This File Name.txt" </code></pre> <p>For pulling off the '.txt' in a reliable way, I recommend <code>os.path.splitext()</code></p> <pre><code>impo...
9
2009-02-05T15:53:24Z
[ "python", "regex" ]
Python regex: Turn "ThisFileName.txt" into "This File Name.txt"
516,451
<p>I'm trying to add a space before every capital letter, except the first one.</p> <p>Here's what I have so far, and the output I'm getting:</p> <pre><code>&gt;&gt;&gt; tex = "ThisFileName.txt" &gt;&gt;&gt; re.sub('[A-Z].', ' ', tex) ' his ile ame.txt' </code></pre> <p>I want: 'This File Name.txt'</p> <p>(It'd ...
2
2009-02-05T15:46:33Z
516,495
<pre><code>re.sub('([a-z])([A-Z])', '\\1 \\2', 'TheFileName.txt') </code></pre> <p>EDIT: StackOverflow eats some \s, when not in 'code mode'... Because I forgot to add a newline after the code above, it was not interpreted in 'code mode' :-((. Since I added that text here I didn't have to change anything and it's corr...
2
2009-02-05T15:55:08Z
[ "python", "regex" ]
Python regex: Turn "ThisFileName.txt" into "This File Name.txt"
516,451
<p>I'm trying to add a space before every capital letter, except the first one.</p> <p>Here's what I have so far, and the output I'm getting:</p> <pre><code>&gt;&gt;&gt; tex = "ThisFileName.txt" &gt;&gt;&gt; re.sub('[A-Z].', ' ', tex) ' his ile ame.txt' </code></pre> <p>I want: 'This File Name.txt'</p> <p>(It'd ...
2
2009-02-05T15:46:33Z
516,533
<p>Another possible regular expression using a look behind:</p> <pre><code>(?&lt;!^)([A-Z]) </code></pre>
2
2009-02-05T16:01:31Z
[ "python", "regex" ]
Python regex: Turn "ThisFileName.txt" into "This File Name.txt"
516,451
<p>I'm trying to add a space before every capital letter, except the first one.</p> <p>Here's what I have so far, and the output I'm getting:</p> <pre><code>&gt;&gt;&gt; tex = "ThisFileName.txt" &gt;&gt;&gt; re.sub('[A-Z].', ' ', tex) ' his ile ame.txt' </code></pre> <p>I want: 'This File Name.txt'</p> <p>(It'd ...
2
2009-02-05T15:46:33Z
518,338
<p>It is not clear what you want to do if the filename is <code>Hello123There.txt</code>. So, if you want a space before all capital letters regardless of what precedes them, you can:</p> <pre><code>import re def add_space_before_caps(text): "Add a space before all caps except at start of text" return re.sub(...
1
2009-02-05T22:49:01Z
[ "python", "regex" ]
Is there a Vim equivalent to the Linux/Unix "fold" command?
516,501
<p>I realize there's a way in Vim to hide/fold lines, but what I'm looking for is a way to select a block of text and have Vim wrap lines at or near column 80. </p> <p>Mostly I want to use this on comments in situations where I'm adding some text to an existing comment that pushes it over 80 characters. It would als...
6
2009-02-05T15:56:00Z
516,536
<pre><code>gq </code></pre> <p>It's controlled by the textwidth option, see <code>":help gq"</code> for more info. </p> <p><code>gq</code> will work on the current line by default, but you can highlight a visual block with <kbd>Ctrl</kbd>+<kbd>V</kbd> and format multiple lines / paragraphs like that.</p> <p><code>gq...
11
2009-02-05T16:02:09Z
[ "python", "vim", "formatting", "comments", "textwrapping" ]
Is there a Vim equivalent to the Linux/Unix "fold" command?
516,501
<p>I realize there's a way in Vim to hide/fold lines, but what I'm looking for is a way to select a block of text and have Vim wrap lines at or near column 80. </p> <p>Mostly I want to use this on comments in situations where I'm adding some text to an existing comment that pushes it over 80 characters. It would als...
6
2009-02-05T15:56:00Z
520,076
<p>Take a look at ":help =" and ":help 'equalprg"</p> <pre><code>:set equalprg=fold </code></pre> <p>and in normal mode == filters the current line through the external fold program. Or visual-select something and hit =</p>
0
2009-02-06T12:12:52Z
[ "python", "vim", "formatting", "comments", "textwrapping" ]
Mixed language source directory layout
516,798
<p>We are running a large project with several different languages: Java, Python, PHP, SQL and Perl. </p> <p>Until now people have been working in their own private repositories, but now we want to merge the entire project in a single repository. The question now is: how should the directory structure look? Should we ...
5
2009-02-05T16:57:15Z
516,827
<p>My experience indicates that this kind of layout is best:</p> <pre><code>mylib/ src/ java/ python/ perl/ .../ bin/ java/ python/ perl/ stage/ dist/ </code></pre> <p><code>src</code> is your source, and is the only thing checked in.</p> <p><code>bin<...
6
2009-02-05T17:01:47Z
[ "java", "python", "sql", "directory" ]
Mixed language source directory layout
516,798
<p>We are running a large project with several different languages: Java, Python, PHP, SQL and Perl. </p> <p>Until now people have been working in their own private repositories, but now we want to merge the entire project in a single repository. The question now is: how should the directory structure look? Should we ...
5
2009-02-05T16:57:15Z
518,493
<p>I think the best thing to do would be to ensure that your various modules don't depend upon being in the same directory (i.e. separate by component). A lot of people seem to be deathly afraid of this idea, but a good set of build scripts should be able to automate away any pain.</p> <p>The end goal would be to mak...
2
2009-02-05T23:37:25Z
[ "java", "python", "sql", "directory" ]
Is plotting an image on a map with matplotlib possible?
516,935
<p>Using basemap it's easy to plot a set of coordinates, like so:</p> <pre><code>x, y = m(lons, lats) m.plot(x, y, 'go') </code></pre> <p>but would it be possible to use an image instead of the green circle ('go')? I didn't find a direct way of doing this from the documentation.</p> <p>So, let's clarify this a b...
8
2009-02-05T17:28:10Z
517,320
<p>If you want to draw <code>.png</code> images then you should try <a href="http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.imshow">http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.imshow</a></p> <p>You might also be interested in the Matplotlib Basemap toolkit. <a href=...
6
2009-02-05T18:47:00Z
[ "python", "matplotlib" ]
Is plotting an image on a map with matplotlib possible?
516,935
<p>Using basemap it's easy to plot a set of coordinates, like so:</p> <pre><code>x, y = m(lons, lats) m.plot(x, y, 'go') </code></pre> <p>but would it be possible to use an image instead of the green circle ('go')? I didn't find a direct way of doing this from the documentation.</p> <p>So, let's clarify this a b...
8
2009-02-05T17:28:10Z
11,548,194
<p>For your reference, I answered a similar question to this the other day: <a href="http://stackoverflow.com/questions/11487797/python-matplotlib-basemap-overlay-small-image-on-map-plot/11495585#11495585">Python Matplotlib Basemap overlay small image on map plot</a></p>
1
2012-07-18T18:41:53Z
[ "python", "matplotlib" ]
Control 2 separate Excel instances by COM independently... can it be done?
516,946
<p>I've got a legacy application which is implemented in a number of Excel workbooks. It's not something that I have the authority to re-implement, however another application that I do maintain does need to be able to call functions in the Excel workbook. </p> <p>It's been given a python interface using the Win32Com ...
5
2009-02-05T17:32:22Z
516,983
<p>If you application uses a single excel file which contains macros which you call, I fear the answer is probably no since aside from COM Excel does not allow the same file to be opened with the same name (even if in different directories). You may be able to get around this by dynamically copying the file to another...
0
2009-02-05T17:42:57Z
[ "python", "windows", "excel", "com" ]
Control 2 separate Excel instances by COM independently... can it be done?
516,946
<p>I've got a legacy application which is implemented in a number of Excel workbooks. It's not something that I have the authority to re-implement, however another application that I do maintain does need to be able to call functions in the Excel workbook. </p> <p>It's been given a python interface using the Win32Com ...
5
2009-02-05T17:32:22Z
517,975
<p>I don't know a thing about Python, unfortunately, but if it works through COM, Excel is not a Single-Instance application, so you should be able to create as many instances of Excel as memory permits.</p> <p>Using C# you can create multiple Excel Application instances via:</p> <pre><code>Excel.Application xlApp1 =...
2
2009-02-05T21:19:34Z
[ "python", "windows", "excel", "com" ]
Control 2 separate Excel instances by COM independently... can it be done?
516,946
<p>I've got a legacy application which is implemented in a number of Excel workbooks. It's not something that I have the authority to re-implement, however another application that I do maintain does need to be able to call functions in the Excel workbook. </p> <p>It's been given a python interface using the Win32Com ...
5
2009-02-05T17:32:22Z
2,263,641
<p>See <a href="http://timgolden.me.uk/python/win32_how_do_i/start-a-new-com-instance.html" rel="nofollow">"Starting a new instance of a COM application" by Tim Golden</a>, also referenced <a href="http://www.thalesians.com/finance/index.php/Knowledge_Base/Python/General#Starting_a_new_instance_of_a_COM_application" re...
4
2010-02-15T01:53:25Z
[ "python", "windows", "excel", "com" ]
return eats exception
517,060
<p>I found the following behavior at least <em>weird</em>:</p> <pre><code>def errors(): try: ErrorErrorError finally: return 10 print errors() # prints: 10 # It should raise: NameError: name 'ErrorErrorError' is not defined </code></pre> <p>The exception disappears when you use <code>return</...
13
2009-02-05T17:59:35Z
517,080
<p>Returning from a finally is <strong>not</strong> a good idea. I know C# specifically forbids doing this.</p>
4
2009-02-05T18:03:11Z
[ "python", "exception", "return", "finally" ]