title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Question about paths in Python | 1,125,399 | <p>let's say i have directory paths looking like this:</p>
<pre><code>this/is/the/basedir/path/a/include
this/is/the/basedir/path/b/include
this/is/the/basedir/path/a
this/is/the/basedir/path/b
</code></pre>
<p>In Python, how can i split these paths up so they will look like this instead:</p>
<pre><code>a/include
b/include
a
b
</code></pre>
<p>If i run os.path.split(path)[1] it will display:</p>
<pre><code>include
include
a
b
</code></pre>
<p>What should i be trying out here, should i be looking at some regex command or can this be done without it? Thanks in advance.</p>
<p>EDIT ALL: I solved it using regular expressions, damn handy tool :)</p>
| 1 | 2009-07-14T13:30:55Z | 1,125,569 | <p>Maybe something like this:</p>
<pre><code>result = []
prefix = os.path.commonprefix(list_of_paths)
for path in list_of_paths:
result.append(os.path.relpath(path, prefix))
</code></pre>
<p>This works only in 2.6. The relapath in 2.5 and before does the work only in case the path is the current working directory.</p>
| 1 | 2009-07-14T13:56:52Z | [
"python",
"operating-system"
] |
Question about paths in Python | 1,125,399 | <p>let's say i have directory paths looking like this:</p>
<pre><code>this/is/the/basedir/path/a/include
this/is/the/basedir/path/b/include
this/is/the/basedir/path/a
this/is/the/basedir/path/b
</code></pre>
<p>In Python, how can i split these paths up so they will look like this instead:</p>
<pre><code>a/include
b/include
a
b
</code></pre>
<p>If i run os.path.split(path)[1] it will display:</p>
<pre><code>include
include
a
b
</code></pre>
<p>What should i be trying out here, should i be looking at some regex command or can this be done without it? Thanks in advance.</p>
<p>EDIT ALL: I solved it using regular expressions, damn handy tool :)</p>
| 1 | 2009-07-14T13:30:55Z | 1,125,837 | <p>While the criterion is not 100% clear, it seems from the OP's comment that the key issue is specifically whether the path's last component ends in "include". If that is the case, and to avoid going wrong when the last component is e.g. "dontinclude" (as another answer does by trying string matching instead of path matching), I suggest:</p>
<pre><code>def lastpart(apath):
pieces = os.path.split(apath)
final = -1
if pieces[-1] == 'include':
final = -2
return '/'.join(pieces[final:])
</code></pre>
| 0 | 2009-07-14T14:36:01Z | [
"python",
"operating-system"
] |
Django persistent database connection | 1,125,504 | <p>I'm using django with apache and mod_wsgi and PostgreSQL (all on same host), and I need to handle a lot of simple dynamic page requests (hundreds per second). I faced with problem that the bottleneck is that a django don't have persistent database connection and reconnects on each requests (that takes near 5ms).
While doing a benchmark I got that with persistent connection I can handle near 500 r/s while without I get only 50 r/s.</p>
<p>Anyone have any advice? How to modify django to use persistent connection? Or speed up connection from python to DB</p>
<p>Thanks in advance.</p>
| 45 | 2009-07-14T13:47:00Z | 1,125,613 | <p>Disclaimer: I have not tried this.</p>
<p>I believe you need to implement a custom database back end. There are a few examples on the web that shows how to implement a database back end with connection pooling.</p>
<p>Using a connection pool would probably be a good solution for you case, as the network connections are kept open when connections are returned to the pool.</p>
<ul>
<li><a href="http://jasonrubenstein.blogspot.com/2008/02/quick-and-dirty-database-pooling-in.html" rel="nofollow">This post</a> accomplishes this by patching Django (one of the comments points out that it is better to implement a custom back end outside of the core django code)</li>
<li><a href="http://node.to/wordpress/2008/09/30/another-database-connection-pool-solution-for-django-mysql/" rel="nofollow">This post</a> is an implementation of a custom db back end</li>
</ul>
<p>Both posts use MySQL - perhaps you are able to use similar techniques with Postgresql.</p>
<p><strong>Edit:</strong></p>
<ul>
<li>The Django Book mentions Postgresql connection pooling, using <a href="http://pgpool.projects.postgresql.org/" rel="nofollow">pgpool</a> (<a href="http://pgpool.projects.postgresql.org/pgpool-II/doc/tutorial-en.html" rel="nofollow">tutorial</a>).</li>
<li>Someone posted <a href="http://www.nabble.com/-PATCH--Proposal:-connection-pooling-with-psycopg2-td20532406.html" rel="nofollow">a patch</a> for the psycopg2 backend that implements connection pooling. I suggest creating a copy of the existing back end in your own project and patching that one.</li>
</ul>
| 3 | 2009-07-14T14:05:49Z | [
"python",
"database",
"django",
"mod-wsgi",
"persistent"
] |
Django persistent database connection | 1,125,504 | <p>I'm using django with apache and mod_wsgi and PostgreSQL (all on same host), and I need to handle a lot of simple dynamic page requests (hundreds per second). I faced with problem that the bottleneck is that a django don't have persistent database connection and reconnects on each requests (that takes near 5ms).
While doing a benchmark I got that with persistent connection I can handle near 500 r/s while without I get only 50 r/s.</p>
<p>Anyone have any advice? How to modify django to use persistent connection? Or speed up connection from python to DB</p>
<p>Thanks in advance.</p>
| 45 | 2009-07-14T13:47:00Z | 1,175,140 | <p>In Django trunk, edit <code>django/db/__init__.py</code> and comment out the line:</p>
<pre><code>signals.request_finished.connect(close_connection)
</code></pre>
<p>This signal handler causes it to disconnect from the database after every request. I don't know what all of the side-effects of doing this will be, but it doesn't make any sense to start a new connection after every request; it destroys performance, as you've noticed.</p>
<p>I'm using this now, but I havn't done a full set of tests to see if anything breaks.</p>
<p>I don't know why everyone thinks this needs a new backend or a special connection pooler or other complex solutions. This seems very simple, though I don't doubt there are some obscure gotchas that made them do this in the first place--which should be dealt with more sensibly; 5ms overhead for every request is quite a lot for a high-performance service, as you've noticed. (It takes me <em>150ms</em>--I havn't figured out why yet.)</p>
<p>Edit: another necessary change is in django/middleware/transaction.py; remove the two transaction.is_dirty() tests and always call commit() or rollback(). Otherwise, it won't commit a transaction if it only read from the database, which will leave locks open that should be closed.</p>
| 17 | 2009-07-23T23:55:40Z | [
"python",
"database",
"django",
"mod-wsgi",
"persistent"
] |
Django persistent database connection | 1,125,504 | <p>I'm using django with apache and mod_wsgi and PostgreSQL (all on same host), and I need to handle a lot of simple dynamic page requests (hundreds per second). I faced with problem that the bottleneck is that a django don't have persistent database connection and reconnects on each requests (that takes near 5ms).
While doing a benchmark I got that with persistent connection I can handle near 500 r/s while without I get only 50 r/s.</p>
<p>Anyone have any advice? How to modify django to use persistent connection? Or speed up connection from python to DB</p>
<p>Thanks in advance.</p>
| 45 | 2009-07-14T13:47:00Z | 1,351,213 | <p>I made some small custom psycopg2 backend that implements persistent connection using global variable.
With this I was able to improve the amout of requests per second from 350 to 1600 (on very simple page with few selects)
Just save it in the file called <code>base.py</code> in any directory (e.g. postgresql_psycopg2_persistent) and set in settings</p>
<p>DATABASE_ENGINE to projectname.postgresql_psycopg2_persistent</p>
<p><strong>NOTE!!! the code is not threadsafe - you can't use it with python threads because of unexpectable results, in case of mod_wsgi please use prefork daemon mode with threads=1</strong></p>
<hr>
<pre><code># Custom DB backend postgresql_psycopg2 based
# implements persistent database connection using global variable
from django.db.backends.postgresql_psycopg2.base import DatabaseError, DatabaseWrapper as BaseDatabaseWrapper, \
IntegrityError
from psycopg2 import OperationalError
connection = None
class DatabaseWrapper(BaseDatabaseWrapper):
def _cursor(self, *args, **kwargs):
global connection
if connection is not None and self.connection is None:
try: # Check if connection is alive
connection.cursor().execute('SELECT 1')
except OperationalError: # The connection is not working, need reconnect
connection = None
else:
self.connection = connection
cursor = super(DatabaseWrapper, self)._cursor(*args, **kwargs)
if connection is None and self.connection is not None:
connection = self.connection
return cursor
def close(self):
if self.connection is not None:
self.connection.commit()
self.connection = None
</code></pre>
<hr>
<p>Or here is a thread safe one, but python threads don't use multiple cores, so you won't get such performance boost as with previous one. You can use this one with multi process one too.</p>
<pre><code># Custom DB backend postgresql_psycopg2 based
# implements persistent database connection using thread local storage
from threading import local
from django.db.backends.postgresql_psycopg2.base import DatabaseError, \
DatabaseWrapper as BaseDatabaseWrapper, IntegrityError
from psycopg2 import OperationalError
threadlocal = local()
class DatabaseWrapper(BaseDatabaseWrapper):
def _cursor(self, *args, **kwargs):
if hasattr(threadlocal, 'connection') and threadlocal.connection is \
not None and self.connection is None:
try: # Check if connection is alive
threadlocal.connection.cursor().execute('SELECT 1')
except OperationalError: # The connection is not working, need reconnect
threadlocal.connection = None
else:
self.connection = threadlocal.connection
cursor = super(DatabaseWrapper, self)._cursor(*args, **kwargs)
if (not hasattr(threadlocal, 'connection') or threadlocal.connection \
is None) and self.connection is not None:
threadlocal.connection = self.connection
return cursor
def close(self):
if self.connection is not None:
self.connection.commit()
self.connection = None
</code></pre>
| 0 | 2009-08-29T11:32:36Z | [
"python",
"database",
"django",
"mod-wsgi",
"persistent"
] |
Django persistent database connection | 1,125,504 | <p>I'm using django with apache and mod_wsgi and PostgreSQL (all on same host), and I need to handle a lot of simple dynamic page requests (hundreds per second). I faced with problem that the bottleneck is that a django don't have persistent database connection and reconnects on each requests (that takes near 5ms).
While doing a benchmark I got that with persistent connection I can handle near 500 r/s while without I get only 50 r/s.</p>
<p>Anyone have any advice? How to modify django to use persistent connection? Or speed up connection from python to DB</p>
<p>Thanks in advance.</p>
| 45 | 2009-07-14T13:47:00Z | 1,698,102 | <p>Try <a href="http://wiki.postgresql.org/wiki/PgBouncer" rel="nofollow">PgBouncer</a> - a lightweight connection pooler for PostgreSQL.
Features:</p>
<ul>
<li>Several levels of brutality when rotating connections:
<ul>
<li>Session pooling</li>
<li>Transaction pooling</li>
<li>Statement pooling</li>
</ul></li>
<li>Low memory requirements (2k per connection by default).</li>
</ul>
| 19 | 2009-11-08T22:15:33Z | [
"python",
"database",
"django",
"mod-wsgi",
"persistent"
] |
Django persistent database connection | 1,125,504 | <p>I'm using django with apache and mod_wsgi and PostgreSQL (all on same host), and I need to handle a lot of simple dynamic page requests (hundreds per second). I faced with problem that the bottleneck is that a django don't have persistent database connection and reconnects on each requests (that takes near 5ms).
While doing a benchmark I got that with persistent connection I can handle near 500 r/s while without I get only 50 r/s.</p>
<p>Anyone have any advice? How to modify django to use persistent connection? Or speed up connection from python to DB</p>
<p>Thanks in advance.</p>
| 45 | 2009-07-14T13:47:00Z | 6,712,190 | <p>I created a small <a href="http://dumpz.org/67550/">Django patch</a> that implements connection pooling of MySQL and PostgreSQL via sqlalchemy pooling.</p>
<p>This works perfectly on production of <a href="http://grandcapital.net/">http://grandcapital.net/</a> for a long period of time.</p>
<p>The patch was written after googling the topic a bit.</p>
| 13 | 2011-07-15T19:26:17Z | [
"python",
"database",
"django",
"mod-wsgi",
"persistent"
] |
Django persistent database connection | 1,125,504 | <p>I'm using django with apache and mod_wsgi and PostgreSQL (all on same host), and I need to handle a lot of simple dynamic page requests (hundreds per second). I faced with problem that the bottleneck is that a django don't have persistent database connection and reconnects on each requests (that takes near 5ms).
While doing a benchmark I got that with persistent connection I can handle near 500 r/s while without I get only 50 r/s.</p>
<p>Anyone have any advice? How to modify django to use persistent connection? Or speed up connection from python to DB</p>
<p>Thanks in advance.</p>
| 45 | 2009-07-14T13:47:00Z | 19,438,241 | <p>Django <strong>1.6</strong> has added <a href="https://docs.djangoproject.com/en/1.9/ref/databases/#persistent-connections" rel="nofollow">persistent connections support (link to doc for django 1.9)</a>:</p>
<blockquote>
<p>Persistent connections avoid the overhead of re-establishing a
connection to the database in each request. Theyâre controlled by the
CONN_MAX_AGE parameter which defines the maximum lifetime of a
connection. It can be set independently for each database.</p>
</blockquote>
| 17 | 2013-10-17T22:13:17Z | [
"python",
"database",
"django",
"mod-wsgi",
"persistent"
] |
Running Python code from a server? | 1,125,637 | <p><strong>Problem:</strong> to run one.py from a server.</p>
<p><strong>Error</strong></p>
<p>When I try to do it in Mac, I get errors:</p>
<pre><code>$python http://cs.edu.com/u/user/TEST/one.py ~
/Library/Frameworks/Python.framework/Versions/2.5/Resources/Python.app/Contents/MacOS/Python: can't open file 'http://cs.edu.com/u/user/TEST/one.py': [Errno 2] No such file or directory
</code></pre>
<p>one.py is like:</p>
<pre><code>print 1
</code></pre>
<p>When I do it in Ubuntu, I get "file is not found".</p>
<p><strong>Question:</strong> How can I run Python code from a server?</p>
| 0 | 2009-07-14T14:10:25Z | 1,125,645 | <p>So far as I know, the standard Python shell doesn't know how to execute remote scripts. Try using <code>curl</code> or <code>wget</code> to retrieve the script and run it from the local copy.</p>
<pre><code>$ wget http://cs.edu.com/u/user/TEST/one.py
$ python one.py
</code></pre>
<p>UPDATE: Based on the <a href="http://stackoverflow.com/questions/1122609/javascript-for-a-form-on-the-server-side">question</a> referenced in the comment to <a href="http://stackoverflow.com/questions/1125637/running-python-code-from-a-server/1125670#1125670">this answer</a>, you need to execute <code>one.py</code> based on incoming HTTP requests from end users. The simplest solution is probably <a href="http://www.garshol.priv.no/download/text/http-tut.html" rel="nofollow">CGI</a>, but depending on what else you need to do, a more robust solution might involve a <a href="http://wiki.python.org/moin/WebFrameworks" rel="nofollow">framework</a> of some sort. They each have there strengths and weaknesses, so you should probably consider your requirements carefully before jumping in.</p>
| 3 | 2009-07-14T14:11:54Z | [
"python"
] |
Running Python code from a server? | 1,125,637 | <p><strong>Problem:</strong> to run one.py from a server.</p>
<p><strong>Error</strong></p>
<p>When I try to do it in Mac, I get errors:</p>
<pre><code>$python http://cs.edu.com/u/user/TEST/one.py ~
/Library/Frameworks/Python.framework/Versions/2.5/Resources/Python.app/Contents/MacOS/Python: can't open file 'http://cs.edu.com/u/user/TEST/one.py': [Errno 2] No such file or directory
</code></pre>
<p>one.py is like:</p>
<pre><code>print 1
</code></pre>
<p>When I do it in Ubuntu, I get "file is not found".</p>
<p><strong>Question:</strong> How can I run Python code from a server?</p>
| 0 | 2009-07-14T14:10:25Z | 1,125,651 | <pre><code>wget http://cs.edu.com/u/user/TEST/one.py
python one.py
</code></pre>
| 1 | 2009-07-14T14:12:32Z | [
"python"
] |
Running Python code from a server? | 1,125,637 | <p><strong>Problem:</strong> to run one.py from a server.</p>
<p><strong>Error</strong></p>
<p>When I try to do it in Mac, I get errors:</p>
<pre><code>$python http://cs.edu.com/u/user/TEST/one.py ~
/Library/Frameworks/Python.framework/Versions/2.5/Resources/Python.app/Contents/MacOS/Python: can't open file 'http://cs.edu.com/u/user/TEST/one.py': [Errno 2] No such file or directory
</code></pre>
<p>one.py is like:</p>
<pre><code>print 1
</code></pre>
<p>When I do it in Ubuntu, I get "file is not found".</p>
<p><strong>Question:</strong> How can I run Python code from a server?</p>
| 0 | 2009-07-14T14:10:25Z | 1,125,656 | <p>You can't do this. If you have SSH access to the server you can then run the python script located on the server using your SSH connection. If you want to write websites in python google python web frameworks for examples of how to set up and run websites with Python.</p>
| 3 | 2009-07-14T14:13:06Z | [
"python"
] |
Running Python code from a server? | 1,125,637 | <p><strong>Problem:</strong> to run one.py from a server.</p>
<p><strong>Error</strong></p>
<p>When I try to do it in Mac, I get errors:</p>
<pre><code>$python http://cs.edu.com/u/user/TEST/one.py ~
/Library/Frameworks/Python.framework/Versions/2.5/Resources/Python.app/Contents/MacOS/Python: can't open file 'http://cs.edu.com/u/user/TEST/one.py': [Errno 2] No such file or directory
</code></pre>
<p>one.py is like:</p>
<pre><code>print 1
</code></pre>
<p>When I do it in Ubuntu, I get "file is not found".</p>
<p><strong>Question:</strong> How can I run Python code from a server?</p>
| 0 | 2009-07-14T14:10:25Z | 1,125,670 | <p>You can mount the remote servers directory with some sort of file networking, like NFS or something. That way it becomes local.</p>
<p>But a better idea is that you explain why you are trying to do this, so we can solve the real usecase. There is most likely tons of better solutions, depending on what the real problem is.</p>
| 1 | 2009-07-14T14:15:40Z | [
"python"
] |
Running Python code from a server? | 1,125,637 | <p><strong>Problem:</strong> to run one.py from a server.</p>
<p><strong>Error</strong></p>
<p>When I try to do it in Mac, I get errors:</p>
<pre><code>$python http://cs.edu.com/u/user/TEST/one.py ~
/Library/Frameworks/Python.framework/Versions/2.5/Resources/Python.app/Contents/MacOS/Python: can't open file 'http://cs.edu.com/u/user/TEST/one.py': [Errno 2] No such file or directory
</code></pre>
<p>one.py is like:</p>
<pre><code>print 1
</code></pre>
<p>When I do it in Ubuntu, I get "file is not found".</p>
<p><strong>Question:</strong> How can I run Python code from a server?</p>
| 0 | 2009-07-14T14:10:25Z | 1,125,674 | <p>The python interpreter doesn't know how to read from a URL. The file needs to be local. </p>
<p>However, if you are trying to get the <em>server</em> to execute the python code, you can use <a href="http://www.modpython.org/" rel="nofollow">mod_python</a> or various kinds of CGI. </p>
<p>You can't do what you are trying to do the way you are trying to do it.</p>
| 1 | 2009-07-14T14:16:44Z | [
"python"
] |
Running Python code from a server? | 1,125,637 | <p><strong>Problem:</strong> to run one.py from a server.</p>
<p><strong>Error</strong></p>
<p>When I try to do it in Mac, I get errors:</p>
<pre><code>$python http://cs.edu.com/u/user/TEST/one.py ~
/Library/Frameworks/Python.framework/Versions/2.5/Resources/Python.app/Contents/MacOS/Python: can't open file 'http://cs.edu.com/u/user/TEST/one.py': [Errno 2] No such file or directory
</code></pre>
<p>one.py is like:</p>
<pre><code>print 1
</code></pre>
<p>When I do it in Ubuntu, I get "file is not found".</p>
<p><strong>Question:</strong> How can I run Python code from a server?</p>
| 0 | 2009-07-14T14:10:25Z | 1,125,712 | <p>Maybe something like this?</p>
<pre><code>python -c "import urllib; eval(urllib.urlopen(\"http://cs.edu.com/u/user/TEST/one.py").read())"
</code></pre>
| 1 | 2009-07-14T14:20:34Z | [
"python"
] |
Running Python code from a server? | 1,125,637 | <p><strong>Problem:</strong> to run one.py from a server.</p>
<p><strong>Error</strong></p>
<p>When I try to do it in Mac, I get errors:</p>
<pre><code>$python http://cs.edu.com/u/user/TEST/one.py ~
/Library/Frameworks/Python.framework/Versions/2.5/Resources/Python.app/Contents/MacOS/Python: can't open file 'http://cs.edu.com/u/user/TEST/one.py': [Errno 2] No such file or directory
</code></pre>
<p>one.py is like:</p>
<pre><code>print 1
</code></pre>
<p>When I do it in Ubuntu, I get "file is not found".</p>
<p><strong>Question:</strong> How can I run Python code from a server?</p>
| 0 | 2009-07-14T14:10:25Z | 1,126,247 | <p>OK, now when you explained, here is a new answer.</p>
<p>You run that script with </p>
<pre><code> python one.py
</code></pre>
<p>It's a server side-script. It's run on the server. It's also located on the server. Why you try to access it via http is beyond me. Run it from the file system.</p>
<p>Although, you should probably look into running Grok or Django or something. This way you'll just end up writing your own Python web framework, you may just as well use one that exists instead. ;)</p>
| 1 | 2009-07-14T15:38:23Z | [
"python"
] |
Running programs w/ a GUI over a remote connection | 1,125,894 | <p>I'm trying to start perfmon and another program that have GUI's through a python script that uses a PKA ssh connection. Is it possible to do this? If so could anyone point me in the right direction?</p>
| 0 | 2009-07-14T14:43:57Z | 1,125,920 | <p>If you mean <a href="http://perfmon.sourceforge.net/" rel="nofollow">this</a> perfmon (the one that runs under Linux &c == I believe there's a honomym program that's Windows-only and would behave very differently), <code>ssh -X</code> or <code>ssh -Y</code> let you open an ssh connection which tunnels an X11 (GUI) connection (if server and client are both configured to allow that, of course).</p>
<p><a href="http://www.vanemery.com/Linux/XoverSSH/X-over-SSH2.html" rel="nofollow">Here</a> are copious details of how to do it "the old way" (with <code>-p</code> etc); <a href="http://www.cyberciti.biz/faq/linux-unix-tunneling-xwindows-securely-over-ssh/" rel="nofollow">here</a>, the explanation of <code>-X</code> and the more secure <code>-Y</code> modern options. As long as the app is running on a Linux box, you can have the display ("X Server") just about anywhere, with a proper ssh tunnel securely connecting them.</p>
<p>If it's Windows you're talking about (i.e. running the <em>perfmon app</em> on a Windows box, wherever it is you want the GUI), I don't know how to tunnel a GUI over ssh (it may not be possible). One possibility is <a href="http://www.tightvnc.com/download.html" rel="nofollow">VNC</a> (there are several implementations of the protocol, both commercial and free) but I'm not all that experienced with it.</p>
| 1 | 2009-07-14T14:48:59Z | [
"python",
"user-interface",
"ssh",
"perfmon"
] |
Running programs w/ a GUI over a remote connection | 1,125,894 | <p>I'm trying to start perfmon and another program that have GUI's through a python script that uses a PKA ssh connection. Is it possible to do this? If so could anyone point me in the right direction?</p>
| 0 | 2009-07-14T14:43:57Z | 1,196,773 | <p>I've found a program called psexec that will open a program remotely on another windows machine. <a href="http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx" rel="nofollow">http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx</a>
There are options or flags that you can use with this command line program to open a program with a GUI and view it on a remote machine.</p>
| 0 | 2009-07-28T21:12:38Z | [
"python",
"user-interface",
"ssh",
"perfmon"
] |
Python: Persistent shell variables in subprocess | 1,126,116 | <p>I'm trying to execute a series of commands using Pythons subprocess module, however I need to set shell variables with export before running them. Of course the shell doesn't seem to be persistent so when I run a command later those shell variables are lost.</p>
<p>Is there any way to go about this? I could create a /bin/sh process, but how would I get the exit codes of the commands run under that?</p>
| 8 | 2009-07-14T15:19:21Z | 1,126,137 | <p><code>subprocess.Popen</code> takes an optional named argument <code>env</code> that's a dictionary to use as the subprocess's environment (what you're describing as "shell variables"). Prepare a dict as you need it (you may start with a copy of <code>os.environ</code> and alter that as you need) and pass it to all the <code>subprocess.Popen</code> calls you perform.</p>
| 13 | 2009-07-14T15:22:45Z | [
"python",
"shell",
"variables",
"subprocess",
"persistent"
] |
Python: Persistent shell variables in subprocess | 1,126,116 | <p>I'm trying to execute a series of commands using Pythons subprocess module, however I need to set shell variables with export before running them. Of course the shell doesn't seem to be persistent so when I run a command later those shell variables are lost.</p>
<p>Is there any way to go about this? I could create a /bin/sh process, but how would I get the exit codes of the commands run under that?</p>
| 8 | 2009-07-14T15:19:21Z | 1,339,904 | <p>Alex is absolutely correct. To give an example</p>
<pre><code>current_env=environ.copy()
current_env["XXX"] = "SOMETHING" #If you want to change some env variable
subProcess.Popen("command_n_args", env=current_env)
</code></pre>
| 5 | 2009-08-27T09:22:32Z | [
"python",
"shell",
"variables",
"subprocess",
"persistent"
] |
writeline problem in python | 1,126,477 | <p>I have a very basic problem. I am learning my first steps with python & scripting in general and so even this makes me wonder:</p>
<p>I want to read & write lines to new file:</p>
<pre><code>ifile=open("C:\Python24\OtsakkeillaSPSS.csv", "r")
ofile = open("C:\Python24\OtsakkeillaSPSSout.csv", "w")
#read first line with headers
line1 = ifile.readline()
print line1
#read following lines which contain data & write it to ofile
for line in ifile:
if not line:
break
ofile.write(line)
</code></pre>
<p>if i print this to the screen i get all my lines done nicely:</p>
<pre><code>0,26100,568,8636
0,11130,555,**3570
0,57100,77,2405**
0,60120,116,1193
0,33540,166,5007
0,95420,318,2310
0,20320,560,7607
0,4300,692,3969
0,65610,341,2073
0,1720,0,0
0,78850,228,1515
0,78870,118,1222
</code></pre>
<p>If i write it to ofile i end up missing some 15 lines:</p>
<pre><code>0,6100,948,8332
0,26100,568,8636
0,11130,555
</code></pre>
<p>I would appreciate if someone could point out to me what is it that i don´t understand?</p>
<p>Reg, </p>
<p>Jaani</p>
| 2 | 2009-07-14T16:15:17Z | 1,126,505 | <pre><code>#read following lines which contain data & write it to ofile
for line in ifile:
if not line:
continue #break stops the loop, you should use continue
ofile.write(line)
</code></pre>
| 4 | 2009-07-14T16:22:15Z | [
"python"
] |
writeline problem in python | 1,126,477 | <p>I have a very basic problem. I am learning my first steps with python & scripting in general and so even this makes me wonder:</p>
<p>I want to read & write lines to new file:</p>
<pre><code>ifile=open("C:\Python24\OtsakkeillaSPSS.csv", "r")
ofile = open("C:\Python24\OtsakkeillaSPSSout.csv", "w")
#read first line with headers
line1 = ifile.readline()
print line1
#read following lines which contain data & write it to ofile
for line in ifile:
if not line:
break
ofile.write(line)
</code></pre>
<p>if i print this to the screen i get all my lines done nicely:</p>
<pre><code>0,26100,568,8636
0,11130,555,**3570
0,57100,77,2405**
0,60120,116,1193
0,33540,166,5007
0,95420,318,2310
0,20320,560,7607
0,4300,692,3969
0,65610,341,2073
0,1720,0,0
0,78850,228,1515
0,78870,118,1222
</code></pre>
<p>If i write it to ofile i end up missing some 15 lines:</p>
<pre><code>0,6100,948,8332
0,26100,568,8636
0,11130,555
</code></pre>
<p>I would appreciate if someone could point out to me what is it that i don´t understand?</p>
<p>Reg, </p>
<p>Jaani</p>
| 2 | 2009-07-14T16:15:17Z | 1,126,515 | <p>You should be calling ofile.close() according to <a href="http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files" rel="nofollow">python docs</a>.</p>
<p>I'm not sure that writes are fully flushed out to a file without an explicit close. </p>
<p>Also, as SilentGhost mentioned, check for empty lines in your input file.</p>
<p>And as mentioned by stefanw below, that "if.. break" statement isn't necessary in a for in.</p>
| 5 | 2009-07-14T16:23:00Z | [
"python"
] |
writeline problem in python | 1,126,477 | <p>I have a very basic problem. I am learning my first steps with python & scripting in general and so even this makes me wonder:</p>
<p>I want to read & write lines to new file:</p>
<pre><code>ifile=open("C:\Python24\OtsakkeillaSPSS.csv", "r")
ofile = open("C:\Python24\OtsakkeillaSPSSout.csv", "w")
#read first line with headers
line1 = ifile.readline()
print line1
#read following lines which contain data & write it to ofile
for line in ifile:
if not line:
break
ofile.write(line)
</code></pre>
<p>if i print this to the screen i get all my lines done nicely:</p>
<pre><code>0,26100,568,8636
0,11130,555,**3570
0,57100,77,2405**
0,60120,116,1193
0,33540,166,5007
0,95420,318,2310
0,20320,560,7607
0,4300,692,3969
0,65610,341,2073
0,1720,0,0
0,78850,228,1515
0,78870,118,1222
</code></pre>
<p>If i write it to ofile i end up missing some 15 lines:</p>
<pre><code>0,6100,948,8332
0,26100,568,8636
0,11130,555
</code></pre>
<p>I would appreciate if someone could point out to me what is it that i don´t understand?</p>
<p>Reg, </p>
<p>Jaani</p>
| 2 | 2009-07-14T16:15:17Z | 1,126,525 | <p>oh, why does it look so foolish, the formation i mean?
Give it another go...</p>
<p>hi,</p>
<p>I have a very basic problem. I am learning my first steps with python & scripting in general and so even this makes me wonder:</p>
<p>I want to read & write lines to new file:</p>
<p>ifile=open("C:\Python24\OtsakkeillaSPSS.csv", "r")
ofile = open("C:\Python24\OtsakkeillaSPSSout.csv", "w")</p>
<p>read first line with headers
line1 = ifile.readline()
print line1
read following lines which contain data & write it to ofile</p>
<p>for line in ifile:
if not line:
break
ofile.write(line)</p>
<p>if i print this to the screen i get all my lines done nicely:</p>
<p>0,26100,568,8636
0,11130,555,3570
0,57100,77,2405
0,60120,116,1193
0,33540,166,5007
0,95420,318,2310
0,20320,560,7607
0,4300,692,3969
0,65610,341,2073
0,1720,0,0
0,78850,228,1515
0,78870,118,1222</p>
<p>If i write it to ofile i end up missing some 15 lines:</p>
<p>0,6100,948,8332
0,26100,568,8636
0,11130,555</p>
<p>I would appreciate if someone could point out to me what is it that i don´t understand?</p>
<p>Reg,</p>
<p>Jaani</p>
| 0 | 2009-07-14T16:24:28Z | [
"python"
] |
writeline problem in python | 1,126,477 | <p>I have a very basic problem. I am learning my first steps with python & scripting in general and so even this makes me wonder:</p>
<p>I want to read & write lines to new file:</p>
<pre><code>ifile=open("C:\Python24\OtsakkeillaSPSS.csv", "r")
ofile = open("C:\Python24\OtsakkeillaSPSSout.csv", "w")
#read first line with headers
line1 = ifile.readline()
print line1
#read following lines which contain data & write it to ofile
for line in ifile:
if not line:
break
ofile.write(line)
</code></pre>
<p>if i print this to the screen i get all my lines done nicely:</p>
<pre><code>0,26100,568,8636
0,11130,555,**3570
0,57100,77,2405**
0,60120,116,1193
0,33540,166,5007
0,95420,318,2310
0,20320,560,7607
0,4300,692,3969
0,65610,341,2073
0,1720,0,0
0,78850,228,1515
0,78870,118,1222
</code></pre>
<p>If i write it to ofile i end up missing some 15 lines:</p>
<pre><code>0,6100,948,8332
0,26100,568,8636
0,11130,555
</code></pre>
<p>I would appreciate if someone could point out to me what is it that i don´t understand?</p>
<p>Reg, </p>
<p>Jaani</p>
| 2 | 2009-07-14T16:15:17Z | 1,126,539 | <p>The "if not line:" - Check is unnecessary.</p>
<pre><code>for line in ifile:
ofile.write(line)
</code></pre>
| 3 | 2009-07-14T16:26:44Z | [
"python"
] |
writeline problem in python | 1,126,477 | <p>I have a very basic problem. I am learning my first steps with python & scripting in general and so even this makes me wonder:</p>
<p>I want to read & write lines to new file:</p>
<pre><code>ifile=open("C:\Python24\OtsakkeillaSPSS.csv", "r")
ofile = open("C:\Python24\OtsakkeillaSPSSout.csv", "w")
#read first line with headers
line1 = ifile.readline()
print line1
#read following lines which contain data & write it to ofile
for line in ifile:
if not line:
break
ofile.write(line)
</code></pre>
<p>if i print this to the screen i get all my lines done nicely:</p>
<pre><code>0,26100,568,8636
0,11130,555,**3570
0,57100,77,2405**
0,60120,116,1193
0,33540,166,5007
0,95420,318,2310
0,20320,560,7607
0,4300,692,3969
0,65610,341,2073
0,1720,0,0
0,78850,228,1515
0,78870,118,1222
</code></pre>
<p>If i write it to ofile i end up missing some 15 lines:</p>
<pre><code>0,6100,948,8332
0,26100,568,8636
0,11130,555
</code></pre>
<p>I would appreciate if someone could point out to me what is it that i don´t understand?</p>
<p>Reg, </p>
<p>Jaani</p>
| 2 | 2009-07-14T16:15:17Z | 1,127,857 | <p>Why are you using python2.4? the latest is python2.6 </p>
<p>and then you can use </p>
<pre><code>from contextlib import nested
ipath = "C:\Python24\OtsakkeillaSPSS.csv"
opath = "C:\Python24\OtsakkeillaSPSSout.csv"
with nested(open(ipath,'r'), open(opath,'w') as ifile, ofile:
#read first line with headers
line1 = ifile.readline()
print line1
#read following lines which contain data & write it to ofile
for line in ifile:
ofile.write(line)
</code></pre>
| 1 | 2009-07-14T20:33:30Z | [
"python"
] |
How would you inherit from and override the django model classes to create a listOfStringsField? | 1,126,642 | <p>I want to create a new type of field for django models that is basically a ListOfStrings. So in your model code you would have the following:</p>
<p><strong>models.py:</strong></p>
<pre><code>from django.db import models
class ListOfStringsField(???):
???
class myDjangoModelClass():
myName = models.CharField(max_length=64)
myFriends = ListOfStringsField() #
</code></pre>
<p><strong>other.py:</strong></p>
<pre><code>myclass = myDjangoModelClass()
myclass.myName = "bob"
myclass.myFriends = ["me", "myself", "and I"]
myclass.save()
id = myclass.id
loadedmyclass = myDjangoModelClass.objects.filter(id__exact=id)
myFriendsList = loadedclass.myFriends
# myFriendsList is a list and should equal ["me", "myself", "and I"]
</code></pre>
<p>How would you go about writing this field type, with the following stipulations?</p>
<ul>
<li>We don't want to do create a field which just crams all the strings together and separates them with a token in one field like <a href="http://www.davidcramer.net/code/181/custom-fields-in-django.html" rel="nofollow">this</a>. It is a good solution in some cases, but we want to keep the string data normalized so tools other than django can query the data.</li>
<li>The field should automatically create any secondary tables needed to store the string data.</li>
<li>The secondary table should ideally have only one copy of each unique string. This is optional, but would be nice to have.</li>
</ul>
<p>Looking in the Django code it looks like I would want to do something similar to what ForeignKey is doing, but the documentation is sparse.</p>
<p>This leads to the following questions:</p>
<ul>
<li>Can this be done?</li>
<li>Has it been done (and if so where)?</li>
<li>Is there any documentation on Django about how to extend and override their model classes, specifically their relationship classes? I have not seen a lot of documentation on that aspect of their code, but there is <a href="http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#howto-custom-model-fields" rel="nofollow">this</a>.</li>
</ul>
<p>This is comes from this <a href="http://stackoverflow.com/questions/1110153/what-is-the-most-efficent-way-to-store-a-list-in-the-django-models">question</a>.</p>
| 6 | 2009-07-14T16:44:43Z | 1,126,953 | <p>I think what you want is a <a href="http://docs.djangoproject.com/en/dev/howto/custom-model-fields/" rel="nofollow">custom model field</a>.</p>
| -1 | 2009-07-14T17:50:43Z | [
"python",
"django",
"inheritance",
"django-models"
] |
How would you inherit from and override the django model classes to create a listOfStringsField? | 1,126,642 | <p>I want to create a new type of field for django models that is basically a ListOfStrings. So in your model code you would have the following:</p>
<p><strong>models.py:</strong></p>
<pre><code>from django.db import models
class ListOfStringsField(???):
???
class myDjangoModelClass():
myName = models.CharField(max_length=64)
myFriends = ListOfStringsField() #
</code></pre>
<p><strong>other.py:</strong></p>
<pre><code>myclass = myDjangoModelClass()
myclass.myName = "bob"
myclass.myFriends = ["me", "myself", "and I"]
myclass.save()
id = myclass.id
loadedmyclass = myDjangoModelClass.objects.filter(id__exact=id)
myFriendsList = loadedclass.myFriends
# myFriendsList is a list and should equal ["me", "myself", "and I"]
</code></pre>
<p>How would you go about writing this field type, with the following stipulations?</p>
<ul>
<li>We don't want to do create a field which just crams all the strings together and separates them with a token in one field like <a href="http://www.davidcramer.net/code/181/custom-fields-in-django.html" rel="nofollow">this</a>. It is a good solution in some cases, but we want to keep the string data normalized so tools other than django can query the data.</li>
<li>The field should automatically create any secondary tables needed to store the string data.</li>
<li>The secondary table should ideally have only one copy of each unique string. This is optional, but would be nice to have.</li>
</ul>
<p>Looking in the Django code it looks like I would want to do something similar to what ForeignKey is doing, but the documentation is sparse.</p>
<p>This leads to the following questions:</p>
<ul>
<li>Can this be done?</li>
<li>Has it been done (and if so where)?</li>
<li>Is there any documentation on Django about how to extend and override their model classes, specifically their relationship classes? I have not seen a lot of documentation on that aspect of their code, but there is <a href="http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#howto-custom-model-fields" rel="nofollow">this</a>.</li>
</ul>
<p>This is comes from this <a href="http://stackoverflow.com/questions/1110153/what-is-the-most-efficent-way-to-store-a-list-in-the-django-models">question</a>.</p>
| 6 | 2009-07-14T16:44:43Z | 1,127,073 | <p>There's some very good documentation on creating custom fields <a href="http://docs.djangoproject.com/en/dev/howto/custom-model-fields/">here</a>. </p>
<p>However, I think you're overthinking this. It sounds like you actually just want a standard foreign key, but with the additional ability to retrieve all the elements as a single list. So the easiest thing would be to just use a ForeignKey, and define a <code>get_myfield_as_list</code> method on the model:</p>
<pre><code>class Friends(model.Model):
name = models.CharField(max_length=100)
my_items = models.ForeignKey(MyModel)
class MyModel(models.Model):
...
def get_my_friends_as_list(self):
return ', '.join(self.friends_set.values_list('name', flat=True))
</code></pre>
<p>Now calling <code>get_my_friends_as_list()</code> on an instance of MyModel will return you a list of strings, as required.</p>
| 6 | 2009-07-14T18:15:54Z | [
"python",
"django",
"inheritance",
"django-models"
] |
How would you inherit from and override the django model classes to create a listOfStringsField? | 1,126,642 | <p>I want to create a new type of field for django models that is basically a ListOfStrings. So in your model code you would have the following:</p>
<p><strong>models.py:</strong></p>
<pre><code>from django.db import models
class ListOfStringsField(???):
???
class myDjangoModelClass():
myName = models.CharField(max_length=64)
myFriends = ListOfStringsField() #
</code></pre>
<p><strong>other.py:</strong></p>
<pre><code>myclass = myDjangoModelClass()
myclass.myName = "bob"
myclass.myFriends = ["me", "myself", "and I"]
myclass.save()
id = myclass.id
loadedmyclass = myDjangoModelClass.objects.filter(id__exact=id)
myFriendsList = loadedclass.myFriends
# myFriendsList is a list and should equal ["me", "myself", "and I"]
</code></pre>
<p>How would you go about writing this field type, with the following stipulations?</p>
<ul>
<li>We don't want to do create a field which just crams all the strings together and separates them with a token in one field like <a href="http://www.davidcramer.net/code/181/custom-fields-in-django.html" rel="nofollow">this</a>. It is a good solution in some cases, but we want to keep the string data normalized so tools other than django can query the data.</li>
<li>The field should automatically create any secondary tables needed to store the string data.</li>
<li>The secondary table should ideally have only one copy of each unique string. This is optional, but would be nice to have.</li>
</ul>
<p>Looking in the Django code it looks like I would want to do something similar to what ForeignKey is doing, but the documentation is sparse.</p>
<p>This leads to the following questions:</p>
<ul>
<li>Can this be done?</li>
<li>Has it been done (and if so where)?</li>
<li>Is there any documentation on Django about how to extend and override their model classes, specifically their relationship classes? I have not seen a lot of documentation on that aspect of their code, but there is <a href="http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#howto-custom-model-fields" rel="nofollow">this</a>.</li>
</ul>
<p>This is comes from this <a href="http://stackoverflow.com/questions/1110153/what-is-the-most-efficent-way-to-store-a-list-in-the-django-models">question</a>.</p>
| 6 | 2009-07-14T16:44:43Z | 1,128,596 | <p>I also think you're going about this the wrong way. Trying to make a Django field create an ancillary database table is almost certainly the wrong approach. It would be very difficult to do, and would likely confuse third party developers if you are trying to make your solution generally useful.</p>
<p>If you're trying to store a denormalized blob of data in a single column, I'd take an approach similar to the one you linked to, serializing the Python data structure and storing it in a TextField. If you want tools other than Django to be able to operate on the data then you can serialize to JSON (or some other format that has wide language support):</p>
<pre><code>from django.db import models
from django.utils import simplejson
class JSONDataField(models.TextField):
__metaclass__ = models.SubfieldBase
def to_python(self, value):
if value is None:
return None
if not isinstance(value, basestring):
return value
return simplejson.loads(value)
def get_db_prep_save(self, value):
if value is None:
return None
return simplejson.dumps(value)
</code></pre>
<p>If you just want a django Manager-like descriptor that lets you operate on a list of strings associated with a model then you can manually create a join table and use a descriptor to manage the relationship. It's not exactly what you need, but <a href="http://gist.github.com/147312">this code should get you started</a>.</p>
| 5 | 2009-07-14T23:13:30Z | [
"python",
"django",
"inheritance",
"django-models"
] |
How would you inherit from and override the django model classes to create a listOfStringsField? | 1,126,642 | <p>I want to create a new type of field for django models that is basically a ListOfStrings. So in your model code you would have the following:</p>
<p><strong>models.py:</strong></p>
<pre><code>from django.db import models
class ListOfStringsField(???):
???
class myDjangoModelClass():
myName = models.CharField(max_length=64)
myFriends = ListOfStringsField() #
</code></pre>
<p><strong>other.py:</strong></p>
<pre><code>myclass = myDjangoModelClass()
myclass.myName = "bob"
myclass.myFriends = ["me", "myself", "and I"]
myclass.save()
id = myclass.id
loadedmyclass = myDjangoModelClass.objects.filter(id__exact=id)
myFriendsList = loadedclass.myFriends
# myFriendsList is a list and should equal ["me", "myself", "and I"]
</code></pre>
<p>How would you go about writing this field type, with the following stipulations?</p>
<ul>
<li>We don't want to do create a field which just crams all the strings together and separates them with a token in one field like <a href="http://www.davidcramer.net/code/181/custom-fields-in-django.html" rel="nofollow">this</a>. It is a good solution in some cases, but we want to keep the string data normalized so tools other than django can query the data.</li>
<li>The field should automatically create any secondary tables needed to store the string data.</li>
<li>The secondary table should ideally have only one copy of each unique string. This is optional, but would be nice to have.</li>
</ul>
<p>Looking in the Django code it looks like I would want to do something similar to what ForeignKey is doing, but the documentation is sparse.</p>
<p>This leads to the following questions:</p>
<ul>
<li>Can this be done?</li>
<li>Has it been done (and if so where)?</li>
<li>Is there any documentation on Django about how to extend and override their model classes, specifically their relationship classes? I have not seen a lot of documentation on that aspect of their code, but there is <a href="http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#howto-custom-model-fields" rel="nofollow">this</a>.</li>
</ul>
<p>This is comes from this <a href="http://stackoverflow.com/questions/1110153/what-is-the-most-efficent-way-to-store-a-list-in-the-django-models">question</a>.</p>
| 6 | 2009-07-14T16:44:43Z | 1,132,043 | <p>Thanks for all those that answered. Even if I didn't use your answer directly the examples and links got me going in the right direction.</p>
<p>I am not sure if this is production ready, but it appears to be working in all my tests so far. </p>
<pre><code>class ListValueDescriptor(object):
def __init__(self, lvd_parent, lvd_model_name, lvd_value_type, lvd_unique, **kwargs):
"""
This descriptor object acts like a django field, but it will accept
a list of values, instead a single value.
For example:
# define our model
class Person(models.Model):
name = models.CharField(max_length=120)
friends = ListValueDescriptor("Person", "Friend", "CharField", True, max_length=120)
# Later in the code we can do this
p = Person("John")
p.save() # we have to have an id
p.friends = ["Jerry", "Jimmy", "Jamail"]
...
p = Person.objects.get(name="John")
friends = p.friends
# and now friends is a list.
lvd_parent - The name of our parent class
lvd_model_name - The name of our new model
lvd_value_type - The value type of the value in our new model
This has to be the name of one of the valid django
model field types such as 'CharField', 'FloatField',
or a valid custom field name.
lvd_unique - Set this to true if you want the values in the list to
be unique in the table they are stored in. For
example if you are storing a list of strings and
the strings are always "foo", "bar", and "baz", your
data table would only have those three strings listed in
it in the database.
kwargs - These are passed to the value field.
"""
self.related_set_name = lvd_model_name.lower() + "_set"
self.model_name = lvd_model_name
self.parent = lvd_parent
self.unique = lvd_unique
# only set this to true if they have not already set it.
# this helps speed up the searchs when unique is true.
kwargs['db_index'] = kwargs.get('db_index', True)
filter = ["lvd_parent", "lvd_model_name", "lvd_value_type", "lvd_unique"]
evalStr = """class %s (models.Model):\n""" % (self.model_name)
evalStr += """ value = models.%s(""" % (lvd_value_type)
evalStr += self._params_from_kwargs(filter, **kwargs)
evalStr += ")\n"
if self.unique:
evalStr += """ parent = models.ManyToManyField('%s')\n""" % (self.parent)
else:
evalStr += """ parent = models.ForeignKey('%s')\n""" % (self.parent)
evalStr += "\n"
evalStr += """self.innerClass = %s\n""" % (self.model_name)
print evalStr
exec (evalStr) # build the inner class
def __get__(self, instance, owner):
value_set = instance.__getattribute__(self.related_set_name)
l = []
for x in value_set.all():
l.append(x.value)
return l
def __set__(self, instance, values):
value_set = instance.__getattribute__(self.related_set_name)
for x in values:
value_set.add(self._get_or_create_value(x))
def __delete__(self, instance):
pass # I should probably try and do something here.
def _get_or_create_value(self, x):
if self.unique:
# Try and find an existing value
try:
return self.innerClass.objects.get(value=x)
except django.core.exceptions.ObjectDoesNotExist:
pass
v = self.innerClass(value=x)
v.save() # we have to save to create the id.
return v
def _params_from_kwargs(self, filter, **kwargs):
"""Given a dictionary of arguments, build a string which
represents it as a parameter list, and filter out any
keywords in filter."""
params = ""
for key in kwargs:
if key not in filter:
value = kwargs[key]
params += "%s=%s, " % (key, value.__repr__())
return params[:-2] # chop off the last ', '
class Person(models.Model):
name = models.CharField(max_length=120)
friends = ListValueDescriptor("Person", "Friend", "CharField", True, max_length=120)
</code></pre>
<p>Ultimately I think this would still be better if it were pushed deeper into the django code and worked more like the ManyToManyField or the ForeignKey.</p>
| 1 | 2009-07-15T15:14:04Z | [
"python",
"django",
"inheritance",
"django-models"
] |
How would you inherit from and override the django model classes to create a listOfStringsField? | 1,126,642 | <p>I want to create a new type of field for django models that is basically a ListOfStrings. So in your model code you would have the following:</p>
<p><strong>models.py:</strong></p>
<pre><code>from django.db import models
class ListOfStringsField(???):
???
class myDjangoModelClass():
myName = models.CharField(max_length=64)
myFriends = ListOfStringsField() #
</code></pre>
<p><strong>other.py:</strong></p>
<pre><code>myclass = myDjangoModelClass()
myclass.myName = "bob"
myclass.myFriends = ["me", "myself", "and I"]
myclass.save()
id = myclass.id
loadedmyclass = myDjangoModelClass.objects.filter(id__exact=id)
myFriendsList = loadedclass.myFriends
# myFriendsList is a list and should equal ["me", "myself", "and I"]
</code></pre>
<p>How would you go about writing this field type, with the following stipulations?</p>
<ul>
<li>We don't want to do create a field which just crams all the strings together and separates them with a token in one field like <a href="http://www.davidcramer.net/code/181/custom-fields-in-django.html" rel="nofollow">this</a>. It is a good solution in some cases, but we want to keep the string data normalized so tools other than django can query the data.</li>
<li>The field should automatically create any secondary tables needed to store the string data.</li>
<li>The secondary table should ideally have only one copy of each unique string. This is optional, but would be nice to have.</li>
</ul>
<p>Looking in the Django code it looks like I would want to do something similar to what ForeignKey is doing, but the documentation is sparse.</p>
<p>This leads to the following questions:</p>
<ul>
<li>Can this be done?</li>
<li>Has it been done (and if so where)?</li>
<li>Is there any documentation on Django about how to extend and override their model classes, specifically their relationship classes? I have not seen a lot of documentation on that aspect of their code, but there is <a href="http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#howto-custom-model-fields" rel="nofollow">this</a>.</li>
</ul>
<p>This is comes from this <a href="http://stackoverflow.com/questions/1110153/what-is-the-most-efficent-way-to-store-a-list-in-the-django-models">question</a>.</p>
| 6 | 2009-07-14T16:44:43Z | 1,153,959 | <p>What you have described sounds to me really similar to the tags.<br />
So, why not using <a href="http://code.google.com/p/django-tagging/">django tagging</a>?<br />
It works like a charm, you can install it independently from your application and its API is quite easy to use.</p>
| 5 | 2009-07-20T14:32:47Z | [
"python",
"django",
"inheritance",
"django-models"
] |
django-timezones | 1,126,811 | <p>I am trying to setup django-timezones but am unfamiliar on how to go about this. The only info that I have found is here: <a href="http://www.ohloh.net/p/django-timezones" rel="nofollow">http://www.ohloh.net/p/django-timezones</a></p>
<pre><code>class MyModel(Model):
timezone = TimeZoneField()
datetime = LocalizedDateTime('timezone')
</code></pre>
<p>I also tried looking through the pinax code or any other projects that use this app but haven't found anything.</p>
<p>Does anyone have an example or some info that they can share on how to use this?</p>
<p>Thanks,
Justin</p>
| 1 | 2009-07-14T17:23:31Z | 1,128,277 | <p>Well, the firs thing you need to do when installing any Django app, is add it to your INSTALLED_APPS in settings.py. This particular app doesn't do to much other then give you some handy fields and things that you can use in other parts of your Django project. Your best bet to understand it is reading the source, I would say.</p>
| 4 | 2009-07-14T21:53:08Z | [
"python",
"django",
"timezone"
] |
Best way to have full Python install under cygwin/XP? | 1,126,842 | <p>Pythons installed under WinXP have dirs like DLLs, DOC, include, etc. but python (2.5) installed with cygwin is a bare python.exe. My motivation for asking is that 'things' under XP don't seem to be finding 'other things' under cygwin and vice versa, I want to start developing with Qt, I like shells, and I do not like MS; I thought if I got all the components under one roof, I could finally start to have scripts find executables which could find files and such. 1. Can I simply copy the contents of an XP installation into the cygwin tree? 2. Is the XP flavor of Python different from the cygwin flavor? (Same CPU, he pointed out, naively.) 3. Someone must work with a full-fledged (if snakes had feathers...) Python from within cygwin; how is it done? </p>
<p>Disclaimer 1: I have never compiled anything under XP or cygwin; had hoped not to have to go there, hence, python in the first place. Disclaimer 2: sorry if this is a ServerFault question, but they seemed to be system people over there and this is (in my case) a lowly desktop.</p>
| 3 | 2009-07-14T17:28:02Z | 1,126,858 | <p>Well, in my windows environment I use <a href="http://www.activestate.com/activepython/" rel="nofollow">active python</a> and it, so far, works for me.</p>
| 0 | 2009-07-14T17:30:49Z | [
"python",
"windows-xp",
"cygwin"
] |
Best way to have full Python install under cygwin/XP? | 1,126,842 | <p>Pythons installed under WinXP have dirs like DLLs, DOC, include, etc. but python (2.5) installed with cygwin is a bare python.exe. My motivation for asking is that 'things' under XP don't seem to be finding 'other things' under cygwin and vice versa, I want to start developing with Qt, I like shells, and I do not like MS; I thought if I got all the components under one roof, I could finally start to have scripts find executables which could find files and such. 1. Can I simply copy the contents of an XP installation into the cygwin tree? 2. Is the XP flavor of Python different from the cygwin flavor? (Same CPU, he pointed out, naively.) 3. Someone must work with a full-fledged (if snakes had feathers...) Python from within cygwin; how is it done? </p>
<p>Disclaimer 1: I have never compiled anything under XP or cygwin; had hoped not to have to go there, hence, python in the first place. Disclaimer 2: sorry if this is a ServerFault question, but they seemed to be system people over there and this is (in my case) a lowly desktop.</p>
| 3 | 2009-07-14T17:28:02Z | 1,126,874 | <p>Just a little off the question, but...</p>
<p>Have you considered running Sun's VirtualBox with Fedora or Ubuntu inside of it? I'm assuming you have to / need to use windows because you still are, but don't like it. Then you would have python running inside a native linux desktop without any of the troubles you mentioned.</p>
<p>And if you want something that is really easy and portable, then just use Python on Windows, not mixed in with cygwin.</p>
<p>$0.02</p>
| 0 | 2009-07-14T17:34:13Z | [
"python",
"windows-xp",
"cygwin"
] |
Best way to have full Python install under cygwin/XP? | 1,126,842 | <p>Pythons installed under WinXP have dirs like DLLs, DOC, include, etc. but python (2.5) installed with cygwin is a bare python.exe. My motivation for asking is that 'things' under XP don't seem to be finding 'other things' under cygwin and vice versa, I want to start developing with Qt, I like shells, and I do not like MS; I thought if I got all the components under one roof, I could finally start to have scripts find executables which could find files and such. 1. Can I simply copy the contents of an XP installation into the cygwin tree? 2. Is the XP flavor of Python different from the cygwin flavor? (Same CPU, he pointed out, naively.) 3. Someone must work with a full-fledged (if snakes had feathers...) Python from within cygwin; how is it done? </p>
<p>Disclaimer 1: I have never compiled anything under XP or cygwin; had hoped not to have to go there, hence, python in the first place. Disclaimer 2: sorry if this is a ServerFault question, but they seemed to be system people over there and this is (in my case) a lowly desktop.</p>
| 3 | 2009-07-14T17:28:02Z | 1,126,885 | <p>I use Python from within cygwin, but I don't use the version that cygwin gives you the option of installing as I don't have the control over version number used that I need (we use an older version at work). I have my python version installed via the windows installer (the xp version as you put it) and add the /cygdrive/c/Python2x directory to my PATH environment variable.</p>
| 2 | 2009-07-14T17:37:23Z | [
"python",
"windows-xp",
"cygwin"
] |
Best way to have full Python install under cygwin/XP? | 1,126,842 | <p>Pythons installed under WinXP have dirs like DLLs, DOC, include, etc. but python (2.5) installed with cygwin is a bare python.exe. My motivation for asking is that 'things' under XP don't seem to be finding 'other things' under cygwin and vice versa, I want to start developing with Qt, I like shells, and I do not like MS; I thought if I got all the components under one roof, I could finally start to have scripts find executables which could find files and such. 1. Can I simply copy the contents of an XP installation into the cygwin tree? 2. Is the XP flavor of Python different from the cygwin flavor? (Same CPU, he pointed out, naively.) 3. Someone must work with a full-fledged (if snakes had feathers...) Python from within cygwin; how is it done? </p>
<p>Disclaimer 1: I have never compiled anything under XP or cygwin; had hoped not to have to go there, hence, python in the first place. Disclaimer 2: sorry if this is a ServerFault question, but they seemed to be system people over there and this is (in my case) a lowly desktop.</p>
| 3 | 2009-07-14T17:28:02Z | 1,128,193 | <p>This probably has little value, but... I found myself in this exact situation -- we use ActivePython2.5 in production (pure windows environment) and I was trying to do my development within cygwin and cygwin's Python... </p>
<p>After ripping out half of my hair, I have now switched over to Console2, gvim, iPython and ActivePython2.5.</p>
<p>I'm less than thrilled dealing with Windows tools (and their concomitant warts), but at least I'm not getting in my own way when it comes to development. For a while I found I was spending more time trying to get my tools to play nice than actually getting any work done.</p>
<p>Good luck on this one.</p>
| 0 | 2009-07-14T21:33:58Z | [
"python",
"windows-xp",
"cygwin"
] |
Best way to have full Python install under cygwin/XP? | 1,126,842 | <p>Pythons installed under WinXP have dirs like DLLs, DOC, include, etc. but python (2.5) installed with cygwin is a bare python.exe. My motivation for asking is that 'things' under XP don't seem to be finding 'other things' under cygwin and vice versa, I want to start developing with Qt, I like shells, and I do not like MS; I thought if I got all the components under one roof, I could finally start to have scripts find executables which could find files and such. 1. Can I simply copy the contents of an XP installation into the cygwin tree? 2. Is the XP flavor of Python different from the cygwin flavor? (Same CPU, he pointed out, naively.) 3. Someone must work with a full-fledged (if snakes had feathers...) Python from within cygwin; how is it done? </p>
<p>Disclaimer 1: I have never compiled anything under XP or cygwin; had hoped not to have to go there, hence, python in the first place. Disclaimer 2: sorry if this is a ServerFault question, but they seemed to be system people over there and this is (in my case) a lowly desktop.</p>
| 3 | 2009-07-14T17:28:02Z | 11,792,553 | <p>I accidentally stumbled on this - If I launch Cygwin from the Cygwin.bat file (which is present directly under the main folder), I get access to the Python version installed under Cygwin (i.e 2.6.8)</p>
<p>If I instead launch the Cygwin from bash.exe under bin directory (C:\Cygwin\bin\bash.exe for me), running "Python -V" shows that I have access to 2.7.3 version of Python (that was installed for Windows).</p>
<p>So, I guess you can do the same.</p>
| 0 | 2012-08-03T09:00:18Z | [
"python",
"windows-xp",
"cygwin"
] |
Is it possible to go into ipython from code? | 1,126,930 | <p>For my debugging needs, <code>pdb</code> is pretty good. However, it would be <em>much</em> cooler (and helpful) if I could go into <code>ipython</code>. Is this thing possible?</p>
| 66 | 2009-07-14T17:45:59Z | 1,127,042 | <p>Normally, when I use ipython, I turn automatic debugging on with the "pdb" command inside it.</p>
<p>I then run my script with the "run myscript.py" command in the directory where my script is located.</p>
<p>If I get an exception, ipython stops the program inside the debugger. Check out the help command for the magic ipython commands (%magic)</p>
| 7 | 2009-07-14T18:08:30Z | [
"python",
"shell",
"debugging",
"ipython",
"pdb"
] |
Is it possible to go into ipython from code? | 1,126,930 | <p>For my debugging needs, <code>pdb</code> is pretty good. However, it would be <em>much</em> cooler (and helpful) if I could go into <code>ipython</code>. Is this thing possible?</p>
| 66 | 2009-07-14T17:45:59Z | 1,127,071 | <p>From the <a href="http://ipython.scipy.org/doc/stable/html/interactive/extension%5Fapi.html#launching-ipython-instance-from-normal-python-code" rel="nofollow">IPython docs</a>:</p>
<pre><code>import IPython.ipapi
namespace = dict(
kissa = 15,
koira = 16)
IPython.ipapi.launch_new_instance(namespace)
</code></pre>
<p>will launch an IPython shell programmatically. Obviously the values in the <code>namespace</code> dict are just dummy values - it might make more sense to use <code>locals()</code> in practice.</p>
<p>Note that you have to hard-code this in; it's not going to work the way <code>pdb</code> does. If that's what you want, DoxaLogos' answer is probably more like what you're looking for.</p>
| 3 | 2009-07-14T18:15:32Z | [
"python",
"shell",
"debugging",
"ipython",
"pdb"
] |
Is it possible to go into ipython from code? | 1,126,930 | <p>For my debugging needs, <code>pdb</code> is pretty good. However, it would be <em>much</em> cooler (and helpful) if I could go into <code>ipython</code>. Is this thing possible?</p>
| 66 | 2009-07-14T17:45:59Z | 1,127,087 | <p>There is an <code>ipdb</code> project which embeds iPython into the standard pdb, so you can just do:</p>
<pre><code>import ipdb; ipdb.set_trace()
</code></pre>
<p>It's installable via the usual <code>easy_install ipdb</code>.</p>
<p><code>ipdb</code> is pretty short, so instead of easy_installing you can also create a file <code>ipdb.py</code> somewhere on your Python path and paste the following into the file:</p>
<pre><code>import sys
from IPython.Debugger import Pdb
from IPython.Shell import IPShell
from IPython import ipapi
shell = IPShell(argv=[''])
def set_trace():
ip = ipapi.get()
def_colors = ip.options.colors
Pdb(def_colors).set_trace(sys._getframe().f_back)
</code></pre>
| 91 | 2009-07-14T18:18:53Z | [
"python",
"shell",
"debugging",
"ipython",
"pdb"
] |
Is it possible to go into ipython from code? | 1,126,930 | <p>For my debugging needs, <code>pdb</code> is pretty good. However, it would be <em>much</em> cooler (and helpful) if I could go into <code>ipython</code>. Is this thing possible?</p>
| 66 | 2009-07-14T17:45:59Z | 1,128,816 | <p>The equivalent of </p>
<pre><code>import pdb; pdb.set_trace()
</code></pre>
<p>with IPython is something like:</p>
<pre><code>from IPython.ipapi import make_session; make_session()
from IPython.Debugger import Pdb; Pdb().set_trace()
</code></pre>
<p>It's a bit verbose, but good to know if you don't have ipdb installed. The <code>make_session</code> call is required once to set up the color scheme, etc, and <code>set_trace</code> calls can be placed anywhere you need to break.</p>
| 9 | 2009-07-15T00:40:39Z | [
"python",
"shell",
"debugging",
"ipython",
"pdb"
] |
Is it possible to go into ipython from code? | 1,126,930 | <p>For my debugging needs, <code>pdb</code> is pretty good. However, it would be <em>much</em> cooler (and helpful) if I could go into <code>ipython</code>. Is this thing possible?</p>
| 66 | 2009-07-14T17:45:59Z | 4,087,236 | <p>The fast-and-easy way:</p>
<pre><code>from IPython.Debugger import Tracer
debug = Tracer()
</code></pre>
<p>Then just write</p>
<pre><code>debug()
</code></pre>
<p>wherever you want to start debugging your program.</p>
| 3 | 2010-11-03T12:57:03Z | [
"python",
"shell",
"debugging",
"ipython",
"pdb"
] |
Is it possible to go into ipython from code? | 1,126,930 | <p>For my debugging needs, <code>pdb</code> is pretty good. However, it would be <em>much</em> cooler (and helpful) if I could go into <code>ipython</code>. Is this thing possible?</p>
| 66 | 2009-07-14T17:45:59Z | 7,411,459 | <p>In IPython 0.11, you can embed IPython directly in your code like this</p>
<p>Your program might look like this</p>
<pre><code>In [5]: cat > tmpf.py
a = 1
from IPython import embed
embed() # drop into an IPython session.
# Any variables you define or modify here
# will not affect program execution
c = 2
^D
</code></pre>
<p>This is what happens when you run it (I arbitrarily chose to run it inside an existing ipython session. Nesting ipython sessions like this in my experience can cause it to crash).</p>
<pre><code>In [6]:
In [6]: run tmpf.py
Python 2.7.2 (default, Aug 25 2011, 00:06:33)
Type "copyright", "credits" or "license" for more information.
IPython 0.11 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]: who
a embed
In [2]: a
Out[2]: 1
In [3]:
Do you really want to exit ([y]/n)? y
In [7]: who
a c embed
</code></pre>
| 35 | 2011-09-14T05:00:59Z | [
"python",
"shell",
"debugging",
"ipython",
"pdb"
] |
Is it possible to go into ipython from code? | 1,126,930 | <p>For my debugging needs, <code>pdb</code> is pretty good. However, it would be <em>much</em> cooler (and helpful) if I could go into <code>ipython</code>. Is this thing possible?</p>
| 66 | 2009-07-14T17:45:59Z | 12,177,383 | <p>I like to simply paste this one-liner in my scripts where I want to set a breakpoint:</p>
<pre><code>__import__('IPython').Debugger.Pdb(color_scheme='Linux').set_trace()
</code></pre>
<p>Newer version might use:</p>
<pre><code>__import__('IPython').core.debugger.Pdb(color_scheme='Linux').set_trace()
</code></pre>
| 6 | 2012-08-29T11:58:31Z | [
"python",
"shell",
"debugging",
"ipython",
"pdb"
] |
Is it possible to go into ipython from code? | 1,126,930 | <p>For my debugging needs, <code>pdb</code> is pretty good. However, it would be <em>much</em> cooler (and helpful) if I could go into <code>ipython</code>. Is this thing possible?</p>
| 66 | 2009-07-14T17:45:59Z | 12,528,973 | <p>If you're using a more modern version of IPython (> 0.10.2) you can use something like</p>
<pre><code>from IPython.core.debugger import Pdb
Pdb().set_trace()
</code></pre>
<p>But it's probably better to just use ipdb </p>
| 9 | 2012-09-21T10:41:44Z | [
"python",
"shell",
"debugging",
"ipython",
"pdb"
] |
Is it possible to go into ipython from code? | 1,126,930 | <p>For my debugging needs, <code>pdb</code> is pretty good. However, it would be <em>much</em> cooler (and helpful) if I could go into <code>ipython</code>. Is this thing possible?</p>
| 66 | 2009-07-14T17:45:59Z | 14,464,781 | <p>Looks like modules have been shuffled around a bit recently. On IPython 0.13.1 the following works for me</p>
<pre><code>from IPython.core.debugger import Tracer; breakpoint = Tracer()
breakpoint() # <= wherever you want to set the breakpoint
</code></pre>
<p>Though alas, it's all pretty <a href="https://github.com/ipython/ipython/issues/902">worthless in qtconsole</a>.</p>
| 5 | 2013-01-22T17:43:14Z | [
"python",
"shell",
"debugging",
"ipython",
"pdb"
] |
Is it possible to go into ipython from code? | 1,126,930 | <p>For my debugging needs, <code>pdb</code> is pretty good. However, it would be <em>much</em> cooler (and helpful) if I could go into <code>ipython</code>. Is this thing possible?</p>
| 66 | 2009-07-14T17:45:59Z | 15,665,321 | <p>Newer versions of IPython provide an easy mechanism for embedding and nesting IPython sessions into any Python programs. You can follow <a href="http://ipython.org/ipython-doc/dev/interactive/reference.html#embedding-ipython" rel="nofollow">the following recipe</a> to embed IPython sessions:</p>
<pre><code>try:
get_ipython
except NameError:
banner=exit_msg=''
else:
banner = '*** Nested interpreter ***'
exit_msg = '*** Back in main IPython ***'
# First import the embed function
from IPython.frontend.terminal.embed import InteractiveShellEmbed
# Now create the IPython shell instance. Put ipshell() anywhere in your code
# where you want it to open.
ipshell = InteractiveShellEmbed(banner1=banner, exit_msg=exit_msg)
</code></pre>
<p>Then use <code>ipshell()</code> whenever you want to drop into an IPython shell. This will allow you to embed (and even nest) IPython interpreters in your code.</p>
| 4 | 2013-03-27T17:22:12Z | [
"python",
"shell",
"debugging",
"ipython",
"pdb"
] |
Is it possible to go into ipython from code? | 1,126,930 | <p>For my debugging needs, <code>pdb</code> is pretty good. However, it would be <em>much</em> cooler (and helpful) if I could go into <code>ipython</code>. Is this thing possible?</p>
| 66 | 2009-07-14T17:45:59Z | 29,082,893 | <p>I had to google this a couple if times the last few days so adding an answer... sometimes it's nice to be able run a script normally and only drop into ipython/ipdb on errors, without having to put <code>ipdb.set_trace()</code> breakpoints into the code</p>
<pre><code>ipython --pdb -c "%run path/to/my/script.py --with-args here"
</code></pre>
<p>(first <code>pip install ipython</code> and <code>pip install ipdb</code> of course)</p>
| 1 | 2015-03-16T17:11:12Z | [
"python",
"shell",
"debugging",
"ipython",
"pdb"
] |
Do I test a class that does nothing? | 1,127,626 | <p>In my application, I have two classes: a logger that actually logs to the database and a dummy logger that does nothing (used when logging is disabled). Here is the entire DummyLog class:</p>
<pre><code>class DummyLog(object):
def insert_master_log(self, spec_name, file_name, data_source,
environment_name):
pass
def update_master_log(self, inserts, updates, failures, total):
pass
</code></pre>
<p>On one hand, I should probably let this go and not test it since there's not really any code to test. But then, my "test-infected" instinct tells me that this is an excuse and that the simplicity of the class means I should be <em>more</em> willing to test it. I'm just having trouble thinking of what to test.</p>
<p>Any ideas? Or should I just let this go and not write any tests?</p>
| 4 | 2009-07-14T19:59:41Z | 1,127,637 | <p>If you don't test, how will you really know it does nothing?
:)</p>
<p>Sorry - couldn't resist. Seriously - I would test because some day it might do more?</p>
| 12 | 2009-07-14T20:02:42Z | [
"python",
"unit-testing",
"testing",
"logging",
"polymorphism"
] |
Do I test a class that does nothing? | 1,127,626 | <p>In my application, I have two classes: a logger that actually logs to the database and a dummy logger that does nothing (used when logging is disabled). Here is the entire DummyLog class:</p>
<pre><code>class DummyLog(object):
def insert_master_log(self, spec_name, file_name, data_source,
environment_name):
pass
def update_master_log(self, inserts, updates, failures, total):
pass
</code></pre>
<p>On one hand, I should probably let this go and not test it since there's not really any code to test. But then, my "test-infected" instinct tells me that this is an excuse and that the simplicity of the class means I should be <em>more</em> willing to test it. I'm just having trouble thinking of what to test.</p>
<p>Any ideas? Or should I just let this go and not write any tests?</p>
| 4 | 2009-07-14T19:59:41Z | 1,127,638 | <p>If it doesn't do anything then there's nothing to test. If you really want you could verify that it doesn't modify any state. I'm not familiar enough with Python to know if there's an easy way to make verify that your methods don't call any other methods, but you could do that as well if you really want.</p>
| 1 | 2009-07-14T20:02:43Z | [
"python",
"unit-testing",
"testing",
"logging",
"polymorphism"
] |
Do I test a class that does nothing? | 1,127,626 | <p>In my application, I have two classes: a logger that actually logs to the database and a dummy logger that does nothing (used when logging is disabled). Here is the entire DummyLog class:</p>
<pre><code>class DummyLog(object):
def insert_master_log(self, spec_name, file_name, data_source,
environment_name):
pass
def update_master_log(self, inserts, updates, failures, total):
pass
</code></pre>
<p>On one hand, I should probably let this go and not test it since there's not really any code to test. But then, my "test-infected" instinct tells me that this is an excuse and that the simplicity of the class means I should be <em>more</em> willing to test it. I'm just having trouble thinking of what to test.</p>
<p>Any ideas? Or should I just let this go and not write any tests?</p>
| 4 | 2009-07-14T19:59:41Z | 1,127,641 | <p>If it can't fail. There is nothing to test.</p>
<p>Test case results need to contain at least one successful state, and at least one unsuccessful state. If any input into the test results in successful output. Then there is not a test you could create the would ever fail.</p>
| 4 | 2009-07-14T20:03:09Z | [
"python",
"unit-testing",
"testing",
"logging",
"polymorphism"
] |
Do I test a class that does nothing? | 1,127,626 | <p>In my application, I have two classes: a logger that actually logs to the database and a dummy logger that does nothing (used when logging is disabled). Here is the entire DummyLog class:</p>
<pre><code>class DummyLog(object):
def insert_master_log(self, spec_name, file_name, data_source,
environment_name):
pass
def update_master_log(self, inserts, updates, failures, total):
pass
</code></pre>
<p>On one hand, I should probably let this go and not test it since there's not really any code to test. But then, my "test-infected" instinct tells me that this is an excuse and that the simplicity of the class means I should be <em>more</em> willing to test it. I'm just having trouble thinking of what to test.</p>
<p>Any ideas? Or should I just let this go and not write any tests?</p>
| 4 | 2009-07-14T19:59:41Z | 1,127,654 | <p>Depends on your theory.</p>
<p>If you do a test driven type of person, then in order for that code to exist, you had to write the test for it.</p>
<p>If you are thinking of it as, I wrote it, how do I test it, then I think it warrants a test since you are relying on it to do nothing. You need the test to make sure someone doesn't come behind you and delete that code (it may even be you).</p>
| 2 | 2009-07-14T20:04:29Z | [
"python",
"unit-testing",
"testing",
"logging",
"polymorphism"
] |
Do I test a class that does nothing? | 1,127,626 | <p>In my application, I have two classes: a logger that actually logs to the database and a dummy logger that does nothing (used when logging is disabled). Here is the entire DummyLog class:</p>
<pre><code>class DummyLog(object):
def insert_master_log(self, spec_name, file_name, data_source,
environment_name):
pass
def update_master_log(self, inserts, updates, failures, total):
pass
</code></pre>
<p>On one hand, I should probably let this go and not test it since there's not really any code to test. But then, my "test-infected" instinct tells me that this is an excuse and that the simplicity of the class means I should be <em>more</em> willing to test it. I'm just having trouble thinking of what to test.</p>
<p>Any ideas? Or should I just let this go and not write any tests?</p>
| 4 | 2009-07-14T19:59:41Z | 1,127,665 | <p>I don't know Python, but I can think of one test- check that the class actually creates without error. This will at least regression test the class and means it should work in all circumstances.</p>
<p>You never know someone might edit the class in the future and get it to throw an exception or something weird!</p>
<p>Personally though, unless you are aiming for an insanely high level of test coverage I wouldn't bother.</p>
<p>That said would it be catastrophic if this class did throw an exception? I'm guessing that would be one of those bugs that without a unit test would only be caught in the field.</p>
| 1 | 2009-07-14T20:05:36Z | [
"python",
"unit-testing",
"testing",
"logging",
"polymorphism"
] |
Do I test a class that does nothing? | 1,127,626 | <p>In my application, I have two classes: a logger that actually logs to the database and a dummy logger that does nothing (used when logging is disabled). Here is the entire DummyLog class:</p>
<pre><code>class DummyLog(object):
def insert_master_log(self, spec_name, file_name, data_source,
environment_name):
pass
def update_master_log(self, inserts, updates, failures, total):
pass
</code></pre>
<p>On one hand, I should probably let this go and not test it since there's not really any code to test. But then, my "test-infected" instinct tells me that this is an excuse and that the simplicity of the class means I should be <em>more</em> willing to test it. I'm just having trouble thinking of what to test.</p>
<p>Any ideas? Or should I just let this go and not write any tests?</p>
| 4 | 2009-07-14T19:59:41Z | 1,127,674 | <p>Be pragmatic, there is nothing to test here. </p>
| 3 | 2009-07-14T20:06:23Z | [
"python",
"unit-testing",
"testing",
"logging",
"polymorphism"
] |
Do I test a class that does nothing? | 1,127,626 | <p>In my application, I have two classes: a logger that actually logs to the database and a dummy logger that does nothing (used when logging is disabled). Here is the entire DummyLog class:</p>
<pre><code>class DummyLog(object):
def insert_master_log(self, spec_name, file_name, data_source,
environment_name):
pass
def update_master_log(self, inserts, updates, failures, total):
pass
</code></pre>
<p>On one hand, I should probably let this go and not test it since there's not really any code to test. But then, my "test-infected" instinct tells me that this is an excuse and that the simplicity of the class means I should be <em>more</em> willing to test it. I'm just having trouble thinking of what to test.</p>
<p>Any ideas? Or should I just let this go and not write any tests?</p>
| 4 | 2009-07-14T19:59:41Z | 1,127,688 | <p>Argument: You don't base your tests on the reading of the implementation but on the intended behaviour. You test that the darn thing doesn't crash when called.</p>
<p>This case a bit obsessive perhaps, and frankly I maybe I wouldn't bother. But it only take a small increment over these null functions for there to be pitfalls worth testing.</p>
| 1 | 2009-07-14T20:08:16Z | [
"python",
"unit-testing",
"testing",
"logging",
"polymorphism"
] |
Do I test a class that does nothing? | 1,127,626 | <p>In my application, I have two classes: a logger that actually logs to the database and a dummy logger that does nothing (used when logging is disabled). Here is the entire DummyLog class:</p>
<pre><code>class DummyLog(object):
def insert_master_log(self, spec_name, file_name, data_source,
environment_name):
pass
def update_master_log(self, inserts, updates, failures, total):
pass
</code></pre>
<p>On one hand, I should probably let this go and not test it since there's not really any code to test. But then, my "test-infected" instinct tells me that this is an excuse and that the simplicity of the class means I should be <em>more</em> willing to test it. I'm just having trouble thinking of what to test.</p>
<p>Any ideas? Or should I just let this go and not write any tests?</p>
| 4 | 2009-07-14T19:59:41Z | 1,127,699 | <p>You could test the arguments that are passed to it. If this is a dummy object that will get called with a particular set of arguments then modifying that arguments will make it fail. A test like that will ensure that if it does get modified at least no other code break that depends on it.</p>
| 0 | 2009-07-14T20:10:22Z | [
"python",
"unit-testing",
"testing",
"logging",
"polymorphism"
] |
Do I test a class that does nothing? | 1,127,626 | <p>In my application, I have two classes: a logger that actually logs to the database and a dummy logger that does nothing (used when logging is disabled). Here is the entire DummyLog class:</p>
<pre><code>class DummyLog(object):
def insert_master_log(self, spec_name, file_name, data_source,
environment_name):
pass
def update_master_log(self, inserts, updates, failures, total):
pass
</code></pre>
<p>On one hand, I should probably let this go and not test it since there's not really any code to test. But then, my "test-infected" instinct tells me that this is an excuse and that the simplicity of the class means I should be <em>more</em> willing to test it. I'm just having trouble thinking of what to test.</p>
<p>Any ideas? Or should I just let this go and not write any tests?</p>
| 4 | 2009-07-14T19:59:41Z | 1,127,713 | <p>According to the "You Ain't Gonna Need It" rule, you shouldn't write a test when there is nothing to test even if one day it might do something.</p>
<p>How to test that something has done nothing? That's a nice philosophical question :)</p>
| 0 | 2009-07-14T20:12:04Z | [
"python",
"unit-testing",
"testing",
"logging",
"polymorphism"
] |
Do I test a class that does nothing? | 1,127,626 | <p>In my application, I have two classes: a logger that actually logs to the database and a dummy logger that does nothing (used when logging is disabled). Here is the entire DummyLog class:</p>
<pre><code>class DummyLog(object):
def insert_master_log(self, spec_name, file_name, data_source,
environment_name):
pass
def update_master_log(self, inserts, updates, failures, total):
pass
</code></pre>
<p>On one hand, I should probably let this go and not test it since there's not really any code to test. But then, my "test-infected" instinct tells me that this is an excuse and that the simplicity of the class means I should be <em>more</em> willing to test it. I'm just having trouble thinking of what to test.</p>
<p>Any ideas? Or should I just let this go and not write any tests?</p>
| 4 | 2009-07-14T19:59:41Z | 1,127,721 | <p>I think the only useful benefit of a test for such a class is to hopefully catch if someone starts modifying it down the road. Otherwise I wouldn't bother.</p>
| 0 | 2009-07-14T20:12:36Z | [
"python",
"unit-testing",
"testing",
"logging",
"polymorphism"
] |
Do I test a class that does nothing? | 1,127,626 | <p>In my application, I have two classes: a logger that actually logs to the database and a dummy logger that does nothing (used when logging is disabled). Here is the entire DummyLog class:</p>
<pre><code>class DummyLog(object):
def insert_master_log(self, spec_name, file_name, data_source,
environment_name):
pass
def update_master_log(self, inserts, updates, failures, total):
pass
</code></pre>
<p>On one hand, I should probably let this go and not test it since there's not really any code to test. But then, my "test-infected" instinct tells me that this is an excuse and that the simplicity of the class means I should be <em>more</em> willing to test it. I'm just having trouble thinking of what to test.</p>
<p>Any ideas? Or should I just let this go and not write any tests?</p>
| 4 | 2009-07-14T19:59:41Z | 1,127,742 | <p>You at least want it to not break anything when used in place of the actual logger. So reuse the actual logger tests and factor out the assertions that test that it actually logs.</p>
| 0 | 2009-07-14T20:15:58Z | [
"python",
"unit-testing",
"testing",
"logging",
"polymorphism"
] |
Do I test a class that does nothing? | 1,127,626 | <p>In my application, I have two classes: a logger that actually logs to the database and a dummy logger that does nothing (used when logging is disabled). Here is the entire DummyLog class:</p>
<pre><code>class DummyLog(object):
def insert_master_log(self, spec_name, file_name, data_source,
environment_name):
pass
def update_master_log(self, inserts, updates, failures, total):
pass
</code></pre>
<p>On one hand, I should probably let this go and not test it since there's not really any code to test. But then, my "test-infected" instinct tells me that this is an excuse and that the simplicity of the class means I should be <em>more</em> willing to test it. I'm just having trouble thinking of what to test.</p>
<p>Any ideas? Or should I just let this go and not write any tests?</p>
| 4 | 2009-07-14T19:59:41Z | 1,127,762 | <p>If anyone's interested, here's a test I ended up writing:</p>
<pre><code>def test_dummy_loader():
from loader_logs import DummyLog
from copy import copy
dummy = DummyLog()
initial = copy(dummy.__dict__)
dummy.insert_master_log('', '', '', '')
dummy.update_master_log(0, 0, 0, 0)
post = copy(dummy.__dict__)
assert initial == post
</code></pre>
<p>Essentially, it tests that there are no attributes getting set on the object when the two dummy methods get called. Granted, it still doesn't test that the methods truly do nothing, but at least it's <em>something</em>.</p>
| 2 | 2009-07-14T20:18:18Z | [
"python",
"unit-testing",
"testing",
"logging",
"polymorphism"
] |
Do I test a class that does nothing? | 1,127,626 | <p>In my application, I have two classes: a logger that actually logs to the database and a dummy logger that does nothing (used when logging is disabled). Here is the entire DummyLog class:</p>
<pre><code>class DummyLog(object):
def insert_master_log(self, spec_name, file_name, data_source,
environment_name):
pass
def update_master_log(self, inserts, updates, failures, total):
pass
</code></pre>
<p>On one hand, I should probably let this go and not test it since there's not really any code to test. But then, my "test-infected" instinct tells me that this is an excuse and that the simplicity of the class means I should be <em>more</em> willing to test it. I'm just having trouble thinking of what to test.</p>
<p>Any ideas? Or should I just let this go and not write any tests?</p>
| 4 | 2009-07-14T19:59:41Z | 1,127,765 | <p>That DummyLogger is what is called in design pattern a "Null Object".
Subclass your real Logger from that, create some test for the real logger and then use the same test but with the DummyLogger.</p>
<pre><code>class TestLogger(unittest.TestCase):
def setUp(self):
self.logger = RealLogger()
def test_log_debug ..
def test_log_error ..
class TestNullLogger(TestLogger):
def setUp(self):
self.logger = DummyLogger()
</code></pre>
<p>But As many suggested you ain't gonna need it. When it brakes, fix it.</p>
| 1 | 2009-07-14T20:19:31Z | [
"python",
"unit-testing",
"testing",
"logging",
"polymorphism"
] |
Do I test a class that does nothing? | 1,127,626 | <p>In my application, I have two classes: a logger that actually logs to the database and a dummy logger that does nothing (used when logging is disabled). Here is the entire DummyLog class:</p>
<pre><code>class DummyLog(object):
def insert_master_log(self, spec_name, file_name, data_source,
environment_name):
pass
def update_master_log(self, inserts, updates, failures, total):
pass
</code></pre>
<p>On one hand, I should probably let this go and not test it since there's not really any code to test. But then, my "test-infected" instinct tells me that this is an excuse and that the simplicity of the class means I should be <em>more</em> willing to test it. I'm just having trouble thinking of what to test.</p>
<p>Any ideas? Or should I just let this go and not write any tests?</p>
| 4 | 2009-07-14T19:59:41Z | 1,127,962 | <p>Of course you can test a class that doesn't do anything. You test that it does, in fact, not do anything.</p>
<p>In practice, that means:</p>
<ul>
<li>it exists and can be instantiated;</li>
<li>it doesn't throw an exception when used; call every method and simply assert that they succeed. This also doubles as checking that the class does, in fact, define every method that it's expected to.</li>
</ul>
<p>Don't run this test on DummyLog; use it as a generic test and run it on <em>all</em> loggers. When you add another method to the real Log class a year from now and forget to add it to DummyLog, the test will notice. (As long as you do remember to add a general test for the method, of course, but hopefully adding the test should be habitual, even if you forget about related classes.)</p>
| 4 | 2009-07-14T20:51:29Z | [
"python",
"unit-testing",
"testing",
"logging",
"polymorphism"
] |
Do I test a class that does nothing? | 1,127,626 | <p>In my application, I have two classes: a logger that actually logs to the database and a dummy logger that does nothing (used when logging is disabled). Here is the entire DummyLog class:</p>
<pre><code>class DummyLog(object):
def insert_master_log(self, spec_name, file_name, data_source,
environment_name):
pass
def update_master_log(self, inserts, updates, failures, total):
pass
</code></pre>
<p>On one hand, I should probably let this go and not test it since there's not really any code to test. But then, my "test-infected" instinct tells me that this is an excuse and that the simplicity of the class means I should be <em>more</em> willing to test it. I'm just having trouble thinking of what to test.</p>
<p>Any ideas? Or should I just let this go and not write any tests?</p>
| 4 | 2009-07-14T19:59:41Z | 1,133,575 | <p>It obviously does something or you wouldn't have written it.</p>
<p>I'm going to guess its meant to mirror the interface of your real logging class. So test that it has the same interface, that it takes the same arguments. You're likely to change your logging while forgetting to update the dummy. If that seems redundant IT IS because they probably should just inherit from the same interface.</p>
<p>And then yes, you can test that it doesn't log anything. It might seem silly but its amazing what maintenance programmers will do.</p>
| 2 | 2009-07-15T19:50:23Z | [
"python",
"unit-testing",
"testing",
"logging",
"polymorphism"
] |
Special chars in Python | 1,127,786 | <p>i have to use special chars in my python-application.
For example: Æ
I have information like this:</p>
<pre><code>U+0183 LATIN SMALL LETTER B WITH TOPBAR
General Character Properties
In Unicode since: 1.1
Unicode category: Letter, Lowercase
Various Useful Representations
UTF-8: 0xC6 0x83
UTF-16: 0x0183
C octal escaped UTF-8: \306\203
XML decimal entity: &# 387;
</code></pre>
<p>But when i just pust symbols into python-script i get an error:</p>
<blockquote>
<p>Non-ASCII character '\xc8' ...
How can i use it in strings for my application?</p>
</blockquote>
| 2 | 2009-07-14T20:21:58Z | 1,127,804 | <p>You should tell the interpreter which encoding you're using, because apparently on your system it defaults to ascii. See <a href="http://www.python.org/dev/peps/pep-0263/" rel="nofollow">PEP 263</a>. In your case, place the following at the top of your file:</p>
<pre><code># -*- coding: utf-8 -*-
</code></pre>
<p>Note that you don't have to write <em>exactly</em> that; PEP 263 allows more freedom, to accommodate several popular editors which use slightly different conventions for the same purpose. Additionally, this string may also be placed on the second line, e.g. when the first is used for the <a href="http://en.wikipedia.org/wiki/Shebang%5F%28Unix%29" rel="nofollow">shebang</a>.</p>
| 11 | 2009-07-14T20:24:50Z | [
"python",
"chars"
] |
Special chars in Python | 1,127,786 | <p>i have to use special chars in my python-application.
For example: Æ
I have information like this:</p>
<pre><code>U+0183 LATIN SMALL LETTER B WITH TOPBAR
General Character Properties
In Unicode since: 1.1
Unicode category: Letter, Lowercase
Various Useful Representations
UTF-8: 0xC6 0x83
UTF-16: 0x0183
C octal escaped UTF-8: \306\203
XML decimal entity: &# 387;
</code></pre>
<p>But when i just pust symbols into python-script i get an error:</p>
<blockquote>
<p>Non-ASCII character '\xc8' ...
How can i use it in strings for my application?</p>
</blockquote>
| 2 | 2009-07-14T20:21:58Z | 1,127,807 | <p>Do you store the Python file as UTF-8? Does your editor support UTF-8? Are you using unicode strings like so?</p>
<pre><code>foo = u'ÆÆÆÆÆ'
</code></pre>
| 1 | 2009-07-14T20:25:25Z | [
"python",
"chars"
] |
Special chars in Python | 1,127,786 | <p>i have to use special chars in my python-application.
For example: Æ
I have information like this:</p>
<pre><code>U+0183 LATIN SMALL LETTER B WITH TOPBAR
General Character Properties
In Unicode since: 1.1
Unicode category: Letter, Lowercase
Various Useful Representations
UTF-8: 0xC6 0x83
UTF-16: 0x0183
C octal escaped UTF-8: \306\203
XML decimal entity: &# 387;
</code></pre>
<p>But when i just pust symbols into python-script i get an error:</p>
<blockquote>
<p>Non-ASCII character '\xc8' ...
How can i use it in strings for my application?</p>
</blockquote>
| 2 | 2009-07-14T20:21:58Z | 1,127,810 | <p>Declare Unicode strings.</p>
<p>somestring = u'æøå'</p>
| 0 | 2009-07-14T20:25:53Z | [
"python",
"chars"
] |
Special chars in Python | 1,127,786 | <p>i have to use special chars in my python-application.
For example: Æ
I have information like this:</p>
<pre><code>U+0183 LATIN SMALL LETTER B WITH TOPBAR
General Character Properties
In Unicode since: 1.1
Unicode category: Letter, Lowercase
Various Useful Representations
UTF-8: 0xC6 0x83
UTF-16: 0x0183
C octal escaped UTF-8: \306\203
XML decimal entity: &# 387;
</code></pre>
<p>But when i just pust symbols into python-script i get an error:</p>
<blockquote>
<p>Non-ASCII character '\xc8' ...
How can i use it in strings for my application?</p>
</blockquote>
| 2 | 2009-07-14T20:21:58Z | 1,127,815 | <p><a href="http://docs.python.org/tutorial/interpreter.html#source-code-encoding" rel="nofollow">http://docs.python.org/tutorial/interpreter.html#source-code-encoding</a></p>
| 3 | 2009-07-14T20:26:41Z | [
"python",
"chars"
] |
Special chars in Python | 1,127,786 | <p>i have to use special chars in my python-application.
For example: Æ
I have information like this:</p>
<pre><code>U+0183 LATIN SMALL LETTER B WITH TOPBAR
General Character Properties
In Unicode since: 1.1
Unicode category: Letter, Lowercase
Various Useful Representations
UTF-8: 0xC6 0x83
UTF-16: 0x0183
C octal escaped UTF-8: \306\203
XML decimal entity: &# 387;
</code></pre>
<p>But when i just pust symbols into python-script i get an error:</p>
<blockquote>
<p>Non-ASCII character '\xc8' ...
How can i use it in strings for my application?</p>
</blockquote>
| 2 | 2009-07-14T20:21:58Z | 1,127,820 | <p>In python it should be</p>
<pre><code>u"\u0183"
</code></pre>
<p>The u before the String start indicates that the String contains Unicode characters.</p>
<p>See here for reference: </p>
<p><a href="http://www.fileformat.info/info/unicode/char/0183/index.htm" rel="nofollow">http://www.fileformat.info/info/unicode/char/0183/index.htm</a>
<a href="http://docs.python.org/tutorial/introduction.html#unicode-strings" rel="nofollow">http://docs.python.org/tutorial/introduction.html#unicode-strings</a></p>
| 0 | 2009-07-14T20:27:15Z | [
"python",
"chars"
] |
Special chars in Python | 1,127,786 | <p>i have to use special chars in my python-application.
For example: Æ
I have information like this:</p>
<pre><code>U+0183 LATIN SMALL LETTER B WITH TOPBAR
General Character Properties
In Unicode since: 1.1
Unicode category: Letter, Lowercase
Various Useful Representations
UTF-8: 0xC6 0x83
UTF-16: 0x0183
C octal escaped UTF-8: \306\203
XML decimal entity: &# 387;
</code></pre>
<p>But when i just pust symbols into python-script i get an error:</p>
<blockquote>
<p>Non-ASCII character '\xc8' ...
How can i use it in strings for my application?</p>
</blockquote>
| 2 | 2009-07-14T20:21:58Z | 1,127,970 | <p>While the answers so fare are all correct, I thought I'd provide a more complete treatment:</p>
<p>The simplest way to represent a non-ASCII character in a script literal is to use the u prefix and u or U escapes, like so:</p>
<pre><code>print u"Look \u0411\u043e\u0440\u0438\u0441, a G-clef: \U0001d11e"
</code></pre>
<p>This illustrates:</p>
<ol>
<li>using the u prefix to make sure the string is a <code>unicode</code> object</li>
<li>using the u escape for characters in the basic multi-lingual plane (U+FFFD and below)</li>
<li>using the U escape for characters in other planes (U+10000 and above)</li>
<li>that Æ (U+0182 LATIN CAPITAL LETTER B WITH TOPBAR) and Ð (U+0411 CYRILLIC CAPTIAL LETTER BE) just one example of many confusingly similar Unicode codepoints</li>
</ol>
<p>The default script encoding for Python that works everywhere is ASCII. As such, you'd have to use the above escapes to encode literals of non-ASCII characters. You can inform the Python interpreter of the encoding of your script with a line like:</p>
<pre><code># -*- coding: utf-8 -*-
</code></pre>
<p>This only changes the encoding of your script. But then you could write:</p>
<pre><code>print u"Look ÐоÑиÑ, a G-clef: "
</code></pre>
<p>Note that you still have to use the u prefix to obtain a <code>unicode</code> object, not a <code>str</code> object.</p>
<p>Lastly, it <em>is</em> possible to change the default encoding used for <code>str</code>... but this not recommended, as it is a global change and may not play well with other python code.</p>
| 3 | 2009-07-14T20:52:26Z | [
"python",
"chars"
] |
Python object has no referrers but still accessible via a weakref? | 1,127,836 | <p>Should it be possible for gc.get_referrers(obj) to return an empty list for an object, but the object still be accessible through a weak reference?</p>
<p>If so how would I start trying to identify the cause for this object not being garbage collected?</p>
<p>Edit: I'm not sure exactly how a code sample would help in this case - there's obviously a strong reference somewhere, but I'll be damned if I can find it. I was of the impression that all strong references to an object would be identified by get_referrers().</p>
<p><strong>Edit: Solved</strong>. I found the variable with a strong reference - It was inside the game event loop but wasn't a class variable so get_referrers wasn't picking it up.</p>
| 3 | 2009-07-14T20:29:34Z | 1,127,854 | <p>Yes: <a href="http://docs.python.org/library/weakref.html" rel="nofollow">http://docs.python.org/library/weakref.html</a></p>
<p>A weak reference won't be keeping the object alive.</p>
<p>The get_referrers() function will only locate those containers which support garbage collection; extension types which do refer to other objects but do not support garbage collection will not be found.</p>
<p>What makes you think the object isn't getting collected? Also, have you tried gc.collect()?</p>
| 1 | 2009-07-14T20:32:51Z | [
"python",
"garbage-collection",
"cpython"
] |
Python object has no referrers but still accessible via a weakref? | 1,127,836 | <p>Should it be possible for gc.get_referrers(obj) to return an empty list for an object, but the object still be accessible through a weak reference?</p>
<p>If so how would I start trying to identify the cause for this object not being garbage collected?</p>
<p>Edit: I'm not sure exactly how a code sample would help in this case - there's obviously a strong reference somewhere, but I'll be damned if I can find it. I was of the impression that all strong references to an object would be identified by get_referrers().</p>
<p><strong>Edit: Solved</strong>. I found the variable with a strong reference - It was inside the game event loop but wasn't a class variable so get_referrers wasn't picking it up.</p>
| 3 | 2009-07-14T20:29:34Z | 1,127,890 | <p>As <a href="http://stackoverflow.com/questions/1127836/python-object-has-no-referrers-but-still-accessible-via-a-weakref/1127854#1127854">Christopher says</a>, a weak reference does not count into object refcount, and therefore is not able to keep Python from deleting an object.</p>
<p>However, Python's garbage collector does not delete objects that are in a circular reference and have a <code>__del__</code> method defined.<br />
You can check (and fix) such situation by using <a href="http://docs.python.org/library/gc.html#gc.garbage" rel="nofollow">gc.garbage</a>.</p>
| 0 | 2009-07-14T20:38:33Z | [
"python",
"garbage-collection",
"cpython"
] |
Python object has no referrers but still accessible via a weakref? | 1,127,836 | <p>Should it be possible for gc.get_referrers(obj) to return an empty list for an object, but the object still be accessible through a weak reference?</p>
<p>If so how would I start trying to identify the cause for this object not being garbage collected?</p>
<p>Edit: I'm not sure exactly how a code sample would help in this case - there's obviously a strong reference somewhere, but I'll be damned if I can find it. I was of the impression that all strong references to an object would be identified by get_referrers().</p>
<p><strong>Edit: Solved</strong>. I found the variable with a strong reference - It was inside the game event loop but wasn't a class variable so get_referrers wasn't picking it up.</p>
| 3 | 2009-07-14T20:29:34Z | 1,128,036 | <p>If you do have a strong reference to the object, use gc.get_referrers(obj) to find it.</p>
<p>This can help if you have a leak and don't know what's leaking:</p>
<p><a href="http://mg.pov.lt/objgraph.py" rel="nofollow">http://mg.pov.lt/objgraph.py</a>
<a href="http://mg.pov.lt/blog/hunting-python-memleaks" rel="nofollow">http://mg.pov.lt/blog/hunting-python-memleaks</a>
<a href="http://mg.pov.lt/blog/python-object-graphs.html" rel="nofollow">http://mg.pov.lt/blog/python-object-graphs.html</a></p>
<p>It's a thin wrapper around the inspect module; it can help a lot if you have hard-to-track unwanted references. For just tracking down a reference, though, gc.get_referrers is probably all you need.</p>
| 0 | 2009-07-14T21:06:00Z | [
"python",
"garbage-collection",
"cpython"
] |
Python object has no referrers but still accessible via a weakref? | 1,127,836 | <p>Should it be possible for gc.get_referrers(obj) to return an empty list for an object, but the object still be accessible through a weak reference?</p>
<p>If so how would I start trying to identify the cause for this object not being garbage collected?</p>
<p>Edit: I'm not sure exactly how a code sample would help in this case - there's obviously a strong reference somewhere, but I'll be damned if I can find it. I was of the impression that all strong references to an object would be identified by get_referrers().</p>
<p><strong>Edit: Solved</strong>. I found the variable with a strong reference - It was inside the game event loop but wasn't a class variable so get_referrers wasn't picking it up.</p>
| 3 | 2009-07-14T20:29:34Z | 1,128,216 | <p>It might also be the case that a reference was leaked by a buggy C extension, IMHO you will not see the referer, yet still the refcount does not go down to 0. You might want to check the return value of <code>sys.getrefcount</code>. </p>
| 1 | 2009-07-14T21:37:41Z | [
"python",
"garbage-collection",
"cpython"
] |
Python object has no referrers but still accessible via a weakref? | 1,127,836 | <p>Should it be possible for gc.get_referrers(obj) to return an empty list for an object, but the object still be accessible through a weak reference?</p>
<p>If so how would I start trying to identify the cause for this object not being garbage collected?</p>
<p>Edit: I'm not sure exactly how a code sample would help in this case - there's obviously a strong reference somewhere, but I'll be damned if I can find it. I was of the impression that all strong references to an object would be identified by get_referrers().</p>
<p><strong>Edit: Solved</strong>. I found the variable with a strong reference - It was inside the game event loop but wasn't a class variable so get_referrers wasn't picking it up.</p>
| 3 | 2009-07-14T20:29:34Z | 4,093,658 | <p>I am glad you have found your problem, unrelated to the initial question. Nonetheless, I have a different take on the answer for posterity, in case others have the problem.</p>
<p>It IS legal for the object to have no referrers and yet not be garbage collected.</p>
<p>From the Python 2.7 manual: "An implementation is allowed to postpone garbage collection or omit it altogether â it is a matter of implementation quality how garbage collection is implemented, as long as no objects are collected that are still reachable."</p>
<p>The NO-OP garbage collector is legal.</p>
<p>The discussions about generational and reference-counting garbage collectors are referring to a particular CPython implementation (as tagged in the question)</p>
| 1 | 2010-11-04T03:26:36Z | [
"python",
"garbage-collection",
"cpython"
] |
wxPython, how do I fire events? | 1,128,074 | <p>I am making my own button class, subclass of a panel where I draw with a DC, and I need to fire wx.EVT_BUTTON when my custom button is pressed. How do I do it?</p>
| 2 | 2009-07-14T21:12:58Z | 1,128,120 | <p>Create a wx.CommandEvent object, call its setters to set the appropriate attributes, and pass it to wx.PostEvent.</p>
<p><a href="http://docs.wxwidgets.org/stable/wx%5Fwxcommandevent.html#wxcommandeventctor">http://docs.wxwidgets.org/stable/wx_wxcommandevent.html#wxcommandeventctor</a></p>
<p><a href="http://docs.wxwidgets.org/stable/wx%5Fmiscellany.html#wxpostevent">http://docs.wxwidgets.org/stable/wx_miscellany.html#wxpostevent</a></p>
<p>This is a duplicate, there is more information here on constructing these objects:</p>
<p><a href="http://stackoverflow.com/questions/747781/wxpython-calling-an-event-manually/747805">http://stackoverflow.com/questions/747781/wxpython-calling-an-event-manually/747805</a></p>
| 6 | 2009-07-14T21:20:39Z | [
"python",
"events",
"wxpython"
] |
wxPython, how do I fire events? | 1,128,074 | <p>I am making my own button class, subclass of a panel where I draw with a DC, and I need to fire wx.EVT_BUTTON when my custom button is pressed. How do I do it?</p>
| 2 | 2009-07-14T21:12:58Z | 1,128,992 | <p>The Wiki is pretty nice for reference. Andrea Gavana has a pretty complete recipe for building your own <a href="http://wiki.wxpython.org/CreatingCustomControls">custom controls</a>. The following is taken directly from there and extends what <a href="http://stackoverflow.com/questions/1128074/wxpython-how-do-i-fire-events/1128120#1128120">FogleBird answered with</a> (note self is referring to a subclass of wx.PyControl):</p>
<pre><code>def SendCheckBoxEvent(self):
""" Actually sends the wx.wxEVT_COMMAND_CHECKBOX_CLICKED event. """
# This part of the code may be reduced to a 3-liner code
# but it is kept for better understanding the event handling.
# If you can, however, avoid code duplication; in this case,
# I could have done:
#
# self._checked = not self.IsChecked()
# checkEvent = wx.CommandEvent(wx.wxEVT_COMMAND_CHECKBOX_CLICKED,
# self.GetId())
# checkEvent.SetInt(int(self._checked))
if self.IsChecked():
# We were checked, so we should become unchecked
self._checked = False
# Fire a wx.CommandEvent: this generates a
# wx.wxEVT_COMMAND_CHECKBOX_CLICKED event that can be caught by the
# developer by doing something like:
# MyCheckBox.Bind(wx.EVT_CHECKBOX, self.OnCheckBox)
checkEvent = wx.CommandEvent(wx.wxEVT_COMMAND_CHECKBOX_CLICKED,
self.GetId())
# Set the integer event value to 0 (we are switching to unchecked state)
checkEvent.SetInt(0)
else:
# We were unchecked, so we should become checked
self._checked = True
checkEvent = wx.CommandEvent(wx.wxEVT_COMMAND_CHECKBOX_CLICKED,
self.GetId())
# Set the integer event value to 1 (we are switching to checked state)
checkEvent.SetInt(1)
# Set the originating object for the event (ourselves)
checkEvent.SetEventObject(self)
# Watch for a possible listener of this event that will catch it and
# eventually process it
self.GetEventHandler().ProcessEvent(checkEvent)
# Refresh ourselves: the bitmap has changed
self.Refresh()
</code></pre>
| 9 | 2009-07-15T01:48:20Z | [
"python",
"events",
"wxpython"
] |
How can I obtain the full AST in Python? | 1,128,234 | <p>I like the options offered by the <b>_ast</b> module, it's really powerful. Is there a way of getting the full AST from it? </p>
<p>For example, if I get the AST of the following code :</p>
<pre><code>
import os
os.listdir(".")
</code></pre>
<p>by using :</p>
<pre><code>
ast = compile(source_string,"<string>","exec",_ast.PyCF_ONLY_AST)
</code></pre>
<p>the body of the <b>ast</b> object will have two elements, an <b>import</b> object, and a <b>expr</b> object. However, I'd like to go further, and obtain the AST of <b>import</b> and <b>listdir</b>, in other words, I'd like to make <b>_ast</b> descend to the lowest level possible. </p>
<p>I think it's logical that this sort of thing should be possible. The question is <b>how</b>?</p>
<p>EDIT: by the lowest level possible, I didn't mean accesing what's "visible". I'd like to get the AST for the implementation of <b>listdir</b> as well: like <b>stat</b> and other function calls that may be executed for it.</p>
| 4 | 2009-07-14T21:43:02Z | 1,128,260 | <pre><code>py> ast._fields
('body',)
py> ast.body
[<_ast.Import object at 0xb7978e8c>, <_ast.Expr object at 0xb7978f0c>]
py> ast.body[1]
<_ast.Expr object at 0xb7978f0c>
py> ast.body[1]._fields
('value',)
py> ast.body[1].value
<_ast.Call object at 0xb7978f2c>
py> ast.body[1].value._fields
('func', 'args', 'keywords', 'starargs', 'kwargs')
py> ast.body[1].value.args
[<_ast.Str object at 0xb7978fac>]
py> ast.body[1].value.args[0]
<_ast.Str object at 0xb7978fac>
py> ast.body[1].value.args[0]._fields
('s',)
py> ast.body[1].value.args[0].s
'.'
</code></pre>
<p>HTH</p>
| 5 | 2009-07-14T21:49:38Z | [
"python",
"abstract-syntax-tree"
] |
How can I obtain the full AST in Python? | 1,128,234 | <p>I like the options offered by the <b>_ast</b> module, it's really powerful. Is there a way of getting the full AST from it? </p>
<p>For example, if I get the AST of the following code :</p>
<pre><code>
import os
os.listdir(".")
</code></pre>
<p>by using :</p>
<pre><code>
ast = compile(source_string,"<string>","exec",_ast.PyCF_ONLY_AST)
</code></pre>
<p>the body of the <b>ast</b> object will have two elements, an <b>import</b> object, and a <b>expr</b> object. However, I'd like to go further, and obtain the AST of <b>import</b> and <b>listdir</b>, in other words, I'd like to make <b>_ast</b> descend to the lowest level possible. </p>
<p>I think it's logical that this sort of thing should be possible. The question is <b>how</b>?</p>
<p>EDIT: by the lowest level possible, I didn't mean accesing what's "visible". I'd like to get the AST for the implementation of <b>listdir</b> as well: like <b>stat</b> and other function calls that may be executed for it.</p>
| 4 | 2009-07-14T21:43:02Z | 1,128,283 | <p>You do get the whole tree this way -- all the way to the bottom -- but, it IS held as a tree, exactly... so at each level to get the children you have to explicitly visit the needed attributes. For example (i'm naming the <code>compile</code> result <code>cf</code> rather than <code>ast</code> because that would hide the standard library ast module -- I assume you only have 2.5 rather than 2.6, which is why you're using the lower-level <code>_ast</code> module instead?)...:</p>
<pre><code>>>> cf.body[0].names[0].name
'os'
</code></pre>
<p>This is what tells you that the import statement is importing name <code>os</code> (and that one only because 1 is the lengths of the <code>.names</code> field of <code>.body[0]</code> which is the <code>import</code>).</p>
<p>In Python 2.6's module <code>ast</code> you also get helpers to let you navigate more easily on a tree (e.g. by the <code>Visitor</code> design pattern) -- but the whole tree is there in either 2.5 (with <code>_ast</code>) or 2.5 (with <code>ast</code>), and in either case is represented in exactly the same way.</p>
<p>To handily visit all the nodes in the tree, in 2.6, use module ast (no leading underscore) and subclass <code>ast.NodeVisitor</code> as appropriate (or equivalently use <code>ast.iter_child_nodes</code> recursively and <code>ast.iter_fields</code> as needed). Of course these helpers can be implemented in pure Python on top of <code>_ast</code> if you're stuck in 2.5 for some reason.</p>
| 8 | 2009-07-14T21:55:19Z | [
"python",
"abstract-syntax-tree"
] |
To understand Typeset for PythonPath | 1,128,366 | <p>One recommends me the following code apparently only in .zshrc without explaining its purpose clearly.</p>
<pre><code>typeset -U PYTHONPATH
</code></pre>
<p>I am interested in how you can use the code in .bashrc. My Bash goes upset about the command.</p>
<p><strong>How can you use the command in Bash?</strong></p>
| 0 | 2009-07-14T22:16:22Z | 1,128,392 | <p>That zsh command is useful because <strong>zsh</strong> can treat the environment variable PYTHONPATH as an actual array of paths. The <code>-U</code> argument to <code>typeset</code> says, then when representing the array in the environment value passed to the program (Python, in this case), only include the first instance of each unique value.</p>
<p>In <strong>bash</strong>, since array variables aren't exported, PYTHONPATH would be just a normal string variable, containing paths separated by colons. Hence, there is no need to tell <strong>bash</strong> to use only unique values. </p>
| 3 | 2009-07-14T22:25:06Z | [
"python",
"bash",
"path",
"zsh",
"typeset"
] |
Need some help with python string / slicing operations | 1,128,431 | <p>This is a very newbie question and i will probably get downvoted for it, but i quite honestly couldn't find the answer after at least an hour googling. I learned how to slice strings based on "exact locations" where you have to know exactly where the word ends. But i did not find any article that explained how do it on "non static" strings that could change.</p>
<p>Also i do not want to use string.split() in this case as its a little overkill for what i need.</p>
<p>I basically have a string like this:</p>
<pre><code>myString = "!save python Python is a high-level object oriented language created by Guido van Rossum."
# the format is !save [singleword] [definition]
</code></pre>
<p>i need to "slice" this string but i cant figure out a proper way to do it.</p>
<p>i need to save a to variable the title (python in this case) and the definition of this string. Somethig like:</p>
<pre><code>title = myString[1]
definition = myString[everything after string[1]
</code></pre>
<p>I'm not exactly sure how to do this when you have a dynamic string where you dont know where each word ends.</p>
<p>I would greatly appreciate some pointers on what functions/methods should i read on to archieve this. Thank you in advance.</p>
| 2 | 2009-07-14T22:31:09Z | 1,128,447 | <p>If you have spaces between your command, title, and definition you could:</p>
<pre><code>wordList = myString.split()
cmd = wordList[0] # !save
title = wordList[1] # python
definition = ' '.join(wordList[2:]) # Python is a high-level object oriented language created by Guido van Rossum.
</code></pre>
<p>If you really would rather not use split you could use regular expressions:</p>
<pre><code>import re
m = re.match('(/S+)/s*(/S+)/s*(.*)')
cmd = m.group(1)
title = m.group(2)
definition = m.group(3)
</code></pre>
| 2 | 2009-07-14T22:34:32Z | [
"python",
"string",
"slice"
] |
Need some help with python string / slicing operations | 1,128,431 | <p>This is a very newbie question and i will probably get downvoted for it, but i quite honestly couldn't find the answer after at least an hour googling. I learned how to slice strings based on "exact locations" where you have to know exactly where the word ends. But i did not find any article that explained how do it on "non static" strings that could change.</p>
<p>Also i do not want to use string.split() in this case as its a little overkill for what i need.</p>
<p>I basically have a string like this:</p>
<pre><code>myString = "!save python Python is a high-level object oriented language created by Guido van Rossum."
# the format is !save [singleword] [definition]
</code></pre>
<p>i need to "slice" this string but i cant figure out a proper way to do it.</p>
<p>i need to save a to variable the title (python in this case) and the definition of this string. Somethig like:</p>
<pre><code>title = myString[1]
definition = myString[everything after string[1]
</code></pre>
<p>I'm not exactly sure how to do this when you have a dynamic string where you dont know where each word ends.</p>
<p>I would greatly appreciate some pointers on what functions/methods should i read on to archieve this. Thank you in advance.</p>
| 2 | 2009-07-14T22:31:09Z | 1,128,452 | <p>Why is split overkill?</p>
<pre><code>verb, title, definition = myString.split (' ', 2)
</code></pre>
| 12 | 2009-07-14T22:35:41Z | [
"python",
"string",
"slice"
] |
Need some help with python string / slicing operations | 1,128,431 | <p>This is a very newbie question and i will probably get downvoted for it, but i quite honestly couldn't find the answer after at least an hour googling. I learned how to slice strings based on "exact locations" where you have to know exactly where the word ends. But i did not find any article that explained how do it on "non static" strings that could change.</p>
<p>Also i do not want to use string.split() in this case as its a little overkill for what i need.</p>
<p>I basically have a string like this:</p>
<pre><code>myString = "!save python Python is a high-level object oriented language created by Guido van Rossum."
# the format is !save [singleword] [definition]
</code></pre>
<p>i need to "slice" this string but i cant figure out a proper way to do it.</p>
<p>i need to save a to variable the title (python in this case) and the definition of this string. Somethig like:</p>
<pre><code>title = myString[1]
definition = myString[everything after string[1]
</code></pre>
<p>I'm not exactly sure how to do this when you have a dynamic string where you dont know where each word ends.</p>
<p>I would greatly appreciate some pointers on what functions/methods should i read on to archieve this. Thank you in advance.</p>
| 2 | 2009-07-14T22:31:09Z | 1,128,781 | <p>The selected answer (after PEP8ing):</p>
<pre><code>verb, title, definition = my_string.split(' ', 2)
</code></pre>
<p>splits on a single space. It's likely a better choice to split on runs of whitespace, just in case there are tabs or multiple spaces on either side of the title:</p>
<pre><code>verb, title, definition = my_string.split(None, 2)
</code></pre>
<p>Also consider normalising the whitespace in the definition:</p>
<pre><code>definition = ' '.join(definition.split())
</code></pre>
| 2 | 2009-07-15T00:26:02Z | [
"python",
"string",
"slice"
] |
How Do I Use A Decimal Number In A Django URL Pattern? | 1,128,693 | <p>I'd like to use a number with a decimal point in a Django URL pattern but I'm not sure whether it's actually possible (I'm not a regex expert).</p>
<p>Here's what I want to use for URLs:</p>
<pre><code>/item/value/0.01
/item/value/0.05
</code></pre>
<p>Those URLs would show items valued at $0.01 or $0.05. Sure, I could take the easy way out and pass the value in cents so it would be /item/value/1, but I'd like to receive the argument in my view as a decimal data type rather than as an integer (and I may have to deal with fractions of a cent at some point). Is it possible to write a regex in a Django URL pattern that will handle this?</p>
| 5 | 2009-07-14T23:45:49Z | 1,128,700 | <p>I don't know about Django specifically, but this should match the URL:</p>
<pre><code>r"^/item/value/(\d+\.\d+)$"
</code></pre>
| 13 | 2009-07-14T23:49:23Z | [
"python",
"regex",
"django",
"django-urls"
] |
How Do I Use A Decimal Number In A Django URL Pattern? | 1,128,693 | <p>I'd like to use a number with a decimal point in a Django URL pattern but I'm not sure whether it's actually possible (I'm not a regex expert).</p>
<p>Here's what I want to use for URLs:</p>
<pre><code>/item/value/0.01
/item/value/0.05
</code></pre>
<p>Those URLs would show items valued at $0.01 or $0.05. Sure, I could take the easy way out and pass the value in cents so it would be /item/value/1, but I'd like to receive the argument in my view as a decimal data type rather than as an integer (and I may have to deal with fractions of a cent at some point). Is it possible to write a regex in a Django URL pattern that will handle this?</p>
| 5 | 2009-07-14T23:45:49Z | 1,128,740 | <p>It can be something like</p>
<pre><code>urlpatterns = patterns('',
(r'^item/value/(?P<value>\d+\.\d{2})/$', 'myapp.views.byvalue'),
... more urls
)
</code></pre>
<p>url should not start with slash.</p>
<p>in views you can have function:</p>
<pre><code>def byvalue(request,value='0.99'):
try:
value = float(value)
except:
...
</code></pre>
| 12 | 2009-07-15T00:08:58Z | [
"python",
"regex",
"django",
"django-urls"
] |
How Do I Use A Decimal Number In A Django URL Pattern? | 1,128,693 | <p>I'd like to use a number with a decimal point in a Django URL pattern but I'm not sure whether it's actually possible (I'm not a regex expert).</p>
<p>Here's what I want to use for URLs:</p>
<pre><code>/item/value/0.01
/item/value/0.05
</code></pre>
<p>Those URLs would show items valued at $0.01 or $0.05. Sure, I could take the easy way out and pass the value in cents so it would be /item/value/1, but I'd like to receive the argument in my view as a decimal data type rather than as an integer (and I may have to deal with fractions of a cent at some point). Is it possible to write a regex in a Django URL pattern that will handle this?</p>
| 5 | 2009-07-14T23:45:49Z | 1,129,903 | <p>If the values to be accepted are only $0.01 or $0.05, the harto's pattern may be specified like this:</p>
<pre><code>r"^/item/value/(\d\.\d{2})$"
</code></pre>
| 3 | 2009-07-15T07:25:44Z | [
"python",
"regex",
"django",
"django-urls"
] |
How to split two nested lists and combine the parts to create two new nested lists | 1,128,924 | <p>I'm trying to code a simple genetic programming utility in python. But right now I'm stuck at the crossover/mate function for my trees. The trees are built by nested lists and look something like this:</p>
<pre><code># f = internal node (a function), c = leaf node (a constant)
tree1 = [f, [f, [f, c, c], [f, c, c]], [f, [f, c, c], [f, c, c]]]
tree2 = [f, [f, [f, c, c], c], [f, [f, c, c], c]]
</code></pre>
<p>I want to randomly select a point in each tree to split at and then I want one part from each tree to be combined into a new tree. There is also a max depth that shouldn't be exceeded so the selects can't really take place anywhere in the tree as it might create a too large tree. Below is an example on how it should work:</p>
<pre><code># f:n, where n is the number of arguments the function take
# + split here
tree1 = [f:2, [f:3, a, a, a], a]
# + split here
tree2 = [f:2, [f:2, a, a], [f:1, a]
tree_child1 = [f:2, [f:1, a], a]
tree_child2 = [f:2, [f:2, a, a], [f:3, a, a, a]]
</code></pre>
<p>I have no idea (at the moment) on how to solve this. Any tips or solutions are more than welcome!</p>
<p>(Added my parse function as it might help someone to understand the structure better.)</p>
<pre><code># My recursive code to parse the tree.
def parse(self, node=None):
if not node:
node = self.root
if isinstance(node, list):
function = node[0]
res = []
for child in node[1:function.arity+1]:
res.append(self.parse(child))
value = function.parse(*res) # function
else:
value = node.parse() # constant
return value
</code></pre>
| 4 | 2009-07-15T01:21:50Z | 1,128,963 | <p>If you store in each internal node a count of the children in each branch, then you could pick a split point by generating a random number from 0 to 1+total children. If the answer is 1, split at that node, otherwise use the number to figure out which subtree to descend to, and repeat the process.</p>
| 0 | 2009-07-15T01:37:05Z | [
"python",
"list",
"genetic-programming"
] |
How to split two nested lists and combine the parts to create two new nested lists | 1,128,924 | <p>I'm trying to code a simple genetic programming utility in python. But right now I'm stuck at the crossover/mate function for my trees. The trees are built by nested lists and look something like this:</p>
<pre><code># f = internal node (a function), c = leaf node (a constant)
tree1 = [f, [f, [f, c, c], [f, c, c]], [f, [f, c, c], [f, c, c]]]
tree2 = [f, [f, [f, c, c], c], [f, [f, c, c], c]]
</code></pre>
<p>I want to randomly select a point in each tree to split at and then I want one part from each tree to be combined into a new tree. There is also a max depth that shouldn't be exceeded so the selects can't really take place anywhere in the tree as it might create a too large tree. Below is an example on how it should work:</p>
<pre><code># f:n, where n is the number of arguments the function take
# + split here
tree1 = [f:2, [f:3, a, a, a], a]
# + split here
tree2 = [f:2, [f:2, a, a], [f:1, a]
tree_child1 = [f:2, [f:1, a], a]
tree_child2 = [f:2, [f:2, a, a], [f:3, a, a, a]]
</code></pre>
<p>I have no idea (at the moment) on how to solve this. Any tips or solutions are more than welcome!</p>
<p>(Added my parse function as it might help someone to understand the structure better.)</p>
<pre><code># My recursive code to parse the tree.
def parse(self, node=None):
if not node:
node = self.root
if isinstance(node, list):
function = node[0]
res = []
for child in node[1:function.arity+1]:
res.append(self.parse(child))
value = function.parse(*res) # function
else:
value = node.parse() # constant
return value
</code></pre>
| 4 | 2009-07-15T01:21:50Z | 1,129,486 | <p>I ended up implementing most of this as an exercise.</p>
<p>First, find the number of possible locations to split: the number of non-function nodes.</p>
<pre><code>def count(obj):
total = 0
for o in obj[1:]:
# Add the node itself.
total += 1
if isinstance(o, list):
total += count(o)
return total
</code></pre>
<p>Then, a helper: given an index in the above range, figure out where it is.</p>
<pre><code>def find_idx(tree, idx):
"""
Return the node containing the idx'th function parameter, and the index of that
parameter. If the tree contains fewer than idx parameters, return (None, None).
"""
if not isinstance(idx, list):
# Stash this in a list, so recursive calls share the same value.
idx = [idx]
for i, o in enumerate(tree):
# Skip the function itself.
if i == 0:
continue
if idx[0] == 0:
return tree, i
idx[0] -= 1
if isinstance(o, list):
container, result_index = find_idx(o, idx)
if container is not None:
return container, result_index
return None, None
</code></pre>
<p>Doing the swap is pretty simple now:</p>
<pre><code>def random_swap(tree1, tree2):
from random import randrange
pos_in_1 = randrange(0, count(tree1))
pos_in_2 = randrange(0, count(tree2))
parent1, idx1 = find_idx(tree1, pos_in_1)
parent2, idx2 = find_idx(tree2, pos_in_2)
# Swap:
parent1[idx1], parent2[idx2] = parent2[idx2], parent1[idx1]
c = 1
tree1 = ["f:2", c, ["f:1", c]]
tree2 = ["f:2", ["f:2", ["f:2", c, c], ["f:2", c, c]], ["f:3", ["f:4", c, c, c, c], ["f:2", c, c], c]]
while True:
random_swap(tree1, tree2)
print tree1
print tree2
</code></pre>
<p>This doesn't implement a max depth, but it's a start.</p>
<p>This will also never replace the root node, where a node in tree1 becomes the new tree2 and all of tree2 becomes a node in tree1. A workaround would be to wrap the whole thing in eg. [lambda a: a, tree], so editable nodes always have a parent node.</p>
<p>This isn't very efficient. Maintaining node counts could make it faster, but then you'd need to store a reference to the parent, too, in order to update the counts efficiently. If you go that route, you'll really want to find or implement a real tree class.</p>
| 2 | 2009-07-15T05:02:11Z | [
"python",
"list",
"genetic-programming"
] |
Is it possible to encode (<em>asdf</em>) in python Textile? | 1,128,951 | <p>I'm using <a href="http://pypi.python.org/pypi/textile" rel="nofollow">python Textile</a> to store markup in the database. I would like to yield the following HTML snippet:</p>
<pre><code>(<em>asdf</em>)
</code></pre>
<p>The obvious doesn't get encoded:</p>
<pre><code>(_asdf_) -> <p>(_asdf_)</p>
</code></pre>
<p>The following works, but yields an ugly space:</p>
<pre><code>( _asdf_) -> <p>( <em>asdf</em>)
</code></pre>
<p>Am I missing something obvious or is this just not possible using python Textile?</p>
| 0 | 2009-07-15T01:31:25Z | 1,129,730 | <p>It's hard to say if this is a bug or not; in the form on the <a href="http://textile.thresholdstate.com/" rel="nofollow">Textile website</a>, <code>(_foo_)</code> works as you want, but in the downloadable PHP implementation, it doesn't.</p>
<p>You should be able to do this:</p>
<pre><code>([_asdf_]) -> <p>(<em>asdf</em>)</p>
</code></pre>
<p>However, this doesn't work, which <strong>is</strong> a bug in py-textile. You either need to use this:</p>
<pre><code>(]_asdf_])
</code></pre>
<p>or patch textile.py by changing line 918 (in the <code>Textile.span()</code> method) to:</p>
<pre><code> (?:^|(?<=[\s>%(pnct)s])|([{[]))
</code></pre>
<p>(the difference is in the final group; the brackets are incorrectly reversed.)</p>
<p>You could also change the line to:</p>
<pre><code> (?:^|(?<=[\s>(%(pnct)s])|([{[]))
</code></pre>
<p>(note the added parenthesis) to get the behavior you desire for <code>(_foo_)</code>, <s>but I'm not sure if that would break anything else.</s></p>
<p><hr /></p>
<p>Follow up: the <a href="http://code.google.com/p/textpattern/source/browse/development/4.x/textpattern/lib/classTextile.php?r=3250#688" rel="nofollow">latest version of the PHP Textile class</a> does indeed make a similar change to the one I suggested.</p>
| 1 | 2009-07-15T06:31:42Z | [
"python",
"markup",
"textile"
] |
How to Redirect To Same Page on Failed Login | 1,129,091 | <p>The Django framework easily handles redirecting when a user fails to log in properly. However, this redirection goes to a separate login page. I can set the template to be the same as the page I logged in on, but none of my other objects exist in the new page.</p>
<p>For example, I have a front page that shows a bunch of news articles. On the sidebar is a login form. When the user logs in, but fails to authenticate, I would like it to return to the front page <em>and</em> preserve all the news articles that show. As of current, none of the news articles show up.</p>
<p>How can I fix this problem? Any help is appreciated.</p>
<p>Edit: Remember that I have dynamic content that is being displayed, and I would like it to still display! Futhermore, the main page is not the only place a user can log in. The sidebar never changes, so the user can potentially log in from any page on the site, and all of the content on that page exactly as it was still needs to be displayed upon failure to log in.</p>
| 2 | 2009-07-15T02:23:46Z | 1,129,123 | <p>Do you want to redirect to the referring page on failed login?</p>
<pre><code>... authentication code above
if user.is_authenticated():
#show success view
else:
return HttpResponseRedirect(request.META.get('HTTP_REFERER', reverse('index'))
</code></pre>
<p>you might want to check that referring page url is set correctly, otherwise set it to default url (assuming that your default url is named "index").</p>
| 6 | 2009-07-15T02:33:46Z | [
"python",
"django",
"authentication",
"redirect",
"login"
] |
How to Redirect To Same Page on Failed Login | 1,129,091 | <p>The Django framework easily handles redirecting when a user fails to log in properly. However, this redirection goes to a separate login page. I can set the template to be the same as the page I logged in on, but none of my other objects exist in the new page.</p>
<p>For example, I have a front page that shows a bunch of news articles. On the sidebar is a login form. When the user logs in, but fails to authenticate, I would like it to return to the front page <em>and</em> preserve all the news articles that show. As of current, none of the news articles show up.</p>
<p>How can I fix this problem? Any help is appreciated.</p>
<p>Edit: Remember that I have dynamic content that is being displayed, and I would like it to still display! Futhermore, the main page is not the only place a user can log in. The sidebar never changes, so the user can potentially log in from any page on the site, and all of the content on that page exactly as it was still needs to be displayed upon failure to log in.</p>
| 2 | 2009-07-15T02:23:46Z | 1,129,743 | <p>This is because redirecting to a view misses the original context you use to render the page in the first place.</p>
<p>You are missing just a simple logic here. You are trying to render the same template again, but with no news_article list. </p>
<p>I suppose (in the first place), you are rendering the template which shows you Articles as well as login form, by sending two things 1. Login Form, and 2. Articles List.
But secondly, when user fails to authenticate, you are not passing the same things again. Pass those variables again as context (you can also add error message if your form is not handling error messages).</p>
<pre><code>if user.is_authenticated():
#show success view
else:
return render_to_response('same_template.html', {
'error_msg': 'Username or password you provided was incorrect',
'news_articles': NewsArticles.objects.all()[:3],
'login_form': LoginForm(request.POST);
})
</code></pre>
<p><strong>Edit:</strong> The reality is that, a context is used to render a template, and it's the complete responsibility of that template, what it wants to pass in further navigation. And as I see, if you are not passing something further, you are not getting it further. </p>
<p>If you want some automated context, develop your own context processor, something like the <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#django-core-context-processors-auth" rel="nofollow">auth-context-processor</a>, which automatically adds like 'user', always available to the template.</p>
<p>And by the way, you are going to miss that kind of context anyway, even if login is authenticated. So if that particular context is really important, either try sending the primary keys of articles along with the login form submit, or store that in global (ugliest thing ever) or just reconsider and separate the flow (good thing, I feel).</p>
| 0 | 2009-07-15T06:34:29Z | [
"python",
"django",
"authentication",
"redirect",
"login"
] |
How to Redirect To Same Page on Failed Login | 1,129,091 | <p>The Django framework easily handles redirecting when a user fails to log in properly. However, this redirection goes to a separate login page. I can set the template to be the same as the page I logged in on, but none of my other objects exist in the new page.</p>
<p>For example, I have a front page that shows a bunch of news articles. On the sidebar is a login form. When the user logs in, but fails to authenticate, I would like it to return to the front page <em>and</em> preserve all the news articles that show. As of current, none of the news articles show up.</p>
<p>How can I fix this problem? Any help is appreciated.</p>
<p>Edit: Remember that I have dynamic content that is being displayed, and I would like it to still display! Futhermore, the main page is not the only place a user can log in. The sidebar never changes, so the user can potentially log in from any page on the site, and all of the content on that page exactly as it was still needs to be displayed upon failure to log in.</p>
| 2 | 2009-07-15T02:23:46Z | 1,149,663 | <ol>
<li>Use an <code><IFRAME></code> in the sidebar to
call the login view -- all postbacks
will happen within the iframe, so
your page stays intact. If the
visitor logs in successfully, you
can use javascript to redirect the
parent page to some other URL</li>
<li>Use <a href="http://malsup.com/jquery/form/" rel="nofollow">AJAX</a> to post the login form --
acheives the same effect as (1), but
it means your visitors will need to
have javascript-enabled browsers</li>
</ol>
<p>I personally prefer to have the login on a separate page. If you're only worried about your visitors losing their current page (and not say, bound by a fussy client), you can have the login show up in a <a href="http://jquery.com/demo/thickbox/" rel="nofollow">lightbox</a>. I've used all three approaches in the past, and I'd be happy to post some code samples if you're interested.</p>
| 0 | 2009-07-19T11:04:35Z | [
"python",
"django",
"authentication",
"redirect",
"login"
] |
How can I make setuptools ignore subversion inventory? | 1,129,180 | <p>When packaging a Python package with a setup.py that uses the setuptools:</p>
<pre><code>from setuptools import setup
...
</code></pre>
<p>the source distribution created by:</p>
<pre><code>python setup.py sdist
</code></pre>
<p>not only includes, as usual, the files specified in MANIFEST.in, but it also, gratuitously, includes all of the files that Subversion lists as being version controlled beneath the package directory. This is vastly annoying. Not only does it make it difficult to exercise any sort of explicit control over what files get distributed with my package, but it means that when I build my package following an "svn export" instead of an "svn checkout", the contents of my package might be quite different, since without the .svn metadata setuptools will make different choices about what to include.</p>
<p>My question: how can I turn off this terrible behavior, so that "setuptools" treats my project the same way whether I'm using Subversion, or version control it's never heard of, or a bare tree created with "svn export" that I've created at the end of my project to make sure it builds cleanly somewhere besides my working directory?</p>
<p>The best I have managed so far is an ugly monkey-patch:</p>
<pre><code>from setuptools.command import sdist
del sdist.finders[:]
</code></pre>
<p>But this is Python, not the jungle, so of course I want a better solution that involves no monkeys at all. How can I tame setuptools, turn off its magic, and have it behave sensibly by looking at the visible, predictable rules in my MANIFEST.py instead?</p>
| 18 | 2009-07-15T03:00:19Z | 1,129,848 | <p>Probably the answer is in your setup.py. Do you use find_packages? This function by default uses the VCS (e.g. subversion, hg, ...). If you don't like it, just write a different Python function which collects only the things you want.</p>
| 1 | 2009-07-15T07:07:32Z | [
"python",
"packaging",
"setuptools",
"egg"
] |
How can I make setuptools ignore subversion inventory? | 1,129,180 | <p>When packaging a Python package with a setup.py that uses the setuptools:</p>
<pre><code>from setuptools import setup
...
</code></pre>
<p>the source distribution created by:</p>
<pre><code>python setup.py sdist
</code></pre>
<p>not only includes, as usual, the files specified in MANIFEST.in, but it also, gratuitously, includes all of the files that Subversion lists as being version controlled beneath the package directory. This is vastly annoying. Not only does it make it difficult to exercise any sort of explicit control over what files get distributed with my package, but it means that when I build my package following an "svn export" instead of an "svn checkout", the contents of my package might be quite different, since without the .svn metadata setuptools will make different choices about what to include.</p>
<p>My question: how can I turn off this terrible behavior, so that "setuptools" treats my project the same way whether I'm using Subversion, or version control it's never heard of, or a bare tree created with "svn export" that I've created at the end of my project to make sure it builds cleanly somewhere besides my working directory?</p>
<p>The best I have managed so far is an ugly monkey-patch:</p>
<pre><code>from setuptools.command import sdist
del sdist.finders[:]
</code></pre>
<p>But this is Python, not the jungle, so of course I want a better solution that involves no monkeys at all. How can I tame setuptools, turn off its magic, and have it behave sensibly by looking at the visible, predictable rules in my MANIFEST.py instead?</p>
| 18 | 2009-07-15T03:00:19Z | 1,129,874 | <p>You probably want something like this:</p>
<pre><code>from distutils.core import setup
def packages():
import os
packages = []
for path, dirs, files in os.walk("yourprogram"):
if ".svn" in dirs:
dirs.remove(".svn")
if "__init__.py" in files:
packages.append(path.replace(os.sep, "."))
return packages
setup(
# name, version, description, etc...
packages = packages(),
# pacakge_data, data_files, etc...
)
</code></pre>
| -1 | 2009-07-15T07:15:15Z | [
"python",
"packaging",
"setuptools",
"egg"
] |
How can I make setuptools ignore subversion inventory? | 1,129,180 | <p>When packaging a Python package with a setup.py that uses the setuptools:</p>
<pre><code>from setuptools import setup
...
</code></pre>
<p>the source distribution created by:</p>
<pre><code>python setup.py sdist
</code></pre>
<p>not only includes, as usual, the files specified in MANIFEST.in, but it also, gratuitously, includes all of the files that Subversion lists as being version controlled beneath the package directory. This is vastly annoying. Not only does it make it difficult to exercise any sort of explicit control over what files get distributed with my package, but it means that when I build my package following an "svn export" instead of an "svn checkout", the contents of my package might be quite different, since without the .svn metadata setuptools will make different choices about what to include.</p>
<p>My question: how can I turn off this terrible behavior, so that "setuptools" treats my project the same way whether I'm using Subversion, or version control it's never heard of, or a bare tree created with "svn export" that I've created at the end of my project to make sure it builds cleanly somewhere besides my working directory?</p>
<p>The best I have managed so far is an ugly monkey-patch:</p>
<pre><code>from setuptools.command import sdist
del sdist.finders[:]
</code></pre>
<p>But this is Python, not the jungle, so of course I want a better solution that involves no monkeys at all. How can I tame setuptools, turn off its magic, and have it behave sensibly by looking at the visible, predictable rules in my MANIFEST.py instead?</p>
| 18 | 2009-07-15T03:00:19Z | 1,130,598 | <p>I know you know much of this, Brandon, but I'll try to give as a complete answer as I can (although I'm no setuptools gury) for the benefit of others.</p>
<p>The problem here is that setuptools itself involves quite a lot of black magick, including using an entry point called setuptools.file_finders where you can add plugins to find files to include. I am, however, at a complete loss as to how REMOVE plugins from it...</p>
<ul>
<li><p>Quick workaround: svn export your package to a temporary directory and run the setup.py from there. That means you have no svn, so the svn finder finds no files to include. :)</p></li>
<li><p>Longer workaround: Do you really need setuptools? Setuptools have a lot of features, so the answer is likely yes, but mainly those features are depdenencies (so your dependencies get installed by easy_install), namespace packages (foo.bar), and entry points. Namespace packages can actually be created without setuptools as well. But if you use none of these you might actually get away with just using distutils.</p></li>
<li><p>Ugly workaround: The monkeypatch you gave to sdist in your question, which simply makes the plugin not have any finders, and exit quickly.</p></li>
</ul>
<p>So as you see, this answer, although as complete as I can make it, is still embarrassingly incomplete. I can't actually answer your question, though I think the answer is "You can't". </p>
| 13 | 2009-07-15T10:27:16Z | [
"python",
"packaging",
"setuptools",
"egg"
] |
How can I make setuptools ignore subversion inventory? | 1,129,180 | <p>When packaging a Python package with a setup.py that uses the setuptools:</p>
<pre><code>from setuptools import setup
...
</code></pre>
<p>the source distribution created by:</p>
<pre><code>python setup.py sdist
</code></pre>
<p>not only includes, as usual, the files specified in MANIFEST.in, but it also, gratuitously, includes all of the files that Subversion lists as being version controlled beneath the package directory. This is vastly annoying. Not only does it make it difficult to exercise any sort of explicit control over what files get distributed with my package, but it means that when I build my package following an "svn export" instead of an "svn checkout", the contents of my package might be quite different, since without the .svn metadata setuptools will make different choices about what to include.</p>
<p>My question: how can I turn off this terrible behavior, so that "setuptools" treats my project the same way whether I'm using Subversion, or version control it's never heard of, or a bare tree created with "svn export" that I've created at the end of my project to make sure it builds cleanly somewhere besides my working directory?</p>
<p>The best I have managed so far is an ugly monkey-patch:</p>
<pre><code>from setuptools.command import sdist
del sdist.finders[:]
</code></pre>
<p>But this is Python, not the jungle, so of course I want a better solution that involves no monkeys at all. How can I tame setuptools, turn off its magic, and have it behave sensibly by looking at the visible, predictable rules in my MANIFEST.py instead?</p>
| 18 | 2009-07-15T03:00:19Z | 1,132,909 | <p>I would argue that the default sdist behavior is correct. When you are building a <strong>source</strong> distribution, I would expect it to contain <strong>everything</strong> that is checked into Subversion. Of course it would be nice to be able to override it cleanly in special circumstances.</p>
<p>Compare sdist to bdist_egg; I bet only the files that are specified explicitly get included.</p>
<p>I did a simple test with three files, all in svn. Empty dummy.lkj and foobar.py and with setup.py looking like this:</p>
<pre><code>import setuptools
setuptools.setup(name='foobar', version='0.1', py_modules=['foobar'])
</code></pre>
<p>sdist creates a tarball that includes dummy.lkj. bdist_egg creates an egg that does not include dummy.lkj.</p>
| 0 | 2009-07-15T17:53:08Z | [
"python",
"packaging",
"setuptools",
"egg"
] |
How can I make setuptools ignore subversion inventory? | 1,129,180 | <p>When packaging a Python package with a setup.py that uses the setuptools:</p>
<pre><code>from setuptools import setup
...
</code></pre>
<p>the source distribution created by:</p>
<pre><code>python setup.py sdist
</code></pre>
<p>not only includes, as usual, the files specified in MANIFEST.in, but it also, gratuitously, includes all of the files that Subversion lists as being version controlled beneath the package directory. This is vastly annoying. Not only does it make it difficult to exercise any sort of explicit control over what files get distributed with my package, but it means that when I build my package following an "svn export" instead of an "svn checkout", the contents of my package might be quite different, since without the .svn metadata setuptools will make different choices about what to include.</p>
<p>My question: how can I turn off this terrible behavior, so that "setuptools" treats my project the same way whether I'm using Subversion, or version control it's never heard of, or a bare tree created with "svn export" that I've created at the end of my project to make sure it builds cleanly somewhere besides my working directory?</p>
<p>The best I have managed so far is an ugly monkey-patch:</p>
<pre><code>from setuptools.command import sdist
del sdist.finders[:]
</code></pre>
<p>But this is Python, not the jungle, so of course I want a better solution that involves no monkeys at all. How can I tame setuptools, turn off its magic, and have it behave sensibly by looking at the visible, predictable rules in my MANIFEST.py instead?</p>
| 18 | 2009-07-15T03:00:19Z | 1,959,924 | <p>Create a MANIFEST.in file with:</p>
<pre><code>recursive-exclude .
# other MANIFEST.in commands go here
# to explicitly include whatever files you want
</code></pre>
<p>See <a href="http://docs.python.org/distutils/commandref.html#sdist-cmd">http://docs.python.org/distutils/commandref.html#sdist-cmd</a> for the MANIFEST.in syntax.</p>
| 8 | 2009-12-24T22:24:50Z | [
"python",
"packaging",
"setuptools",
"egg"
] |
creating non-reloading dynamic webapps using Django | 1,129,210 | <p>As far as I know, for a new request coming from a webapp, you need to reload the page to process and respond to that request. </p>
<p>For example, if you want to show a comment on a post, you need to reload the page, process the comment, and then show it. What I want, however, is I want to be able to add comments (something like facebook, where the comment gets added and shown without having to reload the whole page, for example) without having to reload the web-page. Is it possible to do with only Django and Python with no Javascript/AJAX knowledge?</p>
<p>I have heard it's possible with AJAX (I don't know how), but I was wondering if it was possible to do with Django.</p>
<p>Thanks,</p>
| 0 | 2009-07-15T03:15:27Z | 1,129,222 | <p>You want to do that with out any client side code (javascript and ajax are just examples) and with out reloading your page (or at least part of it)?</p>
<p>If that is your question, then the answer unfortunately is you can't. You need to either have client side code or reload your page.</p>
<p>Think about it, once the client get's the page it will not change unless</p>
<ul>
<li>The client requests the same page from the server and the server returns and updated one</li>
<li>the page has some client side code (eg: javascript) that updates the page.</li>
</ul>
<p>I can not imagine a third possibility. I have not coded in Django for more than 30 mins and this is clearly obvious to me. If I am wrong plz down vote :D</p>
| 7 | 2009-07-15T03:20:55Z | [
"python",
"ajax",
"django"
] |
creating non-reloading dynamic webapps using Django | 1,129,210 | <p>As far as I know, for a new request coming from a webapp, you need to reload the page to process and respond to that request. </p>
<p>For example, if you want to show a comment on a post, you need to reload the page, process the comment, and then show it. What I want, however, is I want to be able to add comments (something like facebook, where the comment gets added and shown without having to reload the whole page, for example) without having to reload the web-page. Is it possible to do with only Django and Python with no Javascript/AJAX knowledge?</p>
<p>I have heard it's possible with AJAX (I don't know how), but I was wondering if it was possible to do with Django.</p>
<p>Thanks,</p>
| 0 | 2009-07-15T03:15:27Z | 1,129,349 | <p>To do it right, ajax would be the way to go BUT in a limited sense you can achieve the same thing by using a <a href="http://www.w3schools.com/TAGS/tag%5Fiframe.asp" rel="nofollow">iframe</a>, iframe is like another page embedded inside main page, so instead of refreshing whole page you may just refresh the inner iframe page and that may give the same effect.</p>
<p>More about iframe patterns you can read at
<a href="http://ajaxpatterns.org/IFrame_Call" rel="nofollow">http://ajaxpatterns.org/IFrame_Call</a></p>
| 1 | 2009-07-15T04:03:03Z | [
"python",
"ajax",
"django"
] |
creating non-reloading dynamic webapps using Django | 1,129,210 | <p>As far as I know, for a new request coming from a webapp, you need to reload the page to process and respond to that request. </p>
<p>For example, if you want to show a comment on a post, you need to reload the page, process the comment, and then show it. What I want, however, is I want to be able to add comments (something like facebook, where the comment gets added and shown without having to reload the whole page, for example) without having to reload the web-page. Is it possible to do with only Django and Python with no Javascript/AJAX knowledge?</p>
<p>I have heard it's possible with AJAX (I don't know how), but I was wondering if it was possible to do with Django.</p>
<p>Thanks,</p>
| 0 | 2009-07-15T03:15:27Z | 1,129,395 | <p>Maybe a few iFrames and some Comet/long-polling? Have the comment submission in an iFrame (so the whole page doesn't reload), and then show the result in the long-polled iFrame...</p>
<p>Having said that, it's a pretty bad design idea, and you probably don't want to be doing this. AJAX/JavaScript is pretty much the way to go for things like this.</p>
<blockquote>
<p>I have heard it's possible with AJAX...but I was
wondering if it was possible to do
with Django.</p>
</blockquote>
<p>There's no reason you can't use both - specifically, AJAX within a Django web application. Django provides your organization and framework needs (and a page that will respond to AJAX requests) and then use some JavaScript on the client side to make AJAX calls to your Django-backed page that will respond correctly.</p>
<p>I suggest you go find a basic jQuery tutorial which should explain enough basic JavaScript to get this working.</p>
| 1 | 2009-07-15T04:17:31Z | [
"python",
"ajax",
"django"
] |
creating non-reloading dynamic webapps using Django | 1,129,210 | <p>As far as I know, for a new request coming from a webapp, you need to reload the page to process and respond to that request. </p>
<p>For example, if you want to show a comment on a post, you need to reload the page, process the comment, and then show it. What I want, however, is I want to be able to add comments (something like facebook, where the comment gets added and shown without having to reload the whole page, for example) without having to reload the web-page. Is it possible to do with only Django and Python with no Javascript/AJAX knowledge?</p>
<p>I have heard it's possible with AJAX (I don't know how), but I was wondering if it was possible to do with Django.</p>
<p>Thanks,</p>
| 0 | 2009-07-15T03:15:27Z | 1,129,685 | <p>You definitely want to use AJAX. Which means the client will need to run some javascript code.</p>
<p>If you don't want to learn javascript you can always try something like <a href="http://pyjs.org/" rel="nofollow">pyjamas</a>. You can check out an example of it's HttpRequest <a href="http://pyjs.org/book/output/Bookreader.html#Rest%20of%20the%20World" rel="nofollow">here</a></p>
<p>But I always feel that using straight javascript via a library (like jQuery) is easier to understand than trying to force one language into another one.</p>
| 3 | 2009-07-15T06:16:58Z | [
"python",
"ajax",
"django"
] |
how do i filter an itertools chain() result? | 1,129,344 | <p>in my views,
if i import an itertools module:</p>
<pre><code>from itertools import chain
</code></pre>
<p>and i chain some objects with it:</p>
<pre><code>franktags = Frank.objects.order_by('date_added').reverse().filter(topic__exact='art')
amytags = Amy.objects.order_by('date_added').reverse().filter(topic__exact='art')
timtags = Tim.objects.order_by('date_added').reverse().filter(topic__exact='art')
erictags = Eric.objects.order_by('date_added').reverse().filter(topic__exact='art')
ourtags = list(chain(franktags, amytags, timtags, erictags))
</code></pre>
<p>how do i then order "ourtags" by the "date_added"?</p>
<p>not surpisingly,</p>
<pre><code>ourtags = list(chain(franktags, amytags, timtags, erictags)).order_by('date_added')
</code></pre>
<p>returns an "'list' object has no attribute 'order_by'" error.</p>
| 3 | 2009-07-15T04:00:25Z | 1,129,381 | <p>By this point in the code, you've already loaded up all of the objects into memory and into a list. Just sort the list like you would any old Python list.</p>
<pre><code>>>> import operator
>>> ourtags.sort(key=operator.attrgetter('date_added'))
</code></pre>
| 4 | 2009-07-15T04:13:54Z | [
"python",
"django",
"django-views",
"itertools"
] |
how do i filter an itertools chain() result? | 1,129,344 | <p>in my views,
if i import an itertools module:</p>
<pre><code>from itertools import chain
</code></pre>
<p>and i chain some objects with it:</p>
<pre><code>franktags = Frank.objects.order_by('date_added').reverse().filter(topic__exact='art')
amytags = Amy.objects.order_by('date_added').reverse().filter(topic__exact='art')
timtags = Tim.objects.order_by('date_added').reverse().filter(topic__exact='art')
erictags = Eric.objects.order_by('date_added').reverse().filter(topic__exact='art')
ourtags = list(chain(franktags, amytags, timtags, erictags))
</code></pre>
<p>how do i then order "ourtags" by the "date_added"?</p>
<p>not surpisingly,</p>
<pre><code>ourtags = list(chain(franktags, amytags, timtags, erictags)).order_by('date_added')
</code></pre>
<p>returns an "'list' object has no attribute 'order_by'" error.</p>
| 3 | 2009-07-15T04:00:25Z | 1,129,387 | <pre><code>import operator
ourtags = sorted(ourtags, key=operator.attrgetter('date_added'))
</code></pre>
| 10 | 2009-07-15T04:15:09Z | [
"python",
"django",
"django-views",
"itertools"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.