title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
Python's sys.path value | 897,792 | <p>Where is Python's sys.path initialized from?</p>
<p><strong>UPD</strong>: Python is adding some paths before refering to PYTHONPATH:</p>
<pre><code> >>> import sys
>>> from pprint import pprint as p
>>> p(sys.path)
['',
'C:\\Python25\\lib\\site-packages\\setuptools-0.6c9-py2.5.egg',
'C:\\Python25\\lib\\site-packages\\orbited-0.7.8-py2.5.egg',
'C:\\Python25\\lib\\site-packages\\morbid-0.8.6.1-py2.5.egg',
'C:\\Python25\\lib\\site-packages\\demjson-1.4-py2.5.egg',
'C:\\Python25\\lib\\site-packages\\stomper-0.2.2-py2.5.egg',
'C:\\Python25\\lib\\site-packages\\uuid-1.30-py2.5.egg',
'C:\\Python25\\lib\\site-packages\\stompservice-0.1.0-py2.5.egg',
'C:\\Python25\\lib\\site-packages\\cherrypy-3.0.1-py2.5.egg',
'C:\\Python25\\lib\\site-packages\\pyorbited-0.2.2-py2.5.egg',
'C:\\Python25\\lib\\site-packages\\flup-1.0.1-py2.5.egg',
'C:\\Python25\\lib\\site-packages\\wsgilog-0.1-py2.5.egg',
'c:\\testdir',
'C:\\Windows\\system32\\python25.zip',
'C:\\Python25\\DLLs',
'C:\\Python25\\lib',
'C:\\Python25\\lib\\plat-win',
'C:\\Python25\\lib\\lib-tk',
'C:\\Python25',
'C:\\Python25\\lib\\site-packages',
'C:\\Python25\\lib\\site-packages\\PIL',
'C:\\Python25\\lib\\site-packages\\win32',
'C:\\Python25\\lib\\site-packages\\win32\\lib',
'C:\\Python25\\lib\\site-packages\\Pythonwin']
</code></pre>
<p>My PYTHONPATH is:</p>
<pre><code> PYTHONPATH=c:\testdir
</code></pre>
<p>I wonder where those paths before PYTHONPATH's ones come from?</p>
| 54 | 2009-05-22T13:19:05Z | 897,810 | <p>"Initialized from the environment variable PYTHONPATH, plus an installation-dependent default"</p>
<p>-- <a href="http://docs.python.org/library/sys.html#sys.path">http://docs.python.org/library/sys.html#sys.path</a></p>
| 28 | 2009-05-22T13:21:25Z | [
"python",
"path",
"sys"
] |
Python's sys.path value | 897,792 | <p>Where is Python's sys.path initialized from?</p>
<p><strong>UPD</strong>: Python is adding some paths before refering to PYTHONPATH:</p>
<pre><code> >>> import sys
>>> from pprint import pprint as p
>>> p(sys.path)
['',
'C:\\Python25\\lib\\site-packages\\setuptools-0.6c9-py2.5.egg',
'C:\\Python25\\lib\\site-packages\\orbited-0.7.8-py2.5.egg',
'C:\\Python25\\lib\\site-packages\\morbid-0.8.6.1-py2.5.egg',
'C:\\Python25\\lib\\site-packages\\demjson-1.4-py2.5.egg',
'C:\\Python25\\lib\\site-packages\\stomper-0.2.2-py2.5.egg',
'C:\\Python25\\lib\\site-packages\\uuid-1.30-py2.5.egg',
'C:\\Python25\\lib\\site-packages\\stompservice-0.1.0-py2.5.egg',
'C:\\Python25\\lib\\site-packages\\cherrypy-3.0.1-py2.5.egg',
'C:\\Python25\\lib\\site-packages\\pyorbited-0.2.2-py2.5.egg',
'C:\\Python25\\lib\\site-packages\\flup-1.0.1-py2.5.egg',
'C:\\Python25\\lib\\site-packages\\wsgilog-0.1-py2.5.egg',
'c:\\testdir',
'C:\\Windows\\system32\\python25.zip',
'C:\\Python25\\DLLs',
'C:\\Python25\\lib',
'C:\\Python25\\lib\\plat-win',
'C:\\Python25\\lib\\lib-tk',
'C:\\Python25',
'C:\\Python25\\lib\\site-packages',
'C:\\Python25\\lib\\site-packages\\PIL',
'C:\\Python25\\lib\\site-packages\\win32',
'C:\\Python25\\lib\\site-packages\\win32\\lib',
'C:\\Python25\\lib\\site-packages\\Pythonwin']
</code></pre>
<p>My PYTHONPATH is:</p>
<pre><code> PYTHONPATH=c:\testdir
</code></pre>
<p>I wonder where those paths before PYTHONPATH's ones come from?</p>
| 54 | 2009-05-22T13:19:05Z | 38,403,654 | <p>Python really tries hard to intelligently set <a href="https://docs.python.org/2/library/sys.html#sys.path" rel="nofollow"><code>sys.path</code></a>. How it is
set can get <a href="https://github.com/python/cpython/blob/master/Modules/getpath.c" rel="nofollow">really</a> <a href="https://github.com/python/cpython/blob/master/PC/getpathp.c" rel="nofollow">complicated</a>. The following guide is a watered-down,
somewhat-incomplete, somewhat-wrong, but hopefully-useful guide
for the rank-and-file python programmer of what happens when python
figures out what to use as the <em>initial values</em> of <code>sys.path</code>,
<code>sys.executable</code>, <code>sys.exec_prefix</code>, and <code>sys.prefix</code> on a <em>normal</em>
python installation.</p>
<p>First, python does its level best to figure out its actual physical
location on the filesystem based on what the operating system tells
it. If the OS just says "python" is running, it finds itself in $PATH.
It resolves any symbolic links. Once it has done this, the path of
the executable that it finds is used as the value for <code>sys.executable</code>, no ifs,
ands, or buts.</p>
<p>Next, it determines the initial values for <code>sys.exec_prefix</code> and
<code>sys.prefix</code>.</p>
<p>If there is a file called <code>pyvenv.cfg</code> in the same directory as
<code>sys.executable</code> or one directory up, python looks at it. Different
OSes do different things with this file.</p>
<p>One of the values in this config file that python looks for is
the configuration option <code>home = <DIRECTORY></code>. Python will use this directory instead of the directory containing <code>sys.executable</code>
when it dynamically sets the initial value of <code>sys.prefix</code> later. If the <code>applocal = true</code> setting appears in the
<code>pyvenv.cfg</code> file on Windows, but not the <code>home = <DIRECTORY></code> setting,
then <code>sys.prefix</code> will be set to the directory containing <code>sys.executable</code>.</p>
<p>Next, the <code>PYTHONHOME</code> environment variable is examined. On Linux and Mac,
<code>sys.prefix</code> and <code>sys.exec_prefix</code> are set to the <code>PYTHONHOME</code> environment variable, if
it exists, <em>superseding</em> any <code>home = <DIRECTORY></code> setting in <code>pyvenv.cfg</code>. On Windows,
<code>sys.prefix</code> and <code>sys.exec_prefix</code> is set to the <code>PYTHONHOME</code> environment variable,
if it exists, <em>unless</em> a <code>home = <DIRECTORY></code> setting is present in <code>pyvenv.cfg</code>,
which is used instead.</p>
<p>Otherwise, these <code>sys.prefix</code> and <code>sys.exec_prefix</code> are found by walking backwards
from the location of <code>sys.executable</code>, or the <code>home</code> directory given by <code>pyvenv.cfg</code> if any.</p>
<p>If the file <code>lib/python<version>/dyn-load</code> is found in that directory
or any of its parent directories, that directory is set to be to be
<code>sys.exec_prefix</code> on Linux or Mac. If the file
<code>lib/python<version>/os.py</code> is is found in the directory or any of its
subdirectories, that directory is set to be <code>sys.prefix</code> on Linux,
Mac, and Windows, with <code>sys.exec_prefix</code> set to the same value as
<code>sys.prefix</code> on Windows. This entire step is skipped on Windows if
<code>applocal = true</code> is set. Either the directory of <code>sys.executable</code> is
used or, if <code>home</code> is set in <code>pyvenv.cfg</code>, that is used instead for
the initial value of <code>sys.prefix</code>.</p>
<p>If it can't find these "landmark" files or <code>sys.prefix</code> hasn't been
found yet, then python sets <code>sys.prefix</code> to a "fallback"
value. Linux and Mac, for example, use pre-compiled defaults as the
values of <code>sys.prefix</code> and <code>sys.exec_prefix</code>. Windows waits
until <code>sys.path</code> is fully figured out to set a fallback value for
<code>sys.prefix</code>.</p>
<p>Then, (what you've all been waiting for,) python determines the initial values
that are to be contained in <code>sys.path</code>.</p>
<ol>
<li>The directory of the script which python is executing is added to <code>sys.path</code>.
On Windows, this is always the empty string, which tells python to
use the present working directory instead.</li>
<li>The contents of PYTHONPATH environment variable, if set, is added to <code>sys.path</code>, <em>unless</em> you're
on Windows and <code>applocal</code> is set to true in <code>pyvenv.cfg</code>.</li>
<li>The zip file path, which is <code><prefix>/lib/python35.zip</code> on Linux/Mac and
<code>os.path.join(os.dirname(sys.executable), "python.zip")</code> on Windows, is added to <code>sys.path</code>.</li>
<li>If on Windows and no <code>applocal = true</code> was set in <code>pyvenv.cfg</code>, then the contents of the subkeys of the registry key
<code>HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\</code> are added, if any.</li>
<li>If on Windows and no <code>applocal = true</code> was set in <code>pyvenv.cfg</code>, and <code>sys.prefix</code> could not be found,
then the <em>core contents</em> of the of the registry key <code>HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\</code> is added, if it exists;</li>
<li>If on Windows and no <code>applocal = true</code> was set in <code>pyvenv.cfg</code>, then the contents of the subkeys of the registry key
<code>HK_LOCAL_MACHINE\Software\Python\PythonCore\<DLLVersion>\PythonPath\</code> are added, if any.</li>
<li>If on Windows and no <code>applocal = true</code> was set in <code>pyvenv.cfg</code>, and <code>sys.prefix</code> could not be found,
then the <em>core contents</em> of the of the registry key <code>HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\</code> is added, if it exists;</li>
<li>If on Windows, and PYTHONPATH was not set, the prefix was not found, and no registry keys were present, then the
relative compile-time value of PYTHONPATH is added; otherwise, this step is ignored.</li>
<li>Paths in the compile-time macro PYTHONPATH are added relative to the dynamically-found <code>sys.prefix</code>.</li>
<li>On Mac and Linux, the value of <code>sys.exec_prefix</code> is added. On Windows, the directory
which was used (or would have been used) to search dynamically for <code>sys.prefix</code> is
added.</li>
</ol>
<p>At this stage on Windows, if no prefix was found, then python will try to
determine it by searching <em>all</em> the directories in <code>sys.path</code> for the landmark files,
as it tried to do with the directory of <code>sys.executable</code> previously, until it finds something.
If it doesn't, <code>sys.prefix</code> is left blank.</p>
<p>Finally, after all this, Python loads the <code>site</code> module, which adds stuff yet further to <code>sys.path</code>:</p>
<blockquote>
<p>It starts by constructing up to four directories from a head and a
tail part. For the head part, it uses sys.prefix and sys.exec_prefix;
empty heads are skipped. For the tail part, it uses the empty string
and then lib/site-packages (on Windows) or lib/pythonX.Y/site-packages
and then lib/site-python (on Unix and Macintosh). For each of the
distinct head-tail combinations, it sees if it refers to an existing
directory, and if so, adds it to sys.path and also inspects the newly
added path for configuration files.</p>
</blockquote>
| 7 | 2016-07-15T19:19:54Z | [
"python",
"path",
"sys"
] |
Python equivalent of PHP's memory_get_usage()? | 897,941 | <p>I've already <a href="http://stackoverflow.com/questions/110259/python-memory-profiler">found the following question</a>, but I was wondering if there was a quicker and dirtier way of grabbing an estimate of how much memory the python interpreter is currently using for my script that doesn't rely on external libraries.</p>
<p>I'm coming from PHP and used to use <a href="http://au.php.net/memory%5Fget%5Fusage">memory_get_usage()</a> and <a href="http://au.php.net/memory%5Fget%5Fpeak%5Fusage">memory_get_peak_usage()</a> a lot for this purpose and I was hoping to find an equivalent.</p>
| 18 | 2009-05-22T13:49:41Z | 897,965 | <p>try <a href="http://guppy-pe.sourceforge.net/#Heapy" rel="nofollow">heapy</a></p>
| 2 | 2009-05-22T13:57:02Z | [
"python"
] |
Python equivalent of PHP's memory_get_usage()? | 897,941 | <p>I've already <a href="http://stackoverflow.com/questions/110259/python-memory-profiler">found the following question</a>, but I was wondering if there was a quicker and dirtier way of grabbing an estimate of how much memory the python interpreter is currently using for my script that doesn't rely on external libraries.</p>
<p>I'm coming from PHP and used to use <a href="http://au.php.net/memory%5Fget%5Fusage">memory_get_usage()</a> and <a href="http://au.php.net/memory%5Fget%5Fpeak%5Fusage">memory_get_peak_usage()</a> a lot for this purpose and I was hoping to find an equivalent.</p>
| 18 | 2009-05-22T13:49:41Z | 898,406 | <p>A simple solution for Linux and other systems with <code>/proc/self/status</code> is the following code, which I use in a project of mine:</p>
<pre><code>def memory_usage():
"""Memory usage of the current process in kilobytes."""
status = None
result = {'peak': 0, 'rss': 0}
try:
# This will only work on systems with a /proc file system
# (like Linux).
status = open('/proc/self/status')
for line in status:
parts = line.split()
key = parts[0][2:-1].lower()
if key in result:
result[key] = int(parts[1])
finally:
if status is not None:
status.close()
return result
</code></pre>
<p>It returns the current and peak resident memory size (which is probably what people mean when they talk about how much RAM an application is using). It is easy to extend it to grab other pieces of information from the <code>/proc/self/status</code> file.</p>
<p>For the curious: the full output of <code>cat /proc/self/status</code> looks like this:</p>
<pre><code>% cat /proc/self/status
Name: cat
State: R (running)
Tgid: 4145
Pid: 4145
PPid: 4103
TracerPid: 0
Uid: 1000 1000 1000 1000
Gid: 1000 1000 1000 1000
FDSize: 32
Groups: 20 24 25 29 40 44 46 100 1000
VmPeak: 3580 kB
VmSize: 3580 kB
VmLck: 0 kB
VmHWM: 472 kB
VmRSS: 472 kB
VmData: 160 kB
VmStk: 84 kB
VmExe: 44 kB
VmLib: 1496 kB
VmPTE: 16 kB
Threads: 1
SigQ: 0/16382
SigPnd: 0000000000000000
ShdPnd: 0000000000000000
SigBlk: 0000000000000000
SigIgn: 0000000000000000
SigCgt: 0000000000000000
CapInh: 0000000000000000
CapPrm: 0000000000000000
CapEff: 0000000000000000
CapBnd: ffffffffffffffff
Cpus_allowed: 03
Cpus_allowed_list: 0-1
Mems_allowed: 1
Mems_allowed_list: 0
voluntary_ctxt_switches: 0
nonvoluntary_ctxt_switches: 0
</code></pre>
| 23 | 2009-05-22T15:14:38Z | [
"python"
] |
Python equivalent of PHP's memory_get_usage()? | 897,941 | <p>I've already <a href="http://stackoverflow.com/questions/110259/python-memory-profiler">found the following question</a>, but I was wondering if there was a quicker and dirtier way of grabbing an estimate of how much memory the python interpreter is currently using for my script that doesn't rely on external libraries.</p>
<p>I'm coming from PHP and used to use <a href="http://au.php.net/memory%5Fget%5Fusage">memory_get_usage()</a> and <a href="http://au.php.net/memory%5Fget%5Fpeak%5Fusage">memory_get_peak_usage()</a> a lot for this purpose and I was hoping to find an equivalent.</p>
| 18 | 2009-05-22T13:49:41Z | 7,669,279 | <p>You could also use the <code>getrusage()</code> function from the standard library module <code>resource</code>. The resulting object has the attribute <code>ru_maxrss</code>, which gives total memory usage for the calling process:</p>
<pre><code>>>> import resource
>>> resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
2656
</code></pre>
<p>The <a href="http://docs.python.org/library/resource.html#resource-usage">Python docs</a> aren't clear on what the units are exactly, but the <a href="http://developer.apple.com/library/mac/#documentation/darwin/reference/manpages/man2/getrusage.2.html">Mac OS X man page</a> for <code>getrusage(2)</code> describes the units as kilobytes.</p>
<p>The Linux man page isn't clear, but it seems to be equivalent to the <code>/proc/self/status</code> information (i.e. kilobytes) described in the accepted answer. For the same process as above, running on Linux, the function listed in the accepted answer gives:</p>
<pre><code>>>> memory_usage()
{'peak': 6392, 'rss': 2656}
</code></pre>
<p>This may not be quite as easy to use as the <code>/proc/self/status</code> solution, but it is standard library, so (provided the units are standard) it should be cross-platform, and usable on systems which lack <code>/proc/</code> (eg Mac OS X and other Unixes, maybe Windows).</p>
<p>Also, <code>getrusage()</code> function can also be given <code>resource.RUSAGE_CHILDREN</code> to get the usage for child processes, and (on some systems) <code>resource.RUSAGE_BOTH</code> for total (self and child) process usage.</p>
<p>This will cover the <code>memory_get_usage()</code> case, but doesn't include peak usage. I'm unsure if any other functions from the <code>resource</code> module can give peak usage. </p>
| 15 | 2011-10-06T00:41:21Z | [
"python"
] |
Python equivalent of PHP's memory_get_usage()? | 897,941 | <p>I've already <a href="http://stackoverflow.com/questions/110259/python-memory-profiler">found the following question</a>, but I was wondering if there was a quicker and dirtier way of grabbing an estimate of how much memory the python interpreter is currently using for my script that doesn't rely on external libraries.</p>
<p>I'm coming from PHP and used to use <a href="http://au.php.net/memory%5Fget%5Fusage">memory_get_usage()</a> and <a href="http://au.php.net/memory%5Fget%5Fpeak%5Fusage">memory_get_peak_usage()</a> a lot for this purpose and I was hoping to find an equivalent.</p>
| 18 | 2009-05-22T13:49:41Z | 12,912,618 | <p>Accepted answer rules, but it might be easier (and more portable) to use <a href="https://github.com/giampaolo/psutil" rel="nofollow">psutil</a>. It does the same and a lot more.</p>
<p>UPDATE: <a href="http://packages.python.org/Pympler/muppy.html" rel="nofollow">muppy</a> is also very convenient (and much better documented than guppy/heapy).</p>
| 10 | 2012-10-16T10:26:49Z | [
"python"
] |
File I/O in the Python 3 C API | 898,136 | <p>The C API in Python 3.0 has changed (deprecated) many of the functions for File Objects.</p>
<p>Before, in 2.X, you could use</p>
<pre><code>PyObject* PyFile_FromString(char *filename, char *mode)
</code></pre>
<p>to create a Python file object, e.g:</p>
<pre><code>PyObject *myFile = PyFile_FromString("test.txt", "r");
</code></pre>
<p>...but such function no longer exists in Python 3.0.
What would be the Python 3.0 equivalent to such call?</p>
| 4 | 2009-05-22T14:23:39Z | 898,160 | <p><a href="http://docs.python.org/3.0/c-api/file.html" rel="nofollow">This page</a> claims the API is:</p>
<pre><code>PyFile_FromFd(int fd, char *name, char *mode, int buffering, char *encoding, char *newline, int closefd);
</code></pre>
<p>Not sure if that means it's not possible to have Python open the file from the filename, but that should be trivial to do yourself, in C.</p>
| 3 | 2009-05-22T14:32:28Z | [
"python",
"python-3.x",
"python-c-api"
] |
File I/O in the Python 3 C API | 898,136 | <p>The C API in Python 3.0 has changed (deprecated) many of the functions for File Objects.</p>
<p>Before, in 2.X, you could use</p>
<pre><code>PyObject* PyFile_FromString(char *filename, char *mode)
</code></pre>
<p>to create a Python file object, e.g:</p>
<pre><code>PyObject *myFile = PyFile_FromString("test.txt", "r");
</code></pre>
<p>...but such function no longer exists in Python 3.0.
What would be the Python 3.0 equivalent to such call?</p>
| 4 | 2009-05-22T14:23:39Z | 900,918 | <p>You can do it the old(new?)-fashioned way, by just calling the io module.</p>
<p>This code works, but it does no error checking. See the docs for explanation.</p>
<pre><code>PyObject *ioMod, *openedFile;
PyGILState_STATE gilState = PyGILState_Ensure();
ioMod = PyImport_ImportModule("io");
openedFile = PyObject_CallMethod(ioMod, "open", "ss", "foo.txt", "wb");
Py_DECREF(ioMod);
PyObject_CallMethod(openedFile, "write", "y", "Written from Python C API!\n");
PyObject_CallMethod(openedFile, "flush", NULL);
PyObject_CallMethod(openedFile, "close", NULL);
Py_DECREF(openedFile);
PyGILState_Release(gilState);
Py_Finalize();
</code></pre>
| 5 | 2009-05-23T05:21:37Z | [
"python",
"python-3.x",
"python-c-api"
] |
Convert list of lists to delimited string | 898,391 | <p>How do I do the following in Python 2.2 using built-in modules only?</p>
<p>I have a list of lists like this:<br />
[['dog', 1], ['cat', 2, 'a'], ['rat', 3, 4], ['bat', 5]]</p>
<p>And from it I'd like to produce a string representation of a table like this where the columns are delimited by tabs and the rows by newlines. </p>
<pre><code>dog 1
cat 2 a
rat 3 4
bat 5
</code></pre>
<p>i.e.<br />
'dog\t1\ncat\t2\ta\nrat\t3\t4\nbat\t5'</p>
| 5 | 2009-05-22T15:11:44Z | 898,404 | <p>Like this, perhaps:</p>
<pre><code>lists = [['dog', 1], ['cat', 2, 'a'], ['rat', 3, 4], ['bat', 5]]
result = "\n".join("\t".join(map(str,l)) for l in lists)
</code></pre>
<p>This joins all the inner lists using tabs, and concatenates the resulting list of strings using newlines.</p>
<p>It uses a feature called <a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions">list comprehension</a> to process the outer list.</p>
| 17 | 2009-05-22T15:13:44Z | [
"python"
] |
Convert list of lists to delimited string | 898,391 | <p>How do I do the following in Python 2.2 using built-in modules only?</p>
<p>I have a list of lists like this:<br />
[['dog', 1], ['cat', 2, 'a'], ['rat', 3, 4], ['bat', 5]]</p>
<p>And from it I'd like to produce a string representation of a table like this where the columns are delimited by tabs and the rows by newlines. </p>
<pre><code>dog 1
cat 2 a
rat 3 4
bat 5
</code></pre>
<p>i.e.<br />
'dog\t1\ncat\t2\ta\nrat\t3\t4\nbat\t5'</p>
| 5 | 2009-05-22T15:11:44Z | 898,411 | <pre><code># rows contains the list of lists
lines = []
for row in rows:
lines.append('\t'.join(map(str, row)))
result = '\n'.join(lines)
</code></pre>
| 4 | 2009-05-22T15:15:39Z | [
"python"
] |
Django shopping cart/basket solution (or should I DIM)? | 898,426 | <p>I'm about to build a site that has about half a dozen fairly similar products. They're all DVDs so they fit into a very "fixed" database very well. I was going to make a DVD model. Tag them up. All very simple. All very easy.</p>
<p>But we need to be able to sell them. The current site outsources the whole purchasing system but that's not going to fly on the new site. We want to integrate everything right up until the payment (for both UX reasons plus we get to customise the process a lot more).</p>
<p>The other problem with the outsourced problem is it doesn't account for people that don't need to pay VAT (sales tax) or for the fact you get a discounts if you buy more than one of the same thing, or more than one SKU at the same time.</p>
<p>So I've been looking around. </p>
<p>Satchmo looks like a whole mini-framework. It has listing options that I just don't need with the quantities of SKUs I'm dealing with.</p>
<p>django-cart has been re-hashed as of March but it looks pretty abandoned since then.</p>
<p>I'm looking for something that will let me:</p>
<ul>
<li>pass it a model instances, a price and a quantity</li>
<li>apply a quantities formula based on the number of unique SKUs and copies in the same title</li>
<li>list what's in the cart on every page</li>
</ul>
<p>That's about it (but it's quite fiddly, nevertheless). I can handle the final order processing nonsense.</p>
<p><hr /></p>
<p>Or am I just being silly? </p>
<p>Should I just get on and Do It Myself? If that's your vote, I've never built a cart before so are there any considerations that are not obvious to somebody who has only used shopping carts before?</p>
| 1 | 2009-05-22T15:19:03Z | 898,520 | <p>There is an open source solution available: <a href="http://www.getlfs.com" rel="nofollow">http://www.getlfs.com</a><br />
I don't know if you could tweak it to suit you but it's based on the technologies you mention. The license is very liberal and it is heavily maintained.</p>
| 2 | 2009-05-22T15:36:26Z | [
"python",
"django",
"e-commerce",
"shopping-cart"
] |
Django shopping cart/basket solution (or should I DIM)? | 898,426 | <p>I'm about to build a site that has about half a dozen fairly similar products. They're all DVDs so they fit into a very "fixed" database very well. I was going to make a DVD model. Tag them up. All very simple. All very easy.</p>
<p>But we need to be able to sell them. The current site outsources the whole purchasing system but that's not going to fly on the new site. We want to integrate everything right up until the payment (for both UX reasons plus we get to customise the process a lot more).</p>
<p>The other problem with the outsourced problem is it doesn't account for people that don't need to pay VAT (sales tax) or for the fact you get a discounts if you buy more than one of the same thing, or more than one SKU at the same time.</p>
<p>So I've been looking around. </p>
<p>Satchmo looks like a whole mini-framework. It has listing options that I just don't need with the quantities of SKUs I'm dealing with.</p>
<p>django-cart has been re-hashed as of March but it looks pretty abandoned since then.</p>
<p>I'm looking for something that will let me:</p>
<ul>
<li>pass it a model instances, a price and a quantity</li>
<li>apply a quantities formula based on the number of unique SKUs and copies in the same title</li>
<li>list what's in the cart on every page</li>
</ul>
<p>That's about it (but it's quite fiddly, nevertheless). I can handle the final order processing nonsense.</p>
<p><hr /></p>
<p>Or am I just being silly? </p>
<p>Should I just get on and Do It Myself? If that's your vote, I've never built a cart before so are there any considerations that are not obvious to somebody who has only used shopping carts before?</p>
| 1 | 2009-05-22T15:19:03Z | 899,393 | <p>Since you asked: if your needs are that limited, it does sound like a DIY situation to me. I don't see what's so fiddly about it; what complexity there is is all in the pricing formula, and you're planning to supply that either way. Add in Django's built-in session support and you're most of the way there.</p>
| 3 | 2009-05-22T18:46:41Z | [
"python",
"django",
"e-commerce",
"shopping-cart"
] |
How can I detect if a file is binary (non-text) in python? | 898,669 | <p>How can I tell if a file is binary (non-text) in python? I am searching through a large set of files in python, and keep getting matches in binary files. This makes the output look incredibly messy.</p>
<p>I know I could use grep -I, but I am doing more with the data than what grep allows for.</p>
<p>In the past I would have just searched for characters greater than 0x7f, but utf8 and the like make that impossible on modern systems. Ideally the solution would be fast, but any solution will do.</p>
| 63 | 2009-05-22T16:09:50Z | 898,690 | <p>are you in unix? if so, then try:</p>
<pre><code>isBinary = os.system("file -b" + name + " | grep text > /dev/null")
</code></pre>
<p>The shell return values are inverted (0 is ok, so if it finds "text" then it will return a 0, and in Python that is a False expression).</p>
| 1 | 2009-05-22T16:14:35Z | [
"python",
"file",
"binary"
] |
How can I detect if a file is binary (non-text) in python? | 898,669 | <p>How can I tell if a file is binary (non-text) in python? I am searching through a large set of files in python, and keep getting matches in binary files. This makes the output look incredibly messy.</p>
<p>I know I could use grep -I, but I am doing more with the data than what grep allows for.</p>
<p>In the past I would have just searched for characters greater than 0x7f, but utf8 and the like make that impossible on modern systems. Ideally the solution would be fast, but any solution will do.</p>
| 63 | 2009-05-22T16:09:50Z | 898,691 | <p>Usually you have to guess.</p>
<p>You can look at the extensions as one clue, if the files have them.</p>
<p>You can also recognise know binary formats, and ignore those.</p>
<p>Otherwise see what proportion of non-printable ASCII bytes you have and take a guess from that.</p>
<p>You can also try decoding from UTF-8 and see if that produces sensible output.</p>
| 4 | 2009-05-22T16:14:44Z | [
"python",
"file",
"binary"
] |
How can I detect if a file is binary (non-text) in python? | 898,669 | <p>How can I tell if a file is binary (non-text) in python? I am searching through a large set of files in python, and keep getting matches in binary files. This makes the output look incredibly messy.</p>
<p>I know I could use grep -I, but I am doing more with the data than what grep allows for.</p>
<p>In the past I would have just searched for characters greater than 0x7f, but utf8 and the like make that impossible on modern systems. Ideally the solution would be fast, but any solution will do.</p>
| 63 | 2009-05-22T16:09:50Z | 898,723 | <p>You can also use the mimetypes module:</p>
<pre><code>import mimetypes
...
mime = mimetypes.guess_type(file)
</code></pre>
<p>It's fairly easy to compile a list of binary mime types. For example Apache distributes with a mime.types file that you could parse into a set of lists, binary and text and then check to see if the mime is in your text or binary list.</p>
| 25 | 2009-05-22T16:21:50Z | [
"python",
"file",
"binary"
] |
How can I detect if a file is binary (non-text) in python? | 898,669 | <p>How can I tell if a file is binary (non-text) in python? I am searching through a large set of files in python, and keep getting matches in binary files. This makes the output look incredibly messy.</p>
<p>I know I could use grep -I, but I am doing more with the data than what grep allows for.</p>
<p>In the past I would have just searched for characters greater than 0x7f, but utf8 and the like make that impossible on modern systems. Ideally the solution would be fast, but any solution will do.</p>
| 63 | 2009-05-22T16:09:50Z | 898,729 | <p>If it helps, many many binary types begin with a magic numbers. <a href="http://www.garykessler.net/library/file%5Fsigs.html">Here is a list</a> of file signatures.</p>
| 8 | 2009-05-22T16:23:17Z | [
"python",
"file",
"binary"
] |
How can I detect if a file is binary (non-text) in python? | 898,669 | <p>How can I tell if a file is binary (non-text) in python? I am searching through a large set of files in python, and keep getting matches in binary files. This makes the output look incredibly messy.</p>
<p>I know I could use grep -I, but I am doing more with the data than what grep allows for.</p>
<p>In the past I would have just searched for characters greater than 0x7f, but utf8 and the like make that impossible on modern systems. Ideally the solution would be fast, but any solution will do.</p>
| 63 | 2009-05-22T16:09:50Z | 898,759 | <p>Here's a suggestion that uses the Unix <a href="http://en.wikipedia.org/wiki/File%5F%28Unix%29">file</a> command:</p>
<pre><code>import re
import subprocess
def istext(path):
return (re.search(r':.* text',
subprocess.Popen(["file", '-L', path],
stdout=subprocess.PIPE).stdout.read())
is not None)
</code></pre>
<p>Example usage:</p>
<pre>
>>> istext('/etc/motd')
True
>>> istext('/vmlinuz')
False
>>> open('/tmp/japanese').read()
'\xe3\x81\x93\xe3\x82\x8c\xe3\x81\xaf\xe3\x80\x81\xe3\x81\xbf\xe3\x81\x9a\xe3\x81\x8c\xe3\x82\x81\xe5\xba\xa7\xe3\x81\xae\xe6\x99\x82\xe4\xbb\xa3\xe3\x81\xae\xe5\xb9\x95\xe9\x96\x8b\xe3\x81\x91\xe3\x80\x82\n'
>>> istext('/tmp/japanese') # works on UTF-8
True
</pre>
<p>It has the downsides of not being portable to Windows (unless you have something like the <code>file</code> command there), and having to spawn an external process for each file, which might not be palatable.</p>
| 5 | 2009-05-22T16:28:25Z | [
"python",
"file",
"binary"
] |
How can I detect if a file is binary (non-text) in python? | 898,669 | <p>How can I tell if a file is binary (non-text) in python? I am searching through a large set of files in python, and keep getting matches in binary files. This makes the output look incredibly messy.</p>
<p>I know I could use grep -I, but I am doing more with the data than what grep allows for.</p>
<p>In the past I would have just searched for characters greater than 0x7f, but utf8 and the like make that impossible on modern systems. Ideally the solution would be fast, but any solution will do.</p>
| 63 | 2009-05-22T16:09:50Z | 899,956 | <p>If you're not on Windows, you can use <a href="http://pypi.python.org/pypi/python-magic/0.1" rel="nofollow">Python Magic</a> to determine the filetype. Then you can check if it is a text/ mime type.</p>
| 3 | 2009-05-22T20:55:56Z | [
"python",
"file",
"binary"
] |
How can I detect if a file is binary (non-text) in python? | 898,669 | <p>How can I tell if a file is binary (non-text) in python? I am searching through a large set of files in python, and keep getting matches in binary files. This makes the output look incredibly messy.</p>
<p>I know I could use grep -I, but I am doing more with the data than what grep allows for.</p>
<p>In the past I would have just searched for characters greater than 0x7f, but utf8 and the like make that impossible on modern systems. Ideally the solution would be fast, but any solution will do.</p>
| 63 | 2009-05-22T16:09:50Z | 3,002,505 | <p>Try this:</p>
<pre><code>def is_binary(filename):
"""Return true if the given filename is binary.
@raise EnvironmentError: if the file does not exist or cannot be accessed.
@attention: found @ http://bytes.com/topic/python/answers/21222-determine-file-type-binary-text on 6/08/2010
@author: Trent Mick <TrentM@ActiveState.com>
@author: Jorge Orpinel <jorge@orpinel.com>"""
fin = open(filename, 'rb')
try:
CHUNKSIZE = 1024
while 1:
chunk = fin.read(CHUNKSIZE)
if '\0' in chunk: # found null byte
return True
if len(chunk) < CHUNKSIZE:
break # done
# A-wooo! Mira, python no necesita el "except:". Achis... Que listo es.
finally:
fin.close()
return False
</code></pre>
| 9 | 2010-06-09T01:14:54Z | [
"python",
"file",
"binary"
] |
How can I detect if a file is binary (non-text) in python? | 898,669 | <p>How can I tell if a file is binary (non-text) in python? I am searching through a large set of files in python, and keep getting matches in binary files. This makes the output look incredibly messy.</p>
<p>I know I could use grep -I, but I am doing more with the data than what grep allows for.</p>
<p>In the past I would have just searched for characters greater than 0x7f, but utf8 and the like make that impossible on modern systems. Ideally the solution would be fast, but any solution will do.</p>
| 63 | 2009-05-22T16:09:50Z | 3,388,546 | <p>I guess that the best solution is to use the guess_type function. It holds a list with several mimetypes and you can also include your own types.
Here come the script that I did to solve my problem:</p>
<pre><code>from mimetypes import guess_type
from mimetypes import add_type
def __init__(self):
self.__addMimeTypes()
def __addMimeTypes(self):
add_type("text/plain",".properties")
def __listDir(self,path):
try:
return listdir(path)
except IOError:
print ("The directory {0} could not be accessed".format(path))
def getTextFiles(self, path):
asciiFiles = []
for files in self.__listDir(path):
if guess_type(files)[0].split("/")[0] == "text":
asciiFiles.append(files)
try:
return asciiFiles
except NameError:
print ("No text files in directory: {0}".format(path))
finally:
del asciiFiles
</code></pre>
<p>It is inside of a Class, as you can see based on the ustructure of the code. But you can pretty much change the things you want to implement it inside your application.
It`s quite simple to use.
The method getTextFiles returns a list object with all the text files that resides on the directory you pass in path variable.</p>
| 1 | 2010-08-02T14:11:20Z | [
"python",
"file",
"binary"
] |
How can I detect if a file is binary (non-text) in python? | 898,669 | <p>How can I tell if a file is binary (non-text) in python? I am searching through a large set of files in python, and keep getting matches in binary files. This makes the output look incredibly messy.</p>
<p>I know I could use grep -I, but I am doing more with the data than what grep allows for.</p>
<p>In the past I would have just searched for characters greater than 0x7f, but utf8 and the like make that impossible on modern systems. Ideally the solution would be fast, but any solution will do.</p>
| 63 | 2009-05-22T16:09:50Z | 7,392,391 | <p>Yet another method <a href="https://github.com/file/file/blob/f2a6e7cb7db9b5fd86100403df6b2f830c7f22ba/src/encoding.c#L151-L228">based on file(1) behavior</a>:</p>
<pre><code>>>> textchars = bytearray({7,8,9,10,12,13,27} | set(range(0x20, 0x100)) - {0x7f})
>>> is_binary_string = lambda bytes: bool(bytes.translate(None, textchars))
</code></pre>
<p>Example:</p>
<pre><code>>>> is_binary_string(open('/usr/bin/python', 'rb').read(1024))
True
>>> is_binary_string(open('/usr/bin/dh_python3', 'rb').read(1024))
False
</code></pre>
| 34 | 2011-09-12T18:44:23Z | [
"python",
"file",
"binary"
] |
How can I detect if a file is binary (non-text) in python? | 898,669 | <p>How can I tell if a file is binary (non-text) in python? I am searching through a large set of files in python, and keep getting matches in binary files. This makes the output look incredibly messy.</p>
<p>I know I could use grep -I, but I am doing more with the data than what grep allows for.</p>
<p>In the past I would have just searched for characters greater than 0x7f, but utf8 and the like make that impossible on modern systems. Ideally the solution would be fast, but any solution will do.</p>
| 63 | 2009-05-22T16:09:50Z | 8,723,624 | <p>I came here looking for exactly the same thing--a comprehensive solution provided by the standard library to detect binary or text. After reviewing the options people suggested, the nix <strong>file</strong> command looks to be the best choice (I'm only developing for linux boxen). Some others posted solutions using <strong>file</strong> but they are unnecessarily complicated in my opinion, so here's what I came up with:</p>
<pre><code>def test_file_isbinary(filename):
cmd = shlex.split("file -b -e soft '{}'".format(filename))
if subprocess.check_output(cmd)[:4] in {'ASCI', 'UTF-'}:
return False
return True
</code></pre>
<p>It should go without saying, but your code that calls this function should make sure you can read a file before testing it, otherwise this will be mistakenly detect the file as binary.</p>
| 1 | 2012-01-04T07:51:21Z | [
"python",
"file",
"binary"
] |
How can I detect if a file is binary (non-text) in python? | 898,669 | <p>How can I tell if a file is binary (non-text) in python? I am searching through a large set of files in python, and keep getting matches in binary files. This makes the output look incredibly messy.</p>
<p>I know I could use grep -I, but I am doing more with the data than what grep allows for.</p>
<p>In the past I would have just searched for characters greater than 0x7f, but utf8 and the like make that impossible on modern systems. Ideally the solution would be fast, but any solution will do.</p>
| 63 | 2009-05-22T16:09:50Z | 11,301,631 | <p>Shorter solution, with UTF-16 warning:</p>
<pre><code>def is_binary(filename):
"""
Return true if the given filename appears to be binary.
File is considered to be binary if it contains a NULL byte.
FIXME: This approach incorrectly reports UTF-16 as binary.
"""
with open(filename, 'rb') as f:
for block in f:
if '\0' in block:
return True
return False
</code></pre>
| 3 | 2012-07-02T21:45:13Z | [
"python",
"file",
"binary"
] |
How can I detect if a file is binary (non-text) in python? | 898,669 | <p>How can I tell if a file is binary (non-text) in python? I am searching through a large set of files in python, and keep getting matches in binary files. This makes the output look incredibly messy.</p>
<p>I know I could use grep -I, but I am doing more with the data than what grep allows for.</p>
<p>In the past I would have just searched for characters greater than 0x7f, but utf8 and the like make that impossible on modern systems. Ideally the solution would be fast, but any solution will do.</p>
| 63 | 2009-05-22T16:09:50Z | 26,797,705 | <p>Use <a href="https://pypi.python.org/pypi/binaryornot/" rel="nofollow">binaryornot</a> library (<a href="https://github.com/audreyr/binaryornot" rel="nofollow">GitHub</a>).</p>
<p>It is very simple and based on the code found in this stackoverflow question.</p>
<p>You can actually write this in 2 lines of code, however this package saves you from having to write and thoroughly test those 2 lines of code with all sorts of weird file types, cross-platform.</p>
| 3 | 2014-11-07T09:10:05Z | [
"python",
"file",
"binary"
] |
How can I detect if a file is binary (non-text) in python? | 898,669 | <p>How can I tell if a file is binary (non-text) in python? I am searching through a large set of files in python, and keep getting matches in binary files. This makes the output look incredibly messy.</p>
<p>I know I could use grep -I, but I am doing more with the data than what grep allows for.</p>
<p>In the past I would have just searched for characters greater than 0x7f, but utf8 and the like make that impossible on modern systems. Ideally the solution would be fast, but any solution will do.</p>
| 63 | 2009-05-22T16:09:50Z | 30,273,352 | <p>If you're using python3 (and utf-8) it's quite straight forward, just open the file in text mode and stop processing if you get <code>UnicodeDecodeError</code>. Python3 will use unicode when handling file in text mode (and bytearray in binary mode) - if your encoding can't decode arbitrary files it's quite likely that you will get <code>UnicodeDecodError</code>. Example:</p>
<pre><code>try:
with open(filename, "r") as f:
for l in f:
process_line(l)
except UnicodDecodeError:
pass # Fond non-text data
</code></pre>
| 0 | 2015-05-16T08:14:24Z | [
"python",
"file",
"binary"
] |
How can I detect if a file is binary (non-text) in python? | 898,669 | <p>How can I tell if a file is binary (non-text) in python? I am searching through a large set of files in python, and keep getting matches in binary files. This makes the output look incredibly messy.</p>
<p>I know I could use grep -I, but I am doing more with the data than what grep allows for.</p>
<p>In the past I would have just searched for characters greater than 0x7f, but utf8 and the like make that impossible on modern systems. Ideally the solution would be fast, but any solution will do.</p>
| 63 | 2009-05-22T16:09:50Z | 30,572,545 | <p>Most of the programs consider the file to be binary (which is any file that is not "line-oriented") if they contains a <a href="https://en.wikipedia.org/wiki/Null_character" rel="nofollow">NULL character</a>.</p>
<p>Here is perl's version of <code>pp_fttext()</code> (<code>pp_sys.c</code>) implemented in Python:</p>
<pre><code>import sys
PY3 = sys.version_info[0] == 3
# A function that takes an integer in the 8-bit range and returns
# a single-character byte object in py3 / a single-character string
# in py2.
#
int2byte = (lambda x: bytes((x,))) if PY3 else chr
_text_characters = (
b''.join(int2byte(i) for i in range(32, 127)) +
b'\n\r\t\f\b')
def istextfile(fileobj, blocksize=512):
""" Uses heuristics to guess whether the given file is text or binary,
by reading a single block of bytes from the file.
If more than 30% of the chars in the block are non-text, or there
are NUL ('\x00') bytes in the block, assume this is a binary file.
"""
block = fileobj.read(blocksize)
if b'\x00' in block:
# Files with null bytes are binary
return False
elif not block:
# An empty file is considered a valid text file
return True
# Use translate's 'deletechars' argument to efficiently remove all
# occurrences of _text_characters from the block
nontext = block.translate(None, _text_characters)
return float(len(nontext)) / len(block) <= 0.30
</code></pre>
<blockquote>
<p>Note also that this code was written to run on both Python 2 and Python 3 without changes.</p>
</blockquote>
<p>Source: <a href="http://eli.thegreenplace.net/2011/10/19/perls-guess-if-file-is-text-or-binary-implemented-in-python/" rel="nofollow">Perl's "guess if file is text or binary" implemented in Python</a></p>
| -1 | 2015-06-01T11:39:45Z | [
"python",
"file",
"binary"
] |
How can I detect if a file is binary (non-text) in python? | 898,669 | <p>How can I tell if a file is binary (non-text) in python? I am searching through a large set of files in python, and keep getting matches in binary files. This makes the output look incredibly messy.</p>
<p>I know I could use grep -I, but I am doing more with the data than what grep allows for.</p>
<p>In the past I would have just searched for characters greater than 0x7f, but utf8 and the like make that impossible on modern systems. Ideally the solution would be fast, but any solution will do.</p>
| 63 | 2009-05-22T16:09:50Z | 30,580,748 | <p>Simpler way is to check if the file consist NULL character (<code>\x00</code>) by using <code>in</code> operator, for instance:</p>
<pre><code>b'\x00' in open("foo.bar", 'rb').read()
</code></pre>
<p>See below the complete example:</p>
<pre><code>#!/usr/bin/env python3
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('file', nargs=1)
args = parser.parse_args()
with open(args.file[0], 'rb') as f:
if b'\x00' in f.read():
print('The file is binary!')
else:
print('The file is not binary!')
</code></pre>
<p>Sample usage:</p>
<pre><code>$ ./is_binary.py /etc/hosts
The file is not binary!
$ ./is_binary.py `which which`
The file is binary!
</code></pre>
| -1 | 2015-06-01T18:35:59Z | [
"python",
"file",
"binary"
] |
How do you set the text direction for a TextTable Cell in OpenOffice? | 898,739 | <p>I want to set the text direction for some cells in a TextTable so that they are vertical (i.e., the text is landscape instead of portrait).
You can do this in Writer by selecting the cell(s), and going to:
Table - Text Properties - Text Flow - Text Direction</p>
<p>However, I cannot figure out how to do this through the API. I tried using CharRotation, but it does not behave the right way. CharRotation simply takes the text, and rotates it (without adjusting any formatting). The text I am dealing with is formatted by tab stops, and does not behave correctly when rotated this way.</p>
| 1 | 2009-05-22T16:24:54Z | 1,664,320 | <p>I finally figured this out after all these months!</p>
<p>You have to set the "WritingMode" property for the cell. In C#:</p>
<pre><code>XCell cell = table.getCellByName(cellName);
((XPropertySet)cell).setPropertyValue("WritingMode", new Any((short)
WritingMode.TB_RL));
</code></pre>
<p>I haven't tried it in python yet, but I suppose it would be something like this:</p>
<pre><code>cell = table.getCellByName(cellName)
cell.WritingMode = 2
</code></pre>
<p>If you're using a statically typed language, make sure you cast it to a short. Doing <code>typeof(WritingMode)</code> won't work, for some odd reason.</p>
<p>See <a href="http://www.openoffice.org/issues/show%5Fbug.cgi?id=106535" rel="nofollow">this issue</a> in the OOo bug tracker.</p>
| 0 | 2009-11-02T23:09:47Z | [
"c#",
"python",
"openoffice.org",
"openoffice-writer",
"uno"
] |
In Python how do I sort a list of dictionaries by a certain value of the dictionary + alphabetically? | 898,773 | <p>Ok, here's what I'm trying to do... I know that itemgetter() sort could to alphabetical sort easy, but if I have something like this:</p>
<blockquote>
<p>[{'Name':'TOTAL', 'Rank':100},
{'Name':'Woo Company', 'Rank':15},
{'Name':'ABC Company', 'Rank':20}]</p>
</blockquote>
<p>And I want it sorted alphabetically (by Name) + include the condition that the one with Name:'TOTAL' should be listed last in the sequence, like this:</p>
<blockquote>
<p>[{'Name':'ABC Company', 'Rank':20},
{'Name':'Woo Company', 'Rank':15},
{'Name':'TOTAL', 'Rank':100}]</p>
</blockquote>
<p>How would I do that?</p>
| 3 | 2009-05-22T16:33:27Z | 898,790 | <p>Use the <a href="http://wiki.python.org/moin/HowTo/Sorting#Sortingbykeys" rel="nofollow">key</a> parameter of sort or sorted.</p>
<p>For example:</p>
<pre><code>dicts = [
{'Name':'TOTAL', 'Rank':100},
{'Name':'Woo Company', 'Rank':15},
{'Name':'ABC Company', 'Rank':20}
]
def total_last(d):
if d['Name'] == 'TOTAL':
return '\xff\xff\xff\xff\xff\xff'
return d['Name'].lower()
import pprint
pprint.pprint(sorted(dicts, key = total_last))
>python sort_dict.py
[{'Name': 'ABC Company', 'Rank': 20},
{'Name': 'Woo Company', 'Rank': 15},
{'Name': 'TOTAL', 'Rank': 100}]
</code></pre>
| 0 | 2009-05-22T16:38:08Z | [
"python",
"list",
"sorting",
"dictionary"
] |
In Python how do I sort a list of dictionaries by a certain value of the dictionary + alphabetically? | 898,773 | <p>Ok, here's what I'm trying to do... I know that itemgetter() sort could to alphabetical sort easy, but if I have something like this:</p>
<blockquote>
<p>[{'Name':'TOTAL', 'Rank':100},
{'Name':'Woo Company', 'Rank':15},
{'Name':'ABC Company', 'Rank':20}]</p>
</blockquote>
<p>And I want it sorted alphabetically (by Name) + include the condition that the one with Name:'TOTAL' should be listed last in the sequence, like this:</p>
<blockquote>
<p>[{'Name':'ABC Company', 'Rank':20},
{'Name':'Woo Company', 'Rank':15},
{'Name':'TOTAL', 'Rank':100}]</p>
</blockquote>
<p>How would I do that?</p>
| 3 | 2009-05-22T16:33:27Z | 898,791 | <p>The best approach here is to decorate the sort key... Python will sort a tuple by the tuple components in order, so build a tuple key with your sorting criteria:</p>
<pre><code>sorted(list_of_dicts, key=lambda d: (d['Name'] == 'TOTAL', d['Name'].lower()))
</code></pre>
<p>This results in a sort key of:</p>
<ul>
<li>(True, 'total') for {'Name': 'TOTAL', 'Rank': 100}</li>
<li>(False, 'woo company') for {'Name': 'Woo Company', 'Rank': 15}</li>
<li>(False, 'abc company') for {'Name': 'ABC Company', 'Rank': 20}</li>
</ul>
<p>Since False sorts earlier than True, the ones whose names aren't TOTAL will end up together, then be sorted alphabetically, and TOTAL will end up at the end. </p>
| 10 | 2009-05-22T16:38:18Z | [
"python",
"list",
"sorting",
"dictionary"
] |
In Python how do I sort a list of dictionaries by a certain value of the dictionary + alphabetically? | 898,773 | <p>Ok, here's what I'm trying to do... I know that itemgetter() sort could to alphabetical sort easy, but if I have something like this:</p>
<blockquote>
<p>[{'Name':'TOTAL', 'Rank':100},
{'Name':'Woo Company', 'Rank':15},
{'Name':'ABC Company', 'Rank':20}]</p>
</blockquote>
<p>And I want it sorted alphabetically (by Name) + include the condition that the one with Name:'TOTAL' should be listed last in the sequence, like this:</p>
<blockquote>
<p>[{'Name':'ABC Company', 'Rank':20},
{'Name':'Woo Company', 'Rank':15},
{'Name':'TOTAL', 'Rank':100}]</p>
</blockquote>
<p>How would I do that?</p>
| 3 | 2009-05-22T16:33:27Z | 898,796 | <pre><code>>>> lst = [{'Name':'TOTAL', 'Rank':100}, {'Name':'Woo Company', 'Rank':15}, {'Name':'ABC Company', 'Rank':20}]
>>> lst.sort(key=lambda d: (d['Name']=='TOTAL',d['Name'].lower()))
>>> print lst
[{'Name': 'ABC Company', 'Rank': 20}, {'Name': 'Woo Company', 'Rank': 15}, {'Name': 'TOTAL', 'Rank': 100}]
</code></pre>
| 1 | 2009-05-22T16:39:07Z | [
"python",
"list",
"sorting",
"dictionary"
] |
In Python how do I sort a list of dictionaries by a certain value of the dictionary + alphabetically? | 898,773 | <p>Ok, here's what I'm trying to do... I know that itemgetter() sort could to alphabetical sort easy, but if I have something like this:</p>
<blockquote>
<p>[{'Name':'TOTAL', 'Rank':100},
{'Name':'Woo Company', 'Rank':15},
{'Name':'ABC Company', 'Rank':20}]</p>
</blockquote>
<p>And I want it sorted alphabetically (by Name) + include the condition that the one with Name:'TOTAL' should be listed last in the sequence, like this:</p>
<blockquote>
<p>[{'Name':'ABC Company', 'Rank':20},
{'Name':'Woo Company', 'Rank':15},
{'Name':'TOTAL', 'Rank':100}]</p>
</blockquote>
<p>How would I do that?</p>
| 3 | 2009-05-22T16:33:27Z | 898,798 | <p>Well, I would sort it in multiple passes, using list's sort method.</p>
<pre><code>list = [{'Name':'TOTAL', 'Rank':100}, {'Name':'Woo Company', 'Rank':15}, {'Name':'ABC Company', 'Rank':20}]
list.sort(key = lambda x: x['Name']) # Sorted by Name, alphabetically
list.sort(key = lambda x: 'b' if x['Name'] == 'TOTAL' else 'a')
</code></pre>
| -1 | 2009-05-22T16:39:27Z | [
"python",
"list",
"sorting",
"dictionary"
] |
How should I verify a log message when testing Python code under nose? | 899,067 | <p>I'm trying to write a simple unit test that will verify that, under a certain condition, a class in my application will log an error via the standard logging API. I can't work out what the cleanest way to test this situation is.</p>
<p>I know that nose already captures logging output through it's logging plugin, but this seems to be intended as a reporting and debugging aid for failed tests. </p>
<p>The two ways to do this I can see are:</p>
<ul>
<li>Mock out the logging module, either in a piecemeal way (mymodule.logging = mockloggingmodule) or with a proper mocking library.</li>
<li>Write or use an existing nose plugin to capture the output and verify it.</li>
</ul>
<p>If I go for the former approach, I'd like to know what the cleanest way to reset the global state to what it was before I mocked out the logging module.</p>
<p>Looking forward to your hints and tips on this one...</p>
| 19 | 2009-05-22T17:42:46Z | 899,106 | <p>You should use mocking, as someday You might want to change Your logger to a, say, database one. You won't be happy if it'll try to connect to the database during nosetests.</p>
<p>Mocking will continue to work even if standard output will be suppressed.</p>
<p>I have used <a href="http://code.google.com/p/pymox/wiki/MoxDocumentation" rel="nofollow">pyMox</a>'s stubs. Remember to unset the stubs after the test.</p>
| 1 | 2009-05-22T17:52:39Z | [
"python",
"unit-testing",
"mocking",
"nose"
] |
How should I verify a log message when testing Python code under nose? | 899,067 | <p>I'm trying to write a simple unit test that will verify that, under a certain condition, a class in my application will log an error via the standard logging API. I can't work out what the cleanest way to test this situation is.</p>
<p>I know that nose already captures logging output through it's logging plugin, but this seems to be intended as a reporting and debugging aid for failed tests. </p>
<p>The two ways to do this I can see are:</p>
<ul>
<li>Mock out the logging module, either in a piecemeal way (mymodule.logging = mockloggingmodule) or with a proper mocking library.</li>
<li>Write or use an existing nose plugin to capture the output and verify it.</li>
</ul>
<p>If I go for the former approach, I'd like to know what the cleanest way to reset the global state to what it was before I mocked out the logging module.</p>
<p>Looking forward to your hints and tips on this one...</p>
| 19 | 2009-05-22T17:42:46Z | 899,109 | <p>Found <a href="http://www.fubar.si/2009/3/4/mocking-logging-python-module-for-unittests" rel="nofollow">one answer</a> since I posted this. Not bad.</p>
| 0 | 2009-05-22T17:52:55Z | [
"python",
"unit-testing",
"mocking",
"nose"
] |
How should I verify a log message when testing Python code under nose? | 899,067 | <p>I'm trying to write a simple unit test that will verify that, under a certain condition, a class in my application will log an error via the standard logging API. I can't work out what the cleanest way to test this situation is.</p>
<p>I know that nose already captures logging output through it's logging plugin, but this seems to be intended as a reporting and debugging aid for failed tests. </p>
<p>The two ways to do this I can see are:</p>
<ul>
<li>Mock out the logging module, either in a piecemeal way (mymodule.logging = mockloggingmodule) or with a proper mocking library.</li>
<li>Write or use an existing nose plugin to capture the output and verify it.</li>
</ul>
<p>If I go for the former approach, I'd like to know what the cleanest way to reset the global state to what it was before I mocked out the logging module.</p>
<p>Looking forward to your hints and tips on this one...</p>
| 19 | 2009-05-22T17:42:46Z | 900,340 | <p>As a follow up to Reef's answer, I took a liberty of coding up an example using <a href="http://code.google.com/p/pymox/" rel="nofollow">pymox</a>.
It introduces some extra helper functions that make it easier to stub functions and methods.</p>
<pre><code>import logging
# Code under test:
class Server(object):
def __init__(self):
self._payload_count = 0
def do_costly_work(self, payload):
# resource intensive logic elided...
pass
def process(self, payload):
self.do_costly_work(payload)
self._payload_count += 1
logging.info("processed payload: %s", payload)
logging.debug("payloads served: %d", self._payload_count)
# Here are some helper functions
# that are useful if you do a lot
# of pymox-y work.
import mox
import inspect
import contextlib
import unittest
def stub_all(self, *targets):
for target in targets:
if inspect.isfunction(target):
module = inspect.getmodule(target)
self.StubOutWithMock(module, target.__name__)
elif inspect.ismethod(target):
self.StubOutWithMock(target.im_self or target.im_class, target.__name__)
else:
raise NotImplementedError("I don't know how to stub %s" % repr(target))
# Monkey-patch Mox class with our helper 'StubAll' method.
# Yucky pymox naming convention observed.
setattr(mox.Mox, 'StubAll', stub_all)
@contextlib.contextmanager
def mocking():
mocks = mox.Mox()
try:
yield mocks
finally:
mocks.UnsetStubs() # Important!
mocks.VerifyAll()
# The test case example:
class ServerTests(unittest.TestCase):
def test_logging(self):
s = Server()
with mocking() as m:
m.StubAll(s.do_costly_work, logging.info, logging.debug)
# expectations
s.do_costly_work(mox.IgnoreArg()) # don't care, we test logging here.
logging.info("processed payload: %s", 'hello')
logging.debug("payloads served: %d", 1)
# verified execution
m.ReplayAll()
s.process('hello')
if __name__ == '__main__':
unittest.main()
</code></pre>
| 3 | 2009-05-22T22:57:26Z | [
"python",
"unit-testing",
"mocking",
"nose"
] |
How should I verify a log message when testing Python code under nose? | 899,067 | <p>I'm trying to write a simple unit test that will verify that, under a certain condition, a class in my application will log an error via the standard logging API. I can't work out what the cleanest way to test this situation is.</p>
<p>I know that nose already captures logging output through it's logging plugin, but this seems to be intended as a reporting and debugging aid for failed tests. </p>
<p>The two ways to do this I can see are:</p>
<ul>
<li>Mock out the logging module, either in a piecemeal way (mymodule.logging = mockloggingmodule) or with a proper mocking library.</li>
<li>Write or use an existing nose plugin to capture the output and verify it.</li>
</ul>
<p>If I go for the former approach, I'd like to know what the cleanest way to reset the global state to what it was before I mocked out the logging module.</p>
<p>Looking forward to your hints and tips on this one...</p>
| 19 | 2009-05-22T17:42:46Z | 1,049,375 | <p>I used to mock loggers, but in this situation I found best to use logging handlers, so I wrote this one based on <a href="http://www.fubar.si/2009/3/4/mocking-logging-python-module-for-unittests">the document suggested by jkp</a>:</p>
<pre><code>class MockLoggingHandler(logging.Handler):
"""Mock logging handler to check for expected logs."""
def __init__(self, *args, **kwargs):
self.reset()
logging.Handler.__init__(self, *args, **kwargs)
def emit(self, record):
self.messages[record.levelname.lower()].append(record.getMessage())
def reset(self):
self.messages = {
'debug': [],
'info': [],
'warning': [],
'error': [],
'critical': [],
}
</code></pre>
| 15 | 2009-06-26T14:13:44Z | [
"python",
"unit-testing",
"mocking",
"nose"
] |
How should I verify a log message when testing Python code under nose? | 899,067 | <p>I'm trying to write a simple unit test that will verify that, under a certain condition, a class in my application will log an error via the standard logging API. I can't work out what the cleanest way to test this situation is.</p>
<p>I know that nose already captures logging output through it's logging plugin, but this seems to be intended as a reporting and debugging aid for failed tests. </p>
<p>The two ways to do this I can see are:</p>
<ul>
<li>Mock out the logging module, either in a piecemeal way (mymodule.logging = mockloggingmodule) or with a proper mocking library.</li>
<li>Write or use an existing nose plugin to capture the output and verify it.</li>
</ul>
<p>If I go for the former approach, I'd like to know what the cleanest way to reset the global state to what it was before I mocked out the logging module.</p>
<p>Looking forward to your hints and tips on this one...</p>
| 19 | 2009-05-22T17:42:46Z | 14,666,268 | <p>Fortunately this is not something that you have to write yourself; the <code>testfixtures</code> package provides a context manager that captures all logging output that occurs in the body of the <code>with</code> statement. You can find the package here:</p>
<p><a href="http://pypi.python.org/pypi/testfixtures">http://pypi.python.org/pypi/testfixtures</a></p>
<p>And here are its docs about how to test logging:</p>
<p><a href="http://testfixtures.readthedocs.org/en/latest/logging.html">http://testfixtures.readthedocs.org/en/latest/logging.html</a></p>
| 18 | 2013-02-02T20:36:27Z | [
"python",
"unit-testing",
"mocking",
"nose"
] |
How should I verify a log message when testing Python code under nose? | 899,067 | <p>I'm trying to write a simple unit test that will verify that, under a certain condition, a class in my application will log an error via the standard logging API. I can't work out what the cleanest way to test this situation is.</p>
<p>I know that nose already captures logging output through it's logging plugin, but this seems to be intended as a reporting and debugging aid for failed tests. </p>
<p>The two ways to do this I can see are:</p>
<ul>
<li>Mock out the logging module, either in a piecemeal way (mymodule.logging = mockloggingmodule) or with a proper mocking library.</li>
<li>Write or use an existing nose plugin to capture the output and verify it.</li>
</ul>
<p>If I go for the former approach, I'd like to know what the cleanest way to reset the global state to what it was before I mocked out the logging module.</p>
<p>Looking forward to your hints and tips on this one...</p>
| 19 | 2009-05-22T17:42:46Z | 20,553,331 | <p>This answer extends the work done in <a href="http://stackoverflow.com/a/1049375/1286628">http://stackoverflow.com/a/1049375/1286628</a>. The handler is largely the same (the constructor is more idiomatic, using <code>super</code>, and <code>emit</code> is now thread safe for testing asynchronous code such as Celery tasks). Further, I add a demonstration of how to use the handler with the standard library's <code>unittest</code>.</p>
<pre><code>class MockLoggingHandler(logging.Handler):
"""Mock logging handler to check for expected logs.
Messages are available from an instance's ``messages`` dict, in order, indexed by
a lowercase log level string (e.g., 'debug', 'info', etc.).
"""
def __init__(self, *args, **kwargs):
self.messages = {'debug': [], 'info': [], 'warning': [], 'error': [],
'critical': []}
super(MockLoggingHandler, self).__init__(*args, **kwargs)
def emit(self, record):
"Store a message from ``record`` in the instance's ``messages`` dict."
self.acquire()
try:
self.messages[record.levelname.lower()].append(record.getMessage())
finally:
self.release()
def reset(self):
self.acquire()
try:
for message_list in self.messages.values():
message_list.clear()
finally:
self.release()
</code></pre>
<p>Then you can use the handler in a standard-library <code>unittest.TestCase</code> like so:</p>
<pre><code>import unittest
import logging
import foo
class TestFoo(unittest.TestCase):
@classmethod
def setUpClass(cls):
super(TestFoo, cls).setUpClass()
# Assuming you follow Python's logging module's documentation's
# recommendation about naming your module's logs after the module's
# __name__,the following getLogger call should fetch the same logger
# you use in the foo module
foo_log = logging.getLogger(foo.__name__)
cls._foo_log_handler = MockLoggingHandler(level='DEBUG')
foo_log.addHandler(cls.foo_log_handler)
cls.foo_log_messages = cls._foo_log_handler.messages
def setUp(self):
super(TestFoo, self).setUp()
self._foo_log_handler.reset() # So each test is independent
def test_foo_objects_fromble_nicely(self):
# Do a bunch of frombling with foo objects
# Now check that they've logged 5 frombling messages at the INFO level
self.assertEqual(len(self.foo_log_messages['info']), 5)
for info_message in self.foo_log_messages['info']:
self.assertIn('fromble', info_message)
</code></pre>
| 11 | 2013-12-12T20:15:41Z | [
"python",
"unit-testing",
"mocking",
"nose"
] |
How should I verify a log message when testing Python code under nose? | 899,067 | <p>I'm trying to write a simple unit test that will verify that, under a certain condition, a class in my application will log an error via the standard logging API. I can't work out what the cleanest way to test this situation is.</p>
<p>I know that nose already captures logging output through it's logging plugin, but this seems to be intended as a reporting and debugging aid for failed tests. </p>
<p>The two ways to do this I can see are:</p>
<ul>
<li>Mock out the logging module, either in a piecemeal way (mymodule.logging = mockloggingmodule) or with a proper mocking library.</li>
<li>Write or use an existing nose plugin to capture the output and verify it.</li>
</ul>
<p>If I go for the former approach, I'd like to know what the cleanest way to reset the global state to what it was before I mocked out the logging module.</p>
<p>Looking forward to your hints and tips on this one...</p>
| 19 | 2009-05-22T17:42:46Z | 27,272,467 | <p>The <code>ExpectLog</code> class implemented in tornado is a great utility:</p>
<pre><code>with ExpectLog('channel', 'message regex'):
do_it()
</code></pre>
<p><a href="http://tornado.readthedocs.org/en/latest/_modules/tornado/testing.html#ExpectLog" rel="nofollow">http://tornado.readthedocs.org/en/latest/_modules/tornado/testing.html#ExpectLog</a></p>
| 0 | 2014-12-03T13:03:35Z | [
"python",
"unit-testing",
"mocking",
"nose"
] |
How should I verify a log message when testing Python code under nose? | 899,067 | <p>I'm trying to write a simple unit test that will verify that, under a certain condition, a class in my application will log an error via the standard logging API. I can't work out what the cleanest way to test this situation is.</p>
<p>I know that nose already captures logging output through it's logging plugin, but this seems to be intended as a reporting and debugging aid for failed tests. </p>
<p>The two ways to do this I can see are:</p>
<ul>
<li>Mock out the logging module, either in a piecemeal way (mymodule.logging = mockloggingmodule) or with a proper mocking library.</li>
<li>Write or use an existing nose plugin to capture the output and verify it.</li>
</ul>
<p>If I go for the former approach, I'd like to know what the cleanest way to reset the global state to what it was before I mocked out the logging module.</p>
<p>Looking forward to your hints and tips on this one...</p>
| 19 | 2009-05-22T17:42:46Z | 28,306,238 | <p>Brandon's answer:</p>
<pre><code>pip install testfixtures
</code></pre>
<p>snippet:</p>
<pre><code>import logging
from testfixtures import LogCapture
logger = logging.getLogger('')
with LogCapture() as logs:
# my awesome code
logger.error('My code logged an error')
assert 'My code logged an error' in str(logs)
</code></pre>
<p>Note: the above does not conflict with calling <strong>nosetests</strong> and getting the output of logCapture plugin of the tool</p>
| 5 | 2015-02-03T18:33:46Z | [
"python",
"unit-testing",
"mocking",
"nose"
] |
How should I verify a log message when testing Python code under nose? | 899,067 | <p>I'm trying to write a simple unit test that will verify that, under a certain condition, a class in my application will log an error via the standard logging API. I can't work out what the cleanest way to test this situation is.</p>
<p>I know that nose already captures logging output through it's logging plugin, but this seems to be intended as a reporting and debugging aid for failed tests. </p>
<p>The two ways to do this I can see are:</p>
<ul>
<li>Mock out the logging module, either in a piecemeal way (mymodule.logging = mockloggingmodule) or with a proper mocking library.</li>
<li>Write or use an existing nose plugin to capture the output and verify it.</li>
</ul>
<p>If I go for the former approach, I'd like to know what the cleanest way to reset the global state to what it was before I mocked out the logging module.</p>
<p>Looking forward to your hints and tips on this one...</p>
| 19 | 2009-05-22T17:42:46Z | 34,734,362 | <p>Keying off @Reef's answer, I did tried the code below. It works well for me both for Python 2.7 (if you install <a href="https://pypi.python.org/pypi/mock" rel="nofollow">mock</a>) and for Python 3.4.</p>
<pre><code>"""
Demo using a mock to test logging output.
"""
import logging
try:
import unittest
except ImportError:
import unittest2 as unittest
try:
# Python >= 3.3
from unittest.mock import Mock, patch
except ImportError:
from mock import Mock, patch
logging.basicConfig()
LOG=logging.getLogger("(logger under test)")
class TestLoggingOutput(unittest.TestCase):
""" Demo using Mock to test logging INPUT. That is, it tests what
parameters were used to invoke the logging method, while still
allowing actual logger to execute normally.
"""
def test_logger_log(self):
"""Check for Logger.log call."""
original_logger = LOG
patched_log = patch('__main__.LOG.log',
side_effect=original_logger.log).start()
log_msg = 'My log msg.'
level = logging.ERROR
LOG.log(level, log_msg)
# call_args is a tuple of positional and kwargs of the last call
# to the mocked function.
# Also consider using call_args_list
# See: https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.call_args
expected = (level, log_msg)
self.assertEqual(expected, patched_log.call_args[0])
if __name__ == '__main__':
unittest.main()
</code></pre>
| 0 | 2016-01-12T01:54:46Z | [
"python",
"unit-testing",
"mocking",
"nose"
] |
How should I verify a log message when testing Python code under nose? | 899,067 | <p>I'm trying to write a simple unit test that will verify that, under a certain condition, a class in my application will log an error via the standard logging API. I can't work out what the cleanest way to test this situation is.</p>
<p>I know that nose already captures logging output through it's logging plugin, but this seems to be intended as a reporting and debugging aid for failed tests. </p>
<p>The two ways to do this I can see are:</p>
<ul>
<li>Mock out the logging module, either in a piecemeal way (mymodule.logging = mockloggingmodule) or with a proper mocking library.</li>
<li>Write or use an existing nose plugin to capture the output and verify it.</li>
</ul>
<p>If I go for the former approach, I'd like to know what the cleanest way to reset the global state to what it was before I mocked out the logging module.</p>
<p>Looking forward to your hints and tips on this one...</p>
| 19 | 2009-05-22T17:42:46Z | 34,920,727 | <p>From python 3.4 on, the standard <em>unittest</em> library offers a new test assertion context manager, <code>assertLogs</code>. From the <a href="https://docs.python.org/3.4/library/unittest.html#unittest.TestCase.assertLogs">docs</a>:</p>
<pre><code>with self.assertLogs('foo', level='INFO') as cm:
logging.getLogger('foo').info('first message')
logging.getLogger('foo.bar').error('second message')
self.assertEqual(cm.output, ['INFO:foo:first message',
'ERROR:foo.bar:second message'])
</code></pre>
| 5 | 2016-01-21T10:08:28Z | [
"python",
"unit-testing",
"mocking",
"nose"
] |
Writing a list to a file with Python | 899,103 | <p>Is this the cleanest way to write a list to a file, since <code>writelines()</code> doesn't insert newline characters?</p>
<pre><code>file.writelines(["%s\n" % item for item in list])
</code></pre>
<p>It seems like there would be a standard way...</p>
| 214 | 2009-05-22T17:52:18Z | 899,149 | <p>The best way is:</p>
<pre><code>outfile.write("\n".join(itemlist))
</code></pre>
| 115 | 2009-05-22T17:58:40Z | [
"python",
"file",
"list",
"file-io",
"newline"
] |
Writing a list to a file with Python | 899,103 | <p>Is this the cleanest way to write a list to a file, since <code>writelines()</code> doesn't insert newline characters?</p>
<pre><code>file.writelines(["%s\n" % item for item in list])
</code></pre>
<p>It seems like there would be a standard way...</p>
| 214 | 2009-05-22T17:52:18Z | 899,176 | <blockquote>
<p><strong>EDIT</strong> Adding info from <a href="http://stackoverflow.com/users/306312/thomas">Thomas</a>' comment</p>
<p>Don't forget to open the file first</p>
<p>thefile = open('test.txt', 'w')</p>
</blockquote>
<p>I'd use a loop:</p>
<pre><code>for item in thelist:
thefile.write("%s\n" % item)
</code></pre>
<p>or:</p>
<pre><code>for item in thelist:
print>>thefile, item
</code></pre>
<p>If you're keen on a single function call, at least remove the square brackets <code>[]</code> so that the strings to be printed get made one at a time (a genexp rather than a listcomp) -- no reason to take up all the memory required to materialize the whole list of strings.</p>
| 313 | 2009-05-22T18:04:21Z | [
"python",
"file",
"list",
"file-io",
"newline"
] |
Writing a list to a file with Python | 899,103 | <p>Is this the cleanest way to write a list to a file, since <code>writelines()</code> doesn't insert newline characters?</p>
<pre><code>file.writelines(["%s\n" % item for item in list])
</code></pre>
<p>It seems like there would be a standard way...</p>
| 214 | 2009-05-22T17:52:18Z | 899,199 | <p>What are you going to do with the file? Does this file exist for humans, or other programs with clear interoperability requirements, or are you just trying to serialize a list to disk for later use by the same python app. If the second case is it, you should be <a href="http://docs.python.org/library/pickle.html">pickleing</a> the list.</p>
<pre><code>import pickle
pickle.dump(itemlist, outfile)
</code></pre>
<p>To read it back:</p>
<pre><code>itemlist = pickle.load(infile)
</code></pre>
| 130 | 2009-05-22T18:10:04Z | [
"python",
"file",
"list",
"file-io",
"newline"
] |
Writing a list to a file with Python | 899,103 | <p>Is this the cleanest way to write a list to a file, since <code>writelines()</code> doesn't insert newline characters?</p>
<pre><code>file.writelines(["%s\n" % item for item in list])
</code></pre>
<p>It seems like there would be a standard way...</p>
| 214 | 2009-05-22T17:52:18Z | 899,254 | <p>Yet another way. Serialize to json using <a href="http://code.google.com/p/simplejson/">simplejson</a> (included as <a href="http://docs.python.org/library/json.html">json</a> in python 2.6):</p>
<pre><code>>>> import simplejson
>>> f = open('output.txt', 'w')
>>> simplejson.dump([1,2,3,4], f)
>>> f.close()
</code></pre>
<p>If you examine output.txt:</p>
<blockquote>
<p>[1, 2, 3, 4]</p>
</blockquote>
<p>This is useful because the syntax is pythonic, it's human readable, and it can be read by other programs in other languages.</p>
| 46 | 2009-05-22T18:20:19Z | [
"python",
"file",
"list",
"file-io",
"newline"
] |
Writing a list to a file with Python | 899,103 | <p>Is this the cleanest way to write a list to a file, since <code>writelines()</code> doesn't insert newline characters?</p>
<pre><code>file.writelines(["%s\n" % item for item in list])
</code></pre>
<p>It seems like there would be a standard way...</p>
| 214 | 2009-05-22T17:52:18Z | 899,301 | <pre><code>file.write('\n'.join(list))
</code></pre>
| 8 | 2009-05-22T18:29:47Z | [
"python",
"file",
"list",
"file-io",
"newline"
] |
Writing a list to a file with Python | 899,103 | <p>Is this the cleanest way to write a list to a file, since <code>writelines()</code> doesn't insert newline characters?</p>
<pre><code>file.writelines(["%s\n" % item for item in list])
</code></pre>
<p>It seems like there would be a standard way...</p>
| 214 | 2009-05-22T17:52:18Z | 5,032,851 | <p>I thought it would be interesting to explore the benefits of using a genexp, so here's my take.</p>
<p>The example in the question uses square brackets to create a temporary list, and so is equivalent to:</p>
<pre><code>file.writelines( list( "%s\n" % item for item in list ) )
</code></pre>
<p>Which needlessly constructs a temporary list of all the lines that will be written out, this may consume significant amounts of memory depending on the size of your list and how verbose the output of <code>str(item)</code> is.</p>
<p>Drop the square brackets (equivalent to removing the wrapping <code>list()</code> call above) will instead pass a temporary <a href="http://www.python.org/dev/peps/pep-0255/">generator</a> to <code>file.writelines()</code>:</p>
<pre><code>file.writelines( "%s\n" % item for item in list )
</code></pre>
<p>This generator will create newline-terminated representation of your <code>item</code> objects on-demand (i.e. as they are written out). This is nice for a couple of reasons:</p>
<ul>
<li>Memory overheads are small, even for very large lists</li>
<li>If <code>str(item)</code> is slow there's visible progress in the file as each item is processed</li>
</ul>
<hr>
<p>This avoids memory issues, such as:</p>
<pre><code>In [1]: import os
In [2]: f = file(os.devnull, "w")
In [3]: %timeit f.writelines( "%s\n" % item for item in xrange(2**20) )
1 loops, best of 3: 385 ms per loop
In [4]: %timeit f.writelines( ["%s\n" % item for item in xrange(2**20)] )
ERROR: Internal Python error in the inspect module.
Below is the traceback from this internal error.
Traceback (most recent call last):
...
MemoryError
</code></pre>
<p>(I triggered this error by limiting Python's max. virtual memory to ~100MB with <code>ulimit -v 102400</code>).</p>
<p>Putting memory usage to one side, this method isn't actually any faster than the original:</p>
<pre><code>In [4]: %timeit f.writelines( "%s\n" % item for item in xrange(2**20) )
1 loops, best of 3: 370 ms per loop
In [5]: %timeit f.writelines( ["%s\n" % item for item in xrange(2**20)] )
1 loops, best of 3: 360 ms per loop
</code></pre>
<p>(Python 2.6.2 on Linux)</p>
| 21 | 2011-02-17T18:13:19Z | [
"python",
"file",
"list",
"file-io",
"newline"
] |
Writing a list to a file with Python | 899,103 | <p>Is this the cleanest way to write a list to a file, since <code>writelines()</code> doesn't insert newline characters?</p>
<pre><code>file.writelines(["%s\n" % item for item in list])
</code></pre>
<p>It seems like there would be a standard way...</p>
| 214 | 2009-05-22T17:52:18Z | 5,787,168 | <p>Let avg be the list, then:</p>
<pre><code>In [29]: a = n.array((avg))
In [31]: a.tofile('avgpoints.dat',sep='\n',dtype = '%f')
</code></pre>
<p>You can use <code>%e</code> or <code>%s</code> depending on your requirement.</p>
| -1 | 2011-04-26T07:16:32Z | [
"python",
"file",
"list",
"file-io",
"newline"
] |
Writing a list to a file with Python | 899,103 | <p>Is this the cleanest way to write a list to a file, since <code>writelines()</code> doesn't insert newline characters?</p>
<pre><code>file.writelines(["%s\n" % item for item in list])
</code></pre>
<p>It seems like there would be a standard way...</p>
| 214 | 2009-05-22T17:52:18Z | 6,791,534 | <p>Using <strong>Python 3</strong> syntax:</p>
<pre><code>with open(filepath, 'w') as file_handler:
for item in the_list:
file_handler.write("{}\n".format(item))
</code></pre>
<p>This is platform-independent.</p>
| 28 | 2011-07-22T14:30:50Z | [
"python",
"file",
"list",
"file-io",
"newline"
] |
Writing a list to a file with Python | 899,103 | <p>Is this the cleanest way to write a list to a file, since <code>writelines()</code> doesn't insert newline characters?</p>
<pre><code>file.writelines(["%s\n" % item for item in list])
</code></pre>
<p>It seems like there would be a standard way...</p>
| 214 | 2009-05-22T17:52:18Z | 16,452,689 | <h1>In General</h1>
<p>Following is the syntax for <strong>writelines()</strong> method</p>
<pre><code>fileObject.writelines( sequence )
</code></pre>
<h1>Example</h1>
<pre><code>#!/usr/bin/python
# Open a file
fo = open("foo.txt", "rw+")
seq = ["This is 6th line\n", "This is 7th line"]
# Write sequence of lines at the end of the file.
line = fo.writelines( seq )
# Close opend file
fo.close()
</code></pre>
<h1>Reference</h1>
<p><a href="http://www.tutorialspoint.com/python/file_writelines.htm">http://www.tutorialspoint.com/python/file_writelines.htm</a></p>
| 10 | 2013-05-09T01:01:40Z | [
"python",
"file",
"list",
"file-io",
"newline"
] |
Writing a list to a file with Python | 899,103 | <p>Is this the cleanest way to write a list to a file, since <code>writelines()</code> doesn't insert newline characters?</p>
<pre><code>file.writelines(["%s\n" % item for item in list])
</code></pre>
<p>It seems like there would be a standard way...</p>
| 214 | 2009-05-22T17:52:18Z | 17,638,623 | <pre><code>poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
'''
f = open('poem.txt', 'w') # open for 'w'riting
f.write(poem) # write text to file
f.close() # close the file
</code></pre>
<p>How It Works:
First, open a ï¬le by using the built-in open function and specifying the name of
the ï¬le and the mode in which we want to open the ï¬le. The mode can be a
read mode (ârâ), write mode (âwâ) or append mode (âaâ). We can also specify
whether we are reading, writing, or appending in text mode (âtâ) or binary
mode (âbâ). There are actually many more modes available and help(open)
will give you more details about them. By default, open() considers the ï¬le to
be a âtâext ï¬le and opens it in ârâead mode.
In our example, we ï¬rst open the ï¬le in write text mode and use the write
method of the ï¬le object to write to the ï¬le and then we ï¬nally close the ï¬le.</p>
<p><strong>The above example is from the book "A Byte of Python" by Swaroop C H.</strong>
<a href="http://swaroopch.com/" rel="nofollow">swaroopch.com</a></p>
| -1 | 2013-07-14T10:37:44Z | [
"python",
"file",
"list",
"file-io",
"newline"
] |
Writing a list to a file with Python | 899,103 | <p>Is this the cleanest way to write a list to a file, since <code>writelines()</code> doesn't insert newline characters?</p>
<pre><code>file.writelines(["%s\n" % item for item in list])
</code></pre>
<p>It seems like there would be a standard way...</p>
| 214 | 2009-05-22T17:52:18Z | 32,107,439 | <p>Why don't you try</p>
<pre><code>file.write(str(list))
</code></pre>
| 0 | 2015-08-19T23:47:34Z | [
"python",
"file",
"list",
"file-io",
"newline"
] |
Writing a list to a file with Python | 899,103 | <p>Is this the cleanest way to write a list to a file, since <code>writelines()</code> doesn't insert newline characters?</p>
<pre><code>file.writelines(["%s\n" % item for item in list])
</code></pre>
<p>It seems like there would be a standard way...</p>
| 214 | 2009-05-22T17:52:18Z | 32,508,983 | <pre><code>with open ("test.txt","w")as fp:
for line in list12:
fp.write(line+"\n")
</code></pre>
| 4 | 2015-09-10T18:14:57Z | [
"python",
"file",
"list",
"file-io",
"newline"
] |
Writing a list to a file with Python | 899,103 | <p>Is this the cleanest way to write a list to a file, since <code>writelines()</code> doesn't insert newline characters?</p>
<pre><code>file.writelines(["%s\n" % item for item in list])
</code></pre>
<p>It seems like there would be a standard way...</p>
| 214 | 2009-05-22T17:52:18Z | 32,876,198 | <p>You can also use the print function if you're on python3 as follows.</p>
<pre><code>f = open("myfile.txt","wb")
print(mylist, file=f)
</code></pre>
| 4 | 2015-09-30T21:50:24Z | [
"python",
"file",
"list",
"file-io",
"newline"
] |
Writing a list to a file with Python | 899,103 | <p>Is this the cleanest way to write a list to a file, since <code>writelines()</code> doesn't insert newline characters?</p>
<pre><code>file.writelines(["%s\n" % item for item in list])
</code></pre>
<p>It seems like there would be a standard way...</p>
| 214 | 2009-05-22T17:52:18Z | 33,775,428 | <p>Serialize list into text file with comma sepparated value</p>
<pre><code>mylist = dir()
with open('filename.txt','w') as f:
f.write( ','.join( mylist ) )
</code></pre>
| 5 | 2015-11-18T08:51:01Z | [
"python",
"file",
"list",
"file-io",
"newline"
] |
Python-like list comprehension in Java | 899,138 | <p>Since Java doesn't allow passing methods as parameters, what trick do you use to implement Python like list comprehension in Java ?</p>
<p>I have a list (ArrayList) of Strings. I need to transform each element by using a function so that I get another list. I have several functions which take a String as input and return another String as output. How do I make a generic method which can be given the list and the function as parameters so that I can get a list back with each element processed. It is not possible in the literal sense, but what trick should I use ?</p>
<p>The other option is to write a new function for each smaller String-processing function which simply loops over the entire list, which is kinda not so cool.</p>
| 42 | 2009-05-22T17:57:13Z | 899,165 | <p>The <a href="http://code.google.com/p/google-collections/">Google Collections library</a> has lots of classes for working with collections and iterators at a much higher level than plain Java supports, and in a functional manner (filter, map, fold, etc.). It defines Function and Predicate interfaces and methods that use them to process collections so that you don't have to. It also has convenience functions that make dealing with Java generics less arduous. </p>
<p>I also use <a href="http://hamcrest.googlecode.com">Hamcrest</a>** for filtering collections.</p>
<p>The two libraries are easy to combine with adapter classes.</p>
<p><hr /></p>
<p>** Declaration of interest: I co-wrote Hamcrest</p>
| 15 | 2009-05-22T18:02:12Z | [
"java",
"python",
"parameters",
"methods",
"list-comprehension"
] |
Python-like list comprehension in Java | 899,138 | <p>Since Java doesn't allow passing methods as parameters, what trick do you use to implement Python like list comprehension in Java ?</p>
<p>I have a list (ArrayList) of Strings. I need to transform each element by using a function so that I get another list. I have several functions which take a String as input and return another String as output. How do I make a generic method which can be given the list and the function as parameters so that I can get a list back with each element processed. It is not possible in the literal sense, but what trick should I use ?</p>
<p>The other option is to write a new function for each smaller String-processing function which simply loops over the entire list, which is kinda not so cool.</p>
| 42 | 2009-05-22T17:57:13Z | 899,172 | <p>Basically, you create a Function interface:</p>
<pre><code>public interface Func<In, Out> {
public Out apply(In in);
}
</code></pre>
<p>and then pass in an anonymous subclass to your method.</p>
<p>Your method could either apply the function to each element in-place:</p>
<pre><code>public static <T> void applyToListInPlace(List<T> list, Func<T, T> f) {
ListIterator<T> itr = list.listIterator();
while (itr.hasNext()) {
T output = f.apply(itr.next());
itr.set(output);
}
}
// ...
List<String> myList = ...;
applyToListInPlace(myList, new Func<String, String>() {
public String apply(String in) {
return in.toLowerCase();
}
});
</code></pre>
<p>or create a new <code>List</code> (basically creating a mapping from the input list to the output list):</p>
<pre><code>public static <In, Out> List<Out> map(List<In> in, Func<In, Out> f) {
List<Out> out = new ArrayList<Out>(in.size());
for (In inObj : in) {
out.add(f.apply(inObj));
}
return out;
}
// ...
List<String> myList = ...;
List<String> lowerCased = map(myList, new Func<String, String>() {
public String apply(String in) {
return in.toLowerCase();
}
});
</code></pre>
<p>Which one is preferable depends on your use case. If your list is extremely large, the in-place solution may be the only viable one; if you wish to apply many different functions to the same original list to make many derivative lists, you will want the <code>map</code> version.</p>
| 31 | 2009-05-22T18:03:05Z | [
"java",
"python",
"parameters",
"methods",
"list-comprehension"
] |
Python-like list comprehension in Java | 899,138 | <p>Since Java doesn't allow passing methods as parameters, what trick do you use to implement Python like list comprehension in Java ?</p>
<p>I have a list (ArrayList) of Strings. I need to transform each element by using a function so that I get another list. I have several functions which take a String as input and return another String as output. How do I make a generic method which can be given the list and the function as parameters so that I can get a list back with each element processed. It is not possible in the literal sense, but what trick should I use ?</p>
<p>The other option is to write a new function for each smaller String-processing function which simply loops over the entire list, which is kinda not so cool.</p>
| 42 | 2009-05-22T17:57:13Z | 899,429 | <p>Apache Commons <a href="http://commons.apache.org/collections/api-release/org/apache/commons/collections/CollectionUtils.html#transform%28java.util.Collection,%20org.apache.commons.collections.Transformer%29" rel="nofollow">CollectionsUtil.transform(Collection, Transformer)</a> is another option.</p>
| 5 | 2009-05-22T18:54:46Z | [
"java",
"python",
"parameters",
"methods",
"list-comprehension"
] |
Python-like list comprehension in Java | 899,138 | <p>Since Java doesn't allow passing methods as parameters, what trick do you use to implement Python like list comprehension in Java ?</p>
<p>I have a list (ArrayList) of Strings. I need to transform each element by using a function so that I get another list. I have several functions which take a String as input and return another String as output. How do I make a generic method which can be given the list and the function as parameters so that I can get a list back with each element processed. It is not possible in the literal sense, but what trick should I use ?</p>
<p>The other option is to write a new function for each smaller String-processing function which simply loops over the entire list, which is kinda not so cool.</p>
| 42 | 2009-05-22T17:57:13Z | 16,732,216 | <p>In Java 8 you can use method references:</p>
<pre><code>List<String> list = ...;
list.replaceAll(String::toUpperCase);
</code></pre>
<p>Or, if you want to create a new list instance:</p>
<pre><code>List<String> upper = list.stream().map(String::toUpperCase).collect(Collectors.toList());
</code></pre>
| 9 | 2013-05-24T09:52:55Z | [
"java",
"python",
"parameters",
"methods",
"list-comprehension"
] |
Python-like list comprehension in Java | 899,138 | <p>Since Java doesn't allow passing methods as parameters, what trick do you use to implement Python like list comprehension in Java ?</p>
<p>I have a list (ArrayList) of Strings. I need to transform each element by using a function so that I get another list. I have several functions which take a String as input and return another String as output. How do I make a generic method which can be given the list and the function as parameters so that I can get a list back with each element processed. It is not possible in the literal sense, but what trick should I use ?</p>
<p>The other option is to write a new function for each smaller String-processing function which simply loops over the entire list, which is kinda not so cool.</p>
| 42 | 2009-05-22T17:57:13Z | 30,923,596 | <p>I'm building this project to write list comprehension in Java, now is a proof of concept in <a href="https://github.com/farolfo/list-comprehension-in-java" rel="nofollow">https://github.com/farolfo/list-comprehension-in-java</a></p>
<p>Examples</p>
<pre><code>// { x | x E {1,2,3,4} ^ x is even }
// gives {2,4}
Predicate<Integer> even = x -> x % 2 == 0;
List<Integer> evens = new ListComprehension<Integer>()
.suchThat(x -> {
x.belongsTo(Arrays.asList(1, 2, 3, 4));
x.is(even);
});
// evens = {2,4};
</code></pre>
<p>And if we want to transform the output expression in some way like</p>
<pre><code>// { x * 2 | x E {1,2,3,4} ^ x is even }
// gives {4,8}
List<Integer> duplicated = new ListComprehension<Integer>()
.giveMeAll((Integer x) -> x * 2)
.suchThat(x -> {
x.belongsTo(Arrays.asList(1, 2, 3, 4));
x.is(even);
});
// duplicated = {4,8}
</code></pre>
| 1 | 2015-06-18T18:58:19Z | [
"java",
"python",
"parameters",
"methods",
"list-comprehension"
] |
Python-like list comprehension in Java | 899,138 | <p>Since Java doesn't allow passing methods as parameters, what trick do you use to implement Python like list comprehension in Java ?</p>
<p>I have a list (ArrayList) of Strings. I need to transform each element by using a function so that I get another list. I have several functions which take a String as input and return another String as output. How do I make a generic method which can be given the list and the function as parameters so that I can get a list back with each element processed. It is not possible in the literal sense, but what trick should I use ?</p>
<p>The other option is to write a new function for each smaller String-processing function which simply loops over the entire list, which is kinda not so cool.</p>
| 42 | 2009-05-22T17:57:13Z | 39,101,269 | <p>You can use lambdas for the function, like so:</p>
<pre><code>class Comprehension<T> {
/**
*in: List int
*func: Function to do to each entry
*/
public List<T> comp(List<T> in, Function<T, T> func) {
List<T> out = new ArrayList<T>();
for(T o: in) {
out.add(func.apply(o));
}
return out;
}
}
</code></pre>
<p>the usage:</p>
<pre><code>List<String> stuff = new ArrayList<String>();
stuff.add("a");
stuff.add("b");
stuff.add("c");
stuff.add("d");
stuff.add("cheese");
List<String> newStuff = new Comprehension<String>().comp(stuff, (a) -> { //The <String> tells the comprehension to return an ArrayList<String>
a.equals("a")? "1":
(a.equals("b")? "2":
(a.equals("c")? "3":
(a.equals("d")? "4": a
)))
});
</code></pre>
<p>will return:</p>
<pre><code>["1", "2", "3", "4", "cheese"]
</code></pre>
| 0 | 2016-08-23T12:29:58Z | [
"java",
"python",
"parameters",
"methods",
"list-comprehension"
] |
How to find a file upwardly in Python? | 899,273 | <p>What is the best way to find a file "upwardly" in Python? (Ideally it would work on Windows too). E.g.,</p>
<pre><code>>>> os.makedirs('/tmp/foo/bar/baz/qux')
>>> open('/tmp/foo/findme.txt', 'w').close()
>>> os.chdir('/tmp/foo/bar/baz/qux')
>>> findup('findme.txt')
'/tmp/foo/findme.txt'
</code></pre>
<p>As far as I can tell, there isn't anything in the Python standard library (although I'd love to be proven wrong). Also, googling around didn't turn up much that's definitive; I'm wondering if there's something out there that "everyone" uses.</p>
| 2 | 2009-05-22T18:23:48Z | 899,297 | <p>The module os.path has what you need, in particular: abspath() (if the path is not absolute), dirname(), isfile(), and join().</p>
<pre><code>dir = os.path.curdir()
filename = None
while True:
filename = os.path.join(dir, 'filename')
if os.path.isfile(filename):
break
updir = os.path.dirname(dir)
if updir == dir:
filename = None
break
dir = updir
</code></pre>
<p>Edit: change posixpath to os.path so that this works on Windows.</p>
<p>Edit x2: add code.</p>
| 1 | 2009-05-22T18:28:23Z | [
"python"
] |
How to find a file upwardly in Python? | 899,273 | <p>What is the best way to find a file "upwardly" in Python? (Ideally it would work on Windows too). E.g.,</p>
<pre><code>>>> os.makedirs('/tmp/foo/bar/baz/qux')
>>> open('/tmp/foo/findme.txt', 'w').close()
>>> os.chdir('/tmp/foo/bar/baz/qux')
>>> findup('findme.txt')
'/tmp/foo/findme.txt'
</code></pre>
<p>As far as I can tell, there isn't anything in the Python standard library (although I'd love to be proven wrong). Also, googling around didn't turn up much that's definitive; I'm wondering if there's something out there that "everyone" uses.</p>
| 2 | 2009-05-22T18:23:48Z | 899,616 | <pre><code>import os
def findup(filename):
drive, thisdir = os.path.splitdrive(os.getcwd())
while True:
fullpath = os.path.join(drive, thisdir, filename)
if os.path.isfile(fullpath):
return fullpath
if thisdir == os.path.sep: #root dir
raise LookupError('file not found: %r' % filename)
thisdir = os.path.dirname(thisdir)
os.makedirs('/tmp/foo/bar/baz/qux')
open('/tmp/foo/findme.txt', 'w').close()
os.chdir('/tmp/foo/bar/baz/qux')
print findup('findme.txt')
</code></pre>
<p>Prints:</p>
<pre><code>/tmp/foo/findme.txt
</code></pre>
<p>Also works on Windows. Probably will work on any platform.</p>
| 4 | 2009-05-22T19:33:25Z | [
"python"
] |
How to find a file upwardly in Python? | 899,273 | <p>What is the best way to find a file "upwardly" in Python? (Ideally it would work on Windows too). E.g.,</p>
<pre><code>>>> os.makedirs('/tmp/foo/bar/baz/qux')
>>> open('/tmp/foo/findme.txt', 'w').close()
>>> os.chdir('/tmp/foo/bar/baz/qux')
>>> findup('findme.txt')
'/tmp/foo/findme.txt'
</code></pre>
<p>As far as I can tell, there isn't anything in the Python standard library (although I'd love to be proven wrong). Also, googling around didn't turn up much that's definitive; I'm wondering if there's something out there that "everyone" uses.</p>
| 2 | 2009-05-22T18:23:48Z | 29,198,207 | <p>I found myself in need of a findup function similar to the node.js version as well, opted for a recursive implementation:</p>
<pre><code>import os
def findup(filename, dir = os.getcwd()):
def inner(drive, dir, filename):
filepath = os.path.join(drive, dir, filename)
if os.path.isfile(filepath):
return filepath
if dir == os.path.sep:
raise LookupError('file not found: %s' % filename)
return inner(drive, os.path.dirname(dir), filename)
drive, start = os.path.splitdrive(os.path.abspath(dir))
return inner(drive, start, filename)
</code></pre>
| 0 | 2015-03-22T18:31:45Z | [
"python"
] |
Python, how to parse strings to look like sys.argv | 899,276 | <p>I would like to parse a string like this:</p>
<pre><code>-o 1 --long "Some long string"
</code></pre>
<p>into this:</p>
<pre><code>["-o", "1", "--long", 'Some long string']
</code></pre>
<p>or similar.</p>
<p>This is different than either getopt, or optparse, which <em>start</em> with sys.argv parsed input (like the output I have above). Is there a standard way to do this? Basically, this is "splitting" while keeping quoted strings together. </p>
<p>My best function so far:</p>
<pre><code>import csv
def split_quote(string,quotechar='"'):
'''
>>> split_quote('--blah "Some argument" here')
['--blah', 'Some argument', 'here']
>>> split_quote("--blah 'Some argument' here", quotechar="'")
['--blah', 'Some argument', 'here']
'''
s = csv.StringIO(string)
C = csv.reader(s, delimiter=" ",quotechar=quotechar)
return list(C)[0]
</code></pre>
| 24 | 2009-05-22T18:24:25Z | 899,314 | <p>I believe you want the <a href="http://docs.python.org/library/shlex.html">shlex</a> module.</p>
<pre><code>>>> import shlex
>>> shlex.split('-o 1 --long "Some long string"')
['-o', '1', '--long', 'Some long string']
</code></pre>
| 44 | 2009-05-22T18:33:07Z | [
"python",
"parsing",
"argv"
] |
Python, how to parse strings to look like sys.argv | 899,276 | <p>I would like to parse a string like this:</p>
<pre><code>-o 1 --long "Some long string"
</code></pre>
<p>into this:</p>
<pre><code>["-o", "1", "--long", 'Some long string']
</code></pre>
<p>or similar.</p>
<p>This is different than either getopt, or optparse, which <em>start</em> with sys.argv parsed input (like the output I have above). Is there a standard way to do this? Basically, this is "splitting" while keeping quoted strings together. </p>
<p>My best function so far:</p>
<pre><code>import csv
def split_quote(string,quotechar='"'):
'''
>>> split_quote('--blah "Some argument" here')
['--blah', 'Some argument', 'here']
>>> split_quote("--blah 'Some argument' here", quotechar="'")
['--blah', 'Some argument', 'here']
'''
s = csv.StringIO(string)
C = csv.reader(s, delimiter=" ",quotechar=quotechar)
return list(C)[0]
</code></pre>
| 24 | 2009-05-22T18:24:25Z | 16,532,488 | <p>Before I was aware of <a href="http://docs.python.org/2/library/shlex.html#shlex.split" rel="nofollow"><code>shlex.split</code></a>, I made the following:</p>
<pre><code>import sys
_WORD_DIVIDERS = set((' ', '\t', '\r', '\n'))
_QUOTE_CHARS_DICT = {
'\\': '\\',
' ': ' ',
'"': '"',
'r': '\r',
'n': '\n',
't': '\t',
}
def _raise_type_error():
raise TypeError("Bytes must be decoded to Unicode first")
def parse_to_argv_gen(instring):
is_in_quotes = False
instring_iter = iter(instring)
join_string = instring[0:0]
c_list = []
c = ' '
while True:
# Skip whitespace
try:
while True:
if not isinstance(c, str) and sys.version_info[0] >= 3:
_raise_type_error()
if c not in _WORD_DIVIDERS:
break
c = next(instring_iter)
except StopIteration:
break
# Read word
try:
while True:
if not isinstance(c, str) and sys.version_info[0] >= 3:
_raise_type_error()
if not is_in_quotes and c in _WORD_DIVIDERS:
break
if c == '"':
is_in_quotes = not is_in_quotes
c = None
elif c == '\\':
c = next(instring_iter)
c = _QUOTE_CHARS_DICT.get(c)
if c is not None:
c_list.append(c)
c = next(instring_iter)
yield join_string.join(c_list)
c_list = []
except StopIteration:
yield join_string.join(c_list)
break
def parse_to_argv(instring):
return list(parse_to_argv_gen(instring))
</code></pre>
<p>This works with Python 2.x and 3.x. On Python 2.x, it works directly with byte strings and Unicode strings. On Python 3.x, it <em>only</em> accepts [Unicode] strings, not <code>bytes</code> objects.</p>
<p>This doesn't behave exactly the same as shell argv splittingâit also allows quoting of CR, LF and TAB characters as <code>\r</code>, <code>\n</code> and <code>\t</code>, converting them to real CR, LF, TAB (<code>shlex.split</code> doesn't do that). So writing my own function was useful for my needs. I guess <code>shlex.split</code> is better if you just want plain shell-style argv splitting. I'm sharing this code in case it's useful as a baseline for doing something slightly different.</p>
| 0 | 2013-05-13T22:55:23Z | [
"python",
"parsing",
"argv"
] |
Bundling PyQwt with py2exe | 899,658 | <p>I have a standard setup script for py2exe with which I bundle PyQt-based applications into Windows .exe files.</p>
<p>Today I tried a simple script that uses the PyQwt module, and it doesn't seem to work. py2exe runs alright, but when I execute the .exe it creates, it dumps the following into a log file and doesn't run:</p>
<pre><code>Traceback (most recent call last):
File "qwt_test.pyw", line 5, in <module>
File "zipextimporter.pyo", line 82, in load_module
File "PyQt4\Qwt5\__init__.pyo", line 32, in <module>
File "zipextimporter.pyo", line 98, in load_module
ImportError: MemoryLoadLibrary failed loading PyQt4\Qwt5\Qwt.pyd
</code></pre>
<p>When I look in <code>PyQt4\Qwt5\</code> in the <code>build\bdist.win32\winexe\collect-2.5</code> directory, <code>Qwt.pyd</code> is definitely there.</p>
<p>I can't seem to find anything useful online regarding this error. What could cause it? Thanks.</p>
| 2 | 2009-05-22T19:46:12Z | 931,562 | <p>py2exe is not the only way, and maybe not the best way, to put together exe files for Python apps -- in particular, it hardly if at all supports pyqt. Please, I beseech you, check out <a href="http://www.pyinstaller.org/" rel="nofollow">PyInstaller</a>, which DOES know about PyQt (and Linux, and Mac, should you care...) -- just make sure you use the SVN head checkout, not the "released" version, which at this time is seriously out of date (an issue that's hopefully going away soon...).</p>
| 4 | 2009-05-31T07:30:49Z | [
"python",
"pyqt",
"py2exe"
] |
Bundling PyQwt with py2exe | 899,658 | <p>I have a standard setup script for py2exe with which I bundle PyQt-based applications into Windows .exe files.</p>
<p>Today I tried a simple script that uses the PyQwt module, and it doesn't seem to work. py2exe runs alright, but when I execute the .exe it creates, it dumps the following into a log file and doesn't run:</p>
<pre><code>Traceback (most recent call last):
File "qwt_test.pyw", line 5, in <module>
File "zipextimporter.pyo", line 82, in load_module
File "PyQt4\Qwt5\__init__.pyo", line 32, in <module>
File "zipextimporter.pyo", line 98, in load_module
ImportError: MemoryLoadLibrary failed loading PyQt4\Qwt5\Qwt.pyd
</code></pre>
<p>When I look in <code>PyQt4\Qwt5\</code> in the <code>build\bdist.win32\winexe\collect-2.5</code> directory, <code>Qwt.pyd</code> is definitely there.</p>
<p>I can't seem to find anything useful online regarding this error. What could cause it? Thanks.</p>
| 2 | 2009-05-22T19:46:12Z | 957,048 | <p>Some options:</p>
<ol>
<li>Try playing with the py2xe <code>bundle_files options</code> (3, 2, 1) (especially if you put them all in one big library zip, some dlls don't like that).</li>
<li>Make sure a copy of <code>msvcp71.dll</code> exists under windows\system32 or in the directory of your executable.</li>
<li>Try excluding the dll explicitely (add Qwt.pyd to the <code>dll_excludes</code> option and (after building) copy Qwt.pyd (and _Qwt.pyd if it exists) to your executable path.</li>
</ol>
| 1 | 2009-06-05T17:16:14Z | [
"python",
"pyqt",
"py2exe"
] |
Pad an integer using a regular expression | 899,804 | <p>I'm using regular expressions with a python framework to pad a specific number in a version number:</p>
<p>10.2.11</p>
<p>I want to transform the second element to be padded with a zero, so it looks like this:</p>
<p>10.02.11</p>
<p>My regular expression looks like this: </p>
<pre><code>^(\d{2}\.)(\d{1})([\.].*)
</code></pre>
<p>If I just regurgitate back the matching groups, I use this string:</p>
<pre><code>\1\2\3
</code></pre>
<p>When I use my favorite regular expression test harness (<a href="http://kodos.sourceforge.net/" rel="nofollow">http://kodos.sourceforge.net/</a>), I can't get it to pad the second group. I tried \1\20\3, but that interprets the second reference as 20, and not 2. </p>
<p>Because of the library I'm using this with, I need it to be a one liner. The library takes a regular expression string, and then a string for what should be used to replace it with.</p>
<p>I'm assuming I just need to escape the matching groups string, but I can't figure it out. Thanks in advance for any help.</p>
| 1 | 2009-05-22T20:18:36Z | 899,824 | <p>Does your library support <a href="http://docs.python.org/howto/regex.html#non-capturing-and-named-groups" rel="nofollow">named groups</a>? That might solve your problem.</p>
| 0 | 2009-05-22T20:23:48Z | [
"python",
"regex"
] |
Pad an integer using a regular expression | 899,804 | <p>I'm using regular expressions with a python framework to pad a specific number in a version number:</p>
<p>10.2.11</p>
<p>I want to transform the second element to be padded with a zero, so it looks like this:</p>
<p>10.02.11</p>
<p>My regular expression looks like this: </p>
<pre><code>^(\d{2}\.)(\d{1})([\.].*)
</code></pre>
<p>If I just regurgitate back the matching groups, I use this string:</p>
<pre><code>\1\2\3
</code></pre>
<p>When I use my favorite regular expression test harness (<a href="http://kodos.sourceforge.net/" rel="nofollow">http://kodos.sourceforge.net/</a>), I can't get it to pad the second group. I tried \1\20\3, but that interprets the second reference as 20, and not 2. </p>
<p>Because of the library I'm using this with, I need it to be a one liner. The library takes a regular expression string, and then a string for what should be used to replace it with.</p>
<p>I'm assuming I just need to escape the matching groups string, but I can't figure it out. Thanks in advance for any help.</p>
| 1 | 2009-05-22T20:18:36Z | 899,826 | <p>Try this:</p>
<pre><code>(^\d(?=\.)|(?<=\.)\d(?=\.)|(?<=\.)\d$)
</code></pre>
<p>And replace the match by <code>0\1</code>. This will make any number at least two digits long.</p>
| 1 | 2009-05-22T20:24:13Z | [
"python",
"regex"
] |
Pad an integer using a regular expression | 899,804 | <p>I'm using regular expressions with a python framework to pad a specific number in a version number:</p>
<p>10.2.11</p>
<p>I want to transform the second element to be padded with a zero, so it looks like this:</p>
<p>10.02.11</p>
<p>My regular expression looks like this: </p>
<pre><code>^(\d{2}\.)(\d{1})([\.].*)
</code></pre>
<p>If I just regurgitate back the matching groups, I use this string:</p>
<pre><code>\1\2\3
</code></pre>
<p>When I use my favorite regular expression test harness (<a href="http://kodos.sourceforge.net/" rel="nofollow">http://kodos.sourceforge.net/</a>), I can't get it to pad the second group. I tried \1\20\3, but that interprets the second reference as 20, and not 2. </p>
<p>Because of the library I'm using this with, I need it to be a one liner. The library takes a regular expression string, and then a string for what should be used to replace it with.</p>
<p>I'm assuming I just need to escape the matching groups string, but I can't figure it out. Thanks in advance for any help.</p>
| 1 | 2009-05-22T20:18:36Z | 899,895 | <p>What about removing the <code>.</code> from the regex?</p>
<pre><code>^(\d{2})\.(\d{1})[\.](.*)
</code></pre>
<p>replace with:</p>
<pre><code>\1.0\2.\3
</code></pre>
| 1 | 2009-05-22T20:40:34Z | [
"python",
"regex"
] |
Pad an integer using a regular expression | 899,804 | <p>I'm using regular expressions with a python framework to pad a specific number in a version number:</p>
<p>10.2.11</p>
<p>I want to transform the second element to be padded with a zero, so it looks like this:</p>
<p>10.02.11</p>
<p>My regular expression looks like this: </p>
<pre><code>^(\d{2}\.)(\d{1})([\.].*)
</code></pre>
<p>If I just regurgitate back the matching groups, I use this string:</p>
<pre><code>\1\2\3
</code></pre>
<p>When I use my favorite regular expression test harness (<a href="http://kodos.sourceforge.net/" rel="nofollow">http://kodos.sourceforge.net/</a>), I can't get it to pad the second group. I tried \1\20\3, but that interprets the second reference as 20, and not 2. </p>
<p>Because of the library I'm using this with, I need it to be a one liner. The library takes a regular expression string, and then a string for what should be used to replace it with.</p>
<p>I'm assuming I just need to escape the matching groups string, but I can't figure it out. Thanks in advance for any help.</p>
| 1 | 2009-05-22T20:18:36Z | 900,223 | <p>How about a completely different approach?</p>
<pre><code>nums = version_string.split('.')
print ".".join("%02d" % int(n) for n in nums)
</code></pre>
| 3 | 2009-05-22T22:16:14Z | [
"python",
"regex"
] |
pywikipedia name wikiquote is not defined? | 900,306 | <p>I'm writing a bot for Wikipedia but have a problem. When I want to get stuff from another Wikimedia site I get the error - error-name 'wikiquote' is not defined.</p>
<p>This is when I start the code off like this-</p>
<pre><code>import wikipedia
site = wikiquote.getSite()
</code></pre>
<p>Yet if I was to start it with wikipedia written instead of wikiquote, it works. From what I can understand it should work on other Mediawiki sites?</p>
<p>Help gratefully appreciated!</p>
<p>Thanks!</p>
| 1 | 2009-05-22T22:39:57Z | 900,320 | <p><code>wikiquote</code> is not defined or imported anywhere in your script. So it is understandable that your code does not work.</p>
<p>According to <a href="http://meta.wikimedia.org/wiki/Wikipedia.py#Page%5Fclass.2C%5Fsite%5Fclass%5Fand%5Fwikipedia.stopme.28.29%5Ffunction" rel="nofollow">documentation of pywikipedia</a>, you need to use this instead:</p>
<pre><code>import wikipedia
site = wikipedia.getSite('en', 'wikiquote')
</code></pre>
| 2 | 2009-05-22T22:48:28Z | [
"python",
"python-2.6",
"pywikipedia"
] |
pywikipedia name wikiquote is not defined? | 900,306 | <p>I'm writing a bot for Wikipedia but have a problem. When I want to get stuff from another Wikimedia site I get the error - error-name 'wikiquote' is not defined.</p>
<p>This is when I start the code off like this-</p>
<pre><code>import wikipedia
site = wikiquote.getSite()
</code></pre>
<p>Yet if I was to start it with wikipedia written instead of wikiquote, it works. From what I can understand it should work on other Mediawiki sites?</p>
<p>Help gratefully appreciated!</p>
<p>Thanks!</p>
| 1 | 2009-05-22T22:39:57Z | 900,381 | <p>If you're only running this for yourself, it doesn't matter, but pywikipedia bots should let the user control which site they're run against (and which account is used). Users specify these settings in the <code>user-config.py</code> file, as described <a href="http://meta.wikimedia.org/wiki/Using%5Fthe%5Fpython%5Fwikipediabot#Configuration%5Ffor%5Fother%5FWikimedia%5Fwikis" rel="nofollow">here</a>. In this case they'd set:</p>
<pre><code>family = 'wikiquote'
</code></pre>
<p>which your bot should process. You can look at the <code>login.py</code> file to see an example of how to consume these configuration settings.</p>
| 0 | 2009-05-22T23:12:48Z | [
"python",
"python-2.6",
"pywikipedia"
] |
Getting the caller function name inside another function in Python? | 900,392 | <p>If you have 2 functions like:</p>
<pre><code>def A
def B
</code></pre>
<p>and A calls B, can you get who is calling B inside B, like:</p>
<pre><code>def A () :
B ()
def B () :
this.caller.name
</code></pre>
| 57 | 2009-05-22T23:19:16Z | 900,404 | <p>You can use the <a href="http://docs.python.org/library/inspect.html">inspect</a> module to get the calling stack. It returns a list of frame records. The third element in each record is the caller name. What you want is this:</p>
<pre><code>>>> import inspect
>>> def f():
... print inspect.stack()[1][3]
...
>>> def g():
... f()
...
>>> g()
g
</code></pre>
<p>Of course, it is a good idea to check that enough frame records exist before trying to access a particular index.</p>
| 75 | 2009-05-22T23:24:18Z | [
"python",
"debugging"
] |
Getting the caller function name inside another function in Python? | 900,392 | <p>If you have 2 functions like:</p>
<pre><code>def A
def B
</code></pre>
<p>and A calls B, can you get who is calling B inside B, like:</p>
<pre><code>def A () :
B ()
def B () :
this.caller.name
</code></pre>
| 57 | 2009-05-22T23:19:16Z | 900,413 | <p><code>sys._getframe(1).f_code.co_name</code> like in the example below:</p>
<pre>
>>> def foo():
... global x
... x = sys._getframe(1)
...
>>> def y(): foo()
...
>>> y()
>>> x.f_code.co_name
'y'
>>>
</pre>
| 6 | 2009-05-22T23:27:35Z | [
"python",
"debugging"
] |
Getting the caller function name inside another function in Python? | 900,392 | <p>If you have 2 functions like:</p>
<pre><code>def A
def B
</code></pre>
<p>and A calls B, can you get who is calling B inside B, like:</p>
<pre><code>def A () :
B ()
def B () :
this.caller.name
</code></pre>
| 57 | 2009-05-22T23:19:16Z | 11,626,868 | <p>you can user the logging module and specify the %(filename)s option in BaseConfig()</p>
<pre><code>import logging
logging.basicConfig(filename='/tmp/test.log', level=logging.DEBUG, format='%(asctime)s | %(levelname)s | %(funcName)s |%(message)s')
def A():
logging.info('info')
</code></pre>
| 2 | 2012-07-24T08:20:05Z | [
"python",
"debugging"
] |
Getting the caller function name inside another function in Python? | 900,392 | <p>If you have 2 functions like:</p>
<pre><code>def A
def B
</code></pre>
<p>and A calls B, can you get who is calling B inside B, like:</p>
<pre><code>def A () :
B ()
def B () :
this.caller.name
</code></pre>
| 57 | 2009-05-22T23:19:16Z | 28,185,561 | <p>There are two ways, using <code>sys</code> and <code>inspect</code> modules:</p>
<ul>
<li><code>sys._getframe(1).f_code.co_name</code></li>
<li><code>inspect.stack()[1][3]</code></li>
</ul>
<p>The <code>stack()</code> form is less readable and is implementation dependent since it calls <code>sys._getframe()</code>, see extract from <code>inspect.py</code>:</p>
<pre><code>def stack(context=1):
"""Return a list of records for the stack above the caller's frame."""
return getouterframes(sys._getframe(1), context)
</code></pre>
| 6 | 2015-01-28T05:52:56Z | [
"python",
"debugging"
] |
Getting the caller function name inside another function in Python? | 900,392 | <p>If you have 2 functions like:</p>
<pre><code>def A
def B
</code></pre>
<p>and A calls B, can you get who is calling B inside B, like:</p>
<pre><code>def A () :
B ()
def B () :
this.caller.name
</code></pre>
| 57 | 2009-05-22T23:19:16Z | 38,536,474 | <p>This works for me! :D</p>
<pre><code>>>> def a():
... import sys
... print sys._getframe(1).f_code.co_name
...
>>> def b():
... a()
...
...
>>> b()
b
>>>
</code></pre>
| 1 | 2016-07-22T23:12:58Z | [
"python",
"debugging"
] |
Is there a high-level way to read in lines from an output file and have the types recognized by the structure of the contents? | 900,396 | <p>Suppose I have an output file that I want to read and each line was created by joining several types together, prepending and appending the list braces, </p>
<pre><code>[('tupleValueA','tupleValueB'), 'someString', ('anotherTupleA','anotherTupleB')]
</code></pre>
<p>I want to read the lines in. Now I can read them in, and operate on the string to assign values and types but I was wondering if Python had a higher level method for this. </p>
<p>After building a function to do this I tried to find a higher level approach but didn't find one.</p>
| 0 | 2009-05-22T23:20:32Z | 900,410 | <p>What you are looking for is <a href="http://docs.python.org/library/functions.html#eval" rel="nofollow">eval</a>. But please keep in mind that this function will evaluate and execute the lines. So don't run it on untrusted input ever!</p>
<pre><code>>>> print eval("[('tupleValueA', 1), 'someString']")
[('tupleValueA', 1), 'someString']
</code></pre>
<p>If you have control over the script that generate the output file, then I would suggest you use <a href="http://docs.python.org/library/json.html" rel="nofollow">json</a> encoding. JSON format is very similar to the python string representation of lists and dictionaries. And will be much more secure and robust to read from.</p>
<pre><code>>>> import json
>>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'
>>> json.loads('["foo", {"bar": ["baz", null, 1.0, 2]}]')
["foo", {"bar": ["baz", null, 1.0, 2]}]
</code></pre>
| 2 | 2009-05-22T23:26:54Z | [
"python",
"string",
"tuples"
] |
Is there a high-level way to read in lines from an output file and have the types recognized by the structure of the contents? | 900,396 | <p>Suppose I have an output file that I want to read and each line was created by joining several types together, prepending and appending the list braces, </p>
<pre><code>[('tupleValueA','tupleValueB'), 'someString', ('anotherTupleA','anotherTupleB')]
</code></pre>
<p>I want to read the lines in. Now I can read them in, and operate on the string to assign values and types but I was wondering if Python had a higher level method for this. </p>
<p>After building a function to do this I tried to find a higher level approach but didn't find one.</p>
| 0 | 2009-05-22T23:20:32Z | 900,446 | <p>The problem you describe is conventionally referred to as <a href="http://en.wikipedia.org/wiki/Serialization" rel="nofollow">serialization</a>. <a href="http://en.wikipedia.org/wiki/JSON" rel="nofollow">JavaScript Object Notation (JSON)</a> is one popular serialization protocol.</p>
| 0 | 2009-05-22T23:46:04Z | [
"python",
"string",
"tuples"
] |
Is there a high-level way to read in lines from an output file and have the types recognized by the structure of the contents? | 900,396 | <p>Suppose I have an output file that I want to read and each line was created by joining several types together, prepending and appending the list braces, </p>
<pre><code>[('tupleValueA','tupleValueB'), 'someString', ('anotherTupleA','anotherTupleB')]
</code></pre>
<p>I want to read the lines in. Now I can read them in, and operate on the string to assign values and types but I was wondering if Python had a higher level method for this. </p>
<p>After building a function to do this I tried to find a higher level approach but didn't find one.</p>
| 0 | 2009-05-22T23:20:32Z | 900,464 | <p>Probably it would be better to store the data with a module like <a href="http://docs.python.org/library/pickle.html" rel="nofollow">pickle</a> in the first place, instead of using normal strings. This way you avoid a lot of problems that come with <code>eval</code> and get a more robust solution.</p>
| 0 | 2009-05-22T23:51:51Z | [
"python",
"string",
"tuples"
] |
Elegant way to compare sequences | 900,420 | <p>Does python provide an elegant way to check for "equality" of sequences of different types? The following work, but they seem rather ugly and verbose for python code:</p>
<pre><code>def comp1(a, b):
if len(a) != len(b):
return False
for i, v in enumerate(a):
if v != b[i]:
return False
return True
</code></pre>
<p>The following is a bit shorter, but also less efficient since a third sequence is created:</p>
<pre><code>def comp2(a, b):
for l, r in map(None, a, b):
if l != r:
return False
return True
</code></pre>
<p>Shoehorning one of those examples into a list comprehension isn't really what I'm looking for either.</p>
<p>Edit: Ideally I am looking for a solution that doesn't create another sequence during the comparison.</p>
| 9 | 2009-05-22T23:32:56Z | 900,426 | <p>Convert both sequences to lists, and use builtin list comparison. It should be sufficient, unless your sequences are really large.</p>
<pre><code>list(a) == list(b)
</code></pre>
<p>Edit:</p>
<p>Testing done by schickb shows that using tuples is slightly faster:</p>
<pre><code>tuple(a) == tuple(b)
</code></pre>
| 17 | 2009-05-22T23:36:48Z | [
"python"
] |
Elegant way to compare sequences | 900,420 | <p>Does python provide an elegant way to check for "equality" of sequences of different types? The following work, but they seem rather ugly and verbose for python code:</p>
<pre><code>def comp1(a, b):
if len(a) != len(b):
return False
for i, v in enumerate(a):
if v != b[i]:
return False
return True
</code></pre>
<p>The following is a bit shorter, but also less efficient since a third sequence is created:</p>
<pre><code>def comp2(a, b):
for l, r in map(None, a, b):
if l != r:
return False
return True
</code></pre>
<p>Shoehorning one of those examples into a list comprehension isn't really what I'm looking for either.</p>
<p>Edit: Ideally I am looking for a solution that doesn't create another sequence during the comparison.</p>
| 9 | 2009-05-22T23:32:56Z | 900,444 | <p>You can determine the equality of any two iterables (strings, tuples, lists, even custom sequences) without creating and storing duplicate lists by using the following:</p>
<pre><code>all(x == y for x, y in itertools.izip_longest(a, b))
</code></pre>
<p>Note that if the two iterables are not the same length, the shorter one will be padded with <code>None</code>s. In other words, it will consider <code>[1, 2, None]</code> to be equal to <code>(1, 2)</code>.</p>
<p><strong>Edit:</strong> As Kamil points out in the comments, <code>izip_longest</code> is only available in Python 2.6. However, <a href="http://docs.python.org/library/itertools.html#itertools.izip%5Flongest" rel="nofollow">the docs for the function</a> also provide an alternate implementation which should work all the way back to 2.3.</p>
<p><strong>Edit 2:</strong> After testing on a few different machines, it looks like this is only faster than <code>list(a) == list(b)</code> in certain circumstances, which I can't isolate. Most of the time, it takes about seven times as long. However, I also found <code>tuple(a) == tuple(b)</code> to be consistently at least twice as fast as the <code>list</code> version.</p>
| 11 | 2009-05-22T23:45:37Z | [
"python"
] |
Elegant way to compare sequences | 900,420 | <p>Does python provide an elegant way to check for "equality" of sequences of different types? The following work, but they seem rather ugly and verbose for python code:</p>
<pre><code>def comp1(a, b):
if len(a) != len(b):
return False
for i, v in enumerate(a):
if v != b[i]:
return False
return True
</code></pre>
<p>The following is a bit shorter, but also less efficient since a third sequence is created:</p>
<pre><code>def comp2(a, b):
for l, r in map(None, a, b):
if l != r:
return False
return True
</code></pre>
<p>Shoehorning one of those examples into a list comprehension isn't really what I'm looking for either.</p>
<p>Edit: Ideally I am looking for a solution that doesn't create another sequence during the comparison.</p>
| 9 | 2009-05-22T23:32:56Z | 900,488 | <p>Since you put the word "equality" in quotes, I assume that you would like to know how the lists are the same and how the are different. Check out <strong>difflib</strong> which has a SequenceMatcher class:</p>
<pre><code> sm = difflib.SequenceMatcher(None, a, b)
for opcode in sm.get_opcodes():
print " (%s %d:%d %d:%d)" % opcode
</code></pre>
<p>You will get back a sequences of descriptions of the differences. It's fairly simple to turn that into <strong>diff</strong>-like output.</p>
| 1 | 2009-05-23T00:03:33Z | [
"python"
] |
Elegant way to compare sequences | 900,420 | <p>Does python provide an elegant way to check for "equality" of sequences of different types? The following work, but they seem rather ugly and verbose for python code:</p>
<pre><code>def comp1(a, b):
if len(a) != len(b):
return False
for i, v in enumerate(a):
if v != b[i]:
return False
return True
</code></pre>
<p>The following is a bit shorter, but also less efficient since a third sequence is created:</p>
<pre><code>def comp2(a, b):
for l, r in map(None, a, b):
if l != r:
return False
return True
</code></pre>
<p>Shoehorning one of those examples into a list comprehension isn't really what I'm looking for either.</p>
<p>Edit: Ideally I am looking for a solution that doesn't create another sequence during the comparison.</p>
| 9 | 2009-05-22T23:32:56Z | 900,490 | <p>It's probably not as efficient, but it looks funky:</p>
<pre><code>def cmpLists(a, b):
return len(a) == len(b) and (False not in [a[i] == b[i] for i in range(0,len(a)])
</code></pre>
<p>I don't know the "all" function that <a href="http://stackoverflow.com/questions/900420/elegant-way-to-compare-sequences/900444#900444">Ben mentioned</a>, but perhaps you could use that instead of "False not in"</p>
| 0 | 2009-05-23T00:05:15Z | [
"python"
] |
Elegant way to compare sequences | 900,420 | <p>Does python provide an elegant way to check for "equality" of sequences of different types? The following work, but they seem rather ugly and verbose for python code:</p>
<pre><code>def comp1(a, b):
if len(a) != len(b):
return False
for i, v in enumerate(a):
if v != b[i]:
return False
return True
</code></pre>
<p>The following is a bit shorter, but also less efficient since a third sequence is created:</p>
<pre><code>def comp2(a, b):
for l, r in map(None, a, b):
if l != r:
return False
return True
</code></pre>
<p>Shoehorning one of those examples into a list comprehension isn't really what I'm looking for either.</p>
<p>Edit: Ideally I am looking for a solution that doesn't create another sequence during the comparison.</p>
| 9 | 2009-05-22T23:32:56Z | 900,533 | <p>It looks like tuple(a) == tuple(b) is the best overall choice. Or perhaps tuple comparison with a preceding len check if they'll often be different lengths. This does create extra lists, but hopefully not an issue except for really huge lists. Here is my comparison of the various alternatives suggested:</p>
<pre><code>import timeit
tests = (
'''
a=b=[5]*100
''',
'''
a=[5]*100
b=[5]*3
''',
'''
a=b=(5,)*100
''',
'''
a=b="This on is a string" * 5
''',
'''
import array
a=b=array.array('B', "This on is a string" * 5)
'''
)
common = '''import itertools
def comp1(a, b):
if len(a) != len(b):
return False
for i, v in enumerate(a):
if v != b[i]:
return False
return True'''
for i, setup in enumerate(tests):
t1 = timeit.Timer("comp1(a, b)", setup + common)
t2 = timeit.Timer("all(x == y for x, y in itertools.izip_longest(a, b))", setup + common)
t3 = timeit.Timer("all([x == y for x, y in itertools.izip_longest(a, b)])", setup + common)
t4 = timeit.Timer("list(a) == list(b)", setup + common)
t5 = timeit.Timer("tuple(a) == tuple(b)", setup + common)
print '==test %d==' % i
print ' comp1: %g' % t1.timeit()
print ' all gen: %g' % t2.timeit()
print 'all list: %g' % t3.timeit()
print ' list: %g' % t4.timeit()
print ' tuple: %g\n' % t5.timeit()
</code></pre>
<p>Here are the results:</p>
<pre><code>==test 0==
comp1: 27.8089
all gen: 31.1406
all list: 29.4887
list: 3.58438
tuple: 3.25859
==test 1==
comp1: 0.833313
all gen: 3.8026
all list: 33.5288
list: 1.90453
tuple: 1.74985
==test 2==
comp1: 30.606
all gen: 31.4755
all list: 29.5637
list: 3.56635
tuple: 1.60032
==test 3==
comp1: 33.3725
all gen: 35.3699
all list: 34.2619
list: 10.2443
tuple: 10.1124
==test 4==
comp1: 31.7014
all gen: 32.0051
all list: 31.0664
list: 8.35031
tuple: 8.16301
</code></pre>
<p><strong>Edit:</strong> Added a few more tests. This was run on an AMD 939 3800+ with 2GB of ram. Linux 32bit, Python 2.6.2</p>
| 2 | 2009-05-23T00:34:34Z | [
"python"
] |
Elegant way to compare sequences | 900,420 | <p>Does python provide an elegant way to check for "equality" of sequences of different types? The following work, but they seem rather ugly and verbose for python code:</p>
<pre><code>def comp1(a, b):
if len(a) != len(b):
return False
for i, v in enumerate(a):
if v != b[i]:
return False
return True
</code></pre>
<p>The following is a bit shorter, but also less efficient since a third sequence is created:</p>
<pre><code>def comp2(a, b):
for l, r in map(None, a, b):
if l != r:
return False
return True
</code></pre>
<p>Shoehorning one of those examples into a list comprehension isn't really what I'm looking for either.</p>
<p>Edit: Ideally I am looking for a solution that doesn't create another sequence during the comparison.</p>
| 9 | 2009-05-22T23:32:56Z | 903,677 | <p>This "functional" code should be fast and generic enough for all purposes.</p>
<pre><code># python 2.6 ⤠x < 3.0
import operator, itertools as it
def seq_cmp(seqa, seqb):
return all(it.starmap(operator.eq, it.izip_longest(seqa, seqb)))
</code></pre>
<p>If on Python 2.5, use the definition for izip_longest from <a href="http://docs.python.org/library/itertools.html#itertools.izip%5Flongest" rel="nofollow">there</a>.</p>
| 0 | 2009-05-24T12:29:19Z | [
"python"
] |
Elegant way to compare sequences | 900,420 | <p>Does python provide an elegant way to check for "equality" of sequences of different types? The following work, but they seem rather ugly and verbose for python code:</p>
<pre><code>def comp1(a, b):
if len(a) != len(b):
return False
for i, v in enumerate(a):
if v != b[i]:
return False
return True
</code></pre>
<p>The following is a bit shorter, but also less efficient since a third sequence is created:</p>
<pre><code>def comp2(a, b):
for l, r in map(None, a, b):
if l != r:
return False
return True
</code></pre>
<p>Shoehorning one of those examples into a list comprehension isn't really what I'm looking for either.</p>
<p>Edit: Ideally I am looking for a solution that doesn't create another sequence during the comparison.</p>
| 9 | 2009-05-22T23:32:56Z | 3,439,976 | <p>Apart from the extra memory used by creating temporary lists/tuples, those answers will lose out to short circuiting generator solutions for large sequences when the inequality occurs early in the sequences</p>
<pre><code>from itertools import starmap, izip
from operator import eq
all(starmap(eq, izip(x, y)))
</code></pre>
<p>or more concisely</p>
<pre><code>from itertools import imap
from operator import eq
all(imap(eq, x, y))
</code></pre>
<p>some benchmarks from ipython</p>
<pre><code>x=range(1000)
y=range(1000); y[10]=0
timeit tuple(x) == tuple(y)
100000 loops, best of 3: 16.9 us per loop
timeit all(imap(eq, x, y))
100000 loops, best of 3: 2.86 us per loop
</code></pre>
| 4 | 2010-08-09T12:30:27Z | [
"python"
] |
Elegant way to compare sequences | 900,420 | <p>Does python provide an elegant way to check for "equality" of sequences of different types? The following work, but they seem rather ugly and verbose for python code:</p>
<pre><code>def comp1(a, b):
if len(a) != len(b):
return False
for i, v in enumerate(a):
if v != b[i]:
return False
return True
</code></pre>
<p>The following is a bit shorter, but also less efficient since a third sequence is created:</p>
<pre><code>def comp2(a, b):
for l, r in map(None, a, b):
if l != r:
return False
return True
</code></pre>
<p>Shoehorning one of those examples into a list comprehension isn't really what I'm looking for either.</p>
<p>Edit: Ideally I am looking for a solution that doesn't create another sequence during the comparison.</p>
| 9 | 2009-05-22T23:32:56Z | 38,861,758 | <p>I think it's a good idea to special case when both sequences are type <code>list</code>. Comparing two lists is faster (and more memory efficient) than converting both to tuples.</p>
<p>In the case that either <code>a</code> or <code>b</code> are not lists, they are both converted to <code>tuple</code>. There is no overhead if one or both are already tuples, as <code>tuple()</code> just returns a reference to the original object in that case. </p>
<pre><code>def comp(a, b):
if len(a) != len(b):
return False
if type(a) == type(b) == list:
return a == b
a = tuple(a)
b = tuple(b)
return a == b
</code></pre>
| 0 | 2016-08-09T23:01:38Z | [
"python"
] |
Understanding python imports | 900,591 | <p>In the process of learning Django and Python. I can't make sense of this.</p>
<p>(Example Notes:'helloworld' is the name of my project. It has 1 app called 'app'.)</p>
<pre><code>from helloworld.views import * # <<-- this works
from helloworld import views # <<-- this doesn't work
from helloworld.app import views # <<-- but this works. why?
</code></pre>
<p>It seems like line #2 and #3 are practically the same. Why does like #2 not work?</p>
<p><strong>Edit -- Added the source of the two files.</strong>
You might recognize this code from the Django Book project (<a href="http://www.djangobook.com/en/2.0/" rel="nofollow">http://www.djangobook.com/en/2.0</a>)</p>
<h2>helloworld/views.py</h2>
<pre><code>from django.shortcuts import render_to_response
from django.http import HttpResponse, Http404
import datetime
def hello(request):
return HttpResponse("Hello world")
def current_datetime(request):
current_date = datetime.datetime.now()
return render_to_response('current_datetime.html', locals())
def offset_datetime(request, offset):
try:
offset = int(offset)
except ValueError:
raise Http404()
next_time = datetime.datetime.now() + datetime.timedelta(hours=offset)
return render_to_response('offset_datetime.html', locals())
def display_meta(request):
values = request.META.items()
values.sort()
path = request.path
return render_to_response('metavalues.html', locals())
</code></pre>
<h2>helloworld/app/views.py</h2>
<pre><code>from django.shortcuts import render_to_response
def search_form(request):
return render_to_response('search_form.html')
def search(request):
if 'q' in request.GET:
message = 'You searched for: %r' % request.GET['q']
else:
message = 'You searched for nothing.'
return render_to_response('search_results.html', locals())
</code></pre>
| 2 | 2009-05-23T01:04:11Z | 900,611 | <pre><code>from helloworld.views import * # <<-- this works
from helloworld import views # <<-- this doesn't work
from helloworld.app import views # <<-- but this works. why?
</code></pre>
<p>#2 and #3 are <em>not</em> the same.</p>
<p>The second one imports <code>views</code> from the package <code>helloworld</code>. The third one imports <code>views</code> from the package <code>helloworld.app</code>, which is a subpackage of <code>helloworld</code>. What it means is that views are specific to your django apps, and not your projects. If you had separate apps, how would you import views from each one? You have to specify the name of the app you want to import from, hence the syntax <code>helloworld.app</code>.</p>
| 4 | 2009-05-23T01:18:24Z | [
"python",
"django",
"import"
] |
Understanding python imports | 900,591 | <p>In the process of learning Django and Python. I can't make sense of this.</p>
<p>(Example Notes:'helloworld' is the name of my project. It has 1 app called 'app'.)</p>
<pre><code>from helloworld.views import * # <<-- this works
from helloworld import views # <<-- this doesn't work
from helloworld.app import views # <<-- but this works. why?
</code></pre>
<p>It seems like line #2 and #3 are practically the same. Why does like #2 not work?</p>
<p><strong>Edit -- Added the source of the two files.</strong>
You might recognize this code from the Django Book project (<a href="http://www.djangobook.com/en/2.0/" rel="nofollow">http://www.djangobook.com/en/2.0</a>)</p>
<h2>helloworld/views.py</h2>
<pre><code>from django.shortcuts import render_to_response
from django.http import HttpResponse, Http404
import datetime
def hello(request):
return HttpResponse("Hello world")
def current_datetime(request):
current_date = datetime.datetime.now()
return render_to_response('current_datetime.html', locals())
def offset_datetime(request, offset):
try:
offset = int(offset)
except ValueError:
raise Http404()
next_time = datetime.datetime.now() + datetime.timedelta(hours=offset)
return render_to_response('offset_datetime.html', locals())
def display_meta(request):
values = request.META.items()
values.sort()
path = request.path
return render_to_response('metavalues.html', locals())
</code></pre>
<h2>helloworld/app/views.py</h2>
<pre><code>from django.shortcuts import render_to_response
def search_form(request):
return render_to_response('search_form.html')
def search(request):
if 'q' in request.GET:
message = 'You searched for: %r' % request.GET['q']
else:
message = 'You searched for nothing.'
return render_to_response('search_results.html', locals())
</code></pre>
| 2 | 2009-05-23T01:04:11Z | 900,615 | <p>As sykora alluded, helloworld is not in-and-of-itself a package, so #2 won't work. You would need a helloworld.py, appropriately set up.</p>
<p>I asked about import a couple of days ago, this might help:
<a href="http://stackoverflow.com/questions/860672/lay-out-import-pathing-in-python-straight-and-simple">http://stackoverflow.com/questions/860672/lay-out-import-pathing-in-python-straight-and-simple</a></p>
| 1 | 2009-05-23T01:21:44Z | [
"python",
"django",
"import"
] |
Understanding python imports | 900,591 | <p>In the process of learning Django and Python. I can't make sense of this.</p>
<p>(Example Notes:'helloworld' is the name of my project. It has 1 app called 'app'.)</p>
<pre><code>from helloworld.views import * # <<-- this works
from helloworld import views # <<-- this doesn't work
from helloworld.app import views # <<-- but this works. why?
</code></pre>
<p>It seems like line #2 and #3 are practically the same. Why does like #2 not work?</p>
<p><strong>Edit -- Added the source of the two files.</strong>
You might recognize this code from the Django Book project (<a href="http://www.djangobook.com/en/2.0/" rel="nofollow">http://www.djangobook.com/en/2.0</a>)</p>
<h2>helloworld/views.py</h2>
<pre><code>from django.shortcuts import render_to_response
from django.http import HttpResponse, Http404
import datetime
def hello(request):
return HttpResponse("Hello world")
def current_datetime(request):
current_date = datetime.datetime.now()
return render_to_response('current_datetime.html', locals())
def offset_datetime(request, offset):
try:
offset = int(offset)
except ValueError:
raise Http404()
next_time = datetime.datetime.now() + datetime.timedelta(hours=offset)
return render_to_response('offset_datetime.html', locals())
def display_meta(request):
values = request.META.items()
values.sort()
path = request.path
return render_to_response('metavalues.html', locals())
</code></pre>
<h2>helloworld/app/views.py</h2>
<pre><code>from django.shortcuts import render_to_response
def search_form(request):
return render_to_response('search_form.html')
def search(request):
if 'q' in request.GET:
message = 'You searched for: %r' % request.GET['q']
else:
message = 'You searched for nothing.'
return render_to_response('search_results.html', locals())
</code></pre>
| 2 | 2009-05-23T01:04:11Z | 900,724 | <p>Python imports can import two different kinds of things: modules and objects.</p>
<pre><code>import x
</code></pre>
<p>Imports an entire module named <code>x</code>.</p>
<pre><code>import x.y
</code></pre>
<p>Imports a module named <code>y</code> and it's container <code>x</code>. You refer to <code>x.y</code>. </p>
<p>When you created it, however, you created this directory structure</p>
<pre><code>x
__init__.py
y.py
</code></pre>
<p>When you add to the import statement, you identify specific objects to pull from the module and move into the global namespace</p>
<pre><code>import x # the module as a whole
x.a # Must pick items out of the module
x.b
from x import a, b # two things lifted out of the module
a # items are global
b
</code></pre>
<p>If helloworld is a package (a directory, with an <code>__init__.py</code> file), it typically doesn't contain any objects.</p>
<pre><code>from x import y # isn't sensible
import x.y # importing a whole module.
</code></pre>
<p>Sometimes, you will have objects defined in the <code>__init__.py</code> file.</p>
<p>Generally, use "from module import x" to pick specific objects out of a module.</p>
<p>Use <code>import module</code> to import an entire module.</p>
| 7 | 2009-05-23T02:35:50Z | [
"python",
"django",
"import"
] |
Need help with the class and instance concept in Python | 900,929 | <p>I have read several documentation already but the definition of "class" and "instance" didnt get really clear for me yet.</p>
<p>Looks like that "class" is like a combination of functions or methods that return some result is that correct? And how about the instance? I read that you work with the class you creat trough the instance but wouldnt be easier to just work direct with the class?</p>
<p>Sometimes geting the concepts of the language is harder than working with it.</p>
| 2 | 2009-05-23T05:32:13Z | 900,940 | <p>Your question is really rather broad as classes and instances/objects are vital parts of object-oriented programming, so this is not really Python specific. I recommend you buy some books on this as, while initially basic, it can get pretty in-depth. <a href="http://en.wikipedia.org/wiki/Class-based%5Fprogramming" rel="nofollow">In essense</a>, however:</p>
<blockquote>
<p>The most popular and developed model of OOP is a class-based model, as opposed to an object-based model. In this model, objects are entities that combine state (i.e., data), behavior (i.e., procedures, or methods) and identity (unique existence among all other objects). The structure and behavior of an object are defined by a class, which is a definition, or blueprint, of all objects of a specific type. An object must be explicitly created based on a class and an object thus created is considered to be an instance of that class. An object is similar to a structure, with the addition of method pointers, member access control, and an implicit data member which locates instances of the class (i.e. actual objects of that class) in the class hierarchy (essential for runtime inheritance features).</p>
</blockquote>
<p>So you would, for example, define a <code>Dog</code> class, and create instances of particular dogs:</p>
<pre><code>>>> class Dog():
... def __init__(self, name, breed):
... self.name = name
... self.breed = breed
... def talk(self):
... print "Hi, my name is " + self.name + ", I am a " + self.breed
...
>>> skip = Dog('Skip','Bulldog')
>>> spot = Dog('Spot','Dalmatian')
>>> spot.talk()
Hi, my name is Spot, I am a Dalmatian
>>> skip.talk()
Hi, my name is Skip, I am a Bulldog
</code></pre>
<p>While this example is silly, you can then start seeing how you might define a <code>Client</code> class that sets a blueprint for what a Client is, has methods to perform actions on a particular client, then manipulate a particular <em>instance</em> of a client by creating an object and calling these methods in that context.</p>
<p>Sometimes, however, you have methods of a class that don't really make sense being accessed through an instance of the class, but more from the class itself. These are known as <a href="http://docs.python.org/library/functions.html#staticmethod" rel="nofollow">static methods</a>. </p>
| 7 | 2009-05-23T05:40:03Z | [
"python"
] |
Need help with the class and instance concept in Python | 900,929 | <p>I have read several documentation already but the definition of "class" and "instance" didnt get really clear for me yet.</p>
<p>Looks like that "class" is like a combination of functions or methods that return some result is that correct? And how about the instance? I read that you work with the class you creat trough the instance but wouldnt be easier to just work direct with the class?</p>
<p>Sometimes geting the concepts of the language is harder than working with it.</p>
| 2 | 2009-05-23T05:32:13Z | 900,943 | <p>In part it is confusing due to the dynamically typed nature of Python, which allows you to operate on a class and an instance in essentially the same way. In other languages, the difference is more concrete in that a class provides a template by which to create an object (instance) and cannot be as directly manipulated as in Python. The benefit of operating on the instance rather than the class is that the class can provide a prototype upon which instances are created. </p>
| 0 | 2009-05-23T05:41:45Z | [
"python"
] |
Need help with the class and instance concept in Python | 900,929 | <p>I have read several documentation already but the definition of "class" and "instance" didnt get really clear for me yet.</p>
<p>Looks like that "class" is like a combination of functions or methods that return some result is that correct? And how about the instance? I read that you work with the class you creat trough the instance but wouldnt be easier to just work direct with the class?</p>
<p>Sometimes geting the concepts of the language is harder than working with it.</p>
| 2 | 2009-05-23T05:32:13Z | 900,948 | <p>It's fairly simple actually. You know how in python they say "everything is an object". Well in simplistic terms you can think of any object as being an 'instance' and the instructions to create an object as the class. Or in biological terms DNA is the class and you are an instance of DNA.</p>
<pre><code>class HumanDNA(): # class
... class attributes ...
you = HumanDNA() # instance
</code></pre>
| 2 | 2009-05-23T05:44:14Z | [
"python"
] |
Need help with the class and instance concept in Python | 900,929 | <p>I have read several documentation already but the definition of "class" and "instance" didnt get really clear for me yet.</p>
<p>Looks like that "class" is like a combination of functions or methods that return some result is that correct? And how about the instance? I read that you work with the class you creat trough the instance but wouldnt be easier to just work direct with the class?</p>
<p>Sometimes geting the concepts of the language is harder than working with it.</p>
| 2 | 2009-05-23T05:32:13Z | 900,953 | <p>I am not sure of what level of knowledge you have, so I apologize if this answer is too simplified (then just ignore it).</p>
<p>A class is a template for an object. Like a blueprint for a car. The instance of a class is like an actual car. So you have one blueprint, but you can have several different instances of cars. The blueprint and the car are different things.</p>
<p>So you make a class that describes what an instance of that class can do and what properties it should have. Then you "build" the instance and get an object that you can work with.</p>
| 3 | 2009-05-23T05:46:44Z | [
"python"
] |
Need help with the class and instance concept in Python | 900,929 | <p>I have read several documentation already but the definition of "class" and "instance" didnt get really clear for me yet.</p>
<p>Looks like that "class" is like a combination of functions or methods that return some result is that correct? And how about the instance? I read that you work with the class you creat trough the instance but wouldnt be easier to just work direct with the class?</p>
<p>Sometimes geting the concepts of the language is harder than working with it.</p>
| 2 | 2009-05-23T05:32:13Z | 901,368 | <p>See <a href="http://homepage.mac.com/s_lott/books/python/htmlchunks/ch21.html" rel="nofollow">http://homepage.mac.com/s_lott/books/python/htmlchunks/ch21.html</a></p>
<blockquote>
<p>Object-oriented programming permits us
to organize our programs around the
interactions of objects. A class
provides the definition of the
structure and behavior of the objects;
each object is an instance of a class.</p>
</blockquote>
<p>Objects ("instances") are things which interact, do work, persist in the file system, etc.</p>
<p>Classes are the definitions for the object's behavior.</p>
<p>Also, a class creates new objects that are members of that class (share common structure and behavior)</p>
| 1 | 2009-05-23T11:29:44Z | [
"python"
] |
Django not picking up changes to INSTALLED_APPS in settings.py | 901,061 | <p>I'm trying to get South to work - it worked fine on my PC, but I'm struggling to deploy it on my webhost.</p>
<p>Right now it seems that any changes I make to add/remove items from INSTALLED_APPS aren't being picked up by <code>syncdb</code> or <code>diffsettings</code>. I've added <code>south</code> to my list of INSTALLED_APPS, but the tables it needs aren't being created when I run <code>syncdb</code>. If I change other settings, they are picked up, it just seems to be INSTALLED_APPS that doesn't work.</p>
<p>If I run</p>
<pre><code>from south.db import db
</code></pre>
<p>from the shell I get with <code>manage.py shell</code>, I don't get any import errors, so I don't think it's a problem with where <code>south</code> is. I've tried removing all my other applications (other than the Django standard ones), and tables for them still get created when I run <code>syncdb</code>.</p>
<p>Even if I delete INSTALLED_APPS completely, I still get the old list of INSTALLED_APPS when I run manage.py diffsettings.</p>
<p>Any ideas what I've done wrong?</p>
<p>Thanks,</p>
<p>Dom</p>
| 2 | 2009-05-23T07:15:26Z | 901,846 | <p>If you write a migration for an application, syncdb wont work.
You have to use </p>
<pre><code>manage.py migrate
</code></pre>
<p>syncdb wont work for applications which are hooked under migration using south. Those applications model change will be noticed only depending on south migration history.</p>
<p><a href="http://south.aeracode.org/wiki/Documentation" rel="nofollow">South Migration Docs</a></p>
| 3 | 2009-05-23T16:22:33Z | [
"python",
"django"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.