title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
pylint not recognizing some of the standard library
1,316,334
<p>I'm using pylint + pydev, with python 2.6. I have a module with just this line of code</p> <pre><code>from email import Message </code></pre> <p>Now when I try to run this module it runs fine. But pylint reports an error:</p> <pre><code>ID: E0611 No name 'Message' in module 'email' </code></pre> <p>Although it exists... Any idea why?</p>
9
2009-08-22T16:19:08Z
6,261,591
<p>realise this is an old question, but the correct answer is that the older ways of invoking what you need, which use the "import hackery" that Richie describes, have long been deprecated (despite still appearing in many tutorials). If you use the new ways, you'll be writing better code and <code>pylint</code> won't complain.</p> <p>e.g.</p> <pre><code>from email import Message from email import Header from email.MIMEText import MIMEText </code></pre> <p>should be </p> <pre><code>from email.message import Message from email.header import Header from email.mime.text import MIMEText </code></pre> <p>etc.</p>
10
2011-06-07T06:53:58Z
[ "python", "email", "import", "pydev", "pylint" ]
zlib decompression in python
1,316,357
<p>Okay so I have some data streams compressed by python's (2.6) zlib.compress() function. When I try to decompress them, some of them won't decompress (zlib error -5, which seems to be a "buffer error", no idea what to make of that). At first, I thought I was done, but I realized that all the ones I couldn't decompress started with 0x78DA (the working ones were 0x789C), and I looked around and it seems to be a different kind of zlib compression -- the magic number changes depending on the compression used. What can I use to decompress the files? Am I hosed?</p>
4
2009-08-22T16:24:56Z
1,317,267
<p>According to <a href="http://www.ietf.org/rfc/rfc1950.txt">RFC 1950</a> , the difference between the "OK" 0x789C and the "bad" 0x78DA is in the FLEVEL bit-field:</p> <pre><code> FLEVEL (Compression level) These flags are available for use by specific compression methods. The "deflate" method (CM = 8) sets these flags as follows: 0 - compressor used fastest algorithm 1 - compressor used fast algorithm 2 - compressor used default algorithm 3 - compressor used maximum compression, slowest algorithm The information in FLEVEL is not needed for decompression; it is there to indicate if recompression might be worthwhile. </code></pre> <p>"OK" uses 2, "bad" uses 3. So that difference in itself is not a problem.</p> <p>To get any further, you might consider supplying the following information for each of compressing and (attempted) decompressing: what platform, what version of Python, what version of the zlib library, what was the actual code used to call the zlib module. Also supply the full traceback and error message from the failing decompression attempts. Have you tried to decompress the failing files with any other zlib-reading software? With what results? Please clarify what you have to work with: Does "Am I hosed?" mean that you don't have access to the original data? How did it get from a stream to a file? What guarantee do you have that the data was not mangled in transmission?</p> <p><strong>UPDATE</strong> Some observations based on partial clarifications published in your self-answer:</p> <p>You are using Windows. Windows distinguishes between binary mode and text mode when reading and writing files. When reading in text mode, Python 2.x changes '\r\n' to '\n', and changes '\n' to '\r\n' when writing. This is not a good idea when dealing with non-text data. Worse, when reading in text mode, '\x1a' aka Ctrl-Z is treated as end-of-file.</p> <p>To compress a file:</p> <pre><code># imports and other superstructure left as a exercise str_object1 = open('my_log_file', 'rb').read() str_object2 = zlib.compress(str_object1, 9) f = open('compressed_file', 'wb') f.write(str_object2) f.close() </code></pre> <p>To decompress a file:</p> <pre><code>str_object1 = open('compressed_file', 'rb').read() str_object2 = zlib.decompress(str_object1) f = open('my_recovered_log_file', 'wb') f.write(str_object2) f.close() </code></pre> <p>Aside: Better to use the gzip module which saves you having to think about nasssties like text mode, at the cost of a few bytes for the extra header info.</p> <p>If you have been using 'rb' and 'wb' in your compression code but not in your decompression code [unlikely?], you are not hosed, you just need to flesh out the above decompression code and go for it.</p> <p>Note carefully the use of "may", "should", etc in the following <em>untested</em> ideas.</p> <p>If you have not been using 'rb' and 'wb' in your compression code, the probability that you have hosed yourself is rather high.</p> <p>If there were any instances of '\x1a' in your original file, any data after the first such is lost -- but in that case it shouldn't fail on decompression (IOW this scenario doesn't match your symptoms).</p> <p>If a Ctrl-Z was generated by zlib itself, this should cause an early EOF upon attempted decompression, which should of course cause an exception. In this case you may be able to gingerly reverse the process by reading the compressed file in binary mode and then substitute '\r\n' with '\n' [i.e. simulate text mode without the Ctrl-Z -> EOF gimmick]. Decompress the result. <strong>Edit</strong> Write the result out in TEXT mode. <strong>End edit</strong></p> <p><strong>UPDATE 2</strong> I can reproduce your symptoms -- with ANY level 1 to 9 -- with the following script:</p> <pre><code>import zlib, sys fn = sys.argv[1] level = int(sys.argv[2]) s1 = open(fn).read() # TEXT mode s2 = zlib.compress(s1, level) f = open(fn + '-ct', 'w') # TEXT mode f.write(s2) f.close() # try to decompress in text mode s1 = open(fn + '-ct').read() # TEXT mode s2 = zlib.decompress(s1) # error -5 f = open(fn + '-dtt', 'w') f.write(s2) f.close() </code></pre> <p>Note: you will need a use a reasonably large text file (I used an 80kb source file) to ensure that the decompression result will contain a '\x1a'.</p> <p>I can recover with this script:</p> <pre><code>import zlib, sys fn = sys.argv[1] # (1) reverse the text-mode write # can't use text-mode read as it will stop at Ctrl-Z s1 = open(fn, 'rb').read() # BINARY mode s1 = s1.replace('\r\n', '\n') # (2) reverse the compression s2 = zlib.decompress(s1) # (3) reverse the text mode read f = open(fn + '-fixed', 'w') # TEXT mode f.write(s2) f.close() </code></pre> <p><em>NOTE: If there is a '\x1a' aka Ctrl-Z byte in the original file, and the file is read in text mode, that byte and all following bytes will NOT be included in the compressed file, and thus can NOT be recovered. For a text file (e.g. source code), this is no loss at all. For a binary file, you are most likely hosed.</em></p> <p><strong>Update 3</strong> [following late revelation that there's an encryption/decryption layer involved in the problem]: </p> <p>The "Error -5" message indicates that the data that you are trying to decompress has been mangled since it was compressed. If it's not caused by using text mode on the files, suspicion obviously(?) falls on your decryption and encryption wrappers. If you want help, you need to divulge the source of those wrappers. In fact what you should try to do is (like I did) put together a small script that reproduces the problem on more than one input file. Secondly (like I did) see whether you can reverse the process under what conditions. If you want help with the second stage, you need to divulge the problem-reproduction script.</p>
22
2009-08-22T23:06:12Z
[ "python", "compression", "zlib", "corruption" ]
zlib decompression in python
1,316,357
<p>Okay so I have some data streams compressed by python's (2.6) zlib.compress() function. When I try to decompress them, some of them won't decompress (zlib error -5, which seems to be a "buffer error", no idea what to make of that). At first, I thought I was done, but I realized that all the ones I couldn't decompress started with 0x78DA (the working ones were 0x789C), and I looked around and it seems to be a different kind of zlib compression -- the magic number changes depending on the compression used. What can I use to decompress the files? Am I hosed?</p>
4
2009-08-22T16:24:56Z
1,317,724
<p>Okay sorry I wasn't clear enough. This is win32, python 2.6.2. I'm afraid I can't find the zlib file, but its whatever is included in the win32 binary release. And I don't have access to the original data -- I've been compressing my log files, and I'd like to get them back. As far as other software, I've naievely tried 7zip, but of course it failed, because it's zlib, not gzip (I couldn't any software to decompress zlib streams directly). I can't give a carbon copy of the traceback now, but it was (traced back to zlib.decompress(data)) zlib.error: Error: -3. Also, to be clear, these are static files, not streams as I made it sound earlier (so no transmission errors). And I'm afraid again I don't have the code, but I know I used zlib.compress(data, 9) (i.e. at the highest compression level -- although, interestingly it seems that not all the zlib output is 78da as you might expect since I put it on the highest level) and just zlib.decompress().</p>
0
2009-08-23T04:01:07Z
[ "python", "compression", "zlib", "corruption" ]
zlib decompression in python
1,316,357
<p>Okay so I have some data streams compressed by python's (2.6) zlib.compress() function. When I try to decompress them, some of them won't decompress (zlib error -5, which seems to be a "buffer error", no idea what to make of that). At first, I thought I was done, but I realized that all the ones I couldn't decompress started with 0x78DA (the working ones were 0x789C), and I looked around and it seems to be a different kind of zlib compression -- the magic number changes depending on the compression used. What can I use to decompress the files? Am I hosed?</p>
4
2009-08-22T16:24:56Z
1,319,471
<p>Ok sorry about my last post, I didn't have everything. And I can't edit my post because I didn't use OpenID. Anyways, here's some data:</p> <p>1) Decompression traceback:</p> <pre><code>Traceback (most recent call last): File "&lt;my file&gt;", line 5, in &lt;module&gt; zlib.decompress(data) zlib.error: Error -5 while decompressing data </code></pre> <p>2) Compression code:</p> <pre><code>#here you can assume the data is the data to be compressed/stored data = encrypt(zlib.compress(data,9)) #a short wrapper around PyCrypto AES encryption f = open("somefile", 'wb') f.write(data) f.close() </code></pre> <p>3) Decompression code:</p> <pre><code>f = open("somefile", 'rb') data = f.read() f.close() zlib.decompress(decrypt(data)) #this yeilds the error in (1) </code></pre>
0
2009-08-23T20:28:24Z
[ "python", "compression", "zlib", "corruption" ]
Downloading compressed content over HTTP using Python
1,316,517
<p>How do I take advantage of HTTP 1.1's compression when downloading web pages using Python?</p> <p>I am currently using the built-in <a href="http://docs.python.org/library/urllib.html" rel="nofollow"><strong>urllib</strong></a> module for downloading web content. Reading through the documentation I couldn't find any information that is indeed using compression.</p> <p>Is it already built-in into <strong>urllib</strong> or is there another library that I can use?</p>
3
2009-08-22T17:25:05Z
1,316,546
<p><a href="http://code.google.com/p/httplib2/" rel="nofollow">httplib2</a> supports 'deflate' and 'gzip' compression. </p> <p><strong>Example</strong></p> <pre><code>import httplib2 h = httplib2.Http(".cache") resp, content = h.request("http://example.org/", "GET") </code></pre> <p>The content is decompressed as necessary. </p>
6
2009-08-22T17:39:59Z
[ "python", "http", "compression", "gzip", "httplib2" ]
Django URL.py and the index
1,316,682
<p>I want to know what is the best way to write in the <code>URL.py</code>. I am trying to get the index in this way: <code>www.example.com</code> with <code>(r'',index)</code>. But when I try <code>r''</code>, all pages in the website are going to the home page.</p> <p>Part of my <code>url.py</code>:</p> <pre><code>(r'^index',homepages), (r'',homepages), </code></pre> <p>Thanks :)</p>
9
2009-08-22T18:35:01Z
1,316,696
<p>Like this:</p> <pre><code> #... (r'^$', index), #... </code></pre>
23
2009-08-22T18:41:43Z
[ "python", "django", "django-urls" ]
Django URL.py and the index
1,316,682
<p>I want to know what is the best way to write in the <code>URL.py</code>. I am trying to get the index in this way: <code>www.example.com</code> with <code>(r'',index)</code>. But when I try <code>r''</code>, all pages in the website are going to the home page.</p> <p>Part of my <code>url.py</code>:</p> <pre><code>(r'^index',homepages), (r'',homepages), </code></pre> <p>Thanks :)</p>
9
2009-08-22T18:35:01Z
1,316,709
<p>Django URL matching is very powerful if not always as convenient as it could be. As Brian says, you need to use the pattern r'^$' to force your pattern to match the entire string. With r'', you are looking for an empty string anywhere in the URL, which is true for every URL.</p> <p>Django URL patterns nearly always start with ^ and end with $. You could in theory do some fancy URL matching where strings found anywhere in the URL determined what view function to call, but it's hard to imagine a scenario.</p>
3
2009-08-22T18:47:11Z
[ "python", "django", "django-urls" ]
How can I explicitly free memory in Python?
1,316,767
<p>I wrote a Python program that acts on a large input file to create a few million objects representing triangles. The algorithm is:</p> <ol> <li>read an input file</li> <li>process the file and create a list of triangles, represented by their vertices</li> <li>output the vertices in the OFF format: a list of vertices followed by a list of triangles. The triangles are represented by indices into the list of vertices</li> </ol> <p>The requirement of OFF that I print out the complete list of vertices before I print out the triangles means that I have to hold the list of triangles in memory before I write the output to file. In the meanwhile I'm getting memory errors because of the sizes of the lists. </p> <p>What is the best way to tell Python that I no longer need some of the data, and it can be freed?</p>
123
2009-08-22T19:10:35Z
1,316,779
<p>Python is garbage-collected, so if you reduce the size of your list, it will reclaim memory. You can also use the "del" statement to get rid of a variable completely:</p> <pre><code>biglist = [blah,blah,blah] #... del biglist </code></pre>
11
2009-08-22T19:14:30Z
[ "python", "memory", "memory-management" ]
How can I explicitly free memory in Python?
1,316,767
<p>I wrote a Python program that acts on a large input file to create a few million objects representing triangles. The algorithm is:</p> <ol> <li>read an input file</li> <li>process the file and create a list of triangles, represented by their vertices</li> <li>output the vertices in the OFF format: a list of vertices followed by a list of triangles. The triangles are represented by indices into the list of vertices</li> </ol> <p>The requirement of OFF that I print out the complete list of vertices before I print out the triangles means that I have to hold the list of triangles in memory before I write the output to file. In the meanwhile I'm getting memory errors because of the sizes of the lists. </p> <p>What is the best way to tell Python that I no longer need some of the data, and it can be freed?</p>
123
2009-08-22T19:10:35Z
1,316,788
<p>The <code>del</code> statement might be of use, but IIRC <strong>it isn't guaranteed to free the memory</strong>. The <a href="http://docs.python.org/reference/simple%5Fstmts.html">docs are here</a> ... and a <a href="http://effbot.org/pyfaq/why-doesnt-python-release-the-memory-when-i-delete-a-large-object.htm">why it isn't released is here</a>. </p> <p>I have heard people on Linux and Unix-type systems forking a python process to do some work, getting results and then killing it. </p> <p><a href="http://evanjones.ca/python-memory.html">This article</a> has notes on the Python garbage collector, but I think <strong>lack of memory control is the downside to managed memory</strong></p>
13
2009-08-22T19:16:12Z
[ "python", "memory", "memory-management" ]
How can I explicitly free memory in Python?
1,316,767
<p>I wrote a Python program that acts on a large input file to create a few million objects representing triangles. The algorithm is:</p> <ol> <li>read an input file</li> <li>process the file and create a list of triangles, represented by their vertices</li> <li>output the vertices in the OFF format: a list of vertices followed by a list of triangles. The triangles are represented by indices into the list of vertices</li> </ol> <p>The requirement of OFF that I print out the complete list of vertices before I print out the triangles means that I have to hold the list of triangles in memory before I write the output to file. In the meanwhile I'm getting memory errors because of the sizes of the lists. </p> <p>What is the best way to tell Python that I no longer need some of the data, and it can be freed?</p>
123
2009-08-22T19:10:35Z
1,316,790
<p>You can't explicitly free memory. What you need to do is to make sure you don't keep references to objects. They will then be garbage collected, freeing the memory.</p> <p>In your case, when you need large lists, you typically need to reorganize the code, typically using generators/iterators instead. That way you don't need to have the large lists in memory at all.</p> <p><a href="http://www.prasannatech.net/2009/07/introduction-python-generators.html">http://www.prasannatech.net/2009/07/introduction-python-generators.html</a></p>
13
2009-08-22T19:16:44Z
[ "python", "memory", "memory-management" ]
How can I explicitly free memory in Python?
1,316,767
<p>I wrote a Python program that acts on a large input file to create a few million objects representing triangles. The algorithm is:</p> <ol> <li>read an input file</li> <li>process the file and create a list of triangles, represented by their vertices</li> <li>output the vertices in the OFF format: a list of vertices followed by a list of triangles. The triangles are represented by indices into the list of vertices</li> </ol> <p>The requirement of OFF that I print out the complete list of vertices before I print out the triangles means that I have to hold the list of triangles in memory before I write the output to file. In the meanwhile I'm getting memory errors because of the sizes of the lists. </p> <p>What is the best way to tell Python that I no longer need some of the data, and it can be freed?</p>
123
2009-08-22T19:10:35Z
1,316,793
<p>According to <a href="http://docs.python.org/library/gc.html">Python Official Documentation</a>, you can force the Garbage Collector to release unreferenced memory with <code>gc.collect()</code></p>
108
2009-08-22T19:18:27Z
[ "python", "memory", "memory-management" ]
How can I explicitly free memory in Python?
1,316,767
<p>I wrote a Python program that acts on a large input file to create a few million objects representing triangles. The algorithm is:</p> <ol> <li>read an input file</li> <li>process the file and create a list of triangles, represented by their vertices</li> <li>output the vertices in the OFF format: a list of vertices followed by a list of triangles. The triangles are represented by indices into the list of vertices</li> </ol> <p>The requirement of OFF that I print out the complete list of vertices before I print out the triangles means that I have to hold the list of triangles in memory before I write the output to file. In the meanwhile I'm getting memory errors because of the sizes of the lists. </p> <p>What is the best way to tell Python that I no longer need some of the data, and it can be freed?</p>
123
2009-08-22T19:10:35Z
1,316,799
<p>Unfortunately (depending on your version and release of Python) some types of objects use "free lists" which are a neat local optimization but may cause memory fragmentation, specifically by making more and more memory "earmarked" for only objects of a certain type and thereby unavailable to the "general fund".</p> <p>The only really reliable way to ensure that a large but temporary use of memory DOES return all resources to the system when it's done, is to have that use happen in a subprocess, which does the memory-hungry work then terminates. Under such conditions, the operating system WILL do its job, and gladly recycle all the resources the subprocess may have gobbled up. Fortunately, the <code>multiprocessing</code> module makes this kind of operation (which used to be rather a pain) not too bad in modern versions of Python.</p> <p>In your use case, it seems that the best way for the subprocesses to accumulate some results and yet ensure those results are available to the main process is to use semi-temporary files (by semi-temporary I mean, NOT the kind of files that automatically go away when closed, just ordinary files that you explicitly delete when you're all done with them).</p>
68
2009-08-22T19:21:21Z
[ "python", "memory", "memory-management" ]
How can I explicitly free memory in Python?
1,316,767
<p>I wrote a Python program that acts on a large input file to create a few million objects representing triangles. The algorithm is:</p> <ol> <li>read an input file</li> <li>process the file and create a list of triangles, represented by their vertices</li> <li>output the vertices in the OFF format: a list of vertices followed by a list of triangles. The triangles are represented by indices into the list of vertices</li> </ol> <p>The requirement of OFF that I print out the complete list of vertices before I print out the triangles means that I have to hold the list of triangles in memory before I write the output to file. In the meanwhile I'm getting memory errors because of the sizes of the lists. </p> <p>What is the best way to tell Python that I no longer need some of the data, and it can be freed?</p>
123
2009-08-22T19:10:35Z
1,316,811
<p>If you don't care about vertex reuse, you could have two output files--one for vertices and one for triangles. Then append the triangle file to the vertex file when you are done.</p>
2
2009-08-22T19:29:19Z
[ "python", "memory", "memory-management" ]
How can I explicitly free memory in Python?
1,316,767
<p>I wrote a Python program that acts on a large input file to create a few million objects representing triangles. The algorithm is:</p> <ol> <li>read an input file</li> <li>process the file and create a list of triangles, represented by their vertices</li> <li>output the vertices in the OFF format: a list of vertices followed by a list of triangles. The triangles are represented by indices into the list of vertices</li> </ol> <p>The requirement of OFF that I print out the complete list of vertices before I print out the triangles means that I have to hold the list of triangles in memory before I write the output to file. In the meanwhile I'm getting memory errors because of the sizes of the lists. </p> <p>What is the best way to tell Python that I no longer need some of the data, and it can be freed?</p>
123
2009-08-22T19:10:35Z
1,316,865
<p>Others have posted some ways that you might be able to "coax" the Python interpreter into freeing the memory (or otherwise avoid having memory problems). Chances are you should try their ideas out first. However, I feel it important to give you a direct answer to your question. </p> <p>There isn't really any way to directly tell Python to free memory. The fact of that matter is that if you want that low a level of control, you're going to have to write an extension in C or C++.</p> <p>That said, there are some tools to help with this:</p> <ul> <li><a href="http://www.cython.org/">cython</a></li> <li><a href="http://www.swig.org/">swig</a></li> <li><a href="http://www.boost.org/doc/libs/1%5F39%5F0/libs/python/doc/index.html">boost python</a></li> </ul>
5
2009-08-22T19:47:09Z
[ "python", "memory", "memory-management" ]
How can I explicitly free memory in Python?
1,316,767
<p>I wrote a Python program that acts on a large input file to create a few million objects representing triangles. The algorithm is:</p> <ol> <li>read an input file</li> <li>process the file and create a list of triangles, represented by their vertices</li> <li>output the vertices in the OFF format: a list of vertices followed by a list of triangles. The triangles are represented by indices into the list of vertices</li> </ol> <p>The requirement of OFF that I print out the complete list of vertices before I print out the triangles means that I have to hold the list of triangles in memory before I write the output to file. In the meanwhile I'm getting memory errors because of the sizes of the lists. </p> <p>What is the best way to tell Python that I no longer need some of the data, and it can be freed?</p>
123
2009-08-22T19:10:35Z
1,317,085
<p>Lists of numbers are much less memory-efficient than the format used by the standard array module or the third-party Numpy module. You would save memory by putting your vertices in a Numpy 3xN array and your triangles in an N-element array.</p>
7
2009-08-22T21:29:57Z
[ "python", "memory", "memory-management" ]
What is the most efficient string concatenation method in python?
1,316,887
<p>Is there any efficient mass string concatenation method in Python (like <em>StringBuilder</em> in C# or <em>StringBuffer</em> in Java)? I found following methods <a href="http://skymind.com/~ocrow/python_string/">here</a>:</p> <ul> <li>Simple concatenation using <code>+</code></li> <li>Using string list and <code>join</code> method</li> <li>Using <code>UserString</code> from <code>MutableString</code> module</li> <li>Using character array and the <code>array</code> module </li> <li>Using <code>cStringIO</code> from <code>StringIO</code> module</li> </ul> <p>But what do you experts use or suggest, and why? </p> <p>[<a href="http://stackoverflow.com/questions/1349311/python-string-join-is-faster-than-but-whats-wrong-here">A related question here</a>]</p>
75
2009-08-22T19:53:41Z
1,316,891
<p><code>''.join(sequenceofstrings)</code> is what usually works best -- simplest and fastest.</p>
42
2009-08-22T19:55:58Z
[ "python", "string" ]
What is the most efficient string concatenation method in python?
1,316,887
<p>Is there any efficient mass string concatenation method in Python (like <em>StringBuilder</em> in C# or <em>StringBuffer</em> in Java)? I found following methods <a href="http://skymind.com/~ocrow/python_string/">here</a>:</p> <ul> <li>Simple concatenation using <code>+</code></li> <li>Using string list and <code>join</code> method</li> <li>Using <code>UserString</code> from <code>MutableString</code> module</li> <li>Using character array and the <code>array</code> module </li> <li>Using <code>cStringIO</code> from <code>StringIO</code> module</li> </ul> <p>But what do you experts use or suggest, and why? </p> <p>[<a href="http://stackoverflow.com/questions/1349311/python-string-join-is-faster-than-but-whats-wrong-here">A related question here</a>]</p>
75
2009-08-22T19:53:41Z
1,316,959
<p>You may be interested in this: <a href="http://www.python.org/doc/essays/list2str/">An optimization anecdote</a> by Guido. Although it is worth remembering also that this is an old article and it predates the existence of things like <code>''.join</code> (although I guess <code>string.joinfields</code> is more-or-less the same)</p> <p>On the strength of that, the <code>array</code> module <em>may</em> be fastest if you can shoehorn your problem into it. But <code>''.join</code> is probably <em>fast enough</em> and has the benefit of being idiomatic and thus easier for other python programmers to understand.</p> <p>Finally, the golden rule of optimization: don't optimize unless you know you need to, and measure rather than guessing.</p> <p>You can measure different methods using the <code>timeit</code> module. That can <em>tell</em> you which is fastest, instead of random strangers on the internet making guesses.</p>
72
2009-08-22T20:26:59Z
[ "python", "string" ]
What is the most efficient string concatenation method in python?
1,316,887
<p>Is there any efficient mass string concatenation method in Python (like <em>StringBuilder</em> in C# or <em>StringBuffer</em> in Java)? I found following methods <a href="http://skymind.com/~ocrow/python_string/">here</a>:</p> <ul> <li>Simple concatenation using <code>+</code></li> <li>Using string list and <code>join</code> method</li> <li>Using <code>UserString</code> from <code>MutableString</code> module</li> <li>Using character array and the <code>array</code> module </li> <li>Using <code>cStringIO</code> from <code>StringIO</code> module</li> </ul> <p>But what do you experts use or suggest, and why? </p> <p>[<a href="http://stackoverflow.com/questions/1349311/python-string-join-is-faster-than-but-whats-wrong-here">A related question here</a>]</p>
75
2009-08-22T19:53:41Z
1,316,982
<p>It depends on what you're doing.</p> <p>After Python 2.5, string concatenation with the + operator is pretty fast. If you're just concatenating a couple of values, using the + operator works best:</p> <pre><code>&gt;&gt;&gt; x = timeit.Timer(stmt="'a' + 'b'") &gt;&gt;&gt; x.timeit() 0.039999961853027344 &gt;&gt;&gt; x = timeit.Timer(stmt="''.join(['a', 'b'])") &gt;&gt;&gt; x.timeit() 0.76200008392333984 </code></pre> <p>However, if you're putting together a string in a loop, you're better off using the list joining method:</p> <pre><code>&gt;&gt;&gt; join_stmt = """ ... joined_str = '' ... for i in xrange(100000): ... joined_str += str(i) ... """ &gt;&gt;&gt; x = timeit.Timer(join_stmt) &gt;&gt;&gt; x.timeit(100) 13.278000116348267 &gt;&gt;&gt; list_stmt = """ ... str_list = [] ... for i in xrange(100000): ... str_list.append(str(i)) ... ''.join(str_list) ... """ &gt;&gt;&gt; x = timeit.Timer(list_stmt) &gt;&gt;&gt; x.timeit(100) 12.401000022888184 </code></pre> <p>...but notice that you have to be putting together a relatively high number of strings before the difference becomes noticeable.</p>
23
2009-08-22T20:36:58Z
[ "python", "string" ]
What is the most efficient string concatenation method in python?
1,316,887
<p>Is there any efficient mass string concatenation method in Python (like <em>StringBuilder</em> in C# or <em>StringBuffer</em> in Java)? I found following methods <a href="http://skymind.com/~ocrow/python_string/">here</a>:</p> <ul> <li>Simple concatenation using <code>+</code></li> <li>Using string list and <code>join</code> method</li> <li>Using <code>UserString</code> from <code>MutableString</code> module</li> <li>Using character array and the <code>array</code> module </li> <li>Using <code>cStringIO</code> from <code>StringIO</code> module</li> </ul> <p>But what do you experts use or suggest, and why? </p> <p>[<a href="http://stackoverflow.com/questions/1349311/python-string-join-is-faster-than-but-whats-wrong-here">A related question here</a>]</p>
75
2009-08-22T19:53:41Z
1,317,432
<p>this url has the comparisons of the different approaches along with some benchmarking:</p> <p><a href="http://skymind.com/~ocrow/python_string/" rel="nofollow">http://skymind.com/~ocrow/python_string/</a></p> <p><hr /> <strong>Please Note:</strong> This is a very old comparison from pre-2009 based on Python 2.2, and so should, in most cases be disregarded.</p>
6
2009-08-23T00:40:20Z
[ "python", "string" ]
What is the most efficient string concatenation method in python?
1,316,887
<p>Is there any efficient mass string concatenation method in Python (like <em>StringBuilder</em> in C# or <em>StringBuffer</em> in Java)? I found following methods <a href="http://skymind.com/~ocrow/python_string/">here</a>:</p> <ul> <li>Simple concatenation using <code>+</code></li> <li>Using string list and <code>join</code> method</li> <li>Using <code>UserString</code> from <code>MutableString</code> module</li> <li>Using character array and the <code>array</code> module </li> <li>Using <code>cStringIO</code> from <code>StringIO</code> module</li> </ul> <p>But what do you experts use or suggest, and why? </p> <p>[<a href="http://stackoverflow.com/questions/1349311/python-string-join-is-faster-than-but-whats-wrong-here">A related question here</a>]</p>
75
2009-08-22T19:53:41Z
12,321,184
<p>I ran into a situation where I needed to have an appendable string of unknown size. These are the benchmark results (python 2.7.3):</p> <pre><code>$ python -m timeit -s 's=""' 's+="a"' 10000000 loops, best of 3: 0.176 usec per loop $ python -m timeit -s 's=[]' 's.append("a")' 10000000 loops, best of 3: 0.196 usec per loop $ python -m timeit -s 's=""' 's="".join((s,"a"))' 100000 loops, best of 3: 16.9 usec per loop $ python -m timeit -s 's=""' 's="%s%s"%(s,"a")' 100000 loops, best of 3: 19.4 usec per loop </code></pre> <p>This seems to show that '+=' is the fastest. The results from the skymind link are a bit out of date. </p> <p>(I realize that the second example is not complete, the final list would need to be joined. This does show, however, that simply preparing the list takes longer than the string concat.)</p>
2
2012-09-07T15:32:45Z
[ "python", "string" ]
What is the most efficient string concatenation method in python?
1,316,887
<p>Is there any efficient mass string concatenation method in Python (like <em>StringBuilder</em> in C# or <em>StringBuffer</em> in Java)? I found following methods <a href="http://skymind.com/~ocrow/python_string/">here</a>:</p> <ul> <li>Simple concatenation using <code>+</code></li> <li>Using string list and <code>join</code> method</li> <li>Using <code>UserString</code> from <code>MutableString</code> module</li> <li>Using character array and the <code>array</code> module </li> <li>Using <code>cStringIO</code> from <code>StringIO</code> module</li> </ul> <p>But what do you experts use or suggest, and why? </p> <p>[<a href="http://stackoverflow.com/questions/1349311/python-string-join-is-faster-than-but-whats-wrong-here">A related question here</a>]</p>
75
2009-08-22T19:53:41Z
14,610,440
<p>Inspired by @JasonBaker's benchmarks, here's a simple one comparing 10 <code>"abcdefghijklmnopqrstuvxyz"</code> strings, showing that <code>.join()</code> is faster; even with this tiny increase in variables:</p> <h3>Catenation</h3> <pre><code>&gt;&gt;&gt; x = timeit.Timer(stmt='"abcdefghijklmnopqrstuvxyz" + "abcdefghijklmnopqrstuvxyz" + "abcdefghijklmnopqrstuvxyz" + "abcdefghijklmnopqrstuvxyz" + "abcdefghijklmnopqrstuvxyz" + "abcdefghijklmnopqrstuvxyz" + "abcdefghijklmnopqrstuvxyz" + "abcdefghijklmnopqrstuvxyz" + "abcdefghijklmnopqrstuvxyz" + "abcdefghijklmnopqrstuvxyz" + "abcdefghijklmnopqrstuvxyz"') &gt;&gt;&gt; x.timeit() 0.9828147209324385 </code></pre> <h3>Join</h3> <pre><code>&gt;&gt;&gt; x = timeit.Timer(stmt='"".join(["abcdefghijklmnopqrstuvxyz", "abcdefghijklmnopqrstuvxyz", "abcdefghijklmnopqrstuvxyz", "abcdefghijklmnopqrstuvxyz", "abcdefghijklmnopqrstuvxyz", "abcdefghijklmnopqrstuvxyz", "abcdefghijklmnopqrstuvxyz", "abcdefghijklmnopqrstuvxyz", "abcdefghijklmnopqrstuvxyz", "abcdefghijklmnopqrstuvxyz", "abcdefghijklmnopqrstuvxyz"])') &gt;&gt;&gt; x.timeit() 0.6114138159765048 </code></pre>
0
2013-01-30T17:48:46Z
[ "python", "string" ]
What is the most efficient string concatenation method in python?
1,316,887
<p>Is there any efficient mass string concatenation method in Python (like <em>StringBuilder</em> in C# or <em>StringBuffer</em> in Java)? I found following methods <a href="http://skymind.com/~ocrow/python_string/">here</a>:</p> <ul> <li>Simple concatenation using <code>+</code></li> <li>Using string list and <code>join</code> method</li> <li>Using <code>UserString</code> from <code>MutableString</code> module</li> <li>Using character array and the <code>array</code> module </li> <li>Using <code>cStringIO</code> from <code>StringIO</code> module</li> </ul> <p>But what do you experts use or suggest, and why? </p> <p>[<a href="http://stackoverflow.com/questions/1349311/python-string-join-is-faster-than-but-whats-wrong-here">A related question here</a>]</p>
75
2009-08-22T19:53:41Z
22,356,177
<p>it pretty much depends on the relative sizes of the new string after every new concatenation. With the <code>+</code> operator, for every concatenation a new string is made. If the intermediary strings are relatively long, the <code>+</code> becomes increasingly slower because the new intermediary string is being stored.</p> <p>Consider this case:</p> <pre><code>from time import time stri='' a='aagsdfghfhdyjddtyjdhmfghmfgsdgsdfgsdfsdfsdfsdfsdfsdfddsksarigqeirnvgsdfsdgfsdfgfg' l=[] #case 1 t=time() for i in range(1000): stri=stri+a+repr(i) print time()-t #case 2 t=time() for i in xrange(1000): l.append(a+repr(i)) z=''.join(l) print time()-t #case 3 t=time() for i in range(1000): stri=stri+repr(i) print time()-t #case 4 t=time() for i in xrange(1000): l.append(repr(i)) z=''.join(l) print time()-t </code></pre> <p><strong>Results</strong></p> <p><strong>1</strong> 0.00493192672729</p> <p><strong>2</strong> 0.000509023666382</p> <p><strong>3</strong> 0.00042200088501</p> <p><strong>4</strong> 0.000482797622681</p> <p>In the case of 1&amp;2, we add a large string, and join() performs about 10 times faster. In case 3&amp;4, we add a small string, and '+' performs slightly faster</p>
4
2014-03-12T15:26:31Z
[ "python", "string" ]
What is the most efficient string concatenation method in python?
1,316,887
<p>Is there any efficient mass string concatenation method in Python (like <em>StringBuilder</em> in C# or <em>StringBuffer</em> in Java)? I found following methods <a href="http://skymind.com/~ocrow/python_string/">here</a>:</p> <ul> <li>Simple concatenation using <code>+</code></li> <li>Using string list and <code>join</code> method</li> <li>Using <code>UserString</code> from <code>MutableString</code> module</li> <li>Using character array and the <code>array</code> module </li> <li>Using <code>cStringIO</code> from <code>StringIO</code> module</li> </ul> <p>But what do you experts use or suggest, and why? </p> <p>[<a href="http://stackoverflow.com/questions/1349311/python-string-join-is-faster-than-but-whats-wrong-here">A related question here</a>]</p>
75
2009-08-22T19:53:41Z
24,718,551
<p>As per John Fouhy's answer, don't optimize unless you have to, but if you're here and asking this question, it may be precisely because you <em>have to</em>. In my case, I needed assemble some URLs from string variables... fast. I noticed no one (so far) seems to be considering the string format method, so I thought I'd try that and, mostly for mild interest, I thought I'd toss the string interpolation operator in there for good measuer. To be honest, I didn't think either of these would stack up to a direct '+' operation or a ''.join(). But guess what? On my Python 2.7.5 system, <strong>the string interpolation operator rules them all</strong> and string.format() is the worst performer:</p> <pre><code># concatenate_test.py from __future__ import print_function import timeit domain = 'some_really_long_example.com' lang = 'en' path = 'some/really/long/path/' iterations = 1000000 def meth_plus(): '''Using + operator''' return 'http://' + domain + '/' + lang + '/' + path def meth_join(): '''Using ''.join()''' return ''.join(['http://', domain, '/', lang, '/', path]) def meth_form(): '''Using string.format''' return 'http://{0}/{1}/{2}'.format(domain, lang, path) def meth_intp(): '''Using string interpolation''' return 'http://%s/%s/%s' % (domain, lang, path) plus = timeit.Timer(stmt="meth_plus()", setup="from __main__ import meth_plus") join = timeit.Timer(stmt="meth_join()", setup="from __main__ import meth_join") form = timeit.Timer(stmt="meth_form()", setup="from __main__ import meth_form") intp = timeit.Timer(stmt="meth_intp()", setup="from __main__ import meth_intp") plus.val = plus.timeit(iterations) join.val = join.timeit(iterations) form.val = form.timeit(iterations) intp.val = intp.timeit(iterations) min_val = min([plus.val, join.val, form.val, intp.val]) print('plus %0.12f (%0.2f%% as fast)' % (plus.val, (100 * min_val / plus.val), )) print('join %0.12f (%0.2f%% as fast)' % (join.val, (100 * min_val / join.val), )) print('form %0.12f (%0.2f%% as fast)' % (form.val, (100 * min_val / form.val), )) print('intp %0.12f (%0.2f%% as fast)' % (intp.val, (100 * min_val / intp.val), )) </code></pre> <p>The results:</p> <pre><code># python2.7 concatenate_test.py plus 0.360787868500 (90.81% as fast) join 0.452811956406 (72.36% as fast) form 0.502608060837 (65.19% as fast) intp 0.327636957169 (100.00% as fast) </code></pre> <p>If I use a shorter domain and shorter path, interpolation still wins out. The difference is more pronounced, though, with longer strings.</p> <p>Now that I had a nice test script, I also tested under Python 2.6, 3.3 and 3.4, here's the results. In Python 2.6, the plus operator is the fastest! On Python 3, join wins out. Note: these tests are very repeatable on my system. So, 'plus' is always faster on 2.6, 'intp' is always faster on 2.7 and 'join' is always faster on Python 3.x.</p> <pre><code># python2.6 concatenate_test.py plus 0.338213920593 (100.00% as fast) join 0.427221059799 (79.17% as fast) form 0.515371084213 (65.63% as fast) intp 0.378169059753 (89.43% as fast) # python3.3 concatenate_test.py plus 0.409130576998 (89.20% as fast) join 0.364938726001 (100.00% as fast) form 0.621366866995 (58.73% as fast) intp 0.419064424001 (87.08% as fast) # python3.4 concatenate_test.py plus 0.481188605998 (85.14% as fast) join 0.409673971997 (100.00% as fast) form 0.652010936996 (62.83% as fast) intp 0.460400978001 (88.98% as fast) </code></pre> <p>Lesson learned:</p> <ul> <li>Sometimes, my assumptions are dead wrong.</li> <li>Test against the system env. you'll be running in production.</li> <li>String interpolation isn't dead yet!</li> </ul> <p><strong>tl;dr:</strong></p> <ul> <li>If you using 2.6, use the + operator.</li> <li>if you're using 2.7 use the '%' operator.</li> <li>if you're using 3.x use ''.join().</li> </ul>
2
2014-07-13T00:39:59Z
[ "python", "string" ]
What is the most efficient string concatenation method in python?
1,316,887
<p>Is there any efficient mass string concatenation method in Python (like <em>StringBuilder</em> in C# or <em>StringBuffer</em> in Java)? I found following methods <a href="http://skymind.com/~ocrow/python_string/">here</a>:</p> <ul> <li>Simple concatenation using <code>+</code></li> <li>Using string list and <code>join</code> method</li> <li>Using <code>UserString</code> from <code>MutableString</code> module</li> <li>Using character array and the <code>array</code> module </li> <li>Using <code>cStringIO</code> from <code>StringIO</code> module</li> </ul> <p>But what do you experts use or suggest, and why? </p> <p>[<a href="http://stackoverflow.com/questions/1349311/python-string-join-is-faster-than-but-whats-wrong-here">A related question here</a>]</p>
75
2009-08-22T19:53:41Z
33,981,580
<p>One Year later, let's test mkoistinen's answer with python 3.4.3:</p> <ul> <li>plus 0.963564149000 (95.83% as fast)</li> <li>join 0.923408469000 (100.00% as fast)</li> <li>form 1.501130934000 (61.51% as fast)</li> <li>intp 1.019677452000 (90.56% as fast)</li> </ul> <p>Nothing changed. Join is still the fastest method. With intp being arguably the best choice in terms of readability you might want to use intp nevertheless.</p>
2
2015-11-29T10:08:17Z
[ "python", "string" ]
What is the most efficient string concatenation method in python?
1,316,887
<p>Is there any efficient mass string concatenation method in Python (like <em>StringBuilder</em> in C# or <em>StringBuffer</em> in Java)? I found following methods <a href="http://skymind.com/~ocrow/python_string/">here</a>:</p> <ul> <li>Simple concatenation using <code>+</code></li> <li>Using string list and <code>join</code> method</li> <li>Using <code>UserString</code> from <code>MutableString</code> module</li> <li>Using character array and the <code>array</code> module </li> <li>Using <code>cStringIO</code> from <code>StringIO</code> module</li> </ul> <p>But what do you experts use or suggest, and why? </p> <p>[<a href="http://stackoverflow.com/questions/1349311/python-string-join-is-faster-than-but-whats-wrong-here">A related question here</a>]</p>
75
2009-08-22T19:53:41Z
38,362,140
<p>Python 3.6 is going to change this for strings that have known components with <a href="https://www.python.org/dev/peps/pep-0498/">Literal String Interpolation</a>.</p> <p>Given the test case from <a href="http://stackoverflow.com/a/24718551/918959">mkoistinen's answer</a>, having strings</p> <pre><code>domain = 'some_really_long_example.com' lang = 'en' path = 'some/really/long/path/' </code></pre> <p>The contenders are </p> <ul> <li><p><code>f'http://{domain}/{lang}/{path}'</code> - unpatched, <strong>0.261</strong> µs</p></li> <li><p><code>'http://%s/%s/%s' % (domain, lang, path)</code> - 0.321 µs</p></li> <li><p><code>'http://' + domain + '/' + lang + '/' + path</code> - 0.356 µs</p></li> <li><p><code>''.join(('http://', domain, '/', lang, '/', path))</code> - <strong>0.249</strong> µs (notice that building a constant tuple is slightly faster than building a constant list).</p></li> </ul> <p>Thus currently the shortest and the most beautiful code possible is almost as fast as the fastest known code.</p> <p>However it doesn't stop there. Python 3.6 is still in alpha stage, and the implementation of format strings is currently the <em>slowest</em> possible - actually the generated byte code is pretty much equivalent to the <code>''.join()'</code> case. However, <a href="https://bugs.python.org/issue27078">issue 27078</a> in CPython issue tracker is tracking some possible optimizations to this. </p> <p>With Serhiy Storchaka's <a href="https://bugs.python.org/file43708/fstring_build_string.patch">suggested patch</a>, <code>f'http://{domain}/{lang}/{path}'</code> takes only <strong><em>0.151 µs</em></strong> and is on track to being the <strong>fastest</strong> concatenation method in Python of <strong>all times</strong>.</p> <p>This can be contrasted with the fastest method for Python 2, which is <code>+</code> concatenation on my computer; and that takes <strong>0.203</strong> µs with 8-bit strings, and <strong>0.259</strong> µs if the strings are all Unicode.</p>
9
2016-07-13T21:38:41Z
[ "python", "string" ]
sqlalchemy flush() and get inserted id?
1,316,952
<p>I want to do something like this:</p> <pre><code>f = Foo(bar='x') session.add(f) session.flush() # do additional queries using f.id before commit() print f.id # should be not None session.commit() </code></pre> <p>But f.id is None when I try it. How can I get this to work?</p> <p>-Dan</p>
40
2009-08-22T20:21:42Z
1,317,382
<p>You should try using <code>session.save_or_update(f)</code> instead of <code>session.add(f)</code>. </p>
-6
2009-08-23T00:04:07Z
[ "python", "sqlalchemy" ]
sqlalchemy flush() and get inserted id?
1,316,952
<p>I want to do something like this:</p> <pre><code>f = Foo(bar='x') session.add(f) session.flush() # do additional queries using f.id before commit() print f.id # should be not None session.commit() </code></pre> <p>But f.id is None when I try it. How can I get this to work?</p> <p>-Dan</p>
40
2009-08-22T20:21:42Z
1,325,560
<p>your sample code should be providing a value for <code>f.id</code>, assuming its an autogenerating primary key column. primary key attributes are populated immediately within the flush() process as they are generated and no call to commit() should be required. So the answer here lies in the details of your mapping, if there are any odd quirks of the backend in use (such as, SQLite doesn't generate integer values for a composite primary key) and/or what the emitted SQL says when you turn on echo.</p>
26
2009-08-25T01:06:33Z
[ "python", "sqlalchemy" ]
sqlalchemy flush() and get inserted id?
1,316,952
<p>I want to do something like this:</p> <pre><code>f = Foo(bar='x') session.add(f) session.flush() # do additional queries using f.id before commit() print f.id # should be not None session.commit() </code></pre> <p>But f.id is None when I try it. How can I get this to work?</p> <p>-Dan</p>
40
2009-08-22T20:21:42Z
5,083,472
<p>I've just run across the same problem, and after testing I have found that NONE of these answers are sufficient. </p> <p>Currently, or as of sqlalchemy .6+, there is a very simple solution (I don't know if this exists in prior version, though I imagine it does):</p> <p><strong>session.refresh()</strong></p> <p>So, your code would look something like this:</p> <pre><code>f = Foo(bar=x) session.add(f) session.flush() # At this point, the object f has been pushed to the DB, # and has been automatically assigned a unique primary key id f.id # is None session.refresh(f) # refresh updates given object in the session with its state in the DB # (and can also only refresh certain attributes - search for documentation) f.id # is the automatically assigned primary key ID given in the database. </code></pre> <p>That's how to do it.</p>
72
2011-02-22T20:21:13Z
[ "python", "sqlalchemy" ]
sqlalchemy flush() and get inserted id?
1,316,952
<p>I want to do something like this:</p> <pre><code>f = Foo(bar='x') session.add(f) session.flush() # do additional queries using f.id before commit() print f.id # should be not None session.commit() </code></pre> <p>But f.id is None when I try it. How can I get this to work?</p> <p>-Dan</p>
40
2009-08-22T20:21:42Z
26,260,822
<p>unlike the answer given by dpb, a refresh is not necessary. once you flush, you can access the id field, sqlalchemy automatically refreshes the id which is auto generated at the backend</p> <p>I encountered this problem and figured the exact reason after some investigation, my model was created with id as integerfield and in my form the id was represented with hiddenfield( since i did not wanted to show the id in my form). The hidden field is by default represented as a text. once I changed the form to integerfield with widget=hiddenInput()) the problem was solved.</p>
2
2014-10-08T15:33:02Z
[ "python", "sqlalchemy" ]
sqlalchemy flush() and get inserted id?
1,316,952
<p>I want to do something like this:</p> <pre><code>f = Foo(bar='x') session.add(f) session.flush() # do additional queries using f.id before commit() print f.id # should be not None session.commit() </code></pre> <p>But f.id is None when I try it. How can I get this to work?</p> <p>-Dan</p>
40
2009-08-22T20:21:42Z
28,721,063
<p>I once had a problem with having assigned <code>0</code> to id before calling <code>session.add</code> method. The id was correctly assigned by the database but the correct id was not retrieved from the session after <code>session.flush()</code>.</p>
1
2015-02-25T14:06:22Z
[ "python", "sqlalchemy" ]
Arbitrary number of positional arguments in django inclusion tag?
1,316,968
<p>I'm trying to write a django inclusion tag that takes an arbitrary number of arguments:</p> <pre><code>@register.inclusion_tag('so.html') def table_field(*args): fields = [] for arg in args: fields.append(arg) return { 'fields': fields, } </code></pre> <p>However, when I call this from django's template engine:</p> <pre><code>{% table_field form.hr form.bp form.o2_sat %} </code></pre> <p>I get the error:</p> <pre><code>table_field takes 0 arguments </code></pre> <p>Is this yet another limitation of django's template engine?</p>
3
2009-08-22T20:29:28Z
1,317,095
<p>You'll have to write your own template tag i guess.</p>
1
2009-08-22T21:35:27Z
[ "python", "django" ]
Arbitrary number of positional arguments in django inclusion tag?
1,316,968
<p>I'm trying to write a django inclusion tag that takes an arbitrary number of arguments:</p> <pre><code>@register.inclusion_tag('so.html') def table_field(*args): fields = [] for arg in args: fields.append(arg) return { 'fields': fields, } </code></pre> <p>However, when I call this from django's template engine:</p> <pre><code>{% table_field form.hr form.bp form.o2_sat %} </code></pre> <p>I get the error:</p> <pre><code>table_field takes 0 arguments </code></pre> <p>Is this yet another limitation of django's template engine?</p>
3
2009-08-22T20:29:28Z
1,317,731
<p>Re: I'm trying to write a django inclusion tag that takes an arbitrary number of arguments</p> <p>I think you should pass the arbitrary number of arguments in from the view as a single argument, as some sort of collection.</p> <p>Based on the <a href="http://docs.djangoproject.com/en/dev/howto/custom-template-tags/" rel="nofollow">documentation</a>, I think you should pass some collection object from the view to the template to the inclusion tag, and write the inclusion tag as:</p> <pre><code>@register.inclusion_tag('so.html') def table_field(args): return { 'fields': [arg for arg in args], } </code></pre> <p>Then your template looks like this:</p> <pre><code>{% table_field whatever_was_passed_in_from_the_view %} </code></pre> <p>I don't think that templates are expected to make presentation decisions regarding the selection of data and that that decision is best handled in the view.</p>
2
2009-08-23T04:08:06Z
[ "python", "django" ]
Arbitrary number of positional arguments in django inclusion tag?
1,316,968
<p>I'm trying to write a django inclusion tag that takes an arbitrary number of arguments:</p> <pre><code>@register.inclusion_tag('so.html') def table_field(*args): fields = [] for arg in args: fields.append(arg) return { 'fields': fields, } </code></pre> <p>However, when I call this from django's template engine:</p> <pre><code>{% table_field form.hr form.bp form.o2_sat %} </code></pre> <p>I get the error:</p> <pre><code>table_field takes 0 arguments </code></pre> <p>Is this yet another limitation of django's template engine?</p>
3
2009-08-22T20:29:28Z
1,349,853
<p>This is another limitation of django's inclusion tags. Currently, in django's trunk version, this cannot be done.</p>
0
2009-08-28T23:22:31Z
[ "python", "django" ]
Arbitrary number of positional arguments in django inclusion tag?
1,316,968
<p>I'm trying to write a django inclusion tag that takes an arbitrary number of arguments:</p> <pre><code>@register.inclusion_tag('so.html') def table_field(*args): fields = [] for arg in args: fields.append(arg) return { 'fields': fields, } </code></pre> <p>However, when I call this from django's template engine:</p> <pre><code>{% table_field form.hr form.bp form.o2_sat %} </code></pre> <p>I get the error:</p> <pre><code>table_field takes 0 arguments </code></pre> <p>Is this yet another limitation of django's template engine?</p>
3
2009-08-22T20:29:28Z
3,527,961
<p>As of 1.2.1 you can pass arguments to inclusion tags.</p> <p>Here is an example from my mods to django voting templatetags</p> <pre><code>@register.inclusion_tag("voting/vote_form.html", takes_context=True) def vote_form(context, vote_object, vote_dict, score_dict): if isinstance(vote_dict, dict): </code></pre> <p>and the template looks like:</p> <pre><code>{% vote_form bookmark vote_dict score_dict %} </code></pre> <p>What I don't like about this is there is no way to name the arguments, only to put them in order, but it does work.</p> <p>What is not so clear to me right now is why when you specify takes_context, that parent context is not passed along with the context that you return to be used in rendering the inclusion template.</p> <p>Your trying to use *args won't work though because the # of args passed is checked against the function.</p>
3
2010-08-20T03:22:04Z
[ "python", "django" ]
Arbitrary number of positional arguments in django inclusion tag?
1,316,968
<p>I'm trying to write a django inclusion tag that takes an arbitrary number of arguments:</p> <pre><code>@register.inclusion_tag('so.html') def table_field(*args): fields = [] for arg in args: fields.append(arg) return { 'fields': fields, } </code></pre> <p>However, when I call this from django's template engine:</p> <pre><code>{% table_field form.hr form.bp form.o2_sat %} </code></pre> <p>I get the error:</p> <pre><code>table_field takes 0 arguments </code></pre> <p>Is this yet another limitation of django's template engine?</p>
3
2009-08-22T20:29:28Z
7,800,625
<p>The current development version does provide a variable number of arguments for the inclusion tag. The patch is described here: </p> <p><a href="https://code.djangoproject.com/ticket/13956" rel="nofollow">https://code.djangoproject.com/ticket/13956</a></p> <p>It will be released with 1.4, see <a href="https://docs.djangoproject.com/en/dev/releases/1.4/#args-and-kwargs-support-for-template-tag-helper-functions" rel="nofollow">release notes</a>.</p>
1
2011-10-17T23:03:07Z
[ "python", "django" ]
use python to access mysql
1,317,103
<p>i am finally starting with python. i wanted to ask if i use the mysql db with python, how should i expect python to connect to the db? what i mean is, i have mysql installed in xampp and have my database created in mysql through php myadmin. now my python is in C:\python25\ and my *.py files would be in the same folder as well. now do i need any prior configuration for the connection?</p> <p><strong>what i am doing now</strong></p> <pre><code>&gt;&gt;&gt; cnx = MySQLdb.connect(host=’localhost’, user=’root’, passwd=’’, db=’tablename’) SyntaxError: invalid syntax </code></pre> <p>how do i need to go around this?</p>
0
2009-08-22T21:37:04Z
1,317,108
<p>If you simply cut and pasted, you have the wrong kind of quotes.</p> <p>You've got some kind of asymmetric quote.</p> <p>Use simple apostrophes <code>'</code> or simple quotes <code>"</code>. </p> <p>Do not use <strong>’</strong> .</p>
2
2009-08-22T21:40:27Z
[ "python", "mysql" ]
use python to access mysql
1,317,103
<p>i am finally starting with python. i wanted to ask if i use the mysql db with python, how should i expect python to connect to the db? what i mean is, i have mysql installed in xampp and have my database created in mysql through php myadmin. now my python is in C:\python25\ and my *.py files would be in the same folder as well. now do i need any prior configuration for the connection?</p> <p><strong>what i am doing now</strong></p> <pre><code>&gt;&gt;&gt; cnx = MySQLdb.connect(host=’localhost’, user=’root’, passwd=’’, db=’tablename’) SyntaxError: invalid syntax </code></pre> <p>how do i need to go around this?</p>
0
2009-08-22T21:37:04Z
1,317,128
<p>the basics is</p> <pre><code>import MySQLdb conn = MySQLdb.connect(host="localhost", user="root", passwd="nobodyknow", db="amit") cursor = conn.cursor() stmt = "SELECT * FROM overflows" cursor.execute(stmt) # Fetch and output result = cursor.fetchall() print result # get the number of rows numrows = int(cursor.rowcount) # Close connection conn.close() </code></pre> <p>and don´t use ’ use single or double ' ou " quotes</p>
4
2009-08-22T21:48:39Z
[ "python", "mysql" ]
Finding matching keys in two large dictionaries and doing it fast
1,317,410
<p>I am trying to find corresponding keys in two different dictionaries. Each has about 600k entries.</p> <p>Say for example:</p> <pre><code> myRDP = { 'Actinobacter': 'GATCGA...TCA', 'subtilus sp.': 'ATCGATT...ACT' } myNames = { 'Actinobacter': '8924342' } </code></pre> <p>I want to print out the value for Actinobacter (8924342) since it matches a value in myRDP.</p> <p>The following code works, but is very slow:</p> <pre><code> for key in myRDP: for jey in myNames: if key == jey: print key, myNames[key] </code></pre> <p>I've tried the following but it always results in a KeyError:</p> <pre><code> for key in myRDP: print myNames[key] </code></pre> <p>Is there perhaps a function implemented in C for doing this? I've googled around but nothing seems to work.</p> <p>Thanks.</p>
10
2009-08-23T00:27:34Z
1,317,411
<p>You could do this:</p> <pre><code>for key in myRDP: if key in myNames: print key, myNames[key] </code></pre> <p>Your first attempt was slow because you were comparing <em>every</em> key in myRDP with <em>every</em> key in myNames. In algorithmic jargon, if myRDP has <strong>n</strong> elements and myNames has <strong>m</strong> elements, then that algorithm would take O(<strong>n</strong>×<strong>m</strong>) operations. For 600k elements each, this is 360,000,000,000 comparisons!</p> <p>But testing whether a particular element is a key of a dictionary is fast -- in fact, this is one of the defining characteristics of dictionaries. In algorithmic terms, the <code>key in dict</code> test is O(1), or constant-time. So my algorithm will take O(<strong>n</strong>) time, which is one 600,000th of the time.</p>
33
2009-08-23T00:30:01Z
[ "python", "bioinformatics" ]
Finding matching keys in two large dictionaries and doing it fast
1,317,410
<p>I am trying to find corresponding keys in two different dictionaries. Each has about 600k entries.</p> <p>Say for example:</p> <pre><code> myRDP = { 'Actinobacter': 'GATCGA...TCA', 'subtilus sp.': 'ATCGATT...ACT' } myNames = { 'Actinobacter': '8924342' } </code></pre> <p>I want to print out the value for Actinobacter (8924342) since it matches a value in myRDP.</p> <p>The following code works, but is very slow:</p> <pre><code> for key in myRDP: for jey in myNames: if key == jey: print key, myNames[key] </code></pre> <p>I've tried the following but it always results in a KeyError:</p> <pre><code> for key in myRDP: print myNames[key] </code></pre> <p>Is there perhaps a function implemented in C for doing this? I've googled around but nothing seems to work.</p> <p>Thanks.</p>
10
2009-08-23T00:27:34Z
1,317,412
<pre><code>for key in myRDP: name = myNames.get(key, None) if name: print key, name </code></pre> <p><code>dict.get</code> returns the default value you give it (in this case, <code>None</code>) if the key doesn't exist.</p>
8
2009-08-23T00:30:47Z
[ "python", "bioinformatics" ]
Finding matching keys in two large dictionaries and doing it fast
1,317,410
<p>I am trying to find corresponding keys in two different dictionaries. Each has about 600k entries.</p> <p>Say for example:</p> <pre><code> myRDP = { 'Actinobacter': 'GATCGA...TCA', 'subtilus sp.': 'ATCGATT...ACT' } myNames = { 'Actinobacter': '8924342' } </code></pre> <p>I want to print out the value for Actinobacter (8924342) since it matches a value in myRDP.</p> <p>The following code works, but is very slow:</p> <pre><code> for key in myRDP: for jey in myNames: if key == jey: print key, myNames[key] </code></pre> <p>I've tried the following but it always results in a KeyError:</p> <pre><code> for key in myRDP: print myNames[key] </code></pre> <p>Is there perhaps a function implemented in C for doing this? I've googled around but nothing seems to work.</p> <p>Thanks.</p>
10
2009-08-23T00:27:34Z
1,317,414
<p>Use the <code>get</code> method instead:</p> <pre><code> for key in myRDP: value = myNames.get(key) if value != None: print key, "=", value </code></pre>
2
2009-08-23T00:31:06Z
[ "python", "bioinformatics" ]
Finding matching keys in two large dictionaries and doing it fast
1,317,410
<p>I am trying to find corresponding keys in two different dictionaries. Each has about 600k entries.</p> <p>Say for example:</p> <pre><code> myRDP = { 'Actinobacter': 'GATCGA...TCA', 'subtilus sp.': 'ATCGATT...ACT' } myNames = { 'Actinobacter': '8924342' } </code></pre> <p>I want to print out the value for Actinobacter (8924342) since it matches a value in myRDP.</p> <p>The following code works, but is very slow:</p> <pre><code> for key in myRDP: for jey in myNames: if key == jey: print key, myNames[key] </code></pre> <p>I've tried the following but it always results in a KeyError:</p> <pre><code> for key in myRDP: print myNames[key] </code></pre> <p>Is there perhaps a function implemented in C for doing this? I've googled around but nothing seems to work.</p> <p>Thanks.</p>
10
2009-08-23T00:27:34Z
1,317,415
<p>Copy both dictionaries into <strong>one</strong> dictionary/array. This makes sense as you have 1:1 related values. Then you need only one search, no comparison loop, and can access the related value directly.</p> <p>Example Resulting Dictionary/Array:</p> <p><code></p> <pre><code>[Name][Value1][Value2] [Actinobacter][GATCGA...TCA][8924342] [XYZbacter][BCABCA...ABC][43594344] </code></pre> <p></code></p> <p>...</p>
0
2009-08-23T00:31:43Z
[ "python", "bioinformatics" ]
Finding matching keys in two large dictionaries and doing it fast
1,317,410
<p>I am trying to find corresponding keys in two different dictionaries. Each has about 600k entries.</p> <p>Say for example:</p> <pre><code> myRDP = { 'Actinobacter': 'GATCGA...TCA', 'subtilus sp.': 'ATCGATT...ACT' } myNames = { 'Actinobacter': '8924342' } </code></pre> <p>I want to print out the value for Actinobacter (8924342) since it matches a value in myRDP.</p> <p>The following code works, but is very slow:</p> <pre><code> for key in myRDP: for jey in myNames: if key == jey: print key, myNames[key] </code></pre> <p>I've tried the following but it always results in a KeyError:</p> <pre><code> for key in myRDP: print myNames[key] </code></pre> <p>Is there perhaps a function implemented in C for doing this? I've googled around but nothing seems to work.</p> <p>Thanks.</p>
10
2009-08-23T00:27:34Z
1,317,416
<p>Use sets, because they have a built-in <code>intersection</code> method which ought to be quick:</p> <pre><code>myRDP = { 'Actinobacter': 'GATCGA...TCA', 'subtilus sp.': 'ATCGATT...ACT' } myNames = { 'Actinobacter': '8924342' } rdpSet = set(myRDP) namesSet = set(myNames) for name in rdpSet.intersection(namesSet): print name, myNames[name] # Prints: Actinobacter 8924342 </code></pre>
21
2009-08-23T00:32:07Z
[ "python", "bioinformatics" ]
Finding matching keys in two large dictionaries and doing it fast
1,317,410
<p>I am trying to find corresponding keys in two different dictionaries. Each has about 600k entries.</p> <p>Say for example:</p> <pre><code> myRDP = { 'Actinobacter': 'GATCGA...TCA', 'subtilus sp.': 'ATCGATT...ACT' } myNames = { 'Actinobacter': '8924342' } </code></pre> <p>I want to print out the value for Actinobacter (8924342) since it matches a value in myRDP.</p> <p>The following code works, but is very slow:</p> <pre><code> for key in myRDP: for jey in myNames: if key == jey: print key, myNames[key] </code></pre> <p>I've tried the following but it always results in a KeyError:</p> <pre><code> for key in myRDP: print myNames[key] </code></pre> <p>Is there perhaps a function implemented in C for doing this? I've googled around but nothing seems to work.</p> <p>Thanks.</p>
10
2009-08-23T00:27:34Z
1,317,423
<p>You could start by finding the common keys and then iterating over them. Set operations should be fast because they are implemented in C, at least in modern versions of Python.</p> <pre><code>common_keys = set(myRDP).intersection(myNames) for key in common_keys: print key, myNames[key] </code></pre>
4
2009-08-23T00:34:51Z
[ "python", "bioinformatics" ]
Finding matching keys in two large dictionaries and doing it fast
1,317,410
<p>I am trying to find corresponding keys in two different dictionaries. Each has about 600k entries.</p> <p>Say for example:</p> <pre><code> myRDP = { 'Actinobacter': 'GATCGA...TCA', 'subtilus sp.': 'ATCGATT...ACT' } myNames = { 'Actinobacter': '8924342' } </code></pre> <p>I want to print out the value for Actinobacter (8924342) since it matches a value in myRDP.</p> <p>The following code works, but is very slow:</p> <pre><code> for key in myRDP: for jey in myNames: if key == jey: print key, myNames[key] </code></pre> <p>I've tried the following but it always results in a KeyError:</p> <pre><code> for key in myRDP: print myNames[key] </code></pre> <p>Is there perhaps a function implemented in C for doing this? I've googled around but nothing seems to work.</p> <p>Thanks.</p>
10
2009-08-23T00:27:34Z
1,317,594
<p>Here is my code for doing intersections, unions, differences, and other set operations on dictionaries:</p> <pre><code>class DictDiffer(object): """ Calculate the difference between two dictionaries as: (1) items added (2) items removed (3) keys same in both but changed values (4) keys same in both and unchanged values """ def __init__(self, current_dict, past_dict): self.current_dict, self.past_dict = current_dict, past_dict self.set_current, self.set_past = set(current_dict.keys()), set(past_dict.keys()) self.intersect = self.set_current.intersection(self.set_past) def added(self): return self.set_current - self.intersect def removed(self): return self.set_past - self.intersect def changed(self): return set(o for o in self.intersect if self.past_dict[o] != self.current_dict[o]) def unchanged(self): return set(o for o in self.intersect if self.past_dict[o] == self.current_dict[o]) if __name__ == '__main__': import unittest class TestDictDifferNoChanged(unittest.TestCase): def setUp(self): self.past = dict((k, 2*k) for k in range(5)) self.current = dict((k, 2*k) for k in range(3,8)) self.d = DictDiffer(self.current, self.past) def testAdded(self): self.assertEqual(self.d.added(), set((5,6,7))) def testRemoved(self): self.assertEqual(self.d.removed(), set((0,1,2))) def testChanged(self): self.assertEqual(self.d.changed(), set()) def testUnchanged(self): self.assertEqual(self.d.unchanged(), set((3,4))) class TestDictDifferNoCUnchanged(unittest.TestCase): def setUp(self): self.past = dict((k, 2*k) for k in range(5)) self.current = dict((k, 2*k+1) for k in range(3,8)) self.d = DictDiffer(self.current, self.past) def testAdded(self): self.assertEqual(self.d.added(), set((5,6,7))) def testRemoved(self): self.assertEqual(self.d.removed(), set((0,1,2))) def testChanged(self): self.assertEqual(self.d.changed(), set((3,4))) def testUnchanged(self): self.assertEqual(self.d.unchanged(), set()) unittest.main() </code></pre>
0
2009-08-23T02:24:02Z
[ "python", "bioinformatics" ]
Dealing with dynamic urls
1,317,541
<p>Let's say my main controller 'hotels' has a pattern for the url, such as:</p> <p>/hotels/colorado/aspen/hotel-name/</p> <p>How should I program my controller ( keep in mind I'm still learning MVC ) to handle this variable?</p> <p>I know that I have to probably check if anything after /hotels/ is set, otherwise show the default hotels page. If a state is set, show the state page, and so forth with the city and hotel name.</p> <pre><code>class hotelController { function state() { } function city() { } function hotel() { } } </code></pre> <p>Should I have 3 separate methods for each of those? Any advice is appreciated.</p>
0
2009-08-23T01:53:38Z
1,318,011
<p>It's perfectly valid to have separate methods to get the state, city and hotel name.</p> <p>An alternative, if your templating language support it, is to have a hotel_info() method that returns a dictionary, so that you in the template do "info/state", info/city", etc.</p> <p>I do however think you should look into an MVC framework, because otherwise you'll just end up writing your own, which is pointless.</p> <p>These are the ones I have looked at, they are all good:</p> <ul> <li>Pylons: <a href="http://pylonshq.com/" rel="nofollow">http://pylonshq.com/</a></li> <li>BFG: <a href="http://bfg.repoze.org/" rel="nofollow">http://bfg.repoze.org/</a></li> <li>Bobo: <a href="http://bobo.digicool.com/" rel="nofollow">http://bobo.digicool.com/</a></li> </ul> <p>There are tons more just for Python.</p>
0
2009-08-23T07:42:34Z
[ "php", "python", "url-routing" ]
Dealing with dynamic urls
1,317,541
<p>Let's say my main controller 'hotels' has a pattern for the url, such as:</p> <p>/hotels/colorado/aspen/hotel-name/</p> <p>How should I program my controller ( keep in mind I'm still learning MVC ) to handle this variable?</p> <p>I know that I have to probably check if anything after /hotels/ is set, otherwise show the default hotels page. If a state is set, show the state page, and so forth with the city and hotel name.</p> <pre><code>class hotelController { function state() { } function city() { } function hotel() { } } </code></pre> <p>Should I have 3 separate methods for each of those? Any advice is appreciated.</p>
0
2009-08-23T01:53:38Z
1,318,251
<p>Usually this is solved with Object Dispatch. You can also create nested Controllers to handle this. An advantage is, that you can follow a major OOP principle, namely encapsulation, as you group all functionality that only concerns Hotels generally in the Hotel controller (for example adding a new one)</p> <p>Another advantage is, you dont have to check what is set after /hotels/ for example. It will only be dispatched to a new controller if there is something left to dispatch i.e. if the current controller wasnt able to handle the entire request.</p> <p>This isnt really specific to a certain framework, but it is fully implemented in Pylons and Turbogears 2.0. (For more details you may refer to <a href="http://turbogears.org/2.0/docs/main/TGControllers.html#the-lookup-method" rel="nofollow">http://turbogears.org/2.0/docs/main/TGControllers.html#the-lookup-method</a> )</p> <pre><code>class HotelController(Controller): """ Controller to handle requests to Hotels """ def index(self): """ Handle the index page here """ pass def addNewHotel(self): """ Register a new hotel here """ pass def lookup(self, state_name, *remainder): """ Read the state, create a new StateController and dispatch """ state_dispatch = StateController(state_name) return state_dispatch, remainder class StateController(object): """ Controller used to dispatch """ def __init__(self, state_name): # do your work on the state here pass def create(self, state_name): """ Create a new state here """ def lookup(self, city_name, *remainder): """ keep on dispatching to other controllers """ city_dispatch = CityController(city_name) return city_dispatch, remainder </code></pre>
1
2009-08-23T10:33:18Z
[ "php", "python", "url-routing" ]
Converting a float to a string without rounding it
1,317,558
<p>I'm making a program that, for reasons not needed to be explained, requires a float to be converted into a string to be counted with len(). However, str(float(x)) results in x being rounded when converted to a string, which throws the entire thing off. Does anyone know of a fix for it? Here's the code being used if you want to know:</p> <pre><code>len(str(float(x)/3)) </code></pre>
39
2009-08-23T02:03:07Z
1,317,563
<pre><code>len(repr(float(x)/3)) </code></pre> <p>However I must say that this isn't as reliable as you think.</p> <p>Floats are entered/displayed as decimal numbers, but your computer (in fact, your standard C library) stores them as binary. You get some side effects from this transition:</p> <pre><code>&gt;&gt;&gt; print len(repr(0.1)) 19 &gt;&gt;&gt; print repr(0.1) 0.10000000000000001 </code></pre> <p>The explanation on why this happens is in <a href="http://docs.python.org/tutorial/floatingpoint.html">this chapter</a> of the python tutorial.</p> <p>A solution would be to use a type that specifically tracks decimal numbers, like python's <a href="http://docs.python.org/library/decimal.html"><code>decimal.Decimal</code></a>:</p> <pre><code>&gt;&gt;&gt; print len(str(decimal.Decimal('0.1'))) 3 </code></pre>
8
2009-08-23T02:05:19Z
[ "python", "string", "floating-point", "rounding" ]
Converting a float to a string without rounding it
1,317,558
<p>I'm making a program that, for reasons not needed to be explained, requires a float to be converted into a string to be counted with len(). However, str(float(x)) results in x being rounded when converted to a string, which throws the entire thing off. Does anyone know of a fix for it? Here's the code being used if you want to know:</p> <pre><code>len(str(float(x)/3)) </code></pre>
39
2009-08-23T02:03:07Z
1,317,578
<p>Some form of rounding is often unavoidable when dealing with floating point numbers. This is because numbers that you can express exactly in base 10 cannot always be expressed exactly in base 2 (which your computer uses).</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; .1 0.10000000000000001 </code></pre> <p>In this case, you're seeing .1 converted to a string using <code>repr</code>:</p> <pre><code>&gt;&gt;&gt; repr(.1) '0.10000000000000001' </code></pre> <p>I believe python chops off the last few digits when you use str() in order to work around this problem, but it's a partial workaround that doesn't substitute for understanding what's going on.</p> <pre><code>&gt;&gt;&gt; str(.1) '0.1' </code></pre> <p>I'm not sure exactly what problems "rounding" is causing you. Perhaps you would do better with string formatting as a way to more precisely control your output?</p> <p>e.g.</p> <pre><code>&gt;&gt;&gt; '%.5f' % .1 '0.10000' &gt;&gt;&gt; '%.5f' % .12345678 '0.12346' </code></pre> <p><a href="http://docs.python.org/library/string.html#formatstrings">Documentation here</a>.</p>
63
2009-08-23T02:10:13Z
[ "python", "string", "floating-point", "rounding" ]
Converting a float to a string without rounding it
1,317,558
<p>I'm making a program that, for reasons not needed to be explained, requires a float to be converted into a string to be counted with len(). However, str(float(x)) results in x being rounded when converted to a string, which throws the entire thing off. Does anyone know of a fix for it? Here's the code being used if you want to know:</p> <pre><code>len(str(float(x)/3)) </code></pre>
39
2009-08-23T02:03:07Z
1,318,207
<p>Other answers already pointed out that the representation of floating numbers is a thorny issue, to say the least.</p> <p>Since you don't give enough context in your question, I cannot know if the decimal module can be useful for your needs:</p> <p><a href="http://docs.python.org/library/decimal.html" rel="nofollow">http://docs.python.org/library/decimal.html</a></p> <p>Among other things you can explicitly specify the precision that you wish to obtain (from the docs):</p> <pre><code>&gt;&gt;&gt; getcontext().prec = 6 &gt;&gt;&gt; Decimal('3.0') Decimal('3.0') &gt;&gt;&gt; Decimal('3.1415926535') Decimal('3.1415926535') &gt;&gt;&gt; Decimal('3.1415926535') + Decimal('2.7182818285') Decimal('5.85987') &gt;&gt;&gt; getcontext().rounding = ROUND_UP &gt;&gt;&gt; Decimal('3.1415926535') + Decimal('2.7182818285') Decimal('5.85988') </code></pre> <p>A simple example from my prompt (python 2.6):</p> <pre><code>&gt;&gt;&gt; import decimal &gt;&gt;&gt; a = decimal.Decimal('10.000000001') &gt;&gt;&gt; a Decimal('10.000000001') &gt;&gt;&gt; print a 10.000000001 &gt;&gt;&gt; b = decimal.Decimal('10.00000000000000000000000000900000002') &gt;&gt;&gt; print b 10.00000000000000000000000000900000002 &gt;&gt;&gt; print str(b) 10.00000000000000000000000000900000002 &gt;&gt;&gt; len(str(b/decimal.Decimal('3.0'))) 29 </code></pre> <p>Maybe this can help? decimal is in python stdlib since 2.4, with additions in python 2.6.</p> <p>Hope this helps, Francesco</p>
3
2009-08-23T10:09:22Z
[ "python", "string", "floating-point", "rounding" ]
Should I use "from package import utils, settings" or "from . import utils, settings"
1,317,624
<p>I'm developing a Python application; it has all its code in one package and runs inside this of course. The application's Python package is of no interest from the interpreter to the user, it's simply a GUI application.</p> <p>The question is, which style is preferred when importing modules inside the application package</p> <pre><code>from application import settings, utils </code></pre> <p>or</p> <pre><code>from . import settings, utils </code></pre> <p>That is I can either specify the name as it is (here 'application') or I can say "current package" by using "."</p> <p>This is a Free software package so the possibility exists that someone wants to make a fork of my application and change its name. In that case, alternative 1 is a slight nuisance. Still, I use style 1 all the time (although early code uses style 2 in some places), since style 1 looks much better.</p> <p>Are there any arguments for my style (1) that I have missed? Or is it stupid not to go with style 2?</p>
4
2009-08-23T02:43:54Z
1,317,642
<p>The <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">Python Style Guide</a> recommends explicitly against relative imports (the . style):</p> <blockquote> <p>Relative imports for intra-package imports are highly discouraged. Always use the absolute package path for all imports. Even now that PEP 328 [7] is fully implemented in Python 2.5, its style of explicit relative imports is actively discouraged; absolute imports are more portable and usually more readable.</p> </blockquote> <p>I tend to agree. Relative imports mean the same module is imported in different ways in different files, and requires that I remember what I'm looking at when reading and writing. Not really worth it, and a rename can be done with <code>sed</code>.</p> <p>Besides the issue of renaming, the only problem with absolute imports is that <code>import foo</code> might mean the top-level module <code>foo</code> or a submodule <code>foo</code> beneath the current module. If this is a problem, you can use <code>from __future__ import absolute_import</code>; this is standard in Python 3.</p>
10
2009-08-23T02:57:34Z
[ "python" ]
How can I filter a date of a DateTimeField in Django?
1,317,714
<p>I am trying to filter a <code>DateTimeField</code> comparing with a date. I mean:</p> <pre><code>MyObject.objects.filter(datetime_attr=datetime.date(2009,8,22)) </code></pre> <p>I get an empty queryset list as an answer because (I think) I am not considering time, but I want "any time".</p> <p>Is there an easy way in Django for doing this?</p> <p>I have the time in the datetime setted, it is not <code>00:00</code>.</p>
112
2009-08-23T03:52:07Z
1,317,725
<pre><code>YourModel.objects.filter(datetime_published__year='2008', datetime_published__month='03', datetime_published__day='27') </code></pre> <p>// edit after comments</p> <pre><code>YourModel.objects.filter(datetime_published=datetime(2008, 03, 27)) </code></pre> <p>doest not work because it creates a datetime object with time values set to 0, so the time in database doesn't match.</p>
67
2009-08-23T04:02:35Z
[ "python", "django", "datetime", "filter", "django-queryset" ]
How can I filter a date of a DateTimeField in Django?
1,317,714
<p>I am trying to filter a <code>DateTimeField</code> comparing with a date. I mean:</p> <pre><code>MyObject.objects.filter(datetime_attr=datetime.date(2009,8,22)) </code></pre> <p>I get an empty queryset list as an answer because (I think) I am not considering time, but I want "any time".</p> <p>Is there an easy way in Django for doing this?</p> <p>I have the time in the datetime setted, it is not <code>00:00</code>.</p>
112
2009-08-23T03:52:07Z
1,317,737
<p>See the article <a href="http://www.djangoproject.com/documentation/models/lookup/" rel="nofollow">Django Documentation</a></p> <p>Its very similar to the JZ answer</p> <pre><code>ur_data_model.objects.filter(ur_date_field=datetime(2005, 7, 27) </code></pre>
0
2009-08-23T04:11:15Z
[ "python", "django", "datetime", "filter", "django-queryset" ]
How can I filter a date of a DateTimeField in Django?
1,317,714
<p>I am trying to filter a <code>DateTimeField</code> comparing with a date. I mean:</p> <pre><code>MyObject.objects.filter(datetime_attr=datetime.date(2009,8,22)) </code></pre> <p>I get an empty queryset list as an answer because (I think) I am not considering time, but I want "any time".</p> <p>Is there an easy way in Django for doing this?</p> <p>I have the time in the datetime setted, it is not <code>00:00</code>.</p>
112
2009-08-23T03:52:07Z
1,417,969
<pre><code>Model.objects.filter(datetime__year=2011, datetime__month=2, datetime__day=30) </code></pre>
0
2009-09-13T15:15:52Z
[ "python", "django", "datetime", "filter", "django-queryset" ]
How can I filter a date of a DateTimeField in Django?
1,317,714
<p>I am trying to filter a <code>DateTimeField</code> comparing with a date. I mean:</p> <pre><code>MyObject.objects.filter(datetime_attr=datetime.date(2009,8,22)) </code></pre> <p>I get an empty queryset list as an answer because (I think) I am not considering time, but I want "any time".</p> <p>Is there an easy way in Django for doing this?</p> <p>I have the time in the datetime setted, it is not <code>00:00</code>.</p>
112
2009-08-23T03:52:07Z
1,973,917
<p>Such lookups are implemented in <code>django.views.generic.date_based</code> as follows:</p> <pre><code>{'date_time_field__range': (datetime.datetime.combine(date, datetime.time.min), datetime.datetime.combine(date, datetime.time.max))} </code></pre> <p>Because it is quite verbose there are plans to improve the syntax using <code>__date</code> operator. Check "<a href="http://code.djangoproject.com/ticket/9596">#9596 Comparing a DateTimeField to a date is too hard</a>" for more details.</p>
90
2009-12-29T10:23:03Z
[ "python", "django", "datetime", "filter", "django-queryset" ]
How can I filter a date of a DateTimeField in Django?
1,317,714
<p>I am trying to filter a <code>DateTimeField</code> comparing with a date. I mean:</p> <pre><code>MyObject.objects.filter(datetime_attr=datetime.date(2009,8,22)) </code></pre> <p>I get an empty queryset list as an answer because (I think) I am not considering time, but I want "any time".</p> <p>Is there an easy way in Django for doing this?</p> <p>I have the time in the datetime setted, it is not <code>00:00</code>.</p>
112
2009-08-23T03:52:07Z
2,262,766
<p>This produces the same results as using __year, __month, and __day and seems to work for me:</p> <pre><code>YourModel.objects.filter(your_datetime_field__startswith=datetime.date(2009,8,22)) </code></pre>
22
2010-02-14T21:05:12Z
[ "python", "django", "datetime", "filter", "django-queryset" ]
How can I filter a date of a DateTimeField in Django?
1,317,714
<p>I am trying to filter a <code>DateTimeField</code> comparing with a date. I mean:</p> <pre><code>MyObject.objects.filter(datetime_attr=datetime.date(2009,8,22)) </code></pre> <p>I get an empty queryset list as an answer because (I think) I am not considering time, but I want "any time".</p> <p>Is there an easy way in Django for doing this?</p> <p>I have the time in the datetime setted, it is not <code>00:00</code>.</p>
112
2009-08-23T03:52:07Z
2,918,306
<p>Hm.. My solution is working:</p> <pre><code>Mymodel.objects.filter(date_time_field__startswith=datetime.datetime(1986, 7, 28)) </code></pre>
1
2010-05-27T03:38:27Z
[ "python", "django", "datetime", "filter", "django-queryset" ]
How can I filter a date of a DateTimeField in Django?
1,317,714
<p>I am trying to filter a <code>DateTimeField</code> comparing with a date. I mean:</p> <pre><code>MyObject.objects.filter(datetime_attr=datetime.date(2009,8,22)) </code></pre> <p>I get an empty queryset list as an answer because (I think) I am not considering time, but I want "any time".</p> <p>Is there an easy way in Django for doing this?</p> <p>I have the time in the datetime setted, it is not <code>00:00</code>.</p>
112
2009-08-23T03:52:07Z
9,414,681
<pre><code>Mymodel.objects.filter(date_time_field__contains=datetime.date(1986, 7, 28)) </code></pre> <p>the above is what I've used. Not only does it work, it also has some inherent logical backing.</p>
22
2012-02-23T14:11:08Z
[ "python", "django", "datetime", "filter", "django-queryset" ]
How can I filter a date of a DateTimeField in Django?
1,317,714
<p>I am trying to filter a <code>DateTimeField</code> comparing with a date. I mean:</p> <pre><code>MyObject.objects.filter(datetime_attr=datetime.date(2009,8,22)) </code></pre> <p>I get an empty queryset list as an answer because (I think) I am not considering time, but I want "any time".</p> <p>Is there an easy way in Django for doing this?</p> <p>I have the time in the datetime setted, it is not <code>00:00</code>.</p>
112
2009-08-23T03:52:07Z
11,174,559
<p>Here are the results I got with ipython's timeit function:</p> <pre><code>from datetime import date today = date.today() timeit[Model.objects.filter(date_created__year=today.year, date_created__month=today.month, date_created__day=today.day)] 1000 loops, best of 3: 652 us per loop timeit[Model.objects.filter(date_created__gte=today)] 1000 loops, best of 3: 631 us per loop timeit[Model.objects.filter(date_created__startswith=today)] 1000 loops, best of 3: 541 us per loop timeit[Model.objects.filter(date_created__contains=today)] 1000 loops, best of 3: 536 us per loop </code></pre> <p><strong>contains</strong> seems to be faster.</p>
51
2012-06-24T02:31:03Z
[ "python", "django", "datetime", "filter", "django-queryset" ]
How can I filter a date of a DateTimeField in Django?
1,317,714
<p>I am trying to filter a <code>DateTimeField</code> comparing with a date. I mean:</p> <pre><code>MyObject.objects.filter(datetime_attr=datetime.date(2009,8,22)) </code></pre> <p>I get an empty queryset list as an answer because (I think) I am not considering time, but I want "any time".</p> <p>Is there an easy way in Django for doing this?</p> <p>I have the time in the datetime setted, it is not <code>00:00</code>.</p>
112
2009-08-23T03:52:07Z
12,042,566
<p>Here is an interesting technique-- I leveraged the startswith procedure as implemented with Django on MySQL to achieve the result of only looking up a datetime through only the date. Basically, when Django does the lookup in the database it has to do a string conversion for the DATETIME MySQL storage object, so you can filter on that, leaving out the timestamp portion of the date-- that way %LIKE% matches only the date object and you'll get every timestamp for the given date. </p> <pre><code>datetime_filter = datetime(2009, 8, 22) MyObject.objects.filter(datetime_attr__startswith=datetime_filter.date()) </code></pre> <p>This will perform the following query:</p> <pre><code>SELECT (values) FROM myapp_my_object \ WHERE myapp_my_object.datetime_attr LIKE BINARY 2009-08-22% </code></pre> <p>The LIKE BINARY in this case will match everything for the date, no matter the timestamp. Including values like:</p> <pre><code>+---------------------+ | datetime_attr | +---------------------+ | 2009-08-22 11:05:08 | +---------------------+ </code></pre> <p>Hopefully this helps everyone until Django comes out with a solution!</p>
2
2012-08-20T17:54:36Z
[ "python", "django", "datetime", "filter", "django-queryset" ]
How can I filter a date of a DateTimeField in Django?
1,317,714
<p>I am trying to filter a <code>DateTimeField</code> comparing with a date. I mean:</p> <pre><code>MyObject.objects.filter(datetime_attr=datetime.date(2009,8,22)) </code></pre> <p>I get an empty queryset list as an answer because (I think) I am not considering time, but I want "any time".</p> <p>Is there an easy way in Django for doing this?</p> <p>I have the time in the datetime setted, it is not <code>00:00</code>.</p>
112
2009-08-23T03:52:07Z
17,351,397
<p>assuming active_on is a date object, increment it by 1 day then do range </p> <pre><code>next_day = active_on + datetime.timedelta(1) queryset = queryset.filter(date_created__range=(active_on, next_day) ) </code></pre>
6
2013-06-27T19:14:04Z
[ "python", "django", "datetime", "filter", "django-queryset" ]
How can I filter a date of a DateTimeField in Django?
1,317,714
<p>I am trying to filter a <code>DateTimeField</code> comparing with a date. I mean:</p> <pre><code>MyObject.objects.filter(datetime_attr=datetime.date(2009,8,22)) </code></pre> <p>I get an empty queryset list as an answer because (I think) I am not considering time, but I want "any time".</p> <p>Is there an easy way in Django for doing this?</p> <p>I have the time in the datetime setted, it is not <code>00:00</code>.</p>
112
2009-08-23T03:52:07Z
32,271,398
<p>Now Django has <a href="https://docs.djangoproject.com/en/dev/ref/models/querysets/#date">__date</a> queryset filter to query datetime objects against dates in development version. Thus, it will be available in 1.9 soon.</p>
7
2015-08-28T12:44:37Z
[ "python", "django", "datetime", "filter", "django-queryset" ]
How can I filter a date of a DateTimeField in Django?
1,317,714
<p>I am trying to filter a <code>DateTimeField</code> comparing with a date. I mean:</p> <pre><code>MyObject.objects.filter(datetime_attr=datetime.date(2009,8,22)) </code></pre> <p>I get an empty queryset list as an answer because (I think) I am not considering time, but I want "any time".</p> <p>Is there an easy way in Django for doing this?</p> <p>I have the time in the datetime setted, it is not <code>00:00</code>.</p>
112
2009-08-23T03:52:07Z
33,221,142
<p>There's a fantastic blogpost that covers this here: <a href="http://blog.zdsmith.com/comparing-dates-and-datetimes-in-the-django-orm.html" rel="nofollow">Comparing Dates and Datetimes in the Django ORM</a></p> <p>The best solution posted for Django>1.7,&lt;1.9 is to register a transform:</p> <pre class="lang-py prettyprint-override"><code>from django.db import models class MySQLDatetimeDate(models.Transform): """ This implements a custom SQL lookup when using `__date` with datetimes. To enable filtering on datetimes that fall on a given date, import this transform and register it with the DateTimeField. """ lookup_name = 'date' def as_sql(self, compiler, connection): lhs, params = compiler.compile(self.lhs) return 'DATE({})'.format(lhs), params @property def output_field(self): return models.DateField() </code></pre> <p>Then you can use it in your filters like this:</p> <pre><code>Foo.objects.filter(created_on__date=date) </code></pre> <p><strong>EDIT</strong></p> <p>This solution is definitely back end dependent. From the article:</p> <blockquote> <p>Of course, this implementation relies on your particular flavor of SQL having a DATE() function. MySQL does. So does SQLite. On the other hand, I haven’t worked with PostgreSQL personally, but some googling leads me to believe that it does not have a DATE() function. So an implementation this simple seems like it will necessarily be somewhat backend-dependent.</p> </blockquote>
0
2015-10-19T18:12:09Z
[ "python", "django", "datetime", "filter", "django-queryset" ]
How can I filter a date of a DateTimeField in Django?
1,317,714
<p>I am trying to filter a <code>DateTimeField</code> comparing with a date. I mean:</p> <pre><code>MyObject.objects.filter(datetime_attr=datetime.date(2009,8,22)) </code></pre> <p>I get an empty queryset list as an answer because (I think) I am not considering time, but I want "any time".</p> <p>Is there an easy way in Django for doing this?</p> <p>I have the time in the datetime setted, it is not <code>00:00</code>.</p>
112
2009-08-23T03:52:07Z
36,462,961
<p>As of Django 1.9, the way to do this is by using <a href="https://docs.djangoproject.com/en/1.9/ref/models/querysets/#date" rel="nofollow"><code>__date</code></a> on a datetime object.</p> <p>For example: <code>MyObject.objects.filter(datetime_attr__date=datetime.date(2009,8,22))</code></p>
2
2016-04-06T21:47:07Z
[ "python", "django", "datetime", "filter", "django-queryset" ]
How can I filter a date of a DateTimeField in Django?
1,317,714
<p>I am trying to filter a <code>DateTimeField</code> comparing with a date. I mean:</p> <pre><code>MyObject.objects.filter(datetime_attr=datetime.date(2009,8,22)) </code></pre> <p>I get an empty queryset list as an answer because (I think) I am not considering time, but I want "any time".</p> <p>Is there an easy way in Django for doing this?</p> <p>I have the time in the datetime setted, it is not <code>00:00</code>.</p>
112
2009-08-23T03:52:07Z
36,714,403
<p>In Django 1.7.6 works:</p> <pre><code>MyObject.objects.filter(datetime_attr__startswith=datetime.date(2009,8,22)) </code></pre>
0
2016-04-19T09:35:26Z
[ "python", "django", "datetime", "filter", "django-queryset" ]
How can I hide incompatible code from older Python versions?
1,317,946
<p>I'm writing unit tests for a function that takes both an <code>*args</code> and a <code>**kwargs</code> argument. A reasonable use-case for this function is using keyword arguments after the <code>*args</code> argment, i.e. of the form</p> <pre><code>def f(a, *b, **c): print a, b, c f(1, *(2, 3, 4), keyword=13) </code></pre> <p>Now this only <a href="http://docs.python.org/whatsnew/2.6.html#other-language-changes" rel="nofollow">became legal in Python 2.6</a>; in earlier versions the above line is a syntax error and so won't even compile to byte-code.</p> <p><strong>My question is:</strong> <em>How can I test the functionality provided in the newer Python version and still have the tests run for older Python versions?</em></p> <p>I should point out that the function itself works fine for earlier Python versions, it is only some invocations that are syntax errors before Python 2.6. The various methods I've seen for checking the Python version don't work for this as it doesn't get past the compilation stage.</p> <p>I would prefer not to have to split the tests into multiple files if at all possible.</p>
3
2009-08-23T06:59:55Z
1,317,951
<p>One approach might be to use <a href="http://docs.python.org/library/functions.html#eval" rel="nofollow"><code>eval()</code></a> or <a href="http://docs.python.org/reference/simple%5Fstmts.html#the-exec-statement" rel="nofollow"><code>exec</code></a> along with a test for the current version of Python. This will defer compilation to runtime, where you can control whether compilation actually happens or not.</p>
2
2009-08-23T07:03:25Z
[ "python", "unit-testing" ]
How can I hide incompatible code from older Python versions?
1,317,946
<p>I'm writing unit tests for a function that takes both an <code>*args</code> and a <code>**kwargs</code> argument. A reasonable use-case for this function is using keyword arguments after the <code>*args</code> argment, i.e. of the form</p> <pre><code>def f(a, *b, **c): print a, b, c f(1, *(2, 3, 4), keyword=13) </code></pre> <p>Now this only <a href="http://docs.python.org/whatsnew/2.6.html#other-language-changes" rel="nofollow">became legal in Python 2.6</a>; in earlier versions the above line is a syntax error and so won't even compile to byte-code.</p> <p><strong>My question is:</strong> <em>How can I test the functionality provided in the newer Python version and still have the tests run for older Python versions?</em></p> <p>I should point out that the function itself works fine for earlier Python versions, it is only some invocations that are syntax errors before Python 2.6. The various methods I've seen for checking the Python version don't work for this as it doesn't get past the compilation stage.</p> <p>I would prefer not to have to split the tests into multiple files if at all possible.</p>
3
2009-08-23T06:59:55Z
1,317,965
<p>I don't think you should be testing whether Python works correctly; instead, focus on testing your own code. In doing so, it is perfectly possible to write the specific invocation in a way that works for all Python versions, namely:</p> <pre><code>f(1, *(2,3,4), **{'keyword':13}) </code></pre>
11
2009-08-23T07:09:44Z
[ "python", "unit-testing" ]
How can I hide incompatible code from older Python versions?
1,317,946
<p>I'm writing unit tests for a function that takes both an <code>*args</code> and a <code>**kwargs</code> argument. A reasonable use-case for this function is using keyword arguments after the <code>*args</code> argment, i.e. of the form</p> <pre><code>def f(a, *b, **c): print a, b, c f(1, *(2, 3, 4), keyword=13) </code></pre> <p>Now this only <a href="http://docs.python.org/whatsnew/2.6.html#other-language-changes" rel="nofollow">became legal in Python 2.6</a>; in earlier versions the above line is a syntax error and so won't even compile to byte-code.</p> <p><strong>My question is:</strong> <em>How can I test the functionality provided in the newer Python version and still have the tests run for older Python versions?</em></p> <p>I should point out that the function itself works fine for earlier Python versions, it is only some invocations that are syntax errors before Python 2.6. The various methods I've seen for checking the Python version don't work for this as it doesn't get past the compilation stage.</p> <p>I would prefer not to have to split the tests into multiple files if at all possible.</p>
3
2009-08-23T06:59:55Z
1,318,050
<p>Why do you want to use such syntax? I mean, this 2.6 feature does not bring any real advantage other than shortcut.</p> <pre><code>a = [2,3,4] a.insert(0, 1) kw = {'keyword'='test'} f(*a, **kw) </code></pre>
1
2009-08-23T08:16:24Z
[ "python", "unit-testing" ]
How to do create_or_update in sqlobject?
1,318,001
<p>I'm using <a href="http://www.sqlobject.org/" rel="nofollow">SQLobject</a> and so far was not able to find a elegant solution for "update row in the db or vreate a new one if it doesn't exist.</p> <p>Currently I use following somewhat convoluted code:</p> <pre><code>args = dict(artnr=artnr, name=name, hersteller='?', hersteller_name='?') if cs.datamart.ArtNrNameHersteller.selectBy(artnr=artnr).count(): row = cs.datamart.ArtNrNameHersteller.selectBy(artnr=artnr)[0] row.set(**args) else: cs.datamart.ArtNrNameHersteller(**args) </code></pre> <p>Obviously this is far from bening consise, robust, elegant or fast. What is <em>the correct way</em>(TM) to do this?</p>
2
2009-08-23T07:34:59Z
1,318,165
<p>I don't know of any special way to do it, when you really don't know in advance whether it's a create or update. There's certainly no special SQL syntax that can do this efficiently(*), so any implementation provided would essentially be doing the same as your code.</p> <p>(*: well, MySQL has the ON DUPLICATE KEY UPDATE and REPLACE mechanisms, but they trigger on any UNIQUE key match not just the primary key, which can be a bit dangerous; and Oracle has the ugly-as-sin MERGE statement. But these are non-standard extensions SQLObject can't really use.)</p>
1
2009-08-23T09:38:35Z
[ "python", "coding-style", "sqlobject" ]
Why is the Borg pattern better than the Singleton pattern in Python
1,318,406
<p>Why is the <a href="http://code.activestate.com/recipes/66531/">Borg pattern</a> better than the <a href="http://stackoverflow.com/questions/31875/is-there-a-simple-elegant-way-to-define-singletons-in-python">Singleton pattern</a>?</p> <p>I ask because I don't see them resulting in anything different.</p> <p>Borg:</p> <pre><code>class Borg: __shared_state = {} # init internal state variables here __register = {} def __init__(self): self.__dict__ = self.__shared_state if not self.__register: self._init_default_register() </code></pre> <p>Singleton:</p> <pre><code>class Singleton: def __init__(self): # init internal state variables here self.__register = {} self._init_default_register() # singleton mechanics external to class, for example this in the module Singleton = Singleton() </code></pre> <p>What I want to display here is that the service object, whether implemented as Borg or Singleton, has a nontrivial internal state (it provides some service based on it) (I mean it has to be something useful it's not a Singleton/Borg just for fun).</p> <p>And this state has to be inited. Here the Singleton implementation is more straightforward, since we treat <strong>init</strong> as the set-up of the global state. I find it awkward that the Borg object has to query its internal state to see if it should update itself.</p> <p>It becomes worse the more internal state you have. For example, if the object has to listen to the Application's teardown signal to save its register to disk, that registration should only be done once as well, and this is easier with a Singleton.</p>
50
2009-08-23T12:01:43Z
1,318,426
<p>It is not. What is generally not recommended is a pattern like this in python:</p> <pre><code>class Singleton(object): _instance = None def __init__(self, ...): ... @classmethod def instance(cls): if cls._instance is None: cls._instance = cls(...) return cls._instance </code></pre> <p>where you use a class method to get the instance instead of the constructor. Python's metaprogramming allows much better methods, e.g. the one on <a href="https://en.wikipedia.org/w/index.php?title=Singleton_pattern&amp;oldid=368154154#Python" rel="nofollow">Wikipedia</a>:</p> <pre><code>class Singleton(type): def __init__(cls, name, bases, dict): super(Singleton, cls).__init__(name, bases, dict) cls.instance = None def __call__(cls, *args, **kw): if cls.instance is None: cls.instance = super(Singleton, cls).__call__(*args, **kw) return cls.instance class MyClass(object): __metaclass__ = Singleton print MyClass() print MyClass() </code></pre>
10
2009-08-23T12:13:06Z
[ "python", "singleton" ]
Why is the Borg pattern better than the Singleton pattern in Python
1,318,406
<p>Why is the <a href="http://code.activestate.com/recipes/66531/">Borg pattern</a> better than the <a href="http://stackoverflow.com/questions/31875/is-there-a-simple-elegant-way-to-define-singletons-in-python">Singleton pattern</a>?</p> <p>I ask because I don't see them resulting in anything different.</p> <p>Borg:</p> <pre><code>class Borg: __shared_state = {} # init internal state variables here __register = {} def __init__(self): self.__dict__ = self.__shared_state if not self.__register: self._init_default_register() </code></pre> <p>Singleton:</p> <pre><code>class Singleton: def __init__(self): # init internal state variables here self.__register = {} self._init_default_register() # singleton mechanics external to class, for example this in the module Singleton = Singleton() </code></pre> <p>What I want to display here is that the service object, whether implemented as Borg or Singleton, has a nontrivial internal state (it provides some service based on it) (I mean it has to be something useful it's not a Singleton/Borg just for fun).</p> <p>And this state has to be inited. Here the Singleton implementation is more straightforward, since we treat <strong>init</strong> as the set-up of the global state. I find it awkward that the Borg object has to query its internal state to see if it should update itself.</p> <p>It becomes worse the more internal state you have. For example, if the object has to listen to the Application's teardown signal to save its register to disk, that registration should only be done once as well, and this is easier with a Singleton.</p>
50
2009-08-23T12:01:43Z
1,318,427
<p>A class basically describes how you can access (read/write) the internal state of your object.</p> <p>In the singleton pattern you can only have a single class, i.e. all your objects will give you the same access points to the shared state. This means that if you have to provide an extended API, you will need to write a wrapper, wrapping around the singleton</p> <p>In the borg pattern you are able to extend the base "borg" class, and thereby more conveniently extend the API for your taste.</p>
5
2009-08-23T12:13:17Z
[ "python", "singleton" ]
Why is the Borg pattern better than the Singleton pattern in Python
1,318,406
<p>Why is the <a href="http://code.activestate.com/recipes/66531/">Borg pattern</a> better than the <a href="http://stackoverflow.com/questions/31875/is-there-a-simple-elegant-way-to-define-singletons-in-python">Singleton pattern</a>?</p> <p>I ask because I don't see them resulting in anything different.</p> <p>Borg:</p> <pre><code>class Borg: __shared_state = {} # init internal state variables here __register = {} def __init__(self): self.__dict__ = self.__shared_state if not self.__register: self._init_default_register() </code></pre> <p>Singleton:</p> <pre><code>class Singleton: def __init__(self): # init internal state variables here self.__register = {} self._init_default_register() # singleton mechanics external to class, for example this in the module Singleton = Singleton() </code></pre> <p>What I want to display here is that the service object, whether implemented as Borg or Singleton, has a nontrivial internal state (it provides some service based on it) (I mean it has to be something useful it's not a Singleton/Borg just for fun).</p> <p>And this state has to be inited. Here the Singleton implementation is more straightforward, since we treat <strong>init</strong> as the set-up of the global state. I find it awkward that the Borg object has to query its internal state to see if it should update itself.</p> <p>It becomes worse the more internal state you have. For example, if the object has to listen to the Application's teardown signal to save its register to disk, that registration should only be done once as well, and this is easier with a Singleton.</p>
50
2009-08-23T12:01:43Z
1,318,444
<p>The real reason that borg is different comes down to subclassing.</p> <p>If you subclass a borg, the subclass' objects have the same state as their parents classes objects, unless you explicitly override the shared state in that subclass. Each subclass of the singleton pattern has its own state and therefore will produce different objects.</p> <p>Also in the singleton pattern the objects are actually the same, not just the state (even though the state is the only thing that really matters).</p>
40
2009-08-23T12:22:22Z
[ "python", "singleton" ]
Why is the Borg pattern better than the Singleton pattern in Python
1,318,406
<p>Why is the <a href="http://code.activestate.com/recipes/66531/">Borg pattern</a> better than the <a href="http://stackoverflow.com/questions/31875/is-there-a-simple-elegant-way-to-define-singletons-in-python">Singleton pattern</a>?</p> <p>I ask because I don't see them resulting in anything different.</p> <p>Borg:</p> <pre><code>class Borg: __shared_state = {} # init internal state variables here __register = {} def __init__(self): self.__dict__ = self.__shared_state if not self.__register: self._init_default_register() </code></pre> <p>Singleton:</p> <pre><code>class Singleton: def __init__(self): # init internal state variables here self.__register = {} self._init_default_register() # singleton mechanics external to class, for example this in the module Singleton = Singleton() </code></pre> <p>What I want to display here is that the service object, whether implemented as Borg or Singleton, has a nontrivial internal state (it provides some service based on it) (I mean it has to be something useful it's not a Singleton/Borg just for fun).</p> <p>And this state has to be inited. Here the Singleton implementation is more straightforward, since we treat <strong>init</strong> as the set-up of the global state. I find it awkward that the Borg object has to query its internal state to see if it should update itself.</p> <p>It becomes worse the more internal state you have. For example, if the object has to listen to the Application's teardown signal to save its register to disk, that registration should only be done once as well, and this is easier with a Singleton.</p>
50
2009-08-23T12:01:43Z
1,318,542
<p>It's only better in those few cases where you actually have a difference. Like when you subclass. The Borg pattern is extremely unusual, I've never needed it for real in ten years of Python programming.</p>
5
2009-08-23T13:24:43Z
[ "python", "singleton" ]
Why is the Borg pattern better than the Singleton pattern in Python
1,318,406
<p>Why is the <a href="http://code.activestate.com/recipes/66531/">Borg pattern</a> better than the <a href="http://stackoverflow.com/questions/31875/is-there-a-simple-elegant-way-to-define-singletons-in-python">Singleton pattern</a>?</p> <p>I ask because I don't see them resulting in anything different.</p> <p>Borg:</p> <pre><code>class Borg: __shared_state = {} # init internal state variables here __register = {} def __init__(self): self.__dict__ = self.__shared_state if not self.__register: self._init_default_register() </code></pre> <p>Singleton:</p> <pre><code>class Singleton: def __init__(self): # init internal state variables here self.__register = {} self._init_default_register() # singleton mechanics external to class, for example this in the module Singleton = Singleton() </code></pre> <p>What I want to display here is that the service object, whether implemented as Borg or Singleton, has a nontrivial internal state (it provides some service based on it) (I mean it has to be something useful it's not a Singleton/Borg just for fun).</p> <p>And this state has to be inited. Here the Singleton implementation is more straightforward, since we treat <strong>init</strong> as the set-up of the global state. I find it awkward that the Borg object has to query its internal state to see if it should update itself.</p> <p>It becomes worse the more internal state you have. For example, if the object has to listen to the Application's teardown signal to save its register to disk, that registration should only be done once as well, and this is easier with a Singleton.</p>
50
2009-08-23T12:01:43Z
20,809,695
<p>In python if you want a unique "object" that you can access from anywhere just create a class <code>Unique</code> that only contains static attributes, <code>@staticmethod</code>s, and <code>@classmethod</code>s; you could call it the Unique Pattern. Here I implement and compare the 3 patterns:</p> <p>Unique</p> <pre><code>#Unique Pattern class Unique: #Define some static variables here x = 1 @classmethod def init(cls): #Define any computation performed when assigning to a "new" object return cls </code></pre> <p>Singleton</p> <pre><code>#Singleton Pattern class Singleton: __single = None def __init__(self): if not Singleton.__single: #Your definitions here self.x = 1 else: raise RuntimeError('A Singleton already exists') @classmethod def getInstance(cls): if not cls.__single: cls.__single = Singleton() return cls.__single </code></pre> <p>Borg</p> <pre><code>#Borg Pattern class Borg: __monostate = None def __init__(self): if not Borg.__monostate: Borg.__monostate = self.__dict__ #Your definitions here self.x = 1 else: self.__dict__ = Borg.__monostate </code></pre> <p>Test</p> <pre><code>#SINGLETON print "\nSINGLETON\n" A = Singleton.getInstance() B = Singleton.getInstance() print "At first B.x = {} and A.x = {}".format(B.x,A.x) A.x = 2 print "After A.x = 2" print "Now both B.x = {} and A.x = {}\n".format(B.x,A.x) print "Are A and B the same object? Answer: {}".format(id(A)==id(B)) #BORG print "\nBORG\n" A = Borg() B = Borg() print "At first B.x = {} and A.x = {}".format(B.x,A.x) A.x = 2 print "After A.x = 2" print "Now both B.x = {} and A.x = {}\n".format(B.x,A.x) print "Are A and B the same object? Answer: {}".format(id(A)==id(B)) #UNIQUE print "\nUNIQUE\n" A = Unique.init() B = Unique.init() print "At first B.x = {} and A.x = {}".format(B.x,A.x) A.x = 2 print "After A.x = 2" print "Now both B.x = {} and A.x = {}\n".format(B.x,A.x) print "Are A and B the same object? Answer: {}".format(id(A)==id(B)) </code></pre> <p>Output:</p> <blockquote> <p>SINGLETON</p> <pre><code>At first B.x = 1 and A.x = 1 After A.x = 2 Now both B.x = 2 and A.x = 2 Are A and B the same object? Answer: True BORG At first B.x = 1 and A.x = 1 After A.x = 2 Now both B.x = 2 and A.x = 2 Are A and B the same object? Answer: False UNIQUE At first B.x = 1 and A.x = 1 After A.x = 2 Now both B.x = 2 and A.x = 2 Are A and B the same object? Answer: True </code></pre> </blockquote> <p>In my opinion, Unique implementation is the easiest, then Borg and finally Singleton with an ugly number of two functions needed for its definition.</p>
11
2013-12-28T00:30:55Z
[ "python", "singleton" ]
In pdb how do you reset the list (l) command line count?
1,318,676
<p>From PDB</p> <pre><code>(Pdb) help l l(ist) [first [,last]] List source code for the current file. Without arguments, list 11 lines around the current line or continue the previous listing. With one argument, list 11 lines starting at that line. With two arguments, list the given range; if the second argument is less than the first, it is a count. </code></pre> <p>The "continue the previous listing" feature is really nice, but how do you turn it off?</p>
22
2009-08-23T14:13:40Z
1,318,787
<p>I don't think there is a way to turn it off. It's annoyed me enough that once I went looking in the pdb source to see if there was an undocumented syntax, but I didn't find any. </p> <p>There really needs to be a syntax that means, "List the lines near the current execution pointer."</p>
3
2009-08-23T15:11:03Z
[ "python", "pdb" ]
In pdb how do you reset the list (l) command line count?
1,318,676
<p>From PDB</p> <pre><code>(Pdb) help l l(ist) [first [,last]] List source code for the current file. Without arguments, list 11 lines around the current line or continue the previous listing. With one argument, list 11 lines starting at that line. With two arguments, list the given range; if the second argument is less than the first, it is a count. </code></pre> <p>The "continue the previous listing" feature is really nice, but how do you turn it off?</p>
22
2009-08-23T14:13:40Z
1,324,264
<p>You could <a href="http://en.wikipedia.org/wiki/Monkey%5Fpatch" rel="nofollow">monkey patch</a> it for the behavior you want. For example, here is a full script which adds a "reset_list" or "rl" command to pdb:</p> <pre><code>import pdb def Pdb_reset_list(self, arg): self.lineno = None print &gt;&gt;self.stdout, "Reset list position." pdb.Pdb.do_reset = Pdb_reset_list pdb.Pdb.do_rl = Pdb_reset_list a = 1 b = 2 pdb.set_trace() print a, b </code></pre> <p>One could conceivably monkey patch the standard <code>list</code> command to not retain the lineno history.</p> <p><em>edit:</em> And here is such a patch:</p> <pre><code>import pdb Pdb = pdb.Pdb Pdb._do_list = Pdb.do_list def pdb_list_wrapper(self, arg): if arg.strip().lower() in ('r', 'reset', 'c', 'current'): self.lineno = None arg = '' self._do_list(arg) Pdb.do_list = Pdb.do_l = pdb_list_wrapper a = 1 b = 2 pdb.set_trace() print a, b </code></pre>
3
2009-08-24T19:31:39Z
[ "python", "pdb" ]
In pdb how do you reset the list (l) command line count?
1,318,676
<p>From PDB</p> <pre><code>(Pdb) help l l(ist) [first [,last]] List source code for the current file. Without arguments, list 11 lines around the current line or continue the previous listing. With one argument, list 11 lines starting at that line. With two arguments, list the given range; if the second argument is less than the first, it is a count. </code></pre> <p>The "continue the previous listing" feature is really nice, but how do you turn it off?</p>
22
2009-08-23T14:13:40Z
2,336,019
<p>If you use <a href="http://bitbucket.org/dugan/epdb/" rel="nofollow" title="Enhanced Python DeBugger">epdb</a> instead of pdb, you can use "l" to go forward like in pdb, but then "l." goes back to the current line number, and "l-" goes backwards through the file. You can also use until # to continue until a given line. Epdb offers a bunch of other niceties too. Need to debug remotely? Try <code>serve()</code> instead of <code>set_trace()</code> and then telnet in (port 8080 is the default port).</p> <pre><code>import epdb epdb.serve() </code></pre>
4
2010-02-25T17:15:46Z
[ "python", "pdb" ]
In pdb how do you reset the list (l) command line count?
1,318,676
<p>From PDB</p> <pre><code>(Pdb) help l l(ist) [first [,last]] List source code for the current file. Without arguments, list 11 lines around the current line or continue the previous listing. With one argument, list 11 lines starting at that line. With two arguments, list the given range; if the second argument is less than the first, it is a count. </code></pre> <p>The "continue the previous listing" feature is really nice, but how do you turn it off?</p>
22
2009-08-23T14:13:40Z
11,848,010
<p>Late but hopefully still helpful. In pdb, make the following alias (which you can add to your .pdbrc file so it's always available): </p> <pre><code>alias ll u;;d;;l </code></pre> <p>Then whenever you type <code>ll</code>, pdb will list from the current position. It works by going up the stack and then down the stack, which resets 'l' to show from the current position. (This won't work if you are at the top of the stack trace.)</p>
13
2012-08-07T14:18:25Z
[ "python", "pdb" ]
Ctypes pro and con
1,318,736
<p>I have heard that Ctypes can cause crashes (or stop errors) in Python and windows. Should I stay away from their use? Where did I hear? It was back when I tried to control various aspects of windows, automation, that sort of thing.</p> <p>I hear of swig, but I see Ctypes more often than not. Any danger here? If so, what should I watch out for?</p> <p>I did search for ctype pro con python.</p>
7
2009-08-23T14:45:21Z
1,318,740
<p>ctypes is a safe module to use, if you use it right.</p> <p>Some libraries provide a lower level access to things, some modules simply allow you to shoot yourself in the foot. So naturally some modules are more dangerous than others. This doesn't mean you should not use them though!</p> <p>You probably heard someone referring to something like this:</p> <pre><code>#Crash python interpreter from ctypes import * def crashme(): c = c_char('x') p = pointer(c) i = 0 while True: p[i] = 'x' i += 1 </code></pre> <p>The python interpreter crashing is different than just the python code itself erroring out with a runtime error. For example infinite recursion with a default recursion limit set would cause a runtime error but the python interpreter would still be alive afterwards. </p> <p>Another good example of this is with the sys module. You wouldn't stop using the sys module though because it can crash the python interpreter. </p> <pre><code>import sys sys.setrecursionlimit(2**30) def f(x): f(x+1) #This will cause no more resources left and then crash the python interpreter f(1) </code></pre> <p>There are many libraries as well that provide lower level access. For example the The gc module can be manipulated to give access to partially constructed object, accessing fields of which can cause crashes.</p> <p>Reference and ideas taken from: <a href="http://wiki.python.org/moin/CrashingPython">Crashing Python</a></p>
5
2009-08-23T14:47:29Z
[ "python", "winapi", "ctypes" ]
Ctypes pro and con
1,318,736
<p>I have heard that Ctypes can cause crashes (or stop errors) in Python and windows. Should I stay away from their use? Where did I hear? It was back when I tried to control various aspects of windows, automation, that sort of thing.</p> <p>I hear of swig, but I see Ctypes more often than not. Any danger here? If so, what should I watch out for?</p> <p>I did search for ctype pro con python.</p>
7
2009-08-23T14:45:21Z
1,318,763
<p><code>ctypes</code> can indeed cause crashes, if the C library you're using can <em>already</em> cause crashes.</p> <p>If anything, <code>ctypes</code> can help reduce crashes, because you can enforce runtime type safety with <a href="http://docs.python.org/library/ctypes.html#specifying-the-required-argument-types-function-prototypes" rel="nofollow">the <code>argtypes</code> property</a> on C functions using <code>ctypes</code>.</p> <p>But if your C library is already stable and tested, there is absolutely no reason not to use <code>ctypes</code> if it performs what you need in terms of bringing C and Python together.</p>
3
2009-08-23T14:58:05Z
[ "python", "winapi", "ctypes" ]
Ctypes pro and con
1,318,736
<p>I have heard that Ctypes can cause crashes (or stop errors) in Python and windows. Should I stay away from their use? Where did I hear? It was back when I tried to control various aspects of windows, automation, that sort of thing.</p> <p>I hear of swig, but I see Ctypes more often than not. Any danger here? If so, what should I watch out for?</p> <p>I did search for ctype pro con python.</p>
7
2009-08-23T14:45:21Z
1,319,150
<p>In terms of robustness, I still think swig is somewhat superior to ctypes, because it's possible to have a C compiler check things more thoroughly for you; however, this is pretty moot by now (while it loomed larger in earlier ctypes versons), thanks to the <code>argtypes</code> feature @Mark already mentioned. However, there is no doubt that the runtime overhead IS much more significant for ctypes than for swig (and sip and boost python and other "wrapping" approaches): so, I think of ctypes as a convenient way to reach for a few functions within a DLL when the calls happen outside of a key bottleneck, not as a way to make large C libraries available to Python in performance-critical situations.</p> <p>For a nice middle way between the runtime performance of swig (&amp;c) and the convenience of ctypes, with the added bonus of being able to add more code that can use a subset of Python syntax yet run at just about C-code speeds, also consider <a href="http://cython.org/">Cython</a> -- a python-like language that compiles down to C and is specialized for writing Python-callable extensions and wrapping C libraries (including ones that may be available only as static libraries, not DLLs: ctypes wouldn't let you play with <em>those</em>;-).</p>
13
2009-08-23T18:00:05Z
[ "python", "winapi", "ctypes" ]
Ctypes pro and con
1,318,736
<p>I have heard that Ctypes can cause crashes (or stop errors) in Python and windows. Should I stay away from their use? Where did I hear? It was back when I tried to control various aspects of windows, automation, that sort of thing.</p> <p>I hear of swig, but I see Ctypes more often than not. Any danger here? If so, what should I watch out for?</p> <p>I did search for ctype pro con python.</p>
7
2009-08-23T14:45:21Z
1,319,638
<p>I highly suggest you look into reading this book:</p> <p><a href="http://rads.stackoverflow.com/amzn/click/1593271921" rel="nofollow">Gray Hat Python: Python Programming for Hackers and Reverse Engineers</a></p> <p>The book functions as an in-depth tutorial for the ctypes library, and shows you how to run incredibly low-level code</p>
2
2009-08-23T21:38:12Z
[ "python", "winapi", "ctypes" ]
Django i18n and python locales (and dates)
1,318,744
<p>I've been playing with Django's i18n system and it seems to be mostly working. However, dates in model code seem to be causing a problem.</p> <p>I use datetime.strftime to populate a few CHOICES tuples which are then used in forms. </p> <p>From what I understood, django will set the locale to the user's choice so that datetime.strftime() will output in the appropriate language, but this doesn't seem to happen.</p> <p>What am I missing here?</p> <p>If I set the locale manually (eg. locale.setlocale(locale.LC_TIME,'de_DE.UTF-8') ) datetime does translate correctly. </p> <p>Thanks,</p> <p>Tom</p>
5
2009-08-23T14:50:01Z
1,321,102
<p>Django does not set locale for translation, just loads translation catalog. To get desired effect you have either set locale (which is not a good option since it works process-wide) or use specialized library. I recommend <a href="http://babel.edgewall.org/" rel="nofollow">Babel</a> which has nice Django integration.</p>
3
2009-08-24T08:23:50Z
[ "python", "django", "internationalization" ]
Django i18n and python locales (and dates)
1,318,744
<p>I've been playing with Django's i18n system and it seems to be mostly working. However, dates in model code seem to be causing a problem.</p> <p>I use datetime.strftime to populate a few CHOICES tuples which are then used in forms. </p> <p>From what I understood, django will set the locale to the user's choice so that datetime.strftime() will output in the appropriate language, but this doesn't seem to happen.</p> <p>What am I missing here?</p> <p>If I set the locale manually (eg. locale.setlocale(locale.LC_TIME,'de_DE.UTF-8') ) datetime does translate correctly. </p> <p>Thanks,</p> <p>Tom</p>
5
2009-08-23T14:50:01Z
5,457,952
<p>I've recently faced similar problem but managed to solve the problem by using <a href="http://code.djangoproject.com/browser/django/trunk/django/utils/dateformat.py#L282" rel="nofollow">format</a> instead of the python <code>strftime</code></p>
1
2011-03-28T10:55:00Z
[ "python", "django", "internationalization" ]
Python list filtering: remove subsets from list of lists
1,318,935
<p>Using Python how do you reduce a list of lists by an ordered subset match <code>[[..],[..],..]</code>? </p> <p>In the context of this question a list L is a <strong><em>subset</em></strong> of list <code>M</code> if <code>M</code> contains all members of <code>L</code>, and in the same order. For example, the list [1,2] is a subset of the list [1,2,3], but not of the list [2,1,3].</p> <p><em>Example input:</em></p> <pre><code>a. [[1, 2, 4, 8], [1, 2, 4, 5, 6], [1, 2, 3], [2, 3, 21], [1, 2, 3, 4], [1, 2, 3, 4, 5, 6, 7]] b. [[2, 16, 17], [1, 2, 3, 4, 5, 6, 7], [1], [1, 2, 3, 4], [1, 2], [17, 18, 19, 22, 41, 48], [2, 3], [1, 2, 3], [50, 69], [1, 2, 3], [2, 3, 21], [1, 2, 3], [1, 2, 4, 8], [1, 2, 4, 5, 6]] </code></pre> <p><em>Expected result:</em></p> <pre><code>a. [[1, 2, 4, 8], [2, 3, 21], [1, 2, 3, 4, 5, 6, 7]] b. [[2, 16, 17], [1, 2, 3, 4, 5, 6, 7], [17, 18, 19, 22, 41, 48], [50, 69], [2, 3, 21], [1, 2, 4, 8], [1, 2, 4, 5, 6]] </code></pre> <p><em>Further Examples:</em></p> <p><code>L = [[1, 2, 3, 4, 5, 6, 7], [1, 2, 5, 6]]</code> - No reduce</p> <p><code>L = [[1, 2, 3, 4, 5, 6, 7],</code> <strike><code>[1, 2, 3]</code></strike>, <code>[1, 2, 4, 8]]</code> - Yes reduce</p> <p><code>L = [[1, 2, 3, 4, 5, 6, 7], [7, 6, 5, 4, 3, 2, 1]]</code> - No reduce</p> <p><em>(Sorry for causing confusion with the incorrect data set.)</em></p>
7
2009-08-23T16:23:20Z
1,318,955
<p>Edit: I really need to improve my reading comprehension. Here's the answer to what was actually asked. It exploits the fact that "<code>A is super of B</code>" implies "<code>len(A) &gt; len(B) or A == B</code>". </p> <pre><code>def advance_to(it, value): """Advances an iterator until it matches the given value. Returns False if not found.""" for item in it: if item == value: return True return False def has_supersequence(seq, super_sequences): """Checks if the given sequence has a supersequence in the list of supersequences.""" candidates = map(iter, super_sequences) for next_item in seq: candidates = [seq for seq in candidates if advance_to(seq, next_item)] return len(candidates) &gt; 0 def find_supersequences(sequences): """Finds the supersequences in the given list of sequences. Sequence A is a supersequence of sequence B if B can be created by removing items from A.""" super_seqs = [] for candidate in sorted(sequences, key=len, reverse=True): if not has_supersequence(candidate, super_seqs): super_seqs.append(candidate) return super_seqs print(find_supersequences([[1, 2, 4, 8], [1, 2, 4, 5, 6], [1, 2, 3], [2, 3, 21], [1, 2, 3, 4], [1, 2, 3, 4, 5, 6, 7]])) #Output: [[1, 2, 3, 4, 5, 6, 7], [1, 2, 4, 8], [2, 3, 21]] </code></pre> <p>If you need to also preserve the original order of the sequences, then the <code>find_supersequences()</code> function needs to keep track of the positions of the sequences and sort the output afterwards.</p>
0
2009-08-23T16:34:34Z
[ "python", "list" ]
Python list filtering: remove subsets from list of lists
1,318,935
<p>Using Python how do you reduce a list of lists by an ordered subset match <code>[[..],[..],..]</code>? </p> <p>In the context of this question a list L is a <strong><em>subset</em></strong> of list <code>M</code> if <code>M</code> contains all members of <code>L</code>, and in the same order. For example, the list [1,2] is a subset of the list [1,2,3], but not of the list [2,1,3].</p> <p><em>Example input:</em></p> <pre><code>a. [[1, 2, 4, 8], [1, 2, 4, 5, 6], [1, 2, 3], [2, 3, 21], [1, 2, 3, 4], [1, 2, 3, 4, 5, 6, 7]] b. [[2, 16, 17], [1, 2, 3, 4, 5, 6, 7], [1], [1, 2, 3, 4], [1, 2], [17, 18, 19, 22, 41, 48], [2, 3], [1, 2, 3], [50, 69], [1, 2, 3], [2, 3, 21], [1, 2, 3], [1, 2, 4, 8], [1, 2, 4, 5, 6]] </code></pre> <p><em>Expected result:</em></p> <pre><code>a. [[1, 2, 4, 8], [2, 3, 21], [1, 2, 3, 4, 5, 6, 7]] b. [[2, 16, 17], [1, 2, 3, 4, 5, 6, 7], [17, 18, 19, 22, 41, 48], [50, 69], [2, 3, 21], [1, 2, 4, 8], [1, 2, 4, 5, 6]] </code></pre> <p><em>Further Examples:</em></p> <p><code>L = [[1, 2, 3, 4, 5, 6, 7], [1, 2, 5, 6]]</code> - No reduce</p> <p><code>L = [[1, 2, 3, 4, 5, 6, 7],</code> <strike><code>[1, 2, 3]</code></strike>, <code>[1, 2, 4, 8]]</code> - Yes reduce</p> <p><code>L = [[1, 2, 3, 4, 5, 6, 7], [7, 6, 5, 4, 3, 2, 1]]</code> - No reduce</p> <p><em>(Sorry for causing confusion with the incorrect data set.)</em></p>
7
2009-08-23T16:23:20Z
1,319,048
<pre><code>list0=[[1, 2, 4, 8], [1, 2, 4, 5, 6], [1, 2, 3], [2, 3, 21], [1, 2, 3, 4], [1, 2, 3, 4, 5, 6, 7]] for list1 in list0[:]: for list2 in list0: if list2!=list1: len1=len(list1) c=0 for n in list2: if n==list1[c]: c+=1 if c==len1: list0.remove(list1) break </code></pre> <p>This filters list0 in place using a copy of it. This is good if the result is expected to be about the same size as the original, there is only a few "subset" to remove.</p> <p>If the result is expected to be small and the original is large, you might prefer this one who is more memory freindly as it doesn't copy the original list.</p> <pre><code>list0=[[1, 2, 4, 8], [1, 2, 4, 5, 6], [1, 2, 3], [2, 3, 21], [1, 2, 3, 4], [1, 2, 3, 4, 5, 6, 7]] result=[] for list1 in list0: subset=False for list2 in list0: if list2!=list1: len1=len(list1) c=0 for n in list2: if n==list1[c]: c+=1 if c==len1: subset=True break if subset: break if not subset: result.append(list1) </code></pre>
0
2009-08-23T17:18:17Z
[ "python", "list" ]
Python list filtering: remove subsets from list of lists
1,318,935
<p>Using Python how do you reduce a list of lists by an ordered subset match <code>[[..],[..],..]</code>? </p> <p>In the context of this question a list L is a <strong><em>subset</em></strong> of list <code>M</code> if <code>M</code> contains all members of <code>L</code>, and in the same order. For example, the list [1,2] is a subset of the list [1,2,3], but not of the list [2,1,3].</p> <p><em>Example input:</em></p> <pre><code>a. [[1, 2, 4, 8], [1, 2, 4, 5, 6], [1, 2, 3], [2, 3, 21], [1, 2, 3, 4], [1, 2, 3, 4, 5, 6, 7]] b. [[2, 16, 17], [1, 2, 3, 4, 5, 6, 7], [1], [1, 2, 3, 4], [1, 2], [17, 18, 19, 22, 41, 48], [2, 3], [1, 2, 3], [50, 69], [1, 2, 3], [2, 3, 21], [1, 2, 3], [1, 2, 4, 8], [1, 2, 4, 5, 6]] </code></pre> <p><em>Expected result:</em></p> <pre><code>a. [[1, 2, 4, 8], [2, 3, 21], [1, 2, 3, 4, 5, 6, 7]] b. [[2, 16, 17], [1, 2, 3, 4, 5, 6, 7], [17, 18, 19, 22, 41, 48], [50, 69], [2, 3, 21], [1, 2, 4, 8], [1, 2, 4, 5, 6]] </code></pre> <p><em>Further Examples:</em></p> <p><code>L = [[1, 2, 3, 4, 5, 6, 7], [1, 2, 5, 6]]</code> - No reduce</p> <p><code>L = [[1, 2, 3, 4, 5, 6, 7],</code> <strike><code>[1, 2, 3]</code></strike>, <code>[1, 2, 4, 8]]</code> - Yes reduce</p> <p><code>L = [[1, 2, 3, 4, 5, 6, 7], [7, 6, 5, 4, 3, 2, 1]]</code> - No reduce</p> <p><em>(Sorry for causing confusion with the incorrect data set.)</em></p>
7
2009-08-23T16:23:20Z
1,319,050
<p>This seems to work:</p> <pre><code>original=[[1, 2, 4, 8], [1, 2, 4, 5, 6], [1, 2, 3], [2, 3, 21], [1, 2, 3, 4], [1, 2, 3, 4, 5, 6, 7]] target=[[1, 2, 4, 8], [2, 3, 21], [1, 2, 3, 4, 5, 6, 7]] class SetAndList: def __init__(self,aList): self.list=aList self.set=set(aList) self.isUnique=True def compare(self,aList): s=set(aList) if self.set.issubset(s): #print self.list,'superceded by',aList self.isUnique=False def listReduce(lists): temp=[] for l in lists: for t in temp: t.compare(l) temp.append( SetAndList(l) ) return [t.list for t in temp if t.isUnique] print listReduce(original) print target </code></pre> <p>This prints the calculated list and the target for visual comparison.</p> <p>Uncomment the print line in the compare method to see how various lists get superceded.</p> <p>Tested with python 2.6.2</p>
0
2009-08-23T17:18:24Z
[ "python", "list" ]
Python list filtering: remove subsets from list of lists
1,318,935
<p>Using Python how do you reduce a list of lists by an ordered subset match <code>[[..],[..],..]</code>? </p> <p>In the context of this question a list L is a <strong><em>subset</em></strong> of list <code>M</code> if <code>M</code> contains all members of <code>L</code>, and in the same order. For example, the list [1,2] is a subset of the list [1,2,3], but not of the list [2,1,3].</p> <p><em>Example input:</em></p> <pre><code>a. [[1, 2, 4, 8], [1, 2, 4, 5, 6], [1, 2, 3], [2, 3, 21], [1, 2, 3, 4], [1, 2, 3, 4, 5, 6, 7]] b. [[2, 16, 17], [1, 2, 3, 4, 5, 6, 7], [1], [1, 2, 3, 4], [1, 2], [17, 18, 19, 22, 41, 48], [2, 3], [1, 2, 3], [50, 69], [1, 2, 3], [2, 3, 21], [1, 2, 3], [1, 2, 4, 8], [1, 2, 4, 5, 6]] </code></pre> <p><em>Expected result:</em></p> <pre><code>a. [[1, 2, 4, 8], [2, 3, 21], [1, 2, 3, 4, 5, 6, 7]] b. [[2, 16, 17], [1, 2, 3, 4, 5, 6, 7], [17, 18, 19, 22, 41, 48], [50, 69], [2, 3, 21], [1, 2, 4, 8], [1, 2, 4, 5, 6]] </code></pre> <p><em>Further Examples:</em></p> <p><code>L = [[1, 2, 3, 4, 5, 6, 7], [1, 2, 5, 6]]</code> - No reduce</p> <p><code>L = [[1, 2, 3, 4, 5, 6, 7],</code> <strike><code>[1, 2, 3]</code></strike>, <code>[1, 2, 4, 8]]</code> - Yes reduce</p> <p><code>L = [[1, 2, 3, 4, 5, 6, 7], [7, 6, 5, 4, 3, 2, 1]]</code> - No reduce</p> <p><em>(Sorry for causing confusion with the incorrect data set.)</em></p>
7
2009-08-23T16:23:20Z
1,319,055
<p>I implemented a different <code>issubseq</code> because yours doesn't say that <code>[1, 2, 4, 5, 6]</code> is a subsequence of <code>[1, 2, 3, 4, 5, 6, 7]</code>, for example (besides being painfully slow). The solution I came up with looks like this:</p> <pre><code> def is_subseq(a, b): if len(a) &gt; len(b): return False start = 0 for el in a: while start &lt; len(b): if el == b[start]: break start = start + 1 else: return False return True def filter_partial_matches(sets): return [s for s in sets if all([not(is_subseq(s, ss)) for ss in sets if s != ss])] </code></pre> <p>A simple test case, given your inputs and outputs:</p> <pre><code>&gt;&gt;&gt; test = [[1, 2, 4, 8], [1, 2, 4, 5, 6], [1, 2, 3], [2, 3, 21], [1, 2, 3, 4], [1, 2, 3, 4, 5, 6, 7]] &gt;&gt;&gt; another_test = [[1, 2, 3, 4], [2, 4, 3], [3, 4, 5]] &gt;&gt;&gt; filter_partial_matches(test) [[1, 2, 4, 8], [2, 3, 21], [1, 2, 3, 4, 5, 6, 7]] &gt;&gt;&gt; filter_partial_matches(another_test) [[1, 2, 3, 4], [2, 4, 3], [3, 4, 5]] </code></pre> <p>Hope it helps!</p>
0
2009-08-23T17:19:33Z
[ "python", "list" ]
Python list filtering: remove subsets from list of lists
1,318,935
<p>Using Python how do you reduce a list of lists by an ordered subset match <code>[[..],[..],..]</code>? </p> <p>In the context of this question a list L is a <strong><em>subset</em></strong> of list <code>M</code> if <code>M</code> contains all members of <code>L</code>, and in the same order. For example, the list [1,2] is a subset of the list [1,2,3], but not of the list [2,1,3].</p> <p><em>Example input:</em></p> <pre><code>a. [[1, 2, 4, 8], [1, 2, 4, 5, 6], [1, 2, 3], [2, 3, 21], [1, 2, 3, 4], [1, 2, 3, 4, 5, 6, 7]] b. [[2, 16, 17], [1, 2, 3, 4, 5, 6, 7], [1], [1, 2, 3, 4], [1, 2], [17, 18, 19, 22, 41, 48], [2, 3], [1, 2, 3], [50, 69], [1, 2, 3], [2, 3, 21], [1, 2, 3], [1, 2, 4, 8], [1, 2, 4, 5, 6]] </code></pre> <p><em>Expected result:</em></p> <pre><code>a. [[1, 2, 4, 8], [2, 3, 21], [1, 2, 3, 4, 5, 6, 7]] b. [[2, 16, 17], [1, 2, 3, 4, 5, 6, 7], [17, 18, 19, 22, 41, 48], [50, 69], [2, 3, 21], [1, 2, 4, 8], [1, 2, 4, 5, 6]] </code></pre> <p><em>Further Examples:</em></p> <p><code>L = [[1, 2, 3, 4, 5, 6, 7], [1, 2, 5, 6]]</code> - No reduce</p> <p><code>L = [[1, 2, 3, 4, 5, 6, 7],</code> <strike><code>[1, 2, 3]</code></strike>, <code>[1, 2, 4, 8]]</code> - Yes reduce</p> <p><code>L = [[1, 2, 3, 4, 5, 6, 7], [7, 6, 5, 4, 3, 2, 1]]</code> - No reduce</p> <p><em>(Sorry for causing confusion with the incorrect data set.)</em></p>
7
2009-08-23T16:23:20Z
1,319,083
<p>This code should be rather memory efficient. Beyond storing your initial list of lists, this code uses negligible extra memory (no temporary sets or copies of lists are created).</p> <pre><code>def is_subset(needle,haystack): """ Check if needle is ordered subset of haystack in O(n) """ if len(haystack) &lt; len(needle): return False index = 0 for element in needle: try: index = haystack.index(element, index) + 1 except ValueError: return False else: return True def filter_subsets(lists): """ Given list of lists, return new list of lists without subsets """ for needle in lists: if not any(is_subset(needle, haystack) for haystack in lists if needle is not haystack): yield needle my_lists = [[1, 2, 4, 8], [1, 2, 4, 5, 6], [1, 2, 3], [2, 3, 21], [1, 2, 3, 4], [1, 2, 3, 4, 5, 6, 7]] print list(filter_subsets(my_lists)) &gt;&gt;&gt; [[1, 2, 4, 8], [2, 3, 21], [1, 2, 3, 4, 5, 6, 7]] </code></pre> <p>And, just for fun, a one-liner:</p> <pre><code>def filter_list(L): return [x for x in L if not any(set(x)&lt;=set(y) for y in L if x is not y)] </code></pre>
4
2009-08-23T17:35:05Z
[ "python", "list" ]
Python list filtering: remove subsets from list of lists
1,318,935
<p>Using Python how do you reduce a list of lists by an ordered subset match <code>[[..],[..],..]</code>? </p> <p>In the context of this question a list L is a <strong><em>subset</em></strong> of list <code>M</code> if <code>M</code> contains all members of <code>L</code>, and in the same order. For example, the list [1,2] is a subset of the list [1,2,3], but not of the list [2,1,3].</p> <p><em>Example input:</em></p> <pre><code>a. [[1, 2, 4, 8], [1, 2, 4, 5, 6], [1, 2, 3], [2, 3, 21], [1, 2, 3, 4], [1, 2, 3, 4, 5, 6, 7]] b. [[2, 16, 17], [1, 2, 3, 4, 5, 6, 7], [1], [1, 2, 3, 4], [1, 2], [17, 18, 19, 22, 41, 48], [2, 3], [1, 2, 3], [50, 69], [1, 2, 3], [2, 3, 21], [1, 2, 3], [1, 2, 4, 8], [1, 2, 4, 5, 6]] </code></pre> <p><em>Expected result:</em></p> <pre><code>a. [[1, 2, 4, 8], [2, 3, 21], [1, 2, 3, 4, 5, 6, 7]] b. [[2, 16, 17], [1, 2, 3, 4, 5, 6, 7], [17, 18, 19, 22, 41, 48], [50, 69], [2, 3, 21], [1, 2, 4, 8], [1, 2, 4, 5, 6]] </code></pre> <p><em>Further Examples:</em></p> <p><code>L = [[1, 2, 3, 4, 5, 6, 7], [1, 2, 5, 6]]</code> - No reduce</p> <p><code>L = [[1, 2, 3, 4, 5, 6, 7],</code> <strike><code>[1, 2, 3]</code></strike>, <code>[1, 2, 4, 8]]</code> - Yes reduce</p> <p><code>L = [[1, 2, 3, 4, 5, 6, 7], [7, 6, 5, 4, 3, 2, 1]]</code> - No reduce</p> <p><em>(Sorry for causing confusion with the incorrect data set.)</em></p>
7
2009-08-23T16:23:20Z
1,319,109
<p>A list is a superlist if it is not a subset of any other list. It's a subset of another list if every element of the list can be found, in order, in another list.</p> <p>Here's my code:</p> <pre><code>def is_sublist_of_any_list(cand, lists): # Compare candidate to a single list def is_sublist_of_list(cand, target): try: i = 0 for c in cand: i = 1 + target.index(c, i) return True except ValueError: return False # See if candidate matches any other list return any(is_sublist_of_list(cand, target) for target in lists if len(cand) &lt;= len(target)) # Compare candidates to all other lists def super_lists(lists): return [cand for i, cand in enumerate(lists) if not is_sublist_of_any_list(cand, lists[:i] + lists[i+1:])] if __name__ == '__main__': lists = [[1, 2, 4, 8], [1, 2, 4, 5, 6], [1, 2, 3], [2, 3, 21], [1, 2, 3, 4], [1, 2, 3, 4, 5, 6, 7]] superlists = super_lists(lists) print superlists </code></pre> <p>Here are the results:</p> <pre><code>[[1, 2, 4, 8], [2, 3, 21], [1, 2, 3, 4, 5, 6, 7]] </code></pre> <p>Edit: Results for your later data set.</p> <pre><code>&gt;&gt;&gt; lists = [[2, 16, 17], [1, 2, 3, 4, 5, 6, 7], [1], [1, 2, 3, 4], [1, 2], [17, 18, 19, 22, 41, 48], [2, 3], [1, 2, 3], [50, 69], [1, 2, 3], [2, 3, 21], [1, 2, 3], [1, 2, 4, 8], [1, 2, 4, 5, 6]] &gt;&gt;&gt; superlists = super_lists(lists) &gt;&gt;&gt; expected = [[2, 16, 17], [1, 2, 3, 4, 5, 6, 7], [17, 18, 19, 22, 41, 48], [5 0, 69], [2, 3, 21], [1, 2, 4, 8]] &gt;&gt;&gt; assert(superlists == expected) &gt;&gt;&gt; print superlists [[2, 16, 17], [1, 2, 3, 4, 5, 6, 7], [17, 18, 19, 22, 41, 48], [50, 69], [2, 3, 21], [1, 2, 4, 8]] </code></pre>
1
2009-08-23T17:42:40Z
[ "python", "list" ]
Python list filtering: remove subsets from list of lists
1,318,935
<p>Using Python how do you reduce a list of lists by an ordered subset match <code>[[..],[..],..]</code>? </p> <p>In the context of this question a list L is a <strong><em>subset</em></strong> of list <code>M</code> if <code>M</code> contains all members of <code>L</code>, and in the same order. For example, the list [1,2] is a subset of the list [1,2,3], but not of the list [2,1,3].</p> <p><em>Example input:</em></p> <pre><code>a. [[1, 2, 4, 8], [1, 2, 4, 5, 6], [1, 2, 3], [2, 3, 21], [1, 2, 3, 4], [1, 2, 3, 4, 5, 6, 7]] b. [[2, 16, 17], [1, 2, 3, 4, 5, 6, 7], [1], [1, 2, 3, 4], [1, 2], [17, 18, 19, 22, 41, 48], [2, 3], [1, 2, 3], [50, 69], [1, 2, 3], [2, 3, 21], [1, 2, 3], [1, 2, 4, 8], [1, 2, 4, 5, 6]] </code></pre> <p><em>Expected result:</em></p> <pre><code>a. [[1, 2, 4, 8], [2, 3, 21], [1, 2, 3, 4, 5, 6, 7]] b. [[2, 16, 17], [1, 2, 3, 4, 5, 6, 7], [17, 18, 19, 22, 41, 48], [50, 69], [2, 3, 21], [1, 2, 4, 8], [1, 2, 4, 5, 6]] </code></pre> <p><em>Further Examples:</em></p> <p><code>L = [[1, 2, 3, 4, 5, 6, 7], [1, 2, 5, 6]]</code> - No reduce</p> <p><code>L = [[1, 2, 3, 4, 5, 6, 7],</code> <strike><code>[1, 2, 3]</code></strike>, <code>[1, 2, 4, 8]]</code> - Yes reduce</p> <p><code>L = [[1, 2, 3, 4, 5, 6, 7], [7, 6, 5, 4, 3, 2, 1]]</code> - No reduce</p> <p><em>(Sorry for causing confusion with the incorrect data set.)</em></p>
7
2009-08-23T16:23:20Z
1,319,127
<p>This could be simplified, but:</p> <pre><code>l = [[1, 2, 4, 8], [1, 2, 4, 5, 6], [1, 2, 3], [2, 3, 21], [1, 2, 3, 4], [1, 2, 3, 4, 5, 6, 7]] l2 = l[:] for m in l: for n in l: if set(m).issubset(set(n)) and m != n: l2.remove(m) break print l2 [[1, 2, 4, 8], [2, 3, 21], [1, 2, 3, 4, 5, 6, 7]] </code></pre>
3
2009-08-23T17:49:14Z
[ "python", "list" ]
Python list filtering: remove subsets from list of lists
1,318,935
<p>Using Python how do you reduce a list of lists by an ordered subset match <code>[[..],[..],..]</code>? </p> <p>In the context of this question a list L is a <strong><em>subset</em></strong> of list <code>M</code> if <code>M</code> contains all members of <code>L</code>, and in the same order. For example, the list [1,2] is a subset of the list [1,2,3], but not of the list [2,1,3].</p> <p><em>Example input:</em></p> <pre><code>a. [[1, 2, 4, 8], [1, 2, 4, 5, 6], [1, 2, 3], [2, 3, 21], [1, 2, 3, 4], [1, 2, 3, 4, 5, 6, 7]] b. [[2, 16, 17], [1, 2, 3, 4, 5, 6, 7], [1], [1, 2, 3, 4], [1, 2], [17, 18, 19, 22, 41, 48], [2, 3], [1, 2, 3], [50, 69], [1, 2, 3], [2, 3, 21], [1, 2, 3], [1, 2, 4, 8], [1, 2, 4, 5, 6]] </code></pre> <p><em>Expected result:</em></p> <pre><code>a. [[1, 2, 4, 8], [2, 3, 21], [1, 2, 3, 4, 5, 6, 7]] b. [[2, 16, 17], [1, 2, 3, 4, 5, 6, 7], [17, 18, 19, 22, 41, 48], [50, 69], [2, 3, 21], [1, 2, 4, 8], [1, 2, 4, 5, 6]] </code></pre> <p><em>Further Examples:</em></p> <p><code>L = [[1, 2, 3, 4, 5, 6, 7], [1, 2, 5, 6]]</code> - No reduce</p> <p><code>L = [[1, 2, 3, 4, 5, 6, 7],</code> <strike><code>[1, 2, 3]</code></strike>, <code>[1, 2, 4, 8]]</code> - Yes reduce</p> <p><code>L = [[1, 2, 3, 4, 5, 6, 7], [7, 6, 5, 4, 3, 2, 1]]</code> - No reduce</p> <p><em>(Sorry for causing confusion with the incorrect data set.)</em></p>
7
2009-08-23T16:23:20Z
1,324,781
<p>Refined answer after new test case:</p> <pre><code>original= [[2, 16, 17], [1, 2, 3, 4, 5, 6, 7], [1], [1, 2, 3, 4], [1, 2], [17, 18, 19, 22, 41, 48], [2, 3], [1, 2, 3], [50, 69], [1, 2, 3], [2, 3, 21], [1, 2, 3], [1, 2, 4, 8], [1, 2, 4, 5, 6]] class SetAndList: def __init__(self,aList): self.list=aList self.set=set(aList) self.isUnique=True def compare(self,other): if self.set.issubset(other.set): #print self.list,'superceded by',other.list self.isUnique=False def listReduce(lists): temp=[] for l in lists: s=SetAndList(l) for t in temp: t.compare(s) s.compare(t) temp.append( s ) temp=[t for t in temp if t.isUnique] return [t.list for t in temp if t.isUnique] print listReduce(original) </code></pre> <p>You didn't give the required output, but I'm guessing this is right, as <code>[1,2,3]</code> does not appear in the output.</p>
0
2009-08-24T21:04:03Z
[ "python", "list" ]
Python list filtering: remove subsets from list of lists
1,318,935
<p>Using Python how do you reduce a list of lists by an ordered subset match <code>[[..],[..],..]</code>? </p> <p>In the context of this question a list L is a <strong><em>subset</em></strong> of list <code>M</code> if <code>M</code> contains all members of <code>L</code>, and in the same order. For example, the list [1,2] is a subset of the list [1,2,3], but not of the list [2,1,3].</p> <p><em>Example input:</em></p> <pre><code>a. [[1, 2, 4, 8], [1, 2, 4, 5, 6], [1, 2, 3], [2, 3, 21], [1, 2, 3, 4], [1, 2, 3, 4, 5, 6, 7]] b. [[2, 16, 17], [1, 2, 3, 4, 5, 6, 7], [1], [1, 2, 3, 4], [1, 2], [17, 18, 19, 22, 41, 48], [2, 3], [1, 2, 3], [50, 69], [1, 2, 3], [2, 3, 21], [1, 2, 3], [1, 2, 4, 8], [1, 2, 4, 5, 6]] </code></pre> <p><em>Expected result:</em></p> <pre><code>a. [[1, 2, 4, 8], [2, 3, 21], [1, 2, 3, 4, 5, 6, 7]] b. [[2, 16, 17], [1, 2, 3, 4, 5, 6, 7], [17, 18, 19, 22, 41, 48], [50, 69], [2, 3, 21], [1, 2, 4, 8], [1, 2, 4, 5, 6]] </code></pre> <p><em>Further Examples:</em></p> <p><code>L = [[1, 2, 3, 4, 5, 6, 7], [1, 2, 5, 6]]</code> - No reduce</p> <p><code>L = [[1, 2, 3, 4, 5, 6, 7],</code> <strike><code>[1, 2, 3]</code></strike>, <code>[1, 2, 4, 8]]</code> - Yes reduce</p> <p><code>L = [[1, 2, 3, 4, 5, 6, 7], [7, 6, 5, 4, 3, 2, 1]]</code> - No reduce</p> <p><em>(Sorry for causing confusion with the incorrect data set.)</em></p>
7
2009-08-23T16:23:20Z
1,327,425
<p>Thanks to all who suggested solutions and coping with my sometimes erroneous data sets. Using <strong>@hughdbrown</strong> solution I modified it to what I wanted:</p> <p>The modification was to use a sliding window over the target to ensure the subset sequence was found. I think I should have used a more appropriate word than 'Set' to describe my problem.</p> <pre><code>def is_sublist_of_any_list(cand, lists): # Compare candidate to a single list def is_sublist_of_list(cand, target): try: i = 0 try: start = target.index(cand[0]) except: return False while start &lt; (len(target) + len(cand)) - start: if cand == target[start:len(cand)]: return True else: start = target.index(cand[0], start + 1) except ValueError: return False # See if candidate matches any other list return any(is_sublist_of_list(cand, target) for target in lists if len(cand) &lt;= len(target)) # Compare candidates to all other lists def super_lists(lists): a = [cand for i, cand in enumerate(lists) if not is_sublist_of_any_list(cand, lists[:i] + lists[i+1:])] return a lists = [[2, 16, 17], [1, 2, 3, 4, 5, 6, 7], [1], [1, 2, 3, 4], [1, 2], [17, 18, 19, 22, 41, 48], [2, 3], [1, 2, 3], [50, 69], [1, 2, 3], [2, 3, 21], [1, 2, 3], [1, 2, 4, 8], [1, 2, 4, 5, 6]] expect = [[2, 16, 17], [1, 2, 3, 4, 5, 6, 7], [17, 18, 19, 22, 41, 48], [50, 69], [2, 3, 21], [1, 2, 4, 8], [1, 2, 4, 5, 6]] def test(): out = super_lists(list(lists)) print "In : ", lists print "Out : ", out assert (out == expect) </code></pre> <p>Result:</p> <pre><code>In : [[2, 16, 17], [1, 2, 3, 4, 5, 6, 7], [1], [1, 2, 3, 4], [1, 2], [17, 18, 19, 22, 41, 48], [2, 3], [1, 2, 3], [50, 69], [1, 2, 3], [2, 3, 21], [1, 2, 3], [1, 2, 4, 8], [1, 2, 4, 5, 6]] Out : [[2, 16, 17], [1, 2, 3, 4, 5, 6, 7], [17, 18, 19, 22, 41, 48], [50, 69], [2, 3, 21], [1, 2, 4, 8], [1, 2, 4, 5, 6]] </code></pre>
0
2009-08-25T10:37:03Z
[ "python", "list" ]
Python list filtering: remove subsets from list of lists
1,318,935
<p>Using Python how do you reduce a list of lists by an ordered subset match <code>[[..],[..],..]</code>? </p> <p>In the context of this question a list L is a <strong><em>subset</em></strong> of list <code>M</code> if <code>M</code> contains all members of <code>L</code>, and in the same order. For example, the list [1,2] is a subset of the list [1,2,3], but not of the list [2,1,3].</p> <p><em>Example input:</em></p> <pre><code>a. [[1, 2, 4, 8], [1, 2, 4, 5, 6], [1, 2, 3], [2, 3, 21], [1, 2, 3, 4], [1, 2, 3, 4, 5, 6, 7]] b. [[2, 16, 17], [1, 2, 3, 4, 5, 6, 7], [1], [1, 2, 3, 4], [1, 2], [17, 18, 19, 22, 41, 48], [2, 3], [1, 2, 3], [50, 69], [1, 2, 3], [2, 3, 21], [1, 2, 3], [1, 2, 4, 8], [1, 2, 4, 5, 6]] </code></pre> <p><em>Expected result:</em></p> <pre><code>a. [[1, 2, 4, 8], [2, 3, 21], [1, 2, 3, 4, 5, 6, 7]] b. [[2, 16, 17], [1, 2, 3, 4, 5, 6, 7], [17, 18, 19, 22, 41, 48], [50, 69], [2, 3, 21], [1, 2, 4, 8], [1, 2, 4, 5, 6]] </code></pre> <p><em>Further Examples:</em></p> <p><code>L = [[1, 2, 3, 4, 5, 6, 7], [1, 2, 5, 6]]</code> - No reduce</p> <p><code>L = [[1, 2, 3, 4, 5, 6, 7],</code> <strike><code>[1, 2, 3]</code></strike>, <code>[1, 2, 4, 8]]</code> - Yes reduce</p> <p><code>L = [[1, 2, 3, 4, 5, 6, 7], [7, 6, 5, 4, 3, 2, 1]]</code> - No reduce</p> <p><em>(Sorry for causing confusion with the incorrect data set.)</em></p>
7
2009-08-23T16:23:20Z
1,331,312
<p>So what you really wanted was to know if a list was a substring, so to speak, of another, with all the matching elements consecutive. Here is code that converts the candidate and the target list to comma-separated strings and does a substring comparison to see if the candidate appears within the target list</p> <pre><code>def is_sublist_of_any_list(cand, lists): def comma_list(l): return "," + ",".join(str(x) for x in l) + "," cand = comma_list(cand) return any(cand in comma_list(target) for target in lists if len(cand) &lt;= len(target)) def super_lists(lists): return [cand for i, cand in enumerate(lists) if not is_sublist_of_any_list(cand, lists[:i] + lists[i+1:])] </code></pre> <p>The function comma_list() puts leading and trailing commas on the list to ensure that integers are fully delimited. Otherwise, [1] would be a subset of [100], for example.</p>
0
2009-08-25T22:10:04Z
[ "python", "list" ]
Python/GAE web request error handling
1,318,960
<p>I am developing an application on the Google App Engine using Python.</p> <p>I have a handler that can return a variety of outputs (html and json at the moment), I am testing for obvious errors in the system based on invalid parameters sent to the request handler.</p> <p>However what I am doing feels dirty (see below):</p> <pre><code>class FeedHandler(webapp.RequestHandler): def get(self): app = self.request.get("id") name = self.request.get("name") output_type = self.request.get("output", default_value = "html") pretty = self.request.get("pretty", default_value = "") application = model.Application.GetByKey(app) if application is None: if output_type == "json": self.response.out.write(simplejson.dumps({ "errorCode" : "Application not found."})) self.set_status(404) return category = model.FeedCategory.GetByKey(application, name) if category is None: if output_type == "json": self.response.out.write(simplejson.dumps({ "errorCode" : "Category not found."})) self.set_status(404) return </code></pre> <p>I am specifically handling cases per output type and also and per "assert".</p> <p>I am keen to here suggestions, patterns and examples on how to clear it up (I know it is going to be a nightmare to try and maintain what I am doing). </p> <p>I am toying with the idea of having and raising custom exceptions and having a decorator that will automatically work out how to display the error messages - I think it is a good idea but I am would love to get some feedback and suggestions based on how people have done this in the past.</p>
4
2009-08-23T16:35:41Z
1,319,122
<p>As least, you should refactor repetitive code such as:</p> <pre><code>if application is None: if output_type == "json": self.response.out.write(simplejson.dumps({ "errorCode" : "Application not found."})) self.set_status(404) return </code></pre> <p>into an auxiliary method:</p> <pre><code>def _Mayerr(self, result, msg): if result is None: if output_type == 'json': self.response.out.write(simplejson.dumps( {"errorCode": msg}) self.set_status(404) return True </code></pre> <p>and call it e.g. as:</p> <pre><code>if self._Mayerr(application, "Application not found."): return </code></pre> <p>Beyond that, custom exceptions (and wrapping all your handlers with a decorator that catches the exceptions and gives proper error messages) is an excellent architecture, though it's more invasive (requires more rework of your code) than the simple refactoring I just mentioned, the extra investment right now may well be worthwhile in preventing repetitious and boilerplatey error handling spread all over your application level code!-)</p>
0
2009-08-23T17:48:34Z
[ "python", "google-app-engine", "error-handling", "design-patterns" ]
Python/GAE web request error handling
1,318,960
<p>I am developing an application on the Google App Engine using Python.</p> <p>I have a handler that can return a variety of outputs (html and json at the moment), I am testing for obvious errors in the system based on invalid parameters sent to the request handler.</p> <p>However what I am doing feels dirty (see below):</p> <pre><code>class FeedHandler(webapp.RequestHandler): def get(self): app = self.request.get("id") name = self.request.get("name") output_type = self.request.get("output", default_value = "html") pretty = self.request.get("pretty", default_value = "") application = model.Application.GetByKey(app) if application is None: if output_type == "json": self.response.out.write(simplejson.dumps({ "errorCode" : "Application not found."})) self.set_status(404) return category = model.FeedCategory.GetByKey(application, name) if category is None: if output_type == "json": self.response.out.write(simplejson.dumps({ "errorCode" : "Category not found."})) self.set_status(404) return </code></pre> <p>I am specifically handling cases per output type and also and per "assert".</p> <p>I am keen to here suggestions, patterns and examples on how to clear it up (I know it is going to be a nightmare to try and maintain what I am doing). </p> <p>I am toying with the idea of having and raising custom exceptions and having a decorator that will automatically work out how to display the error messages - I think it is a good idea but I am would love to get some feedback and suggestions based on how people have done this in the past.</p>
4
2009-08-23T16:35:41Z
1,319,433
<p>There's a couple of handy methods here. The first is self.<a href="http://code.google.com/p/googleappengine/source/browse/trunk/python/google/appengine/ext/webapp/%5F%5Finit%5F%5F.py#353">error</a>(code). By default this method simply sets the status code and clears the output buffer, but you can override it to output custom error pages depending on the error result.</p> <p>The second method is self.<a href="http://code.google.com/p/googleappengine/source/browse/trunk/python/google/appengine/ext/webapp/%5F%5Finit%5F%5F.py#377">handle__exception</a>(exception, debug_mode). This method is called by the webapp infrastructure if any of your get/post/etc methods return an unhandled exception. By default it calls self.error(500) and logs the exception (as well as printing it to the output if debug mode is enabled). You can override this method to handle exceptions however you like. Here's an example to allow you to throw exceptions for various statuses:</p> <pre><code>class StatusCodeException(Exception): def __init__(self, code): self.status_code = code class RedirectException(StatusCodeException): def __init__(self, location, status=302): super(RedirectException, self).__init__(status) self.location = location class ForbiddenException(StatusCodeException): def __init__(self): super(ForbiddenException, self).__init__(403) class ExtendedHandler(webapp.RequestHandler): def handle_exception(self, exception, debug_mode): if isinstance(exception, RedirectException): self.redirect(exception.location) else: self.error(exception.status_code) </code></pre>
9
2009-08-23T20:12:58Z
[ "python", "google-app-engine", "error-handling", "design-patterns" ]
Parallel Python: What is a callback?
1,319,074
<p>In <a href="http://www.parallelpython.com/">Parallel Python</a> it has something in the <i>submit</i> function called a <i>callback</i> (<a href="http://www.parallelpython.com/content/view/15/30/">documentation</a>) however it doesn't seem to explain it too well. I've posted on their forum a couple days ago and I've not received a response. Would someone explain what a callback is and what it's used for?</p> <p>Thank you.</p>
20
2009-08-23T17:30:50Z
1,319,104
<p>Looking at the link, just looks like a hook which is called.</p> <blockquote> <p>callback - callback function which will be called with argument list equal to callbackargs+(result,) as soon as calculation is done</p> </blockquote> <p>The "as soon as calculation is done" bit seems ambiguous. The point, as far as I can see of this thing is that the <code>submit()</code> call distributes work to other servers and then returns. Because the finishing is asynchronous, rather block, it allows you to provide a function which is called when some unit of work finishes. If you do:</p> <pre><code>submit( ..., callback=work_finished, ... ) </code></pre> <p>Then submit will ensure <code>work_finished()</code> is called when the unit of distributed work is completed on the target server.</p> <p>When you call <code>submit()</code> you can provide a <strong>callback</strong> which is called in the same runtime as the caller of <code>submit()</code> ... and it is called after the distribution of the workload function is complete.</p> <p>Kind of like "call foo(x,y) when you have done some stuff in submit()"</p> <p>But yea, the documentation could be better. Have a ganders at the ppython source and see at which point the callback is called in <code>submit()</code></p>
3
2009-08-23T17:41:35Z
[ "python", "callback", "parallel-python" ]
Parallel Python: What is a callback?
1,319,074
<p>In <a href="http://www.parallelpython.com/">Parallel Python</a> it has something in the <i>submit</i> function called a <i>callback</i> (<a href="http://www.parallelpython.com/content/view/15/30/">documentation</a>) however it doesn't seem to explain it too well. I've posted on their forum a couple days ago and I've not received a response. Would someone explain what a callback is and what it's used for?</p> <p>Thank you.</p>
20
2009-08-23T17:30:50Z
1,319,108
<p>The relevant spot in the docs:</p> <pre><code>callback - callback function which will be called with argument list equal to callbackargs+(result,) as soon as calculation is done callbackargs - additional arguments for callback function </code></pre> <p>So, if you want some code to be executed as soon as the result is ready, you put that code into a function and pass that function as the <code>callback</code> argument. If you don't need other arguments, it will be just, e.g.:</p> <pre><code>def itsdone(result): print "Done! result=%r" % (result,) ... submit(..., callback=itsdone) </code></pre> <p>For more on the <code>callback</code> pattern in Python, see e.g. my presentation <a href="http://www.listal.com/video/8878369">here</a>.</p>
13
2009-08-23T17:42:35Z
[ "python", "callback", "parallel-python" ]
Parallel Python: What is a callback?
1,319,074
<p>In <a href="http://www.parallelpython.com/">Parallel Python</a> it has something in the <i>submit</i> function called a <i>callback</i> (<a href="http://www.parallelpython.com/content/view/15/30/">documentation</a>) however it doesn't seem to explain it too well. I've posted on their forum a couple days ago and I've not received a response. Would someone explain what a callback is and what it's used for?</p> <p>Thank you.</p>
20
2009-08-23T17:30:50Z
1,319,110
<p>A callback is simply a function. In Python, functions are just more objects, and so the name of a function can be used as a variable, like so:</p> <pre><code>def func(): ... something(func) </code></pre> <p>Note that many functions which accept a callback as an argument usually require that the callback accept certain arguments. In this case, the callback function will need to accept a list of arguments specified in callbackargs. I'm not familiar with Parallel Python so I don't know exactly what it wants.</p>
1
2009-08-23T17:42:47Z
[ "python", "callback", "parallel-python" ]
Parallel Python: What is a callback?
1,319,074
<p>In <a href="http://www.parallelpython.com/">Parallel Python</a> it has something in the <i>submit</i> function called a <i>callback</i> (<a href="http://www.parallelpython.com/content/view/15/30/">documentation</a>) however it doesn't seem to explain it too well. I've posted on their forum a couple days ago and I've not received a response. Would someone explain what a callback is and what it's used for?</p> <p>Thank you.</p>
20
2009-08-23T17:30:50Z
1,319,118
<p>A <a href="http://en.wikipedia.org/wiki/Callback%5Ffunction" rel="nofollow">callback</a> is a function you define that's later called by a function you call.</p> <p>As an example, consider how AJAX works: you write code that calls a back-end server function. At some point in the future, it returns from that function (the "A" stands for Asynchronous, which is what the "Parallel" in "Parallel Python" is all about). Now - because your code calls the code on the server, you want it to tell you when it's done, and you want to do something with its results. It does so by calling your <em>callback function</em>.</p> <p>When the called function completes, the standard way for it to tell you it's done is for you to tell it to call a function in your code. That's the callback function, and its job is to handle the results/output from the lower-level function you've called.</p>
3
2009-08-23T17:44:09Z
[ "python", "callback", "parallel-python" ]
Parallel Python: What is a callback?
1,319,074
<p>In <a href="http://www.parallelpython.com/">Parallel Python</a> it has something in the <i>submit</i> function called a <i>callback</i> (<a href="http://www.parallelpython.com/content/view/15/30/">documentation</a>) however it doesn't seem to explain it too well. I've posted on their forum a couple days ago and I've not received a response. Would someone explain what a callback is and what it's used for?</p> <p>Thank you.</p>
20
2009-08-23T17:30:50Z
1,319,135
<p>A callback is a function provided by the consumer of an API that the API can then turn around and invoke (calling you back). If I setup a Dr.'s appointment, I can give them my phone number, so they can call me the day before to confirm the appointment. A callback is like that, except instead of just being a phone number, it can be arbitrary instructions like "send me an email at this address, and also call my secretary and have her put it in my calendar. </p> <p>Callbacks are often used in situations where an action is asynchronous. If you need to call a function, and immediately continue working, you can't sit there wait for its return value to let you know what happened, so you provide a callback. When the function is done completely its asynchronous work it will then invoke your callback with some predetermined arguments (usually some you supply, and some about the status and result of the asynchronous action you requested). </p> <p>If the Dr. is out of the office, or they are still working on the schedule, rather than having me wait on hold until he gets back, which could be several hours, we hang up, and once the appointment has been scheduled, they call me.</p> <p>In this specific case, Parallel Python's submit function will invoke your callback with any arguments you supply and the result of <code>func</code>, once <code>func</code> has finished executing.</p>
83
2009-08-23T17:52:53Z
[ "python", "callback", "parallel-python" ]