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: Locks from `threading` and `multiprocessing` interchangable?
739,687
<p>Are the locks from the <code>threading</code> module interchangeable with those from the <code>multiprocessing</code> module?</p>
5
2009-04-11T07:37:24Z
739,705
<p>Yes, you can use locks from the multiprocessing module as normal in your one-process application, but if you're using multiprocessing, you should use its locks.</p>
1
2009-04-11T07:48:01Z
[ "python", "multithreading", "locking", "multiprocessing" ]
Python: Locks from `threading` and `multiprocessing` interchangable?
739,687
<p>Are the locks from the <code>threading</code> module interchangeable with those from the <code>multiprocessing</code> module?</p>
5
2009-04-11T07:37:24Z
740,197
<p>You can typically use the two interchangeably, but you need to cognizant of the differences. For example, multiprocessing.Event is backed by a named semaphore, which is sensitive to the platform under the application. </p> <p>Multiprocessing.Lock is backed by Multiprocessing.SemLock - so it needs named semaphores. In essence, you can use them interchangeably, but using multiprocessing's locks introduces some platform requirements on the application (namely, it doesn't run on BSD :)) </p>
7
2009-04-11T14:34:57Z
[ "python", "multithreading", "locking", "multiprocessing" ]
Iterating over object instances of a given class in Python
739,882
<p>Given a class that keeps a registry of its Objects:</p> <pre><code>class Person(object): __registry = [] def __init__(self, name): self.__registry.append(self) self.name = name </code></pre> <p>How would I make the following code work (without using Person.__registry):</p> <pre><code>for personobject in Person: print personobject </code></pre> <p>While researching I found a hint that one could go for a <code>__metaclass__</code> with a <code>__getitem__</code>-method. Any ideas how this would look like?</p>
12
2009-04-11T11:13:09Z
739,896
<p>you can do it with:</p> <pre><code>for item in Person.__registry: print(item) </code></pre>
2
2009-04-11T11:24:13Z
[ "python", "oop" ]
Iterating over object instances of a given class in Python
739,882
<p>Given a class that keeps a registry of its Objects:</p> <pre><code>class Person(object): __registry = [] def __init__(self, name): self.__registry.append(self) self.name = name </code></pre> <p>How would I make the following code work (without using Person.__registry):</p> <pre><code>for personobject in Person: print personobject </code></pre> <p>While researching I found a hint that one could go for a <code>__metaclass__</code> with a <code>__getitem__</code>-method. Any ideas how this would look like?</p>
12
2009-04-11T11:13:09Z
739,936
<p>First, do not use double <code>__</code> names. They're reserved for use by Python. If you want "private" use single <code>_</code>.</p> <p>Second, keep this kind of thing as simple as possible. Don't waste a lot of time and energy on something complex. This is a simple problem, keep the code as simple as possible to get the job done.</p> <pre><code>class Person(object): _registry = [] def __init__(self, name): self._registry.append(self) self.name = name for p in Person._registry: print p </code></pre>
7
2009-04-11T11:57:21Z
[ "python", "oop" ]
Iterating over object instances of a given class in Python
739,882
<p>Given a class that keeps a registry of its Objects:</p> <pre><code>class Person(object): __registry = [] def __init__(self, name): self.__registry.append(self) self.name = name </code></pre> <p>How would I make the following code work (without using Person.__registry):</p> <pre><code>for personobject in Person: print personobject </code></pre> <p>While researching I found a hint that one could go for a <code>__metaclass__</code> with a <code>__getitem__</code>-method. Any ideas how this would look like?</p>
12
2009-04-11T11:13:09Z
739,954
<p>You can make your class object iterable with a simple metaclass.</p> <pre><code>class IterRegistry(type): def __iter__(cls): return iter(cls._registry) class Person(object): __metaclass__ = IterRegistry _registry = [] def __init__(self, name): self._registry.append(self) self.name = name </code></pre> <p>(I have also changed <code>__registry</code> to <code>_registry</code> to make it easier to access from the metaclass). Then,</p> <pre><code>&gt;&gt;&gt; p = Person('John') &gt;&gt;&gt; p2 = Person('Mary') &gt;&gt;&gt; for personobject in Person: ... print personobject ... &lt;person.Person object at 0x70410&gt; &lt;person.Person object at 0x70250&gt; </code></pre>
18
2009-04-11T12:10:20Z
[ "python", "oop" ]
How can I get a list of locally installed Python modules?
739,993
<p>I would like to get a list of Python modules, which are in my Python installation (UNIX server).</p> <p><strong>How can you get a list of Python modules installed in your computer?</strong></p>
533
2009-04-11T12:34:18Z
740,000
<p>From the shell</p> <pre><code>ls site-packages </code></pre> <p>If that's not helpful, you can do this.</p> <pre><code>import sys import os for p in sys.path: print os.listdir( p ) </code></pre> <p>And see what that produces.</p>
-8
2009-04-11T12:38:07Z
[ "python", "module", "pip" ]
How can I get a list of locally installed Python modules?
739,993
<p>I would like to get a list of Python modules, which are in my Python installation (UNIX server).</p> <p><strong>How can you get a list of Python modules installed in your computer?</strong></p>
533
2009-04-11T12:34:18Z
740,018
<pre><code>help('modules') </code></pre> <p>in a Python shell/prompt.</p>
631
2009-04-11T12:45:45Z
[ "python", "module", "pip" ]
How can I get a list of locally installed Python modules?
739,993
<p>I would like to get a list of Python modules, which are in my Python installation (UNIX server).</p> <p><strong>How can you get a list of Python modules installed in your computer?</strong></p>
533
2009-04-11T12:34:18Z
4,703,670
<p>Now, these methods I tried myself, and I got exactly what was advertised: All the modules.</p> <p>Alas, really you don't care much about the stdlib, you know what you get with a python install. </p> <p>Really, I want the stuff that <em>I</em> installed. </p> <p>What actually, surprisingly, worked just fine was:</p> <pre><code>pip freeze </code></pre> <p>Which returned:</p> <pre><code>Fabric==0.9.3 apache-libcloud==0.4.0 bzr==2.3b4 distribute==0.6.14 docutils==0.7 greenlet==0.3.1 ipython==0.10.1 iterpipes==0.4 libxml2-python==2.6.21 </code></pre> <p>I say "surprisingly" because the package install tool is the exact place one would expect to find this functionality, although not under the name 'freeze' but python packaging is so weird, that I am flabbergasted that this tool makes sense. Pip 0.8.2, Python 2.7. </p>
173
2011-01-16T03:42:15Z
[ "python", "module", "pip" ]
How can I get a list of locally installed Python modules?
739,993
<p>I would like to get a list of Python modules, which are in my Python installation (UNIX server).</p> <p><strong>How can you get a list of Python modules installed in your computer?</strong></p>
533
2009-04-11T12:34:18Z
9,194,180
<ul> <li><p>In <a href="http://ipython.org/"><code>ipython</code></a> you can type "<code>import</code><kbd>Tab</kbd>".</p></li> <li><p>In the standard Python interpreter, you can type "<code>help('modules')</code>".</p></li> <li><p>At the command-line, you can use <a href="http://docs.python.org/library/pydoc.html"><code>pydoc</code></a> <code>modules</code>.</p></li> <li><p>In a script, call <a href="http://docs.python.org/library/pkgutil.html#pkgutil.iter_modules"><code>pkgutil.iter_modules()</code></a>.</p></li> </ul>
59
2012-02-08T13:24:27Z
[ "python", "module", "pip" ]
How can I get a list of locally installed Python modules?
739,993
<p>I would like to get a list of Python modules, which are in my Python installation (UNIX server).</p> <p><strong>How can you get a list of Python modules installed in your computer?</strong></p>
533
2009-04-11T12:34:18Z
10,563,781
<p>Very simple searching using <a href="http://docs.python.org/library/pkgutil.html#pkgutil.iter_modules">pkgutil.iter_modules</a></p> <pre><code>from pkgutil import iter_modules a=iter_modules() while True: try: x=a.next() except: break if 'searchstr' in x[1]: print x[1] </code></pre>
9
2012-05-12T12:34:44Z
[ "python", "module", "pip" ]
How can I get a list of locally installed Python modules?
739,993
<p>I would like to get a list of Python modules, which are in my Python installation (UNIX server).</p> <p><strong>How can you get a list of Python modules installed in your computer?</strong></p>
533
2009-04-11T12:34:18Z
11,164,710
<p>I just use this to see currently used modules:</p> <pre><code>import sys as s s.modules.keys() </code></pre> <p>which shows all modules running on your python.</p> <p>For all built-in modules use:</p> <pre><code>s.modules </code></pre> <p>Which is a dict containing all modules and import objects.</p>
31
2012-06-22T22:02:06Z
[ "python", "module", "pip" ]
How can I get a list of locally installed Python modules?
739,993
<p>I would like to get a list of Python modules, which are in my Python installation (UNIX server).</p> <p><strong>How can you get a list of Python modules installed in your computer?</strong></p>
533
2009-04-11T12:34:18Z
12,107,636
<p>I ran into a custom installed python 2.7 on OS X. It required X11 to list modules installed (both using help and pydoc).</p> <p>To be able to list all modules without installing X11 I ran pydoc as http-server, i.e.:</p> <pre><code>pydoc -p 12345 </code></pre> <p>Then it's possible to direct Safari to <code>http://localhost:12345/</code> to see all modules.</p>
10
2012-08-24T10:28:05Z
[ "python", "module", "pip" ]
How can I get a list of locally installed Python modules?
739,993
<p>I would like to get a list of Python modules, which are in my Python installation (UNIX server).</p> <p><strong>How can you get a list of Python modules installed in your computer?</strong></p>
533
2009-04-11T12:34:18Z
14,529,730
<p>Aside from using <code>pip freeze</code> I have been installing <a href="http://pypi.python.org/pypi/yolk" rel="nofollow">yolk</a> in my virtual environments.</p>
5
2013-01-25T20:20:06Z
[ "python", "module", "pip" ]
How can I get a list of locally installed Python modules?
739,993
<p>I would like to get a list of Python modules, which are in my Python installation (UNIX server).</p> <p><strong>How can you get a list of Python modules installed in your computer?</strong></p>
533
2009-04-11T12:34:18Z
17,870,160
<p>Since pip version 1.3, you've got access to:</p> <pre><code>pip list </code></pre> <p>Which seems to be syntactic sugar for "pip freeze". It will list all of the modules particular to your installation or virtualenv, along with their version numbers. Unfortunately it does not display the current version number of any module, nor does it wash your dishes or shine your shoes.</p>
38
2013-07-25T22:56:32Z
[ "python", "module", "pip" ]
How can I get a list of locally installed Python modules?
739,993
<p>I would like to get a list of Python modules, which are in my Python installation (UNIX server).</p> <p><strong>How can you get a list of Python modules installed in your computer?</strong></p>
533
2009-04-11T12:34:18Z
18,399,722
<p>In normal shell just use</p> <pre><code>pydoc modules </code></pre>
41
2013-08-23T09:45:31Z
[ "python", "module", "pip" ]
How can I get a list of locally installed Python modules?
739,993
<p>I would like to get a list of Python modules, which are in my Python installation (UNIX server).</p> <p><strong>How can you get a list of Python modules installed in your computer?</strong></p>
533
2009-04-11T12:34:18Z
20,413,093
<p>In case you have an <a href="https://store.continuum.io/cshop/anaconda/" rel="nofollow">anaconda python distribution</a> installed, you could also use</p> <pre><code>$conda list </code></pre> <p>in addition to solutions described above.</p>
3
2013-12-05T23:38:03Z
[ "python", "module", "pip" ]
How can I get a list of locally installed Python modules?
739,993
<p>I would like to get a list of Python modules, which are in my Python installation (UNIX server).</p> <p><strong>How can you get a list of Python modules installed in your computer?</strong></p>
533
2009-04-11T12:34:18Z
20,879,819
<p>If we need to know list of installed packages in python , we can use 'help' command like given below (in python shell)</p> <pre><code>&gt;&gt;help('modules package') </code></pre>
9
2014-01-02T09:26:40Z
[ "python", "module", "pip" ]
How can I get a list of locally installed Python modules?
739,993
<p>I would like to get a list of Python modules, which are in my Python installation (UNIX server).</p> <p><strong>How can you get a list of Python modules installed in your computer?</strong></p>
533
2009-04-11T12:34:18Z
21,250,992
<ol> <li>to get all available modules, run <code>sys.modules</code></li> <li>to get all <em>installed</em> modules (read: installed by <code>pip</code>), you may look at <code>pip.get_installed_distributions()</code></li> </ol> <p>For the second purpose, example code:</p> <pre><code>import pip for package in pip.get_installed_distributions(): name = package.project_name # SQLAlchemy, Django, Flask-OAuthlib key = package.key # sqlalchemy, django, flask-oauthlib module_name = package._get_metadata("top_level.txt") # sqlalchemy, django, flask_oauthlib location = package.location # virtualenv lib directory etc. version = package.version # version number </code></pre>
3
2014-01-21T06:42:12Z
[ "python", "module", "pip" ]
How can I get a list of locally installed Python modules?
739,993
<p>I would like to get a list of Python modules, which are in my Python installation (UNIX server).</p> <p><strong>How can you get a list of Python modules installed in your computer?</strong></p>
533
2009-04-11T12:34:18Z
23,885,252
<h2>Solution</h2> <p>My 50 cents for getting a <code>pip freeze</code>-like list from a Python script:</p> <pre class="lang-python prettyprint-override"><code>import pip installed_packages = pip.get_installed_distributions() installed_packages_list = sorted(["%s==%s" % (i.key, i.version) for i in installed_packages]) print(installed_packages_list) </code></pre> <p>As a (too long) one liner:</p> <pre class="lang-python prettyprint-override"><code>sorted(["%s==%s" % (i.key, i.version) for i in pip.get_installed_distributions()]) </code></pre> <p>Giving:</p> <pre class="lang-js prettyprint-override"><code>['behave==1.2.4', 'enum34==1.0', 'flask==0.10.1', 'itsdangerous==0.24', 'jinja2==2.7.2', 'jsonschema==2.3.0', 'markupsafe==0.23', 'nose==1.3.3', 'parse-type==0.3.4', 'parse==1.6.4', 'prettytable==0.7.2', 'requests==2.3.0', 'six==1.6.1', 'vioozer-metadata==0.1', 'vioozer-users-server==0.1', 'werkzeug==0.9.4'] </code></pre> <h2>Scope</h2> <p>This solution applies to the system scope or to a virtual environment scope, and covers packages installed by <code>setuptools</code>, <code>pip</code> and (<a href="http://stackoverflow.com/questions/3220404/why-use-pip-over-easy-install">god forbid</a>) <code>easy_install</code>.</p> <h2>My use case</h2> <p>I added the result of this call to my flask server, so when I call it with <code>http://example.com/exampleServer/environment</code> I get the list of packages installed on the server's virtualenv. It makes debugging a whole lot easier.</p> <h2>Caveats</h2> <p>I have noticed a strange behaviour of this technique - when the Python interpreter is invoked in the same directory as a <code>setup.py</code> file, it does not list the package installed by <code>setup.py</code>.</p> <h3>Steps to reproduce:</h3> Create a virtual environment <pre><code>$ cd /tmp $ virtualenv test_env New python executable in test_env/bin/python Installing setuptools, pip...done. $ source test_env/bin/activate (test_env) $ </code></pre> Clone a git repo with <code>setup.py</code> <pre><code>(test_env) $ git clone https://github.com/behave/behave.git Cloning into 'behave'... remote: Reusing existing pack: 4350, done. remote: Total 4350 (delta 0), reused 0 (delta 0) Receiving objects: 100% (4350/4350), 1.85 MiB | 418.00 KiB/s, done. Resolving deltas: 100% (2388/2388), done. Checking connectivity... done. </code></pre> <p>We have behave's <code>setup.py</code> in <code>/tmp/behave</code>:</p> <pre><code>(test_env) $ ls /tmp/behave/setup.py /tmp/behave/setup.py </code></pre> Install the python package from the git repo <pre><code>(test_env) $ cd /tmp/behave &amp;&amp; python setup.py install running install ... Installed /private/tmp/test_env/lib/python2.7/site-packages/enum34-1.0-py2.7.egg Finished processing dependencies for behave==1.2.5a1 </code></pre> <h3>If we run the aforementioned solution from <code>/tmp</code></h3> <pre><code>&gt;&gt;&gt; import pip &gt;&gt;&gt; sorted(["%s==%s" % (i.key, i.version) for i in pip.get_installed_distributions()]) ['behave==1.2.5a1', 'enum34==1.0', 'parse-type==0.3.4', 'parse==1.6.4', 'six==1.6.1'] &gt;&gt;&gt; import os &gt;&gt;&gt; os.getcwd() '/private/tmp' </code></pre> <h3>If we run the aforementioned solution from <code>/tmp/behave</code></h3> <pre><code>&gt;&gt;&gt; import pip &gt;&gt;&gt; sorted(["%s==%s" % (i.key, i.version) for i in pip.get_installed_distributions()]) ['enum34==1.0', 'parse-type==0.3.4', 'parse==1.6.4', 'six==1.6.1'] &gt;&gt;&gt; import os &gt;&gt;&gt; os.getcwd() '/private/tmp/behave' </code></pre> <p><code>behave==1.2.5a1</code> is missing from the second example, because the working directory contains <code>behave</code>'s <code>setup.py</code> file.</p> <p>I could not find any reference to this issue in the documentation. Perhaps I shall open a bug for it.</p>
260
2014-05-27T09:05:42Z
[ "python", "module", "pip" ]
How can I get a list of locally installed Python modules?
739,993
<p>I would like to get a list of Python modules, which are in my Python installation (UNIX server).</p> <p><strong>How can you get a list of Python modules installed in your computer?</strong></p>
533
2009-04-11T12:34:18Z
34,224,653
<p>on windows, Enter this in cmd</p> <pre><code>c:\python\libs&gt;python -m pip freeze </code></pre>
1
2015-12-11T13:26:27Z
[ "python", "module", "pip" ]
How can I get a list of locally installed Python modules?
739,993
<p>I would like to get a list of Python modules, which are in my Python installation (UNIX server).</p> <p><strong>How can you get a list of Python modules installed in your computer?</strong></p>
533
2009-04-11T12:34:18Z
36,767,383
<p><strong>pip freeze</strong> does it all finding packages however one can simply write the following command to list all paths where python packages are.</p> <pre><code>&gt;&gt;&gt; import site; site.getsitepackages() ['/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages'] </code></pre>
2
2016-04-21T10:52:02Z
[ "python", "module", "pip" ]
How to check if one of the following items is in a list?
740,287
<p>I'm trying to find a short way to see if any of the following items is in a list, but my first attempt does not work. Besides writing a function to accomplish this, is the any short way to check if one of multiple items is in a list.</p> <pre><code>&gt;&gt;&gt; a = [2,3,4] &gt;&gt;&gt; print (1 or 2) in a False &gt;&gt;&gt; print (2 or 1) in a True </code></pre>
104
2009-04-11T15:13:07Z
740,291
<p>Think about what the code actually says!</p> <pre><code>&gt;&gt;&gt; (1 or 2) 1 &gt;&gt;&gt; (2 or 1) 2 </code></pre> <p>That should probably explain it. :) Python apparently implements "lazy or", which should come as no surprise. It performs it something like this:</p> <pre><code>def or(x, y): if x: return x if y: return y return False </code></pre> <p>In the first example, <code>x == 1</code> and <code>y == 2</code>. In the second example, it's vice versa. That's why it returns different values depending on the order of them.</p>
15
2009-04-11T15:16:29Z
[ "python" ]
How to check if one of the following items is in a list?
740,287
<p>I'm trying to find a short way to see if any of the following items is in a list, but my first attempt does not work. Besides writing a function to accomplish this, is the any short way to check if one of multiple items is in a list.</p> <pre><code>&gt;&gt;&gt; a = [2,3,4] &gt;&gt;&gt; print (1 or 2) in a False &gt;&gt;&gt; print (2 or 1) in a True </code></pre>
104
2009-04-11T15:13:07Z
740,294
<pre><code>&gt;&gt;&gt; L1 = [2,3,4] &gt;&gt;&gt; L2 = [1,2] &gt;&gt;&gt; [i for i in L1 if i in L2] [2] &gt;&gt;&gt; S1 = set(L1) &gt;&gt;&gt; S2 = set(L2) &gt;&gt;&gt; S1.intersection(S2) set([2]) </code></pre> <p>Both empty lists and empty sets are False, so you can use the value directly as a truth value.</p>
119
2009-04-11T15:22:07Z
[ "python" ]
How to check if one of the following items is in a list?
740,287
<p>I'm trying to find a short way to see if any of the following items is in a list, but my first attempt does not work. Besides writing a function to accomplish this, is the any short way to check if one of multiple items is in a list.</p> <pre><code>&gt;&gt;&gt; a = [2,3,4] &gt;&gt;&gt; print (1 or 2) in a False &gt;&gt;&gt; print (2 or 1) in a True </code></pre>
104
2009-04-11T15:13:07Z
740,297
<p>Best I could come up with:</p> <pre><code>any([True for e in (1, 2) if e in a]) </code></pre>
3
2009-04-11T15:24:02Z
[ "python" ]
How to check if one of the following items is in a list?
740,287
<p>I'm trying to find a short way to see if any of the following items is in a list, but my first attempt does not work. Besides writing a function to accomplish this, is the any short way to check if one of multiple items is in a list.</p> <pre><code>&gt;&gt;&gt; a = [2,3,4] &gt;&gt;&gt; print (1 or 2) in a False &gt;&gt;&gt; print (2 or 1) in a True </code></pre>
104
2009-04-11T15:13:07Z
740,300
<p>This will do it in one line.</p> <pre><code>&gt;&gt;&gt; a=[2,3,4] &gt;&gt;&gt; b=[1,2] &gt;&gt;&gt; bool(sum(map(lambda x: x in b, a))) True </code></pre>
1
2009-04-11T15:26:36Z
[ "python" ]
How to check if one of the following items is in a list?
740,287
<p>I'm trying to find a short way to see if any of the following items is in a list, but my first attempt does not work. Besides writing a function to accomplish this, is the any short way to check if one of multiple items is in a list.</p> <pre><code>&gt;&gt;&gt; a = [2,3,4] &gt;&gt;&gt; print (1 or 2) in a False &gt;&gt;&gt; print (2 or 1) in a True </code></pre>
104
2009-04-11T15:13:07Z
740,309
<p>In some cases (e.g. unique list elements), set operations can be used.</p> <pre><code>&gt;&gt;&gt; a=[2,3,4] &gt;&gt;&gt; set(a) - set([2,3]) != set(a) True &gt;&gt;&gt; </code></pre> <p>Or, using <a href="http://docs.python.org/library/stdtypes.html#set.isdisjoint" rel="nofollow">set.isdisjoint()</a>,</p> <pre><code>&gt;&gt;&gt; not set(a).isdisjoint(set([2,3])) True &gt;&gt;&gt; not set(a).isdisjoint(set([5,6])) False &gt;&gt;&gt; </code></pre>
3
2009-04-11T15:32:41Z
[ "python" ]
How to check if one of the following items is in a list?
740,287
<p>I'm trying to find a short way to see if any of the following items is in a list, but my first attempt does not work. Besides writing a function to accomplish this, is the any short way to check if one of multiple items is in a list.</p> <pre><code>&gt;&gt;&gt; a = [2,3,4] &gt;&gt;&gt; print (1 or 2) in a False &gt;&gt;&gt; print (2 or 1) in a True </code></pre>
104
2009-04-11T15:13:07Z
740,359
<p>Maybe a bit more lazy:</p> <pre><code>a = [1,2,3,4] b = [2,7] print any((True for x in a if x in b)) </code></pre>
12
2009-04-11T16:12:42Z
[ "python" ]
How to check if one of the following items is in a list?
740,287
<p>I'm trying to find a short way to see if any of the following items is in a list, but my first attempt does not work. Besides writing a function to accomplish this, is the any short way to check if one of multiple items is in a list.</p> <pre><code>&gt;&gt;&gt; a = [2,3,4] &gt;&gt;&gt; print (1 or 2) in a False &gt;&gt;&gt; print (2 or 1) in a True </code></pre>
104
2009-04-11T15:13:07Z
740,384
<p>Ah, Tobias you beat me to it. I was thinking of this slight variation on your solution:</p> <pre><code>print any(x in a for x in b) </code></pre>
103
2009-04-11T16:30:38Z
[ "python" ]
How to check if one of the following items is in a list?
740,287
<p>I'm trying to find a short way to see if any of the following items is in a list, but my first attempt does not work. Besides writing a function to accomplish this, is the any short way to check if one of multiple items is in a list.</p> <pre><code>&gt;&gt;&gt; a = [2,3,4] &gt;&gt;&gt; print (1 or 2) in a False &gt;&gt;&gt; print (2 or 1) in a True </code></pre>
104
2009-04-11T15:13:07Z
15,710,833
<pre><code>print (1 in a) or (2 in a) print (2 in a) or (5 in a) </code></pre> <p>This is a very old question, but I wasn't happy with any of the answers, so I had to add this for posterity's sake.</p>
0
2013-03-29T20:21:33Z
[ "python" ]
How to check if one of the following items is in a list?
740,287
<p>I'm trying to find a short way to see if any of the following items is in a list, but my first attempt does not work. Besides writing a function to accomplish this, is the any short way to check if one of multiple items is in a list.</p> <pre><code>&gt;&gt;&gt; a = [2,3,4] &gt;&gt;&gt; print (1 or 2) in a False &gt;&gt;&gt; print (2 or 1) in a True </code></pre>
104
2009-04-11T15:13:07Z
21,248,370
<p>When you think "check to see if a in b", think hashes (in this case, sets). The fastest way is to hash the list you want to check, and then check each item in there.</p> <p>This is why Joe Koberg's answer is fast: checking set intersection is very fast.</p> <p>When you don't have a lot of data though, making sets can be a waste of time. So, you can make a set of the list and just check each item. I wrote this:</p> <pre><code>tocheck = [1,2] # items to check a = [2,3,4] # the list a = set(a) # convert to set (O(len(a))) print [i for i in tocheck if i in a] # check items (O(len(tocheck))) </code></pre> <p>When the number of items you want to check is small, the difference can be negligible. But check lots of numbers against a large list...</p> <p>tests:</p> <pre><code>from timeit import timeit methods = ['''tocheck = [1,2] # items to check a = [2,3,4] # the list a = set(a) # convert to set (O(n)) [i for i in tocheck if i in a] # check items (O(m))''', '''L1 = [2,3,4] L2 = [1,2] [i for i in L1 if i in L2]''', '''S1 = set([2,3,4]) S2 = set([1,2]) S1.intersection(S2)''', '''a = [1,2] b = [2,3,4] any(x in a for x in b)'''] for method in methods: print timeit(method, number=10000) print methods = ['''tocheck = range(200,300) # items to check a = range(2, 10000) # the list a = set(a) # convert to set (O(n)) [i for i in tocheck if i in a] # check items (O(m))''', '''L1 = range(2, 10000) L2 = range(200,300) [i for i in L1 if i in L2]''', '''S1 = set(range(2, 10000)) S2 = set(range(200,300)) S1.intersection(S2)''', '''a = range(200,300) b = range(2, 10000) any(x in a for x in b)'''] for method in methods: print timeit(method, number=1000) </code></pre> <p>speeds:</p> <pre><code>M1: 0.0170331001282 # make one set M2: 0.0164539813995 # list comprehension M3: 0.0286040306091 # set intersection M4: 0.0305438041687 # any M1: 0.49850320816 # make one set M2: 25.2735087872 # list comprehension M3: 0.466138124466 # set intersection M4: 0.668627977371 # any </code></pre> <p>The method that is consistently fast is to make one set (of the list), but the intersection works on large data sets the best!</p>
1
2014-01-21T03:07:07Z
[ "python" ]
How to check if one of the following items is in a list?
740,287
<p>I'm trying to find a short way to see if any of the following items is in a list, but my first attempt does not work. Besides writing a function to accomplish this, is the any short way to check if one of multiple items is in a list.</p> <pre><code>&gt;&gt;&gt; a = [2,3,4] &gt;&gt;&gt; print (1 or 2) in a False &gt;&gt;&gt; print (2 or 1) in a True </code></pre>
104
2009-04-11T15:13:07Z
22,682,523
<pre><code>a = {2,3,4} if {1,2} &amp; a: pass </code></pre> <p>Code golf version. Consider using a set if it makes sense to do so. I find this more readable than a list comprehension.</p>
7
2014-03-27T08:56:02Z
[ "python" ]
How to check if one of the following items is in a list?
740,287
<p>I'm trying to find a short way to see if any of the following items is in a list, but my first attempt does not work. Besides writing a function to accomplish this, is the any short way to check if one of multiple items is in a list.</p> <pre><code>&gt;&gt;&gt; a = [2,3,4] &gt;&gt;&gt; print (1 or 2) in a False &gt;&gt;&gt; print (2 or 1) in a True </code></pre>
104
2009-04-11T15:13:07Z
24,399,987
<p>1 line without list comprehensions.</p> <pre><code>&gt;&gt;&gt; any(map(lambda each: each in [2,3,4], [1,2])) True &gt;&gt;&gt; any(map(lambda each: each in [2,3,4], [1,5])) False &gt;&gt;&gt; any(map(lambda each: each in [2,3,4], [2,4])) True </code></pre>
5
2014-06-25T04:02:23Z
[ "python" ]
How to check if one of the following items is in a list?
740,287
<p>I'm trying to find a short way to see if any of the following items is in a list, but my first attempt does not work. Besides writing a function to accomplish this, is the any short way to check if one of multiple items is in a list.</p> <pre><code>&gt;&gt;&gt; a = [2,3,4] &gt;&gt;&gt; print (1 or 2) in a False &gt;&gt;&gt; print (2 or 1) in a True </code></pre>
104
2009-04-11T15:13:07Z
30,169,646
<p>Simple.</p> <pre><code>_new_list = [] for item in a: if item in b: _new_list.append(item) else: pass </code></pre>
-2
2015-05-11T13:58:00Z
[ "python" ]
SQLAlchemy many-to-many orphan deletion
740,630
<p>I'm trying to use SQLAlchemy to implement a basic users-groups model where users can have multiple groups and groups can have multiple users.</p> <p>When a group becomes empty, I want the group to be deleted, (along with other things associated with the group. Fortunately, SQLAlchemy's cascade works fine with these more simple situations).</p> <p>The problem is that cascade='all, delete-orphan' doesn't do exactly what I want; instead of deleting the group when the group becomes empty, it deletes the group when <em>any</em> member leaves the group.</p> <p>Adding triggers to the database works fine for deleting a group when it becomes empty, except that triggers seem to bypass SQLAlchemy's cascade processing so things associated with the group don't get deleted.</p> <p>What is the best way to delete a group when all of its members leave and have this deletion cascade to related entities.</p> <p>I understand that I could do this manually by finding every place in my code where a user can leave a group and then doing the same thing as the trigger however, I'm afraid that I would miss places in the code (and I'm lazy).</p>
8
2009-04-11T19:07:17Z
763,256
<p>The way I've generally handled this is to have a function on your user or group called leave_group. When you want a user to leave a group, you call that function, and you can add any side effects you want into there. In the long term, this makes it easier to add more and more side effects. (For example when you want to check that someone is allowed to leave a group).</p>
3
2009-04-18T10:29:31Z
[ "python", "sqlalchemy" ]
SQLAlchemy many-to-many orphan deletion
740,630
<p>I'm trying to use SQLAlchemy to implement a basic users-groups model where users can have multiple groups and groups can have multiple users.</p> <p>When a group becomes empty, I want the group to be deleted, (along with other things associated with the group. Fortunately, SQLAlchemy's cascade works fine with these more simple situations).</p> <p>The problem is that cascade='all, delete-orphan' doesn't do exactly what I want; instead of deleting the group when the group becomes empty, it deletes the group when <em>any</em> member leaves the group.</p> <p>Adding triggers to the database works fine for deleting a group when it becomes empty, except that triggers seem to bypass SQLAlchemy's cascade processing so things associated with the group don't get deleted.</p> <p>What is the best way to delete a group when all of its members leave and have this deletion cascade to related entities.</p> <p>I understand that I could do this manually by finding every place in my code where a user can leave a group and then doing the same thing as the trigger however, I'm afraid that I would miss places in the code (and I'm lazy).</p>
8
2009-04-11T19:07:17Z
770,287
<p>I think you want <code>cascade='save, update, merge, expunge, refresh, delete-orphan'</code>. This will prevent the "delete" cascade (which you get from "all") but maintain the "delete-orphan", which is what you're looking for, I think (delete when there are no more parents).</p>
3
2009-04-20T22:00:12Z
[ "python", "sqlalchemy" ]
SQLAlchemy many-to-many orphan deletion
740,630
<p>I'm trying to use SQLAlchemy to implement a basic users-groups model where users can have multiple groups and groups can have multiple users.</p> <p>When a group becomes empty, I want the group to be deleted, (along with other things associated with the group. Fortunately, SQLAlchemy's cascade works fine with these more simple situations).</p> <p>The problem is that cascade='all, delete-orphan' doesn't do exactly what I want; instead of deleting the group when the group becomes empty, it deletes the group when <em>any</em> member leaves the group.</p> <p>Adding triggers to the database works fine for deleting a group when it becomes empty, except that triggers seem to bypass SQLAlchemy's cascade processing so things associated with the group don't get deleted.</p> <p>What is the best way to delete a group when all of its members leave and have this deletion cascade to related entities.</p> <p>I understand that I could do this manually by finding every place in my code where a user can leave a group and then doing the same thing as the trigger however, I'm afraid that I would miss places in the code (and I'm lazy).</p>
8
2009-04-11T19:07:17Z
776,246
<p>Could you post a sample of your table and mapper set up? It might be easier to spot what is going on.</p> <p>Without seeing the code it is hard to tell, but perhaps there is something wrong with the direction of the relationship?</p>
0
2009-04-22T08:48:37Z
[ "python", "sqlalchemy" ]
SQLAlchemy many-to-many orphan deletion
740,630
<p>I'm trying to use SQLAlchemy to implement a basic users-groups model where users can have multiple groups and groups can have multiple users.</p> <p>When a group becomes empty, I want the group to be deleted, (along with other things associated with the group. Fortunately, SQLAlchemy's cascade works fine with these more simple situations).</p> <p>The problem is that cascade='all, delete-orphan' doesn't do exactly what I want; instead of deleting the group when the group becomes empty, it deletes the group when <em>any</em> member leaves the group.</p> <p>Adding triggers to the database works fine for deleting a group when it becomes empty, except that triggers seem to bypass SQLAlchemy's cascade processing so things associated with the group don't get deleted.</p> <p>What is the best way to delete a group when all of its members leave and have this deletion cascade to related entities.</p> <p>I understand that I could do this manually by finding every place in my code where a user can leave a group and then doing the same thing as the trigger however, I'm afraid that I would miss places in the code (and I'm lazy).</p>
8
2009-04-11T19:07:17Z
803,584
<p>I had the same problem about 3 months ago, i have a Post/Tags relation and wanted to delete unused Tags. I asked on irc and SA's author told me that cascades on many-to-many relations are not supported, which kind of makes sense since there is no "parent" in many-to-many.</p> <p>But extending SA is easy, you can probably use a <a href="http://www.sqlalchemy.org/docs/05/reference/orm/interfaces.html" rel="nofollow">AttributeExtension</a> to check if the group became empty when is removed from a User and delete it from there.</p>
2
2009-04-29T18:15:16Z
[ "python", "sqlalchemy" ]
Dynamic processes in Python
740,717
<p>I have a question concerning Python multiprocessing. I am trying to take a dataset, break into chunks, and pass those chunks to concurrently running processes. I need to transform large tables of data using simple calculations (eg. electrical resistance -> temperature for a thermistor).</p> <p>The code listed below almost works as desired, but it doesn't seem to be spawning any new processes (or if so only one at a time). I am new to Python, so there is probably quite a simple solution to this problem.</p> <p>Thanks in advance!</p> <pre>from multiprocessing import Process class Worker(Process): # example data transform def process(self, x): return (x * 2) / 3 def __init__(self, list): self.data = list self.result = map(self.process, self.data) super(Worker, self).__init__() if __name__ == '__main__': start = datetime.datetime.now() dataset = range(10000) # null dataset processes = 3 for i in range(processes): chunk = int(math.floor(len(dataset) / float(processes))) if i + 1 == processes: remainder = len(dataset) % processes else: remainder = 0 tmp = dataset[i * chunk : (i + 1) * chunk + remainder] exec('worker'+str(i)+' = Worker(tmp)') exec('worker'+str(i)+'.start()') for i in range(processes): exec('worker'+str(i)+'.join()') # just a placeholder to make sure the initial values of the set are as expected exec('print worker'+str(i)+'.result[0]')</pre>
2
2009-04-11T20:15:47Z
740,759
<p>You haven't overridden the <code>run</code> method. There are two ways with processes (or threads) to have it execute code:</p> <ol> <li>Create a process specifying target</li> <li>Subclass the process, overriding the <code>run</code> method.</li> </ol> <p>Overriding <code>__init__</code> just means your process is all dressed up with nowhere to go. It should be used to give it attributes that it needs to perform what it needs to perform, but it shouldn't specify the task to be performed.</p> <p>In your code, all the heavy lifting is done in this line:</p> <pre><code>exec('worker'+str(i)+' = Worker(tmp)') </code></pre> <p>and nothing is done here:</p> <pre><code>exec('worker'+str(i)+'.start()') </code></pre> <p>So checking the results with <code>exec('print worker'+str(i)+'.result[0]')</code> should give you something meaningful, but only because the code you want to be executed <em>has</em> been executed, but on process construction, not on process start.</p> <p>Try this:</p> <pre><code>class Worker(Process): # example data transform def process(self, x): return (x * 2) / 3 def __init__(self, list): self.data = list self.result = [] super(Worker, self).__init__() def run(self): self.result = map(self.process, self.data) </code></pre> <p>EDIT:</p> <p>Okay... so I was just flying based on my threading instincts here, and they were all wrong. What we both didn't understand about processes is that you can't directly share variables. Whatever you pass to a new process to start is read, copied, and gone forever. Unless you use one of the two standard ways to share data: <a href="http://docs.python.org/library/multiprocessing.html#exchanging-objects-between-processes" rel="nofollow">queues and pipes</a>. I've played around a little bit trying to get your code to work, but so far no luck. I think that will put you on the right track.</p>
1
2009-04-11T20:53:34Z
[ "python", "multithreading", "multiprocessing" ]
Dynamic processes in Python
740,717
<p>I have a question concerning Python multiprocessing. I am trying to take a dataset, break into chunks, and pass those chunks to concurrently running processes. I need to transform large tables of data using simple calculations (eg. electrical resistance -> temperature for a thermistor).</p> <p>The code listed below almost works as desired, but it doesn't seem to be spawning any new processes (or if so only one at a time). I am new to Python, so there is probably quite a simple solution to this problem.</p> <p>Thanks in advance!</p> <pre>from multiprocessing import Process class Worker(Process): # example data transform def process(self, x): return (x * 2) / 3 def __init__(self, list): self.data = list self.result = map(self.process, self.data) super(Worker, self).__init__() if __name__ == '__main__': start = datetime.datetime.now() dataset = range(10000) # null dataset processes = 3 for i in range(processes): chunk = int(math.floor(len(dataset) / float(processes))) if i + 1 == processes: remainder = len(dataset) % processes else: remainder = 0 tmp = dataset[i * chunk : (i + 1) * chunk + remainder] exec('worker'+str(i)+' = Worker(tmp)') exec('worker'+str(i)+'.start()') for i in range(processes): exec('worker'+str(i)+'.join()') # just a placeholder to make sure the initial values of the set are as expected exec('print worker'+str(i)+'.result[0]')</pre>
2
2009-04-11T20:15:47Z
743,032
<p>Ok, so it looks like the list was not thread safe, and I have moved to using a Queue (although it appears to be much slower). This code essentially accomplishes what I was trying to do:</p> <pre><code>import math, multiprocessing class Worker(multiprocessing.Process): def process(self, x): for i in range(15): x += (float(i) / 2.6) return x def __init__(self, input, output, chunksize): self.input = input self.output = output self.chunksize = chunksize super(Worker, self).__init__() def run(self): for x in range(self.chunksize): self.output.put(self.process(self.input.get())) if __name__ == '__main__': dataset = range(10) processes = multiprocessing.cpu_count() input = multiprocessing.Queue() output = multiprocessing.Queue() for obj in dataset: input.put(obj) for i in range(processes): chunk = int(math.floor(len(dataset) / float(processes))) if i + 1 == processes: remainder = len(dataset) % processes else: remainder = 0 Worker(input, output, chunk + remainder).start() for i in range(len(dataset)): print output.get() </code></pre>
0
2009-04-13T04:25:52Z
[ "python", "multithreading", "multiprocessing" ]
Dynamic processes in Python
740,717
<p>I have a question concerning Python multiprocessing. I am trying to take a dataset, break into chunks, and pass those chunks to concurrently running processes. I need to transform large tables of data using simple calculations (eg. electrical resistance -> temperature for a thermistor).</p> <p>The code listed below almost works as desired, but it doesn't seem to be spawning any new processes (or if so only one at a time). I am new to Python, so there is probably quite a simple solution to this problem.</p> <p>Thanks in advance!</p> <pre>from multiprocessing import Process class Worker(Process): # example data transform def process(self, x): return (x * 2) / 3 def __init__(self, list): self.data = list self.result = map(self.process, self.data) super(Worker, self).__init__() if __name__ == '__main__': start = datetime.datetime.now() dataset = range(10000) # null dataset processes = 3 for i in range(processes): chunk = int(math.floor(len(dataset) / float(processes))) if i + 1 == processes: remainder = len(dataset) % processes else: remainder = 0 tmp = dataset[i * chunk : (i + 1) * chunk + remainder] exec('worker'+str(i)+' = Worker(tmp)') exec('worker'+str(i)+'.start()') for i in range(processes): exec('worker'+str(i)+'.join()') # just a placeholder to make sure the initial values of the set are as expected exec('print worker'+str(i)+'.result[0]')</pre>
2
2009-04-11T20:15:47Z
743,104
<p>No need to send the number of chunks to each process, just use get_nowait() and handle the eventual Queue.Empty exception. Every process will get different amounts of CPU time and this should keep them all busy.</p> <pre><code>import multiprocessing, Queue class Worker(multiprocessing.Process): def process(self, x): for i in range(15): x += (float(i) / 2.6) return x def __init__(self, input, output): self.input = input self.output = output super(Worker, self).__init__() def run(self): try: while True: self.output.put(self.process(self.input.get_nowait())) except Queue.Empty: pass if name == 'main': dataset = range(10) processes = multiprocessing.cpu_count() input = multiprocessing.Queue() output = multiprocessing.Queue() for obj in dataset: input.put(obj) for i in range(processes): Worker(input, output).start() for i in range(len(dataset)): print output.get() </code></pre>
1
2009-04-13T05:20:54Z
[ "python", "multithreading", "multiprocessing" ]
python write string directly to tarfile
740,820
<p>Is there a way to write a string directly to a tarfile? From <a href="http://docs.python.org/library/tarfile.html">http://docs.python.org/library/tarfile.html</a> it looks like only files already written to the file system can be added.</p>
21
2009-04-11T21:41:08Z
740,839
<p>I would say it's possible, by playing with TarInfo e TarFile.addfile passing a StringIO as a fileobject. </p> <p>Very rough, but works</p> <pre><code>import tarfile import StringIO tar = tarfile.TarFile("test.tar","w") string = StringIO.StringIO() string.write("hello") string.seek(0) info = tarfile.TarInfo(name="foo") info.size=len(string.buf) tar.addfile(tarinfo=info, fileobj=string) tar.close() </code></pre>
24
2009-04-11T21:48:26Z
[ "python", "file", "file-io", "tar" ]
python write string directly to tarfile
740,820
<p>Is there a way to write a string directly to a tarfile? From <a href="http://docs.python.org/library/tarfile.html">http://docs.python.org/library/tarfile.html</a> it looks like only files already written to the file system can be added.</p>
21
2009-04-11T21:41:08Z
740,854
<p>As Stefano pointed out, you can use <code>TarFile.addfile</code> and <code>StringIO</code>.</p> <pre><code>import tarfile, StringIO data = 'hello, world!' tarinfo = tarfile.TarInfo('test.txt') tarinfo.size = len(data) tar = tarfile.open('test.tar', 'a') tar.addfile(tarinfo, StringIO.StringIO(data)) tar.close() </code></pre> <p>You'll probably want to fill other fields of <code>tarinfo</code> (e.g. <code>mtime</code>, <code>uname</code> etc.) as well.</p>
9
2009-04-11T22:02:46Z
[ "python", "file", "file-io", "tar" ]
python write string directly to tarfile
740,820
<p>Is there a way to write a string directly to a tarfile? From <a href="http://docs.python.org/library/tarfile.html">http://docs.python.org/library/tarfile.html</a> it looks like only files already written to the file system can be added.</p>
21
2009-04-11T21:41:08Z
740,856
<p>You have to use TarInfo objects and the addfile method instead of the usual add method:</p> <pre><code>from StringIO import StringIO from tarfile import open, TarInfo s = "Hello World!" ti = TarInfo("test.txt") ti.size = len(s) tf = open("testtar.tar", "w") tf.addfile(ti, StringIO(s)) </code></pre>
1
2009-04-11T22:04:37Z
[ "python", "file", "file-io", "tar" ]
python write string directly to tarfile
740,820
<p>Is there a way to write a string directly to a tarfile? From <a href="http://docs.python.org/library/tarfile.html">http://docs.python.org/library/tarfile.html</a> it looks like only files already written to the file system can be added.</p>
21
2009-04-11T21:41:08Z
18,031,786
<p>In my case I wanted to read from an existing tar file, append some data to the contents, and write it to a new file. Something like:</p> <pre><code>for ti in tar_in: buf_in = tar.extractfile(ti) buf_out = io.BytesIO() size = buf_out.write(buf_in.read()) size += buf_out.write(other data) buf_out.seek(0) ti.size = size tar_out.addfile(ti, fileobj=buf_out) </code></pre> <p>Extra code is needed for handling directories and links.</p>
2
2013-08-03T10:21:11Z
[ "python", "file", "file-io", "tar" ]
python write string directly to tarfile
740,820
<p>Is there a way to write a string directly to a tarfile? From <a href="http://docs.python.org/library/tarfile.html">http://docs.python.org/library/tarfile.html</a> it looks like only files already written to the file system can be added.</p>
21
2009-04-11T21:41:08Z
25,157,700
<p>Just for the record: <br> StringIO objects have a .len property.<br> No need to seek(0) and do len(foo.buf)<br> No need to keep the entire string around to do len() on, or God forbid, do the accounting yourself.</p> <p>( Maybe it did not at the time the OP was written. )</p>
2
2014-08-06T10:12:30Z
[ "python", "file", "file-io", "tar" ]
Python multiprocessing: Pool of custom Processes
740,844
<p>I am subclassing the Process class, into a class I call EdgeRenderer. I want to use <code>multiprocessing.Pool</code>, except instead of regular Processes, I want them to be instances of my EdgeRenderer. Possible? How?</p>
4
2009-04-11T21:53:55Z
741,123
<p>I don't see any hook for it in the API. You might be able to get away with replicating your desired functionality by using <code>initializer</code> and <code>initargs</code> argument. Alternately, you can build the functionality into the callable object that you use for mapping:</p> <pre><code>class EdgeRenderTask(object): def op1(self,*args): ... def op2(self,*args): ... p = Pool(processes = 10) e = EdgeRenderTask() p.apply_async(e.op1,arg_list) p.map(e.op2,arg_list) </code></pre>
2
2009-04-12T01:26:06Z
[ "python", "multiprocessing", "pool" ]
Python multiprocessing: Pool of custom Processes
740,844
<p>I am subclassing the Process class, into a class I call EdgeRenderer. I want to use <code>multiprocessing.Pool</code>, except instead of regular Processes, I want them to be instances of my EdgeRenderer. Possible? How?</p>
4
2009-04-11T21:53:55Z
741,852
<p>From Jesse Noller:</p> <blockquote> <p>It is not currently supported in the API, but would not be a bad addition. I'll look at adding it to python2.7/2.6.3 3.1 this week</p> </blockquote>
2
2009-04-12T14:24:46Z
[ "python", "multiprocessing", "pool" ]
Can InstantDjango be Used Rather than the Normal Installation
740,929
<p>Is it possible to do development just using Instant Django? Do I need to have the normal version working or can I just use this instant version? Has anyone used it?</p>
3
2009-04-11T22:48:33Z
740,950
<p>It is, of course, possible to use InstantDjango for development. InstantDjango uses SQLite3, which is a perfectly reasonable relational database for embedded or light/sometimes-moderate use. The whole purpose of django is that the ORM layer gives you database portability.</p> <p>That said, I would not use InstantDjango for deployment in a halfway-serious web app. SQLite just does not scale anywhere near as far as Apache (etc) with MySQL/Postgres. In some cases, the way that SQLite handles data types (or, rather, glosses over data types) can lead to issues with a django app that is subsequently deployed with MySQL/Postgres... if you develop using SQLite, always test with your actual deployment environment before going live.</p> <p>You've asked a number of questions on SO in the last couple days about deploying Django with one or the other of the major relational database packages (<a href="http://stackoverflow.com/questions/738433/getting-started-with-django-instant-django">http://stackoverflow.com/questions/738433/getting-started-with-django-instant-django</a> ; <a href="http://stackoverflow.com/questions/719431/is-it-me-or-are-rails-and-django-difficult-to-install-on-windows">http://stackoverflow.com/questions/719431/is-it-me-or-are-rails-and-django-difficult-to-install-on-windows</a> ). I suspect the reason you've not had many answers, and therefore feel the need to keep asking the same question with different phrasing, is that we need more specific examples of the errors you're having. </p> <p>Plenty of folks install Django with MySQL, Postgres, and other databases, every day on Windows and *nix systems. If you give us the exact details of which non-SQLite database you're trying to use, the way you've installed it, how your settings for that database are configured in django, and the error messages you're getting, we will have a better shot at helping you. </p> <p>If you're still having trouble based on the answers you've had, perhaps you can turn to a professional system administrator and/or DBA you know to show you the ropes with installing and configuring this kind of software.</p> <p>Until that time, by all means, start developing using InstantDjango and SQLite. It will not have to be thrown away for vastly re-written when you migrate to a different relational database, and will help you make forward-progress with the framework that can only bolster your knowledge for understanding how to deploy it in production.</p>
4
2009-04-11T23:02:47Z
[ "python", "django", "instant" ]
Django: Adding additional properties to Model Class Object
741,270
<p>This is using Google App Engine. I am not sure if this is applicable to just normal Django development or if Google App Engine will play a part. If it does, would you let me know so I can update the description of this problem.</p> <pre><code>class MessageModel(db.Model): to_user_id = db.IntegerProperty() to_user = db.StringProperty(multiline=False) message = db.StringProperty(multiline=False) date_created = db.DateTimeProperty(auto_now_add=True) </code></pre> <p>Now when I do a query a get a list of "MessageModel" and send it to the template.html to bind against, I would like to include a few more properties such as the "since_date_created" to output how long ago since the last output, potentially play around with the message property and add other parameters that will help with the layout such as "highlight" , "background-color" etc...</p> <p>The only way I thought of is to loop through the initial Query Object and create a new list where I would add the property values and then append it back to a list.</p> <pre><code> for msg in messagesSQL: msg.lalaland = "test" msg.since_created_time = 321932 msglist.append(msg) </code></pre> <p>Then instead of passing the template.html messagesSQL, I will now pass it msglist.</p>
1
2009-04-12T04:36:51Z
741,444
<p>You should still be able to send it messagesSQL to the template after you've added elements to it via the for loop. Python allows that sort of thing.</p> <p>Something else that might make sense in some cases would be to give your MessageModel methods. For instance, if you have a </p> <pre><code>def since_date_created(self): '''Compute the time since creation time based on self.date_created.''' </code></pre> <p>Then (assuming you have "messagesSQL" in the template), you can use the function as</p> <pre><code>{% for msg in messagesSQL %} {{ msg.since_date_created }} {% endfor %} </code></pre> <p>Basically, you can call any method in the model as long as you it needs no arguments passed to it.</p>
5
2009-04-12T08:10:08Z
[ "python", "django", "google-app-engine" ]
Django: Adding additional properties to Model Class Object
741,270
<p>This is using Google App Engine. I am not sure if this is applicable to just normal Django development or if Google App Engine will play a part. If it does, would you let me know so I can update the description of this problem.</p> <pre><code>class MessageModel(db.Model): to_user_id = db.IntegerProperty() to_user = db.StringProperty(multiline=False) message = db.StringProperty(multiline=False) date_created = db.DateTimeProperty(auto_now_add=True) </code></pre> <p>Now when I do a query a get a list of "MessageModel" and send it to the template.html to bind against, I would like to include a few more properties such as the "since_date_created" to output how long ago since the last output, potentially play around with the message property and add other parameters that will help with the layout such as "highlight" , "background-color" etc...</p> <p>The only way I thought of is to loop through the initial Query Object and create a new list where I would add the property values and then append it back to a list.</p> <pre><code> for msg in messagesSQL: msg.lalaland = "test" msg.since_created_time = 321932 msglist.append(msg) </code></pre> <p>Then instead of passing the template.html messagesSQL, I will now pass it msglist.</p>
1
2009-04-12T04:36:51Z
741,448
<p>You can obtain that by defining methods in the model like</p> <pre><code>class MessageModel(db.Model): # Definition def since_date_created(self): # ... </code></pre> <p>Now in the template, you can use it like</p> <pre><code>Time since created {{ message.since_date_created }} </code></pre>
4
2009-04-12T08:10:59Z
[ "python", "django", "google-app-engine" ]
How do I tell matplotlib that I am done with a plot?
741,877
<p>The following code plots to two <a href="http://en.wikipedia.org/wiki/PostScript">PostScript</a> (.ps) files, but the second one contains both lines.</p> <pre><code>import matplotlib import matplotlib.pyplot as plt import matplotlib.mlab as mlab plt.subplot(111) x = [1,10] y = [30, 1000] plt.loglog(x, y, basex=10, basey=10, ls="-") plt.savefig("first.ps") plt.subplot(111) x = [10,100] y = [10, 10000] plt.loglog(x, y, basex=10, basey=10, ls="-") plt.savefig("second.ps") </code></pre> <p>How can I tell matplotlib to start afresh for the second plot?</p>
92
2009-04-12T14:40:55Z
741,884
<p>You can use <code>figure</code> to create a new plot, for example, or use <code>close</code> after the first plot.</p>
81
2009-04-12T14:43:47Z
[ "python", "matplotlib", "plot" ]
How do I tell matplotlib that I am done with a plot?
741,877
<p>The following code plots to two <a href="http://en.wikipedia.org/wiki/PostScript">PostScript</a> (.ps) files, but the second one contains both lines.</p> <pre><code>import matplotlib import matplotlib.pyplot as plt import matplotlib.mlab as mlab plt.subplot(111) x = [1,10] y = [30, 1000] plt.loglog(x, y, basex=10, basey=10, ls="-") plt.savefig("first.ps") plt.subplot(111) x = [10,100] y = [10, 10000] plt.loglog(x, y, basex=10, basey=10, ls="-") plt.savefig("second.ps") </code></pre> <p>How can I tell matplotlib to start afresh for the second plot?</p>
92
2009-04-12T14:40:55Z
742,062
<p>There is a clear figure command, and it should do it for you:</p> <pre><code>plt.clf() </code></pre> <p>If you have multiple subplots in the same figure</p> <pre><code>plt.cla() </code></pre> <p>clears the current axes.</p>
109
2009-04-12T17:08:30Z
[ "python", "matplotlib", "plot" ]
How do I tell matplotlib that I am done with a plot?
741,877
<p>The following code plots to two <a href="http://en.wikipedia.org/wiki/PostScript">PostScript</a> (.ps) files, but the second one contains both lines.</p> <pre><code>import matplotlib import matplotlib.pyplot as plt import matplotlib.mlab as mlab plt.subplot(111) x = [1,10] y = [30, 1000] plt.loglog(x, y, basex=10, basey=10, ls="-") plt.savefig("first.ps") plt.subplot(111) x = [10,100] y = [10, 10000] plt.loglog(x, y, basex=10, basey=10, ls="-") plt.savefig("second.ps") </code></pre> <p>How can I tell matplotlib to start afresh for the second plot?</p>
92
2009-04-12T14:40:55Z
742,489
<p>As stated from David Cournapeau, use figure().</p> <pre><code>import matplotlib import matplotlib.pyplot as plt import matplotlib.mlab as mlab plt.figure() x = [1,10] y = [30, 1000] plt.loglog(x, y, basex=10, basey=10, ls="-") plt.savefig("first.ps") plt.figure() x = [10,100] y = [10, 10000] plt.loglog(x, y, basex=10, basey=10, ls="-") plt.savefig("second.ps") </code></pre> <p>Or subplot(121) / subplot(122) for the same plot, different position.</p> <pre><code>import matplotlib import matplotlib.pyplot as plt import matplotlib.mlab as mlab plt.subplot(121) x = [1,10] y = [30, 1000] plt.loglog(x, y, basex=10, basey=10, ls="-") plt.subplot(122) x = [10,100] y = [10, 10000] plt.loglog(x, y, basex=10, basey=10, ls="-") plt.savefig("second.ps") </code></pre>
20
2009-04-12T21:44:36Z
[ "python", "matplotlib", "plot" ]
How do I tell matplotlib that I am done with a plot?
741,877
<p>The following code plots to two <a href="http://en.wikipedia.org/wiki/PostScript">PostScript</a> (.ps) files, but the second one contains both lines.</p> <pre><code>import matplotlib import matplotlib.pyplot as plt import matplotlib.mlab as mlab plt.subplot(111) x = [1,10] y = [30, 1000] plt.loglog(x, y, basex=10, basey=10, ls="-") plt.savefig("first.ps") plt.subplot(111) x = [10,100] y = [10, 10000] plt.loglog(x, y, basex=10, basey=10, ls="-") plt.savefig("second.ps") </code></pre> <p>How can I tell matplotlib to start afresh for the second plot?</p>
92
2009-04-12T14:40:55Z
9,820,820
<p>Just enter <code>plt.hold(False)</code> before the first plt.plot, and you can stick to your original code.</p>
11
2012-03-22T10:52:09Z
[ "python", "matplotlib", "plot" ]
How do I tell matplotlib that I am done with a plot?
741,877
<p>The following code plots to two <a href="http://en.wikipedia.org/wiki/PostScript">PostScript</a> (.ps) files, but the second one contains both lines.</p> <pre><code>import matplotlib import matplotlib.pyplot as plt import matplotlib.mlab as mlab plt.subplot(111) x = [1,10] y = [30, 1000] plt.loglog(x, y, basex=10, basey=10, ls="-") plt.savefig("first.ps") plt.subplot(111) x = [10,100] y = [10, 10000] plt.loglog(x, y, basex=10, basey=10, ls="-") plt.savefig("second.ps") </code></pre> <p>How can I tell matplotlib to start afresh for the second plot?</p>
92
2009-04-12T14:40:55Z
38,976,379
<p>If you're using matplotlib interactively for example in a web application (e.g. ipython) you maybe looking for</p> <pre><code>plt.show() </code></pre> <p>Instead of <code>plt.close()</code> or <code>plt.clf()</code></p>
1
2016-08-16T13:33:22Z
[ "python", "matplotlib", "plot" ]
Programatically determining amount of parameters a function requires - Python
741,950
<p>I was creating a simple command line utility and using a dictionary as a sort of case statement with key words linking to their apropriate function. The functions all have different amount of arguments required so currently to check if the user entered the correct amount of arguments needed for each function I placed the required amount inside the dictionary case statement in the form <code>{Keyword:(FunctionName, AmountofArguments)}</code>.</p> <p>This current setup works perfectly fine however I was just wondering in the interest of self improval if there was a way to determine the required number of arguments in a function and my google attempts have returned so far nothing of value but I see how args and kwargs could screw such a command up because of the limitless amount of arguments they allow.</p> <p>Thanks for any help.</p>
30
2009-04-12T15:43:34Z
741,957
<p><a href="http://docs.python.org/library/inspect.html#inspect.getargspec">inspect.getargspec()</a>:</p> <blockquote> <p>Get the names and default values of a function’s arguments. A tuple of four things is returned: (args, varargs, varkw, defaults). args is a list of the argument names (it may contain nested lists). varargs and varkw are the names of the * and ** arguments or None. defaults is a tuple of default argument values or None if there are no default arguments; if this tuple has n elements, they correspond to the last n elements listed in args.</p> </blockquote>
34
2009-04-12T15:48:52Z
[ "python", "parameters", "function" ]
Programatically determining amount of parameters a function requires - Python
741,950
<p>I was creating a simple command line utility and using a dictionary as a sort of case statement with key words linking to their apropriate function. The functions all have different amount of arguments required so currently to check if the user entered the correct amount of arguments needed for each function I placed the required amount inside the dictionary case statement in the form <code>{Keyword:(FunctionName, AmountofArguments)}</code>.</p> <p>This current setup works perfectly fine however I was just wondering in the interest of self improval if there was a way to determine the required number of arguments in a function and my google attempts have returned so far nothing of value but I see how args and kwargs could screw such a command up because of the limitless amount of arguments they allow.</p> <p>Thanks for any help.</p>
30
2009-04-12T15:43:34Z
741,961
<p>What you want is in general not possible, because of the use of varargs and kwargs, but <code>inspect.getargspec</code> (Python 2.x) and <code>inspect.getfullargspec</code> (Python 3.x) come close.</p> <ul> <li><p>Python 2.x:</p> <pre><code>&gt;&gt;&gt; import inspect &gt;&gt;&gt; def add(a, b=0): ... return a + b ... &gt;&gt;&gt; inspect.getargspec(add) (['a', 'b'], None, None, (0,)) &gt;&gt;&gt; len(inspect.getargspec(add)[0]) 2 </code></pre></li> <li><p>Python 3.x:</p> <pre><code>&gt;&gt;&gt; import inspect &gt;&gt;&gt; def add(a, b=0): ... return a + b ... &gt;&gt;&gt; inspect.getfullargspec(add) FullArgSpec(args=['a', 'b'], varargs=None, varkw=None, defaults=(0,), kwonlyargs=[], kwonlydefaults=None, annotations={}) &gt;&gt;&gt; len(inspect.getfullargspec(add).args) 2 </code></pre></li> </ul>
13
2009-04-12T15:53:40Z
[ "python", "parameters", "function" ]
Programatically determining amount of parameters a function requires - Python
741,950
<p>I was creating a simple command line utility and using a dictionary as a sort of case statement with key words linking to their apropriate function. The functions all have different amount of arguments required so currently to check if the user entered the correct amount of arguments needed for each function I placed the required amount inside the dictionary case statement in the form <code>{Keyword:(FunctionName, AmountofArguments)}</code>.</p> <p>This current setup works perfectly fine however I was just wondering in the interest of self improval if there was a way to determine the required number of arguments in a function and my google attempts have returned so far nothing of value but I see how args and kwargs could screw such a command up because of the limitless amount of arguments they allow.</p> <p>Thanks for any help.</p>
30
2009-04-12T15:43:34Z
742,452
<p>Make each command a class, derived from an abstract base defining the general structure of a command. As much as possible, the definition of command properties should be put into class variables with methods defined in the base class handling that data.</p> <p>Register each of these subclasses with a factory class. This factory class get the argument list an decides which command to execute by instantiating the appropriate command sub class.</p> <p>Argument checking is handled by the command sub classes themselves, using properly defined general methods form the command base class.</p> <p>This way, you never need to repeatedly code the same stuff, and there is really no need to emulate the switch statement. It also makes extending and adding commands very easy, as you can simply add and register a new class. Nothing else to change.</p>
1
2009-04-12T21:20:51Z
[ "python", "parameters", "function" ]
Programatically determining amount of parameters a function requires - Python
741,950
<p>I was creating a simple command line utility and using a dictionary as a sort of case statement with key words linking to their apropriate function. The functions all have different amount of arguments required so currently to check if the user entered the correct amount of arguments needed for each function I placed the required amount inside the dictionary case statement in the form <code>{Keyword:(FunctionName, AmountofArguments)}</code>.</p> <p>This current setup works perfectly fine however I was just wondering in the interest of self improval if there was a way to determine the required number of arguments in a function and my google attempts have returned so far nothing of value but I see how args and kwargs could screw such a command up because of the limitless amount of arguments they allow.</p> <p>Thanks for any help.</p>
30
2009-04-12T15:43:34Z
12,405,945
<p>Excellent question. I just had the problem that I wanted to write a function that takes a callback argument. Depending on the number of arguments of that callback, it needs to be called differently.</p> <p>I started with gimel's answer, then expanded to be able to deal with builtins which don't react well with the <code>inspect</code> module (<code>raise TypeError</code>).</p> <p>So here's code to check if a function expects exactly one argument:</p> <pre><code>def func_has_one_arg_only(func, typical_argument=None, ignore_varargs=False): """True if given func expects only one argument Example (testbench): assert not func_has_one_arg_only(dict.__getitem__), 'builtin 2 args' assert func_has_one_arg_only(lambda k: k), 'lambda 1 arg' assert not func_has_one_arg_only(lambda k,x: k), 'lambda 2 args' assert not func_has_one_arg_only(lambda *a: k), 'lambda *a' assert not func_has_one_arg_only(lambda **a: k), 'lambda **a' assert not func_has_one_arg_only(lambda k,**a: k), 'lambda k,**a' assert not func_has_one_arg_only(lambda k,*a: k), 'lambda k,*a' assert func_has_one_arg_only(lambda k: k, ignore_varargs=True), 'lambda 1 arg' assert not func_has_one_arg_only(lambda k,x: k, ignore_varargs=True), 'lambda 2 args' assert not func_has_one_arg_only(lambda *a: k, ignore_varargs=True), 'lambda *a' assert not func_has_one_arg_only(lambda **a: k, ignore_varargs=True), 'lambda **a' assert func_has_one_arg_only(lambda k,**a: k, ignore_varargs=True), 'lambda k,**a' assert func_has_one_arg_only(lambda k,*a: k, ignore_varargs=True), 'lambda k,*a' """ try: import inspect argspec = inspect.getargspec(func) except TypeError: # built-in c-code (e.g. dict.__getitem__) try: func(typical_argument) except TypeError: return False else: return True else: if not ignore_varargs: if argspec.varargs or argspec.keywords: return False if 1 == len(argspec.args): return True return False raise RuntimeError('This line should not be reached') </code></pre> <p>You can control the behaviour related to varargs arguments <code>*args</code> and <code>**kwargs</code> with the <code>ignore_varargs</code> parameter.</p> <p>The <code>typical_argument</code> parameter is a kludge: If <code>inspect</code> fails to work, e.g. on the aforementioned builtins, then we just try to call the function with one argument and see what happens.</p> <p>The problem with this approach is that there are multiple reasons to <code>raise TypeError</code>: Either the wrong number of arguments is used, or the wrong type of arguments is used. By allowing the user to provide a <code>typical_argument</code> I'm trying to circumvent this issue.</p> <p>This is not nice. But it may help folks having the same question and also running into the fact that <code>inspect</code> cannot inspect C-coded function implementations. Maybe folks have a better suggestion?</p>
0
2012-09-13T12:10:16Z
[ "python", "parameters", "function" ]
Programatically determining amount of parameters a function requires - Python
741,950
<p>I was creating a simple command line utility and using a dictionary as a sort of case statement with key words linking to their apropriate function. The functions all have different amount of arguments required so currently to check if the user entered the correct amount of arguments needed for each function I placed the required amount inside the dictionary case statement in the form <code>{Keyword:(FunctionName, AmountofArguments)}</code>.</p> <p>This current setup works perfectly fine however I was just wondering in the interest of self improval if there was a way to determine the required number of arguments in a function and my google attempts have returned so far nothing of value but I see how args and kwargs could screw such a command up because of the limitless amount of arguments they allow.</p> <p>Thanks for any help.</p>
30
2009-04-12T15:43:34Z
38,776,881
<p>This has already been answered but without the inspect module you can also use <code>someMethod.func_code.co_argcount</code></p>
0
2016-08-04T20:28:28Z
[ "python", "parameters", "function" ]
Python strange behavior in for loop or lists
742,371
<p>I'm currently developing a program in python and I just noticed that something was wrong with the foreach loop in the language, or maybe the list structure. I'll just give a generic example of my problem to simplify, since I get the same erroneous behavior on both my program and my generic example:</p> <pre><code>x = [1,2,2,2,2] for i in x: x.remove(i) print x </code></pre> <p>Well, the problem here is simple, I though that this code was supposed to remove all elements from a list. Well, the problem is that after it's execution, I always get 2 remaining elements in the list.</p> <p>What am I doing wrong? Thanks for all the help in advance.</p> <p>Edit: I don't want to empty a list, this is just an example...</p>
7
2009-04-12T20:30:22Z
742,383
<p>This is a well-documented behaviour in Python, that you aren't supposed to modify the list being iterated through. Try this instead:</p> <pre><code>for i in x[:]: x.remove(i) </code></pre> <p>The <code>[:]</code> returns a "slice" of <code>x</code>, which happens to contain all its elements, and is thus effectively a copy of <code>x</code>.</p>
28
2009-04-12T20:36:58Z
[ "python", "list", "foreach" ]
Python strange behavior in for loop or lists
742,371
<p>I'm currently developing a program in python and I just noticed that something was wrong with the foreach loop in the language, or maybe the list structure. I'll just give a generic example of my problem to simplify, since I get the same erroneous behavior on both my program and my generic example:</p> <pre><code>x = [1,2,2,2,2] for i in x: x.remove(i) print x </code></pre> <p>Well, the problem here is simple, I though that this code was supposed to remove all elements from a list. Well, the problem is that after it's execution, I always get 2 remaining elements in the list.</p> <p>What am I doing wrong? Thanks for all the help in advance.</p> <p>Edit: I don't want to empty a list, this is just an example...</p>
7
2009-04-12T20:30:22Z
742,386
<p>When you delete an element, and the for-loop incs to the next index, you then skip an element.</p> <p>Do it backwards. Or please state your real problem.</p>
10
2009-04-12T20:37:18Z
[ "python", "list", "foreach" ]
Python strange behavior in for loop or lists
742,371
<p>I'm currently developing a program in python and I just noticed that something was wrong with the foreach loop in the language, or maybe the list structure. I'll just give a generic example of my problem to simplify, since I get the same erroneous behavior on both my program and my generic example:</p> <pre><code>x = [1,2,2,2,2] for i in x: x.remove(i) print x </code></pre> <p>Well, the problem here is simple, I though that this code was supposed to remove all elements from a list. Well, the problem is that after it's execution, I always get 2 remaining elements in the list.</p> <p>What am I doing wrong? Thanks for all the help in advance.</p> <p>Edit: I don't want to empty a list, this is just an example...</p>
7
2009-04-12T20:30:22Z
742,388
<p>Why don't you just use:</p> <pre><code>x = [] </code></pre> <p>It's probably because you're changing the same array that you're iterating over.</p> <p>Try Chris-Jester Young's answer if you want to clear the array your way.</p>
3
2009-04-12T20:38:05Z
[ "python", "list", "foreach" ]
Python strange behavior in for loop or lists
742,371
<p>I'm currently developing a program in python and I just noticed that something was wrong with the foreach loop in the language, or maybe the list structure. I'll just give a generic example of my problem to simplify, since I get the same erroneous behavior on both my program and my generic example:</p> <pre><code>x = [1,2,2,2,2] for i in x: x.remove(i) print x </code></pre> <p>Well, the problem here is simple, I though that this code was supposed to remove all elements from a list. Well, the problem is that after it's execution, I always get 2 remaining elements in the list.</p> <p>What am I doing wrong? Thanks for all the help in advance.</p> <p>Edit: I don't want to empty a list, this is just an example...</p>
7
2009-04-12T20:30:22Z
742,906
<p>I think, broadly speaking, that when you write:</p> <pre><code>for x in lst: # loop body goes here </code></pre> <p>under the hood, python is doing something like this:</p> <pre><code>i = 0 while i &lt; len(lst): x = lst[i] # loop body goes here i += 1 </code></pre> <p>If you insert <code>lst.remove(x)</code> for the loop body, perhaps then you'll be able to see why you get the result you do?</p> <p>Essentially, python uses a moving pointer to traverse the list. The pointer starts by pointing at the first element. Then you remove the first element, thus making the <em>second</em> element the new first element. Then the pointer move to the new second – previously third – element. And so on. (it might be clearer if you use [1,2,3,4,5] instead of [1,2,2,2,2] as your sample list)</p>
4
2009-04-13T02:43:03Z
[ "python", "list", "foreach" ]
Python strange behavior in for loop or lists
742,371
<p>I'm currently developing a program in python and I just noticed that something was wrong with the foreach loop in the language, or maybe the list structure. I'll just give a generic example of my problem to simplify, since I get the same erroneous behavior on both my program and my generic example:</p> <pre><code>x = [1,2,2,2,2] for i in x: x.remove(i) print x </code></pre> <p>Well, the problem here is simple, I though that this code was supposed to remove all elements from a list. Well, the problem is that after it's execution, I always get 2 remaining elements in the list.</p> <p>What am I doing wrong? Thanks for all the help in advance.</p> <p>Edit: I don't want to empty a list, this is just an example...</p>
7
2009-04-12T20:30:22Z
1,693,733
<p>I agree with John Fouhy regarding the break condition. Traversing a copy of the list works for the remove() method, as Chris Jester-Young suggested. But if one needs to pop() specific items, then iterating in reverse works, as Erik mentioned, in which case the operation can be done in place. For example:</p> <pre><code>def r_enumerate(iterable): """enumerator for reverse iteration of an iterable""" enum = enumerate(reversed(iterable)) last = len(iterable)-1 return ((last - i, x) for i,x in enum) x = [1,2,3,4,5] y = [] for i,v in r_enumerate(x): if v != 3: y.append(x.pop(i)) print 'i=%d, v=%d, x=%s, y=%s' %(i,v,x,y) </code></pre> <p><br> or with xrange: <br></p> <pre><code>x = [1,2,3,4,5] y = [] for i in xrange(len(x)-1,-1,-1): if x[i] != 3: y.append(x.pop(i)) print 'i=%d, x=%s, y=%s' %(i,x,y) </code></pre>
1
2009-11-07T17:12:18Z
[ "python", "list", "foreach" ]
Python strange behavior in for loop or lists
742,371
<p>I'm currently developing a program in python and I just noticed that something was wrong with the foreach loop in the language, or maybe the list structure. I'll just give a generic example of my problem to simplify, since I get the same erroneous behavior on both my program and my generic example:</p> <pre><code>x = [1,2,2,2,2] for i in x: x.remove(i) print x </code></pre> <p>Well, the problem here is simple, I though that this code was supposed to remove all elements from a list. Well, the problem is that after it's execution, I always get 2 remaining elements in the list.</p> <p>What am I doing wrong? Thanks for all the help in advance.</p> <p>Edit: I don't want to empty a list, this is just an example...</p>
7
2009-04-12T20:30:22Z
38,798,324
<p>I know this is an old post with an accepted answer but for those that may still come along...</p> <p>A few previous answers have indicated it's a bad idea to change an iterable during iteration. But as a way to highlight what is happening...</p> <pre><code>&gt;&gt;&gt; x=[1,2,3,4,5] &gt;&gt;&gt; for i in x: ... print i, x.index(i) ... x.remove(i) ... print x ... 1 0 [2, 3, 4, 5] 3 1 [2, 4, 5] 5 2 [2, 4] </code></pre> <p>Hopefully the visual helps clarify.</p>
0
2016-08-05T22:01:31Z
[ "python", "list", "foreach" ]
Encapsulation vs. inheritance, help making a choice
742,376
<p>I need to write handlers for several different case types (in Python). The interface for all this types are the same, but the handling logic is different. </p> <p>One option would be defining a common class that receives the particular handler type as one of the __init__ parameters:</p> <pre><code>class Handler: def __init__ (self, handlerType): self._handlerType = handlerType self._handler = handlerType.handleStuff def handleStuff(self, *args, **kwargs): return self._handler(args, kwargs) # case specific handlers class Handler_Case1: def handleStuff(self, *args, **kwargs): print 'Handling Case 1' class Handler_Case2: def handleStuff(self, *args, **kwargs): print 'Handling Case 2' if __name__ == '__main__': handlers = [] handlers.append(Handler(Handler_Case1)) handlers.append(Handler(Handler_Case2)) for h in handlers: h.handleStuff() </code></pre> <p>However, this results in a TypeError:</p> <blockquote> <p>TypeError: unbound method handleStuff() must be called with Handler_Case1 instance as first argument (got tuple instance instead)</p> </blockquote> <p>Another option is to mimic abstract function, as shown <a href="http://norvig.com/python-iaq.html" rel="nofollow">here</a>("Q: Can you implement abstract classes in Python in 0 lines of code?"):</p> <pre><code>class Handler: def handleStuff(self, *args, **kwargs): abstract def commonFunction(self): print 'Common function' # case specific handlers class Handler_Case1(Handler): def handleStuff(self, *args, **kwargs): print 'Handling Case 1' class Handler_Case2(Handler): def handleStuff(self, *args, **kwargs): print 'Handling Case 2' if __name__ == '__main__': handlers = [] h1 = (Handler_Case1()) h2 = (Handler_Case2()) handlers.append(h1) handlers.append(h2) for h in handlers: h.handleStuff() print </code></pre> <p>So, actually, I have two questions: </p> <ol> <li>Which of the two approaches is more pythonic? and</li> <li>How to implement the first one?</li> </ol>
1
2009-04-12T20:32:47Z
742,405
<p>I might be missing some subtle intricacy in your question, but given your first example, what precludes you from doing something like this:</p> <pre><code>class HandlerCase1(object): def handle_stuff(self, *args, **kwargs): print "Handling case 1" class HandlerCase2(object): def handle_stuff(self, *args, **kwargs): print "Handling case 2" if __name__ == "__main__": handlers = [] handlers.append(HandlerCase1()) handlers.append(HandlerCase2()) for h in handlers: h.handle_stuff() </code></pre> <p>And if you want the classes to share some common (base) functionality, is there something keeping you from doing this:</p> <pre><code>class Handler(object): def common_function(self): print "Common function" class HandlerCase1(Handler): def handle_stuff(self, *args, **kwargs): print "Handling case 1" class HandlerCase2(Handler): def handle_stuff(self, *args, **kwargs): print "Handling case 2" if __name__ == "__main__": handlers = [] handlers.append(HandlerCase1()) handlers.append(HandlerCase2()) for h in handlers: h.handle_stuff() h.common_function() </code></pre>
4
2009-04-12T20:50:25Z
[ "python", "design-patterns", "inheritance", "abstract-class" ]
Code works in global scope but not local scope?
742,496
<p>This function should be returning 36 but it returns 0. If I run through the logic line by line in interactive mode I get 36.</p> <p>Code</p> <pre><code>from math import * line = ((2, 5), (4, -1)) point = (6, 11) def cross(line, point): #reference: http://www.topcoder.com/tc?module=Static&amp;d1=tutorials&amp;d2=geometry1 ab = ac = [None, None] ab[0] = line[1][0] - line[0][0] ab[1] = line[1][1] - line[0][1] print ab ac[0] = point[0] - line[0][0] ac[1] = point[1] - line[0][1] print ac step1 = ab[0] * ac[1] print step1 step2 = ab[1] * ac[0] print step2 step3 = step1 - step2 print step3 return float(value) cross(line, point) </code></pre> <p>Output</p> <pre><code>[2, -6] # ab [4, 6] #ac 24 #step 1 (Should be 12) 24 #step 2 (Should be -24) 0 #step 3 (Should be 36) </code></pre> <p>According to the interactive mode this should be the result of step1, step2, and step3</p> <pre><code>&gt;&gt;&gt; ab = [2, -6] &gt;&gt;&gt; ac = [4, 6] &gt;&gt;&gt; step1 = ab[0] * ac[1] &gt;&gt;&gt; step1 12 &gt;&gt;&gt; step2 = ab[1] * ac[0] &gt;&gt;&gt; step2 -24 &gt;&gt;&gt; step3 = step1 - step2 &gt;&gt;&gt; step3 36 </code></pre> <p>(It would be great if someone can give this a good title)</p>
0
2009-04-12T21:50:15Z
742,509
<p>You have ab and ac pointing to the same reference. Change this:</p> <pre><code>ab = ac = [None, None] </code></pre> <p>to this:</p> <pre><code>ab = [None, None] ac = [None, None] </code></pre>
5
2009-04-12T21:57:27Z
[ "python" ]
Code works in global scope but not local scope?
742,496
<p>This function should be returning 36 but it returns 0. If I run through the logic line by line in interactive mode I get 36.</p> <p>Code</p> <pre><code>from math import * line = ((2, 5), (4, -1)) point = (6, 11) def cross(line, point): #reference: http://www.topcoder.com/tc?module=Static&amp;d1=tutorials&amp;d2=geometry1 ab = ac = [None, None] ab[0] = line[1][0] - line[0][0] ab[1] = line[1][1] - line[0][1] print ab ac[0] = point[0] - line[0][0] ac[1] = point[1] - line[0][1] print ac step1 = ab[0] * ac[1] print step1 step2 = ab[1] * ac[0] print step2 step3 = step1 - step2 print step3 return float(value) cross(line, point) </code></pre> <p>Output</p> <pre><code>[2, -6] # ab [4, 6] #ac 24 #step 1 (Should be 12) 24 #step 2 (Should be -24) 0 #step 3 (Should be 36) </code></pre> <p>According to the interactive mode this should be the result of step1, step2, and step3</p> <pre><code>&gt;&gt;&gt; ab = [2, -6] &gt;&gt;&gt; ac = [4, 6] &gt;&gt;&gt; step1 = ab[0] * ac[1] &gt;&gt;&gt; step1 12 &gt;&gt;&gt; step2 = ab[1] * ac[0] &gt;&gt;&gt; step2 -24 &gt;&gt;&gt; step3 = step1 - step2 &gt;&gt;&gt; step3 36 </code></pre> <p>(It would be great if someone can give this a good title)</p>
0
2009-04-12T21:50:15Z
742,510
<p>In the line <code>ab = ac = [None, None]</code>, you assign the <strong>same list</strong> to the variables ab and ac. When you change one, you change the other at the same time.</p> <p>The reason it works interactively, is that you don't init the lists in the same way.</p> <p>Swap the first line in your function with this:</p> <pre><code>ab = [None, None] ac = [None, None] </code></pre>
1
2009-04-12T21:58:38Z
[ "python" ]
Get the amplitude at a given time within a sound file?
742,546
<p>I'm working on a project where I need to know the amplitude of sound coming in from a microphone on a computer. </p> <p>I'm currently using Python with the <a href="http://www.speech.kth.se/snack/" rel="nofollow">Snack Sound Toolkit</a> and I can record audio coming in from the microphone, but I need to know how loud that audio is. I could save the recording to a file and use another toolkit to read in the amplitude at given points in time from the audio file, or try and get the amplitude while the audio is coming in (which could be more error prone).</p> <p>Are there any libraries or sample code that can help me out with this? I've been looking and so far the Snack Sound Toolkit seems to be my best hope, yet there doesn't seem to be a way to get direct access to amplitude.</p>
2
2009-04-12T22:36:30Z
742,575
<p>Looking at the Snack Sound Toolkit examples, there seems to be a dbPowerSpectrum function. </p> <p>From the reference:</p> <blockquote> <p>dBPowerSpectrum ( )</p> <p>Computes the log FFT power spectrum of the sound (at the sample number given in the start option) and returns a list of dB values. See the section item for a description of the rest of the options. Optionally an ending point can be given, using the end option. In this case the result is the average of consecutive FFTs in the specified range. Their default spacing is taken from the fftlength but this can be changed using the skip option, which tells how many points to move the FFT window each step. Options:</p> </blockquote> <p>EDIT: I am assuming when you say amplitude, you mean how "loud" the sound appears to a human, and not the time domain voltage(Which would probably be 0 throughout the entire length since the integral of sine waves is going to be 0. eg: 10 * sin(t) is louder than 5 * sin(t), but their average value over time is 0. (You do not want to send non-AC voltages to a speaker anyways)). </p> <p>To get how loud the sound is, you will need to determine the amplitudes of each frequency component. This is done with a Fourier Transform (FFT), which breaks down the sound into it's frequency components. The dbPowerSpectrum function seems to give you a list of the magnitudes (forgive me if this differs from the exact definition of a power spectrum) of each frequency. To get the total volume, you can just sum the entire list (Which will be close, xept it still might be different from percieved loudness since the human ear has a frequency response itself).</p>
3
2009-04-12T22:56:54Z
[ "python", "audio", "input", "microphone", "amplitude" ]
Get the amplitude at a given time within a sound file?
742,546
<p>I'm working on a project where I need to know the amplitude of sound coming in from a microphone on a computer. </p> <p>I'm currently using Python with the <a href="http://www.speech.kth.se/snack/" rel="nofollow">Snack Sound Toolkit</a> and I can record audio coming in from the microphone, but I need to know how loud that audio is. I could save the recording to a file and use another toolkit to read in the amplitude at given points in time from the audio file, or try and get the amplitude while the audio is coming in (which could be more error prone).</p> <p>Are there any libraries or sample code that can help me out with this? I've been looking and so far the Snack Sound Toolkit seems to be my best hope, yet there doesn't seem to be a way to get direct access to amplitude.</p>
2
2009-04-12T22:36:30Z
782,014
<p>I disagree completely with this "answer" from CookieOfFortune.</p> <p>granted, the question is poorly phrased... but this answer is making things much more complex than necessary. I am assuming that by 'amplitude' you mean perceived loudness. as technically each sample in the (PCM) audio stream represents an amplitude of the signal at a given time-slice. to get a loudness representation try a simple RMS calculation:</p> <p><a href="http://en.wikipedia.org/wiki/Root%5Fmean%5Fsquare" rel="nofollow">RMS</a></p> <p>|K&lt;</p>
1
2009-04-23T14:28:38Z
[ "python", "audio", "input", "microphone", "amplitude" ]
Get the amplitude at a given time within a sound file?
742,546
<p>I'm working on a project where I need to know the amplitude of sound coming in from a microphone on a computer. </p> <p>I'm currently using Python with the <a href="http://www.speech.kth.se/snack/" rel="nofollow">Snack Sound Toolkit</a> and I can record audio coming in from the microphone, but I need to know how loud that audio is. I could save the recording to a file and use another toolkit to read in the amplitude at given points in time from the audio file, or try and get the amplitude while the audio is coming in (which could be more error prone).</p> <p>Are there any libraries or sample code that can help me out with this? I've been looking and so far the Snack Sound Toolkit seems to be my best hope, yet there doesn't seem to be a way to get direct access to amplitude.</p>
2
2009-04-12T22:36:30Z
845,613
<p>I'm not sure if this will help, but skimpygimpy provides facilities for parsing WAVE files into python sequences and back -- you could potentially use this to examine the wave form samples directly and do what you like. You will have to read some source, these subcomponents are not documented.</p>
0
2009-05-10T16:30:16Z
[ "python", "audio", "input", "microphone", "amplitude" ]
For each function in class within python
742,708
<p>In python is it possible to run each function inside a class?</p> <p><strong>EDIT:</strong> What i am trying to do is call of the functions inside a class, collect their return variables and work with that.</p>
5
2009-04-13T00:30:07Z
742,723
<p>yes, you can. Quick and dirty: </p> <pre><code>class foo: def one(self): print "here is one" def two(self): print "here is two" def three(self): print "here is three" obj = foo() for entry in dir(obj): print entry, callable(getattr(obj,entry)) if callable(getattr(obj,entry)): getattr(obj,entry)() </code></pre> <p>If you want a more refined concept, check the unittest.py module. There should be code that executes all methods starting with the string "test"</p>
4
2009-04-13T00:41:33Z
[ "python", "reflection", "oop" ]
For each function in class within python
742,708
<p>In python is it possible to run each function inside a class?</p> <p><strong>EDIT:</strong> What i am trying to do is call of the functions inside a class, collect their return variables and work with that.</p>
5
2009-04-13T00:30:07Z
742,724
<p>Depends what you mean by "function". Something like this could work, though:</p> <pre><code>import inspect def methods(c): return (m for m in (getattr(c, d) for d in dir(c)) if inspect.ismethoddescriptor(m) or inspect.ismethod(m)) </code></pre> <p>Then:</p> <pre><code>class C: def f(self): pass &gt;&gt;&gt; list(methods(C)) [&lt;unbound method C.f&gt;] </code></pre>
3
2009-04-13T00:42:26Z
[ "python", "reflection", "oop" ]
For each function in class within python
742,708
<p>In python is it possible to run each function inside a class?</p> <p><strong>EDIT:</strong> What i am trying to do is call of the functions inside a class, collect their return variables and work with that.</p>
5
2009-04-13T00:30:07Z
742,913
<p>Here is one that uses yield to loop through the functions in the class. </p> <pre><code>def get_functions(mod): for entry in dir(mod): obj=getattr(mod,entry); if hasattr(obj, '__call__') and hasattr(obj,'__func__') : yield obj class foo: def one(self): print ("here is two") return 1 def two(self): print ("here is two") return 2 def three(self): print ("here is three") return 3 print(sum([fun() for fun in get_functions(foo())])) </code></pre>
1
2009-04-13T02:49:06Z
[ "python", "reflection", "oop" ]
For each function in class within python
742,708
<p>In python is it possible to run each function inside a class?</p> <p><strong>EDIT:</strong> What i am trying to do is call of the functions inside a class, collect their return variables and work with that.</p>
5
2009-04-13T00:30:07Z
743,528
<p>Since you wrote the class, you already <em>know</em> all the functions.</p> <pre><code>class ThisIsPeculiar( object ): def aFunction( self, arg1 ): pass def anotherFunction( self, thisArg, thatArg ): pass functionsToCall = [ aFunction, anotherFunction ] &gt;&gt;&gt; p= ThisIsPeculiar() &gt;&gt;&gt; p.functionsToCall [&lt;function aFunction at 0x6b830&gt;, &lt;function anotherFunction at 0x6b870&gt;] </code></pre>
1
2009-04-13T10:18:15Z
[ "python", "reflection", "oop" ]
For each function in class within python
742,708
<p>In python is it possible to run each function inside a class?</p> <p><strong>EDIT:</strong> What i am trying to do is call of the functions inside a class, collect their return variables and work with that.</p>
5
2009-04-13T00:30:07Z
743,959
<p>Try using the <a href="http://docs.python.org/library/inspect.html" rel="nofollow">inspect module</a>:</p> <pre><code>import inspect class Spam: def eggs(self): print "eggs" def ducks(self): print "ducks" value = "value" spam = Spam() for name, method in inspect.getmembers(spam, callable): method() </code></pre> <p>Output:</p> <pre><code>ducks eggs </code></pre>
1
2009-04-13T14:02:09Z
[ "python", "reflection", "oop" ]
For each function in class within python
742,708
<p>In python is it possible to run each function inside a class?</p> <p><strong>EDIT:</strong> What i am trying to do is call of the functions inside a class, collect their return variables and work with that.</p>
5
2009-04-13T00:30:07Z
747,958
<p>The <a href="http://docs.python.org/library/functions.html#dir" rel="nofollow"><code>dir</code> builtin</a> will list all attributes of an object, for example:</p> <pre><code>&gt;&gt;&gt; class MyClass: ... def one(self): ... print "one" ... def two(self): ... print "two" ... def three(self): ... print "three" ... &gt;&gt;&gt; dir(MyClass) ['__doc__', '__module__', 'one', 'three', 'two'] </code></pre> <p>It also works on an initialised class..</p> <pre><code>&gt;&gt;&gt; c = MyClass() &gt;&gt;&gt; dir(c) ['__doc__', '__module__', 'one', 'three', 'two'] </code></pre> <p>Methods are just attributes which happen to be callable (via <code>c.attribute()</code> ) - we can use the <code>getattr</code> function to reference that method via a variable..</p> <pre><code>&gt;&gt;&gt; myfunc = getattr(c, 'one') &gt;&gt;&gt; myfunc &lt;bound method MyClass.one of &lt;__main__.MyClass instance at 0x7b0d0&gt;&gt; </code></pre> <p>Then we can simply call that variable..</p> <pre><code>&gt;&gt;&gt; myfunc() one # the output from the c.one() method </code></pre> <p>Since some attributes are not functions (in the above example, <code>__doc__</code> and <code>__module__</code>). We can us the <a href="http://docs.python.org/library/functions.html#callable" rel="nofollow">callable builtin</a> to check if it's a callable method (a function):</p> <pre><code>&gt;&gt;&gt; callable(c.three) True &gt;&gt;&gt; callable(c.__doc__) False </code></pre> <p>So to combine all that into a loop:</p> <pre><code>&gt;&gt;&gt; for cur_method_name in dir(c): ... the_attr = getattr(c, cur_method_name) ... if callable(the_attr): ... the_attr() ... one three two </code></pre> <p>Remember this will call methods like <code>__init__</code> again, which probably isn't desired. You might want to skip any <code>cur_method_name</code> which start with an underscore</p>
3
2009-04-14T14:46:40Z
[ "python", "reflection", "oop" ]
Discrete Event Queuing Simulation
742,776
<p>I'm stuck trying to implement a single server queue. I've adapted some <a href="http://pastebin.com/m17c230e6" rel="nofollow">pseudocode</a> from Norm Matloff's Simpy tutorial to Python and the code is <a href="http://pastebin.com/m566e1c12" rel="nofollow">here</a>. Now I am struggling to find some way to calculate the mean waiting time of a job/customer. </p> <p>At this point my brain has tied itself into a knot! Any pointers, ideas, tips or pseudocode would be appreciated.</p>
2
2009-04-13T01:18:54Z
742,825
<p>You should know when each customer arrived in the queue. When they arrive at the server you should add one to the number of customers served as well as accumulate the amount of time he waited. At the end of the simulation you simply divide the accumulated time by the number of customers and you have a mean wait time for the job/customer.</p> <p>The core problem is in accounting for different events and updating statistics based on those events.</p> <p>Your simulation should initialize all of the structures of your simulation into a reasonable state:</p> <ul> <li>Initialize the queue of customers to no one in it</li> <li>Initialize any count of served customers to 0</li> <li>Initialize any accumulated wait times to 0</li> <li>Initialize the current system time to 0</li> <li>Etc.</li> </ul> <p>Once all the system has been initailized you create an event that a cusotmer arrives. This will normally be determined by some given distribution. Generating system events will need to update the statistics of the system. You have a choice at this point of generating all of the job/customers arrival times. The service time of each customer is also something that you will generate from a given distribution.</p> <p>You must then handle each event and update the statistics accordingly. For example when the first customer arrives the queue has been empty from the time the simulation started to the current time. The average number of customers in the queue is likely a parameter of interest. You should accumulate the 0 * elapsed seconds into an accumulator. Once the customer arrives at the empty queue you should generate the service time. Either the next customer will arrive before or after the given job finishes. If the next cusomter arrives before the previous one has been serviced then you add him into the queue (accumulating the fact no one has been waiting). Depending on what event occurs next you must accumulate the statistics that occur in that time interval. The idle time of the server is also a parameter of interest in such simulations. </p> <p>To make things more clear consider the fact there are 18 people in line and the server has completed a job for the first customer. The interval of between the arrival of the 18th customer and the time the first persons job is complete is a weighted average to be added to an accumulator. There have been 18 people in line for 4 seconds for example. </p> <p>The server has not been idle so you should take an entry off the queue and start processing the next job. The job will take some amount of time usually defined from some distribution. If the next customer arrives before the current job is finished the fact 17 people were in line would be added to your weighted value.</p> <p>Again at the fundamental level you are accumulating statistics between relevant events in your system:</p> <pre><code>while (current_time &lt; total_simulation_time) handle_next_event generate_subsequent_events accumulate_statistics update_current_time endwhile Display "Average wait time: " accumulated_wait_time / number_of_customers_served </code></pre> <p>Hope that helps it seems a bit longwinded.</p>
5
2009-04-13T01:47:21Z
[ "python", "queue" ]
Immutability and thread safety in Python
742,882
<p>I'm cleaning some of the Python code I wrote when I was...not as knowledgeable. Primarily I am killing some of the complexity that stemmed from an incomplete understanding of threading in Python. I need to make a list of items thread-safe, and I'd like to do it via immutable lists, instead of the usual locking approach. I know that immutable objects are very special with regard to threading because all the thread-safety issues surrounding incomplete state changes simply disappear.</p> <p>So, I ask: is the following code thread-safe?</p> <pre><code>class ImmutableList(object): def __init__(self): self._list = () def __iter__(self): return self._list.__iter__() def append(self, x): self._list = self._list + tuple([x]) </code></pre> <p>I think it is, because a new list is constructed each time. If the list is updated while another thread is iterating through it, the old list will continue to be used for the remainder of the iteration. This is fine by me, but may not be for everyone.</p> <p>Also, is this a good idea? I only want to apply this to a few situations where the list size is small, and the lists aren't changed much (event listeners spring to mind).</p>
4
2009-04-13T02:25:58Z
742,899
<p>First of all, appending to a list is already thread-safe in the CPython reference implementation of the Python programming language. In other words, while the language specification doesn't require that the list class be thread-safe, it is anyway. So unless you're using Jython or IronPython or some other Python implementation like that, then you're fine.</p> <p>Second, you'd also need to overload the other list operations, such as <code>__setitem__</code> and <code>__setslice__</code>, etc. I'm assuming that your implementation handles this.</p> <p>Finally, the answer to your question is no: your code isn't thread safe. Consider the following situation:</p> <ul> <li>Your list contains (5, 6)</li> <li>Thread 1 tries to append 7, and Thread 2 tries to append 8</li> <li>Thread 1 constructs another tuple (5, 6, 7) and before that can be assigned to _list, there's a context switch</li> <li>Thread 2 performs its assignment, so the list is now (5, 6, 8)</li> <li>Thread 1 gets control of the CPU back and assigns to _list, overwriting the previous append. The list is now (5, 6, 7) and the 8 has been lost.</li> </ul> <p>The moral of this story is that you should use locking and avoid cleverness.</p>
15
2009-04-13T02:35:47Z
[ "python", "multithreading", "immutability" ]
Immutability and thread safety in Python
742,882
<p>I'm cleaning some of the Python code I wrote when I was...not as knowledgeable. Primarily I am killing some of the complexity that stemmed from an incomplete understanding of threading in Python. I need to make a list of items thread-safe, and I'd like to do it via immutable lists, instead of the usual locking approach. I know that immutable objects are very special with regard to threading because all the thread-safety issues surrounding incomplete state changes simply disappear.</p> <p>So, I ask: is the following code thread-safe?</p> <pre><code>class ImmutableList(object): def __init__(self): self._list = () def __iter__(self): return self._list.__iter__() def append(self, x): self._list = self._list + tuple([x]) </code></pre> <p>I think it is, because a new list is constructed each time. If the list is updated while another thread is iterating through it, the old list will continue to be used for the remainder of the iteration. This is fine by me, but may not be for everyone.</p> <p>Also, is this a good idea? I only want to apply this to a few situations where the list size is small, and the lists aren't changed much (event listeners spring to mind).</p>
4
2009-04-13T02:25:58Z
742,923
<p>A true immutable list implementation will not allow the underlying list structure to change, like you are here. As @[Eli Courtwright] pointed out, your implementation is not thread safe. That is because it is not really immutable. To make an immutable implementation, any methods that would have changed the list, would instead return a new list reflecting the desired change.</p> <p>With respect to your code example, this would require you to do something like this:</p> <pre><code>class ImmutableList(object): def __init__(self): self._list = () def __iter__(self): return self._list.__iter__() def append(self, x): return self._list + tuple([x]) </code></pre>
4
2009-04-13T02:57:27Z
[ "python", "multithreading", "immutability" ]
Django RSS Feed Wrong Domain
742,974
<p>I have an RSS feed that I'm setting up on my new site using Django. Currently I have an RSS feed being served per user, rather than just one big nasty, global RSS feed. The only problem is that the links that are returned by the RSS feed have the completely wrong domain name in the links. The end path is perfectly correct, and the get_absolute_url method seems to work everything else in my applications, just not here. You would think I'd be getting the default "www.example.com/item/item_id", but instead I get another domain that's hosted on this server. At first I was thinking it was just pulling the hostname of the server, but it's not. It's also not pulling what the SITE_ID is set to either. Django docs say that the feeds will pull the domain from the SITE_ID setting, but it's just not. I've grepped my entire application for the domain it's pulling, and found absolutely nothing. </p> <p>I'm sure I'm missing something simple, but for the life of me I can't deduce it. The domain it's building the URLs with simply doesn't exist anywhere in the application's code or database. So where on Earth is it coming up with the domain? </p> <p>UPDATE:</p> <p>ServerName in Apache was set to the domain that I was seeing being used by the RSS Feeds to build the URLs. I changed that, and restarted Apached, wrong domain still in use. Any other ideas on how to force Django to use the right domain?</p>
3
2009-04-13T03:36:50Z
744,191
<p>May be it's coming from environment variables? Try:</p> <pre><code>export | grep your.mistery.domain </code></pre> <p>see if that comes up with anything, do that as the same user under which you are running your Django apps.</p> <p>You know you can always implement your item_link() method which would return the URL that you want, see documentation <a href="http://docs.djangoproject.com/en/dev/ref/contrib/syndication/?from=olddocs#feed-classes" rel="nofollow">here</a></p>
3
2009-04-13T15:08:41Z
[ "python", "django", "rss" ]
Trying to embed python into tinycc, says python symbols are undefined
743,044
<p>I've literally spent the past half hour searching for the solution to this, and everything involves GCC. What I do here works absolutely fine with GCC, however I'm using TinyCC, and this is where I'm getting confused. First the code:</p> <pre><code>#include &lt;Python.h&gt; #include &lt;stdio.h&gt; int main(int argc, char*argv[]) { Py_Initialize(); PyRun_SimpleString("print(\"Hello World!\")"); Py_Finalize(); return 0; } </code></pre> <p>I then call tcc like so:</p> <pre><code>tcc -o tinypyembed.exe tiny.c -IC:\Python26\include -LC:\Python26\libs -lpython26 </code></pre> <p>It then becomes a big fat jerk and spits out </p> <pre><code>tcc: undefined symbol 'Py_Initialize' tcc: undefined symbol 'PyRun_SimpleStringFlags' tcc: undefined symbol 'Py_Finalize' </code></pre> <p>I'm totally at my wits end and really do appreciate it if anyone knows what's up.</p> <p>After asking a friend to try this out I have discovered that it is in fact a windows issue. May this stay here as a warning to anyone else who may try tinycc with python on windows.</p>
1
2009-04-13T04:32:36Z
743,217
<p>Did you use <code>tiny_impdef.exe</code> to create a <code>.def</code> file for the Python DLL?</p>
2
2009-04-13T06:57:54Z
[ "python", "c", "compilation" ]
Trying to embed python into tinycc, says python symbols are undefined
743,044
<p>I've literally spent the past half hour searching for the solution to this, and everything involves GCC. What I do here works absolutely fine with GCC, however I'm using TinyCC, and this is where I'm getting confused. First the code:</p> <pre><code>#include &lt;Python.h&gt; #include &lt;stdio.h&gt; int main(int argc, char*argv[]) { Py_Initialize(); PyRun_SimpleString("print(\"Hello World!\")"); Py_Finalize(); return 0; } </code></pre> <p>I then call tcc like so:</p> <pre><code>tcc -o tinypyembed.exe tiny.c -IC:\Python26\include -LC:\Python26\libs -lpython26 </code></pre> <p>It then becomes a big fat jerk and spits out </p> <pre><code>tcc: undefined symbol 'Py_Initialize' tcc: undefined symbol 'PyRun_SimpleStringFlags' tcc: undefined symbol 'Py_Finalize' </code></pre> <p>I'm totally at my wits end and really do appreciate it if anyone knows what's up.</p> <p>After asking a friend to try this out I have discovered that it is in fact a windows issue. May this stay here as a warning to anyone else who may try tinycc with python on windows.</p>
1
2009-04-13T04:32:36Z
1,459,983
<p>Full solution for Windows:</p> <ol> <li><p>tiny_impdef as per bk1e's advice</p> <p><code>tiny_impdef.exe c:\WINDOWS\system32\python25.dll</code></p></li> <li><p>add python25.def (or python26.def) to compilation list</p> <p><code>tcc tiny.c python25.def -IC:\Python25\include -LC:\Python25\libs -lpython25</code></p> <p>(replace 25 with 26 for Python2.6)</p></li> </ol>
2
2009-09-22T13:04:32Z
[ "python", "c", "compilation" ]
Emulate a do-while loop in Python?
743,164
<p>I need to emulate a do-while loop in a Python program. Unfortunately, the following straightforward code does not work:</p> <pre><code>l = [ 1, 2, 3 ] i = l.__iter__() s = None while True : if s : print s try : s = i.next() except StopIteration : break print "done" </code></pre> <p>Instead of "1,2,3,done", it prints the following output:</p> <pre><code>[stdout:]1 [stdout:]2 [stdout:]3 None['Traceback (most recent call last): ', ' File "test_python.py", line 8, in &lt;module&gt; s = i.next() ', 'StopIteration '] </code></pre> <p>What can I do in order to catch the 'stop iteration' exception and break a while loop properly?</p> <p>An example of why such a thing may be needed is shown below as pseudocode.</p> <p>State machine:</p> <pre><code>s = "" while True : if state is STATE_CODE : if "//" in s : tokens.add( TOKEN_COMMENT, s.split( "//" )[1] ) state = STATE_COMMENT else : tokens.add( TOKEN_CODE, s ) if state is STATE_COMMENT : if "//" in s : tokens.append( TOKEN_COMMENT, s.split( "//" )[1] ) else state = STATE_CODE # Re-evaluate same line continue try : s = i.next() except StopIteration : break </code></pre>
357
2009-04-13T06:18:42Z
743,174
<p>Why don't you just do</p> <pre><code>for s in l : print s print "done" </code></pre> <p>?</p>
3
2009-04-13T06:23:44Z
[ "python", "while-loop", "do-while" ]
Emulate a do-while loop in Python?
743,164
<p>I need to emulate a do-while loop in a Python program. Unfortunately, the following straightforward code does not work:</p> <pre><code>l = [ 1, 2, 3 ] i = l.__iter__() s = None while True : if s : print s try : s = i.next() except StopIteration : break print "done" </code></pre> <p>Instead of "1,2,3,done", it prints the following output:</p> <pre><code>[stdout:]1 [stdout:]2 [stdout:]3 None['Traceback (most recent call last): ', ' File "test_python.py", line 8, in &lt;module&gt; s = i.next() ', 'StopIteration '] </code></pre> <p>What can I do in order to catch the 'stop iteration' exception and break a while loop properly?</p> <p>An example of why such a thing may be needed is shown below as pseudocode.</p> <p>State machine:</p> <pre><code>s = "" while True : if state is STATE_CODE : if "//" in s : tokens.add( TOKEN_COMMENT, s.split( "//" )[1] ) state = STATE_COMMENT else : tokens.add( TOKEN_CODE, s ) if state is STATE_COMMENT : if "//" in s : tokens.append( TOKEN_COMMENT, s.split( "//" )[1] ) else state = STATE_CODE # Re-evaluate same line continue try : s = i.next() except StopIteration : break </code></pre>
357
2009-04-13T06:18:42Z
743,186
<p>I am not sure what you are trying to do. You can implement a do-while loop like this:</p> <pre><code>while True: stuff() if fail_condition: break </code></pre> <p>Or:</p> <pre><code>stuff() while not fail_condition: stuff() </code></pre> <p>What are you doing trying to use a do while loop to print the stuff in the list? Why not just use:</p> <pre><code>for i in l: print i print "done" </code></pre> <p>Update:</p> <p>So do you have a list of lines? And you want to keep iterating through it? How about: </p> <pre><code>for s in l: while True: stuff() # use a "break" instead of s = i.next() </code></pre> <p>Does that seem like something close to what you would want? With your code example, it would be:</p> <pre><code>for s in some_list: while True : if state is STATE_CODE : if "//" in s : tokens.add( TOKEN_COMMENT, s.split( "//" )[1] ) state = STATE_COMMENT else : tokens.add( TOKEN_CODE, s ) if state is STATE_COMMENT : if "//" in s : tokens.append( TOKEN_COMMENT, s.split( "//" )[1] ) break # get next s else state = STATE_CODE # re-evaluate same line # continues automatically </code></pre>
449
2009-04-13T06:28:43Z
[ "python", "while-loop", "do-while" ]
Emulate a do-while loop in Python?
743,164
<p>I need to emulate a do-while loop in a Python program. Unfortunately, the following straightforward code does not work:</p> <pre><code>l = [ 1, 2, 3 ] i = l.__iter__() s = None while True : if s : print s try : s = i.next() except StopIteration : break print "done" </code></pre> <p>Instead of "1,2,3,done", it prints the following output:</p> <pre><code>[stdout:]1 [stdout:]2 [stdout:]3 None['Traceback (most recent call last): ', ' File "test_python.py", line 8, in &lt;module&gt; s = i.next() ', 'StopIteration '] </code></pre> <p>What can I do in order to catch the 'stop iteration' exception and break a while loop properly?</p> <p>An example of why such a thing may be needed is shown below as pseudocode.</p> <p>State machine:</p> <pre><code>s = "" while True : if state is STATE_CODE : if "//" in s : tokens.add( TOKEN_COMMENT, s.split( "//" )[1] ) state = STATE_COMMENT else : tokens.add( TOKEN_CODE, s ) if state is STATE_COMMENT : if "//" in s : tokens.append( TOKEN_COMMENT, s.split( "//" )[1] ) else state = STATE_CODE # Re-evaluate same line continue try : s = i.next() except StopIteration : break </code></pre>
357
2009-04-13T06:18:42Z
743,231
<p>Exception will break the loop, so you might as well handle it outside the loop.</p> <pre><code>try: while True: if s: print s s = i.next() except StopIteration: pass </code></pre> <p>I guess that the problem with your code is that behaviour of <code>break</code> inside <code>except</code> is not defined. Generally <code>break</code> goes only one level up, so e.g. <code>break</code> inside <code>try</code> goes directly to <code>finally</code> (if it exists) an out of the <code>try</code>, but not out of the loop.</p> <p>Related PEP: <a href="http://www.python.org/dev/peps/pep-3136">http://www.python.org/dev/peps/pep-3136</a> <br/> Related question: <a href="http://stackoverflow.com/questions/653509/breaking-out-of-nested-loops">http://stackoverflow.com/questions/653509/breaking-out-of-nested-loops</a></p>
22
2009-04-13T07:06:40Z
[ "python", "while-loop", "do-while" ]
Emulate a do-while loop in Python?
743,164
<p>I need to emulate a do-while loop in a Python program. Unfortunately, the following straightforward code does not work:</p> <pre><code>l = [ 1, 2, 3 ] i = l.__iter__() s = None while True : if s : print s try : s = i.next() except StopIteration : break print "done" </code></pre> <p>Instead of "1,2,3,done", it prints the following output:</p> <pre><code>[stdout:]1 [stdout:]2 [stdout:]3 None['Traceback (most recent call last): ', ' File "test_python.py", line 8, in &lt;module&gt; s = i.next() ', 'StopIteration '] </code></pre> <p>What can I do in order to catch the 'stop iteration' exception and break a while loop properly?</p> <p>An example of why such a thing may be needed is shown below as pseudocode.</p> <p>State machine:</p> <pre><code>s = "" while True : if state is STATE_CODE : if "//" in s : tokens.add( TOKEN_COMMENT, s.split( "//" )[1] ) state = STATE_COMMENT else : tokens.add( TOKEN_CODE, s ) if state is STATE_COMMENT : if "//" in s : tokens.append( TOKEN_COMMENT, s.split( "//" )[1] ) else state = STATE_CODE # Re-evaluate same line continue try : s = i.next() except StopIteration : break </code></pre>
357
2009-04-13T06:18:42Z
743,339
<p>See if this helps :</p> <p>Set a flag inside the exception handler and check it before working on the s.</p> <pre><code>flagBreak = false; while True : if flagBreak : break if s : print s try : s = i.next() except StopIteration : flagBreak = true print "done" </code></pre>
-1
2009-04-13T08:17:55Z
[ "python", "while-loop", "do-while" ]
Emulate a do-while loop in Python?
743,164
<p>I need to emulate a do-while loop in a Python program. Unfortunately, the following straightforward code does not work:</p> <pre><code>l = [ 1, 2, 3 ] i = l.__iter__() s = None while True : if s : print s try : s = i.next() except StopIteration : break print "done" </code></pre> <p>Instead of "1,2,3,done", it prints the following output:</p> <pre><code>[stdout:]1 [stdout:]2 [stdout:]3 None['Traceback (most recent call last): ', ' File "test_python.py", line 8, in &lt;module&gt; s = i.next() ', 'StopIteration '] </code></pre> <p>What can I do in order to catch the 'stop iteration' exception and break a while loop properly?</p> <p>An example of why such a thing may be needed is shown below as pseudocode.</p> <p>State machine:</p> <pre><code>s = "" while True : if state is STATE_CODE : if "//" in s : tokens.add( TOKEN_COMMENT, s.split( "//" )[1] ) state = STATE_COMMENT else : tokens.add( TOKEN_CODE, s ) if state is STATE_COMMENT : if "//" in s : tokens.append( TOKEN_COMMENT, s.split( "//" )[1] ) else state = STATE_CODE # Re-evaluate same line continue try : s = i.next() except StopIteration : break </code></pre>
357
2009-04-13T06:18:42Z
743,944
<pre><code>do { stuff() } while (condition()) </code></pre> <p>-></p> <pre><code>while True: stuff() if not condition(): break </code></pre> <p>You can do a function:</p> <pre><code>def do_while(stuff, condition): while condition(stuff()): pass </code></pre> <p>But 1) It's ugly. 2) Condition should be a function with one parameter, supposed to be filled by stuff (it's the only reason <em>not</em> to use the classic while loop.)</p>
20
2009-04-13T13:57:02Z
[ "python", "while-loop", "do-while" ]
Emulate a do-while loop in Python?
743,164
<p>I need to emulate a do-while loop in a Python program. Unfortunately, the following straightforward code does not work:</p> <pre><code>l = [ 1, 2, 3 ] i = l.__iter__() s = None while True : if s : print s try : s = i.next() except StopIteration : break print "done" </code></pre> <p>Instead of "1,2,3,done", it prints the following output:</p> <pre><code>[stdout:]1 [stdout:]2 [stdout:]3 None['Traceback (most recent call last): ', ' File "test_python.py", line 8, in &lt;module&gt; s = i.next() ', 'StopIteration '] </code></pre> <p>What can I do in order to catch the 'stop iteration' exception and break a while loop properly?</p> <p>An example of why such a thing may be needed is shown below as pseudocode.</p> <p>State machine:</p> <pre><code>s = "" while True : if state is STATE_CODE : if "//" in s : tokens.add( TOKEN_COMMENT, s.split( "//" )[1] ) state = STATE_COMMENT else : tokens.add( TOKEN_CODE, s ) if state is STATE_COMMENT : if "//" in s : tokens.append( TOKEN_COMMENT, s.split( "//" )[1] ) else state = STATE_CODE # Re-evaluate same line continue try : s = i.next() except StopIteration : break </code></pre>
357
2009-04-13T06:18:42Z
1,662,604
<p>Here is a crazier solution of a different pattern -- using coroutines. The code is still very similar, but with one important difference; there are no exit conditions at all! The coroutine (chain of coroutines really) just stops when you stop feeding it with data.</p> <pre><code>def coroutine(func): """Coroutine decorator Coroutines must be started, advanced to their first "yield" point, and this decorator does this automatically. """ def startcr(*ar, **kw): cr = func(*ar, **kw) cr.next() return cr return startcr @coroutine def collector(storage): """Act as "sink" and collect all sent in @storage""" while True: storage.append((yield)) @coroutine def state_machine(sink): """ .send() new parts to be tokenized by the state machine, tokens are passed on to @sink """ s = "" state = STATE_CODE while True: if state is STATE_CODE : if "//" in s : sink.send((TOKEN_COMMENT, s.split( "//" )[1] )) state = STATE_COMMENT else : sink.send(( TOKEN_CODE, s )) if state is STATE_COMMENT : if "//" in s : sink.send(( TOKEN_COMMENT, s.split( "//" )[1] )) else state = STATE_CODE # re-evaluate same line continue s = (yield) tokens = [] sm = state_machine(collector(tokens)) for piece in i: sm.send(piece) </code></pre> <p>The code above collects all tokens as tuples in <code>tokens</code> and I assume there is no difference between <code>.append()</code> and <code>.add()</code> in the original code.</p>
13
2009-11-02T17:32:02Z
[ "python", "while-loop", "do-while" ]
Emulate a do-while loop in Python?
743,164
<p>I need to emulate a do-while loop in a Python program. Unfortunately, the following straightforward code does not work:</p> <pre><code>l = [ 1, 2, 3 ] i = l.__iter__() s = None while True : if s : print s try : s = i.next() except StopIteration : break print "done" </code></pre> <p>Instead of "1,2,3,done", it prints the following output:</p> <pre><code>[stdout:]1 [stdout:]2 [stdout:]3 None['Traceback (most recent call last): ', ' File "test_python.py", line 8, in &lt;module&gt; s = i.next() ', 'StopIteration '] </code></pre> <p>What can I do in order to catch the 'stop iteration' exception and break a while loop properly?</p> <p>An example of why such a thing may be needed is shown below as pseudocode.</p> <p>State machine:</p> <pre><code>s = "" while True : if state is STATE_CODE : if "//" in s : tokens.add( TOKEN_COMMENT, s.split( "//" )[1] ) state = STATE_COMMENT else : tokens.add( TOKEN_CODE, s ) if state is STATE_COMMENT : if "//" in s : tokens.append( TOKEN_COMMENT, s.split( "//" )[1] ) else state = STATE_CODE # Re-evaluate same line continue try : s = i.next() except StopIteration : break </code></pre>
357
2009-04-13T06:18:42Z
2,440,643
<p>Here's a very simple way to emulate a do-while loop:</p> <pre><code>condition = True while condition: # loop body here condition = test_loop_condition() # end of loop </code></pre> <p>The key features of a do-while loop are that the loop body always executes at least once, and that the condition is evaluated at the bottom of the loop body. The control structure show here accomplishes both of these with no need for exceptions or break statements. It does introduce one extra Boolean variable.</p>
152
2010-03-14T00:09:54Z
[ "python", "while-loop", "do-while" ]
Emulate a do-while loop in Python?
743,164
<p>I need to emulate a do-while loop in a Python program. Unfortunately, the following straightforward code does not work:</p> <pre><code>l = [ 1, 2, 3 ] i = l.__iter__() s = None while True : if s : print s try : s = i.next() except StopIteration : break print "done" </code></pre> <p>Instead of "1,2,3,done", it prints the following output:</p> <pre><code>[stdout:]1 [stdout:]2 [stdout:]3 None['Traceback (most recent call last): ', ' File "test_python.py", line 8, in &lt;module&gt; s = i.next() ', 'StopIteration '] </code></pre> <p>What can I do in order to catch the 'stop iteration' exception and break a while loop properly?</p> <p>An example of why such a thing may be needed is shown below as pseudocode.</p> <p>State machine:</p> <pre><code>s = "" while True : if state is STATE_CODE : if "//" in s : tokens.add( TOKEN_COMMENT, s.split( "//" )[1] ) state = STATE_COMMENT else : tokens.add( TOKEN_CODE, s ) if state is STATE_COMMENT : if "//" in s : tokens.append( TOKEN_COMMENT, s.split( "//" )[1] ) else state = STATE_CODE # Re-evaluate same line continue try : s = i.next() except StopIteration : break </code></pre>
357
2009-04-13T06:18:42Z
4,309,796
<pre><code>while condition is True: stuff() else: stuff() </code></pre>
5
2010-11-30T01:38:03Z
[ "python", "while-loop", "do-while" ]
Emulate a do-while loop in Python?
743,164
<p>I need to emulate a do-while loop in a Python program. Unfortunately, the following straightforward code does not work:</p> <pre><code>l = [ 1, 2, 3 ] i = l.__iter__() s = None while True : if s : print s try : s = i.next() except StopIteration : break print "done" </code></pre> <p>Instead of "1,2,3,done", it prints the following output:</p> <pre><code>[stdout:]1 [stdout:]2 [stdout:]3 None['Traceback (most recent call last): ', ' File "test_python.py", line 8, in &lt;module&gt; s = i.next() ', 'StopIteration '] </code></pre> <p>What can I do in order to catch the 'stop iteration' exception and break a while loop properly?</p> <p>An example of why such a thing may be needed is shown below as pseudocode.</p> <p>State machine:</p> <pre><code>s = "" while True : if state is STATE_CODE : if "//" in s : tokens.add( TOKEN_COMMENT, s.split( "//" )[1] ) state = STATE_COMMENT else : tokens.add( TOKEN_CODE, s ) if state is STATE_COMMENT : if "//" in s : tokens.append( TOKEN_COMMENT, s.split( "//" )[1] ) else state = STATE_CODE # Re-evaluate same line continue try : s = i.next() except StopIteration : break </code></pre>
357
2009-04-13T06:18:42Z
5,957,047
<p>for a do - while loop containing try statements</p> <pre><code>loop = True while loop: generic_stuff() try: questionable_stuff() # to break from successful completion # loop = False except: optional_stuff() # to break from unsuccessful completion - # the case referenced in the OP's question loop = False finally: more_generic_stuff() </code></pre> <p>alternatively, when there's no need for the 'finally' clause</p> <pre><code>while True: generic_stuff() try: questionable_stuff() # to break from successful completion # break except: optional_stuff() # to break from unsuccessful completion - # the case referenced in the OP's question break </code></pre>
8
2011-05-10T22:03:06Z
[ "python", "while-loop", "do-while" ]
Emulate a do-while loop in Python?
743,164
<p>I need to emulate a do-while loop in a Python program. Unfortunately, the following straightforward code does not work:</p> <pre><code>l = [ 1, 2, 3 ] i = l.__iter__() s = None while True : if s : print s try : s = i.next() except StopIteration : break print "done" </code></pre> <p>Instead of "1,2,3,done", it prints the following output:</p> <pre><code>[stdout:]1 [stdout:]2 [stdout:]3 None['Traceback (most recent call last): ', ' File "test_python.py", line 8, in &lt;module&gt; s = i.next() ', 'StopIteration '] </code></pre> <p>What can I do in order to catch the 'stop iteration' exception and break a while loop properly?</p> <p>An example of why such a thing may be needed is shown below as pseudocode.</p> <p>State machine:</p> <pre><code>s = "" while True : if state is STATE_CODE : if "//" in s : tokens.add( TOKEN_COMMENT, s.split( "//" )[1] ) state = STATE_COMMENT else : tokens.add( TOKEN_CODE, s ) if state is STATE_COMMENT : if "//" in s : tokens.append( TOKEN_COMMENT, s.split( "//" )[1] ) else state = STATE_CODE # Re-evaluate same line continue try : s = i.next() except StopIteration : break </code></pre>
357
2009-04-13T06:18:42Z
16,136,518
<p>Quick hack:</p> <pre><code>def dowhile(func = None, condition = None): if not func or not condition: return else: func() while condition(): func() </code></pre> <p>Use like so:</p> <pre><code>&gt;&gt;&gt; x = 10 &gt;&gt;&gt; def f(): ... global x ... x = x - 1 &gt;&gt;&gt; def c(): global x return x &gt; 0 &gt;&gt;&gt; dowhile(f, c) &gt;&gt;&gt; print x 0 </code></pre>
4
2013-04-21T21:42:57Z
[ "python", "while-loop", "do-while" ]
Emulate a do-while loop in Python?
743,164
<p>I need to emulate a do-while loop in a Python program. Unfortunately, the following straightforward code does not work:</p> <pre><code>l = [ 1, 2, 3 ] i = l.__iter__() s = None while True : if s : print s try : s = i.next() except StopIteration : break print "done" </code></pre> <p>Instead of "1,2,3,done", it prints the following output:</p> <pre><code>[stdout:]1 [stdout:]2 [stdout:]3 None['Traceback (most recent call last): ', ' File "test_python.py", line 8, in &lt;module&gt; s = i.next() ', 'StopIteration '] </code></pre> <p>What can I do in order to catch the 'stop iteration' exception and break a while loop properly?</p> <p>An example of why such a thing may be needed is shown below as pseudocode.</p> <p>State machine:</p> <pre><code>s = "" while True : if state is STATE_CODE : if "//" in s : tokens.add( TOKEN_COMMENT, s.split( "//" )[1] ) state = STATE_COMMENT else : tokens.add( TOKEN_CODE, s ) if state is STATE_COMMENT : if "//" in s : tokens.append( TOKEN_COMMENT, s.split( "//" )[1] ) else state = STATE_CODE # Re-evaluate same line continue try : s = i.next() except StopIteration : break </code></pre>
357
2009-04-13T06:18:42Z
27,095,765
<p>My code below might be a useful implementation, highlighting the main difference between <a href="/questions/tagged/do-while" class="post-tag" title="show questions tagged &#39;do-while&#39;" rel="tag">do-while</a> vs <a href="/questions/tagged/while" class="post-tag" title="show questions tagged &#39;while&#39;" rel="tag">while</a> as I understand it. </p> <p>So in this one case, you always go through the loop at least once.</p> <pre><code>firstPass = True while firstPass or Condition: firstPass = False do_stuff() </code></pre>
14
2014-11-23T23:37:17Z
[ "python", "while-loop", "do-while" ]
Something wrong with output from list in Python
743,248
<p>I want a Python program to import a list of words from a text file and print out the content of the text file as two lists. The data in the text file is on this form: </p> <pre><code>A Alfa B Betta C Charlie </code></pre> <p>I want a Python program to print out one list with A,B,C and one with Alfa, Betta, Charlie.</p> <p>This is what I've written:</p> <pre><code>english2german = open('english2german.txt', 'r') englist = [] gerlist = [] for i, line in enumerate(english2german): englist[i:], gerlist[i:] = line.split() </code></pre> <p>This is making two lists, but will only print out the first letter in each word. How can I make my code to print out the whole word?</p>
2
2009-04-13T07:16:48Z
743,268
<p>You want something like this:</p> <pre><code>english2german = open("english2german.txt") englist = [] gerlist = [] for line in english2german: (e, g) = line.split() englist.append(e) gerlist.append(g) </code></pre> <p>The problem with your code before is that <code>englist[i:]</code> is actually a <em>slice</em> of a list, not just a single index. A string is also iterable, so you were basically stuffing a single letter into several indices. In other words, something like <code>gerlist[0:] = "alfa"</code> actually results in <code>gerlist = ['a', 'l', 'f', 'a']</code>.</p>
6
2009-04-13T07:30:34Z
[ "python", "list", "text" ]
Something wrong with output from list in Python
743,248
<p>I want a Python program to import a list of words from a text file and print out the content of the text file as two lists. The data in the text file is on this form: </p> <pre><code>A Alfa B Betta C Charlie </code></pre> <p>I want a Python program to print out one list with A,B,C and one with Alfa, Betta, Charlie.</p> <p>This is what I've written:</p> <pre><code>english2german = open('english2german.txt', 'r') englist = [] gerlist = [] for i, line in enumerate(english2german): englist[i:], gerlist[i:] = line.split() </code></pre> <p>This is making two lists, but will only print out the first letter in each word. How can I make my code to print out the whole word?</p>
2
2009-04-13T07:16:48Z
743,274
<p>Like this you mean:</p> <pre><code>english2german = open('k.txt', 'r') englist = [] gerlist = [] for i, line in enumerate(english2german): englist.append(line.split()[0]) gerlist.append(line.split()[1]) print englist print gerlist </code></pre> <p>which generates:</p> <p>['A', 'B', 'C'] ['Alfa', 'Betta', 'Charlie']</p>
1
2009-04-13T07:32:34Z
[ "python", "list", "text" ]
Something wrong with output from list in Python
743,248
<p>I want a Python program to import a list of words from a text file and print out the content of the text file as two lists. The data in the text file is on this form: </p> <pre><code>A Alfa B Betta C Charlie </code></pre> <p>I want a Python program to print out one list with A,B,C and one with Alfa, Betta, Charlie.</p> <p>This is what I've written:</p> <pre><code>english2german = open('english2german.txt', 'r') englist = [] gerlist = [] for i, line in enumerate(english2german): englist[i:], gerlist[i:] = line.split() </code></pre> <p>This is making two lists, but will only print out the first letter in each word. How can I make my code to print out the whole word?</p>
2
2009-04-13T07:16:48Z
743,313
<p>And even shorter than <a href="http://stackoverflow.com/questions/743248/something-wrong-with-output-from-list-in-python/743274#743274">amo-ej1's answer</a>, and likely faster:</p> <pre><code>In [1]: english2german = open('english2german.txt') In [2]: eng, ger = zip(*( line.split() for line in english2german )) In [3]: eng Out[3]: ('A', 'B', 'C') In [4]: ger Out[4]: ('Alfa', 'Betta', 'Charlie') </code></pre> <p>If you're using Python 3.0 or <code>from future_builtins import zip</code>, this is memory-efficient too. Otherwise replace <code>zip</code> with <code>izip</code> from <code>itertools</code> if <code>english2german</code> is very long.</p>
6
2009-04-13T07:58:57Z
[ "python", "list", "text" ]
Something wrong with output from list in Python
743,248
<p>I want a Python program to import a list of words from a text file and print out the content of the text file as two lists. The data in the text file is on this form: </p> <pre><code>A Alfa B Betta C Charlie </code></pre> <p>I want a Python program to print out one list with A,B,C and one with Alfa, Betta, Charlie.</p> <p>This is what I've written:</p> <pre><code>english2german = open('english2german.txt', 'r') englist = [] gerlist = [] for i, line in enumerate(english2german): englist[i:], gerlist[i:] = line.split() </code></pre> <p>This is making two lists, but will only print out the first letter in each word. How can I make my code to print out the whole word?</p>
2
2009-04-13T07:16:48Z
743,378
<p>The solutions already posted are OK if you have no spaces in any of the words (ie each line has a single space). If I understand correctly, you are trying to build a dictionary, so I would suggest you consider the fact that you can also have definitions of multiple word expressions. In that case, you'd better use some other character instead of a space to separate the definition from the word. Something like "|", which is impossible to appear in a word.</p> <p>Then, you do something like this:</p> <pre><code>for line in english2german: (e, g) = line.split("|") englist.append(e) gerlist.append(g) </code></pre>
1
2009-04-13T08:46:23Z
[ "python", "list", "text" ]
Something wrong with output from list in Python
743,248
<p>I want a Python program to import a list of words from a text file and print out the content of the text file as two lists. The data in the text file is on this form: </p> <pre><code>A Alfa B Betta C Charlie </code></pre> <p>I want a Python program to print out one list with A,B,C and one with Alfa, Betta, Charlie.</p> <p>This is what I've written:</p> <pre><code>english2german = open('english2german.txt', 'r') englist = [] gerlist = [] for i, line in enumerate(english2german): englist[i:], gerlist[i:] = line.split() </code></pre> <p>This is making two lists, but will only print out the first letter in each word. How can I make my code to print out the whole word?</p>
2
2009-04-13T07:16:48Z
743,968
<p>just an addition: you're working with files. please close them :) or use the with construct:</p> <pre><code>with open('english2german.txt') as english2german: englist, gerlist = zip(*(line.split() for line in english2german)) </code></pre>
3
2009-04-13T14:04:15Z
[ "python", "list", "text" ]