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
A data-structure for 1:1 mappings in python?
863,935
<p>I have a problem which requires a reversable 1:1 mapping of keys to values. </p> <p>That means sometimes I want to find the value given a key, but at other times I want to find the key given the value. Both keys and values are guaranteed unique. </p> <pre><code>x = D[y] y == D.inverse[x] </code></pre> <p>The obvi...
24
2009-05-14T15:14:18Z
864,071
<blockquote> <p><em>The other alternative is to make a new class which unites two dictionaries, one for each kind of lookup. That would most likely be fast but would use up twice as much memory as a single dict.</em></p> </blockquote> <p>Not really. Have you measured that? Since both dictionaries would use...
25
2009-05-14T15:34:35Z
[ "python", "data-structures" ]
A data-structure for 1:1 mappings in python?
863,935
<p>I have a problem which requires a reversable 1:1 mapping of keys to values. </p> <p>That means sometimes I want to find the value given a key, but at other times I want to find the key given the value. Both keys and values are guaranteed unique. </p> <pre><code>x = D[y] y == D.inverse[x] </code></pre> <p>The obvi...
24
2009-05-14T15:14:18Z
864,151
<p>"We can guarantee that either the key or the value (or both) will be an integer"</p> <p>That's weirdly written -- "key or the value (or both)" doesn't feel right. Either they're all integers, or they're not all integers. </p> <p>It sounds like they're all integers.</p> <p>Or, it sounds like you're thinking of...
1
2009-05-14T15:50:46Z
[ "python", "data-structures" ]
A data-structure for 1:1 mappings in python?
863,935
<p>I have a problem which requires a reversable 1:1 mapping of keys to values. </p> <p>That means sometimes I want to find the value given a key, but at other times I want to find the key given the value. Both keys and values are guaranteed unique. </p> <pre><code>x = D[y] y == D.inverse[x] </code></pre> <p>The obvi...
24
2009-05-14T15:14:18Z
864,280
<p>It so happens that I find myself asking this question all the time (yesterday in particular). I agree with the approach of making two dictionaries. Do some benchmarking to see how much memory it's taking. I've never needed to make it mutable, but here's how I abstract it, if it's of any use:</p> <pre><code>class...
0
2009-05-14T16:12:40Z
[ "python", "data-structures" ]
A data-structure for 1:1 mappings in python?
863,935
<p>I have a problem which requires a reversable 1:1 mapping of keys to values. </p> <p>That means sometimes I want to find the value given a key, but at other times I want to find the key given the value. Both keys and values are guaranteed unique. </p> <pre><code>x = D[y] y == D.inverse[x] </code></pre> <p>The obvi...
24
2009-05-14T15:14:18Z
864,385
<p>How about using sqlite? Just create a :memory: database with a two-column table. You can even add indexes, then query by either one. Wrap it in a class if it's something you're going to use a lot. </p>
2
2009-05-14T16:29:52Z
[ "python", "data-structures" ]
A data-structure for 1:1 mappings in python?
863,935
<p>I have a problem which requires a reversable 1:1 mapping of keys to values. </p> <p>That means sometimes I want to find the value given a key, but at other times I want to find the key given the value. Both keys and values are guaranteed unique. </p> <pre><code>x = D[y] y == D.inverse[x] </code></pre> <p>The obvi...
24
2009-05-14T15:14:18Z
1,374,617
<pre><code>class TwoWay: def __init__(self): self.d = {} def add(self, k, v): self.d[k] = v self.d[v] = k def remove(self, k): self.d.pop(self.d.pop(k)) def get(self, k): return self.d[k] </code></pre>
11
2009-09-03T16:46:21Z
[ "python", "data-structures" ]
A data-structure for 1:1 mappings in python?
863,935
<p>I have a problem which requires a reversable 1:1 mapping of keys to values. </p> <p>That means sometimes I want to find the value given a key, but at other times I want to find the key given the value. Both keys and values are guaranteed unique. </p> <pre><code>x = D[y] y == D.inverse[x] </code></pre> <p>The obvi...
24
2009-05-14T15:14:18Z
3,861,641
<p>Here is my own solution to this problem: <a href="http://github.com/spenthil/pymathmap/blob/master/pymathmap.py" rel="nofollow">http://github.com/spenthil/pymathmap/blob/master/pymathmap.py</a></p> <p>The goal is to make it as transparent to the user as possible. The only introduced significant attribute is <code>p...
2
2010-10-05T07:30:31Z
[ "python", "data-structures" ]
how to modify choices on admin pages - django
864,433
<p>I have a model that has a field named "state":</p> <pre><code>class Foo(models.Model): ... state = models.IntegerField(choices = STATES) ... </code></pre> <p>For every state, possible choices are a certain subset of all STATES. For example:</p> <pre><code>if foo.state == STATES.OPEN: #if foo is op...
7
2009-05-14T16:42:16Z
864,675
<p>I see what you're trying to do, but why not just display all of them and if the person picks the (already set) current state, just don't change anything?</p> <p>you could also just build a view with a form to provide this functionality</p>
-1
2009-05-14T17:32:41Z
[ "python", "django", "django-models", "django-admin" ]
how to modify choices on admin pages - django
864,433
<p>I have a model that has a field named "state":</p> <pre><code>class Foo(models.Model): ... state = models.IntegerField(choices = STATES) ... </code></pre> <p>For every state, possible choices are a certain subset of all STATES. For example:</p> <pre><code>if foo.state == STATES.OPEN: #if foo is op...
7
2009-05-14T16:42:16Z
865,932
<p>You need to <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form">use a custom ModelForm</a> in the ModelAdmin class for that model. In the custom ModelForm's __init__ method, you can dynamically set the choices for that field:</p> <pre><code>class FooForm(forms.Mod...
6
2009-05-14T21:35:38Z
[ "python", "django", "django-models", "django-admin" ]
how to modify choices on admin pages - django
864,433
<p>I have a model that has a field named "state":</p> <pre><code>class Foo(models.Model): ... state = models.IntegerField(choices = STATES) ... </code></pre> <p>For every state, possible choices are a certain subset of all STATES. For example:</p> <pre><code>if foo.state == STATES.OPEN: #if foo is op...
7
2009-05-14T16:42:16Z
865,961
<p>This seems like a job for some javascript. You want the list of items in a select box to change depending on the value of something else, which is presumably a checkbox or radio button. The only way to make that happen dynamically - without getting the user to save the form and reload the page - would be with javasc...
0
2009-05-14T21:40:32Z
[ "python", "django", "django-models", "django-admin" ]
how to modify choices on admin pages - django
864,433
<p>I have a model that has a field named "state":</p> <pre><code>class Foo(models.Model): ... state = models.IntegerField(choices = STATES) ... </code></pre> <p>For every state, possible choices are a certain subset of all STATES. For example:</p> <pre><code>if foo.state == STATES.OPEN: #if foo is op...
7
2009-05-14T16:42:16Z
16,367,595
<p>When you create a new admin interface for a model (e.g. MyModelAdmin) there are specific methods for override the default choices of a field. For a generic <a href="https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_for_choice_field">choice field</a>:</p> <pre><code>c...
7
2013-05-03T21:09:39Z
[ "python", "django", "django-models", "django-admin" ]
Python While Loop Condition Evaluation
864,603
<p>Say I have the following loop:</p> <pre><code>i = 0 l = [0, 1, 2, 3] while i &lt; len(l): if something_happens: l.append(something) i += 1 </code></pre> <p>Will the <code>len(i)</code> condition being evaluated in the while loop be updated when something is appended to <code>l</code>?</p>
0
2009-05-14T17:17:07Z
864,612
<p>Yes it will.</p>
11
2009-05-14T17:19:32Z
[ "python", "while-loop" ]
Python While Loop Condition Evaluation
864,603
<p>Say I have the following loop:</p> <pre><code>i = 0 l = [0, 1, 2, 3] while i &lt; len(l): if something_happens: l.append(something) i += 1 </code></pre> <p>Will the <code>len(i)</code> condition being evaluated in the while loop be updated when something is appended to <code>l</code>?</p>
0
2009-05-14T17:17:07Z
864,717
<p>Your code will work, but using a loop counter is often not considered very "pythonic". Using <code>for</code> works just as well and eliminates the counter:</p> <pre><code>&gt;&gt;&gt; foo = [0, 1, 2] &gt;&gt;&gt; for bar in foo: if bar % 2: # append to foo for every odd number foo.append(len(foo)) ...
3
2009-05-14T17:40:31Z
[ "python", "while-loop" ]
How to get a subclassed object of a django model
864,769
<p>When I have a given django model class like this:</p> <pre><code>class BaseClass(models.Model): some_field = models.CharField(max_length = 80) ... </code></pre> <p>and some subclasses of it, for example</p> <pre><code>class SomeClass(BaseClass): other_field = models.CharField(max_length = 80) </co...
2
2009-05-14T17:50:21Z
864,802
<blockquote> <p>How can I get to the subclassed object without knowing it's class in advance?</p> </blockquote> <p>Why would this be useful? If you don't know what class you want, you also won't know which methods to call or which attributes can be inspected.</p> <p><hr /></p> <blockquote> <p>The idea is to load...
2
2009-05-14T17:57:12Z
[ "python", "django", "inheritance", "model" ]
How to get a subclassed object of a django model
864,769
<p>When I have a given django model class like this:</p> <pre><code>class BaseClass(models.Model): some_field = models.CharField(max_length = 80) ... </code></pre> <p>and some subclasses of it, for example</p> <pre><code>class SomeClass(BaseClass): other_field = models.CharField(max_length = 80) </co...
2
2009-05-14T17:50:21Z
864,911
<p>There isn't a built-in way.</p> <p>Perhaps the best thing to do is to define a <code>derived_type</code> field on your base class, which is set automatically on save of the derived class. You could then have a <code>get_derived</code> method on the base which checks the value of <code>derived_type</code> and return...
3
2009-05-14T18:22:47Z
[ "python", "django", "inheritance", "model" ]
How to get a subclassed object of a django model
864,769
<p>When I have a given django model class like this:</p> <pre><code>class BaseClass(models.Model): some_field = models.CharField(max_length = 80) ... </code></pre> <p>and some subclasses of it, for example</p> <pre><code>class SomeClass(BaseClass): other_field = models.CharField(max_length = 80) </co...
2
2009-05-14T17:50:21Z
9,820,063
<p>For people looking into this answer a bit later than the question was posted and the accepted answer was given, in the newer versions of django, this is possible more directly, see: <a href="https://docs.djangoproject.com/en/dev/topics/db/models/#multi-table-inheritance" rel="nofollow">django documentation about mul...
2
2012-03-22T10:05:57Z
[ "python", "django", "inheritance", "model" ]
How to get a subclassed object of a django model
864,769
<p>When I have a given django model class like this:</p> <pre><code>class BaseClass(models.Model): some_field = models.CharField(max_length = 80) ... </code></pre> <p>and some subclasses of it, for example</p> <pre><code>class SomeClass(BaseClass): other_field = models.CharField(max_length = 80) </co...
2
2009-05-14T17:50:21Z
22,840,641
<p>If you use the InheritanceManager from django-model-utils then you can select the subclasses when you query without knowing what they are ahead of time.</p> <p><a href="https://django-model-utils.readthedocs.org/en/latest/managers.html#inheritancemanager" rel="nofollow">https://django-model-utils.readthedocs.org/en...
0
2014-04-03T14:23:03Z
[ "python", "django", "inheritance", "model" ]
Python os.forkpty why can't I make it work
864,826
<pre><code>import pty import os import sys import time pid, fd = os.forkpty() if pid == 0: # Slave os.execlp("su","su","MYUSERNAME","-c","id") # Master print os.read(fd, 1000) os.write(fd,"MYPASSWORD\n") time.sleep(1) print os.read(fd, 1000) os.waitpid(pid,0) print "Why have I not seen any output from id?" <...
2
2009-05-14T18:03:16Z
865,279
<p>You are sleeping for too long. Your best bet is to start reading as soon as you can one byte at a time.</p> <pre><code>#!/usr/bin/env python import os import sys pid, fd = os.forkpty() if pid == 0: # child os.execlp("ssh","ssh","hostname","uname") else: # parent print os.read(fd, 1000) os.wri...
5
2009-05-14T19:41:02Z
[ "python", "pty" ]
How do I write a float list of lists to file in Python
864,883
<p>I need to write a series of matrices out to a plain text file from python. All my matricies are in float format so the simple file.write() and file.writelines()</p> <p>do not work. Is there a conversion method I can employ that doesn't have me looping through all the lists (matrix = list of lists in my case) con...
5
2009-05-14T18:16:54Z
864,910
<p>the following works for me:</p> <pre><code>with open(fname, 'w') as f: f.writelines(','.join(str(j) for j in i) + '\n' for i in matrix) </code></pre>
7
2009-05-14T18:22:43Z
[ "python", "file-io" ]
How do I write a float list of lists to file in Python
864,883
<p>I need to write a series of matrices out to a plain text file from python. All my matricies are in float format so the simple file.write() and file.writelines()</p> <p>do not work. Is there a conversion method I can employ that doesn't have me looping through all the lists (matrix = list of lists in my case) con...
5
2009-05-14T18:16:54Z
864,916
<pre><code>m = [[1.1, 2.1, 3.1], [4.1, 5.1, 6.1], [7.1, 8.1, 9.1]] file.write(str(m)) </code></pre> <p>If you want more control over the format of each value:</p> <pre><code>def format(value): return "%.3f" % value formatted = [[format(v) for v in r] for r in m] file.write(str(formatted)) </code></pre>
7
2009-05-14T18:23:25Z
[ "python", "file-io" ]
How do I write a float list of lists to file in Python
864,883
<p>I need to write a series of matrices out to a plain text file from python. All my matricies are in float format so the simple file.write() and file.writelines()</p> <p>do not work. Is there a conversion method I can employ that doesn't have me looping through all the lists (matrix = list of lists in my case) con...
5
2009-05-14T18:16:54Z
865,208
<p>Why not use <a href="http://docs.python.org/library/pickle.html" rel="nofollow">pickle</a>?</p> <pre><code>import cPickle as pickle pckl_file = file("test.pckl", "w") pickle.dump([1,2,3], pckl_file) pckl_file.close() </code></pre>
5
2009-05-14T19:27:48Z
[ "python", "file-io" ]
How do I write a float list of lists to file in Python
864,883
<p>I need to write a series of matrices out to a plain text file from python. All my matricies are in float format so the simple file.write() and file.writelines()</p> <p>do not work. Is there a conversion method I can employ that doesn't have me looping through all the lists (matrix = list of lists in my case) con...
5
2009-05-14T18:16:54Z
3,962,822
<pre><code>import pickle # write object to file a = ['hello', 'world'] pickle.dump(a, open('delme.txt', 'wb')) # read object from file b = pickle.load(open('delme.txt', 'rb')) print b # ['hello', 'world'] </code></pre> <p>At this point you can look at the file 'delme.txt' with vi</p> <pre><code>vi delme.txt ...
1
2010-10-18T19:52:40Z
[ "python", "file-io" ]
How do I write a float list of lists to file in Python
864,883
<p>I need to write a series of matrices out to a plain text file from python. All my matricies are in float format so the simple file.write() and file.writelines()</p> <p>do not work. Is there a conversion method I can employ that doesn't have me looping through all the lists (matrix = list of lists in my case) con...
5
2009-05-14T18:16:54Z
4,588,481
<p>for row in matrix: file.write(" ".join(map(str,row))+"\n")</p> <p>This works for me... and writes the output in matrix format</p>
1
2011-01-03T21:21:50Z
[ "python", "file-io" ]
Beginning Windows Mobile 6.1 Development With Python
864,887
<p>I've wanted to get into Python development for awhile and most of my programming experience has been in .NET and no mobile development. I recently thought of a useful app to make for my windows mobile phone and thought this could be a great first Python project. </p> <p>I did a little research online and found Py...
0
2009-05-14T18:17:27Z
864,988
<p>Can't help you much with Python\CE but if you want a great db for mobile devices SQLLite will do the job for you. If you do a quick google you'll find there are libraries for connecting to SQLLite with Python too.</p>
1
2009-05-14T18:36:53Z
[ "python", "windows-mobile", "mobile-phones" ]
Problems using nose in a virtualenv
864,956
<p>I am unable to use nose (nosetests) in a virtualenv project - it can't seem to find the packages installed in the virtualenv environment.</p> <p>The odd thing is that i can set</p> <pre><code>test_suite = 'nose.collector' </code></pre> <p>in setup.py and run the tests just fine as</p> <pre><code>python setup.py ...
34
2009-05-14T18:30:15Z
864,967
<p>Are you able to run <code>myenv/bin/python /usr/bin/nosetests</code>? That should run Nose using the virtual environment's library set.</p>
37
2009-05-14T18:32:54Z
[ "python", "virtualenv", "nose", "nosetests" ]
Problems using nose in a virtualenv
864,956
<p>I am unable to use nose (nosetests) in a virtualenv project - it can't seem to find the packages installed in the virtualenv environment.</p> <p>The odd thing is that i can set</p> <pre><code>test_suite = 'nose.collector' </code></pre> <p>in setup.py and run the tests just fine as</p> <pre><code>python setup.py ...
34
2009-05-14T18:30:15Z
865,737
<p>Here's what works for me:</p> <pre><code>$ virtualenv --no-site-packages env1 $ cd env1 $ source bin/activate # makes "env1" environment active, # you will notice that the command prompt # now has the environment name in it. (env1)$ easy_...
8
2009-05-14T20:59:22Z
[ "python", "virtualenv", "nose", "nosetests" ]
Problems using nose in a virtualenv
864,956
<p>I am unable to use nose (nosetests) in a virtualenv project - it can't seem to find the packages installed in the virtualenv environment.</p> <p>The odd thing is that i can set</p> <pre><code>test_suite = 'nose.collector' </code></pre> <p>in setup.py and run the tests just fine as</p> <pre><code>python setup.py ...
34
2009-05-14T18:30:15Z
5,409,951
<p>I got a similar problem. The following workaround helped:</p> <pre><code>python `which nosetests` </code></pre> <p>(instead of just <code>nosestests</code>)</p>
7
2011-03-23T18:35:21Z
[ "python", "virtualenv", "nose", "nosetests" ]
Problems using nose in a virtualenv
864,956
<p>I am unable to use nose (nosetests) in a virtualenv project - it can't seem to find the packages installed in the virtualenv environment.</p> <p>The odd thing is that i can set</p> <pre><code>test_suite = 'nose.collector' </code></pre> <p>in setup.py and run the tests just fine as</p> <pre><code>python setup.py ...
34
2009-05-14T18:30:15Z
5,918,777
<p>You need to have a copy of nose installed in the virtual environment. In order to force installation of nose into the virtualenv, even though it is already installed in the global site-packages, run <code>pip install</code> with the <code>-I</code> flag:</p> <pre><code>(env1)$ pip install nose -I </code></pre> <p>...
46
2011-05-07T02:35:46Z
[ "python", "virtualenv", "nose", "nosetests" ]
Problems using nose in a virtualenv
864,956
<p>I am unable to use nose (nosetests) in a virtualenv project - it can't seem to find the packages installed in the virtualenv environment.</p> <p>The odd thing is that i can set</p> <pre><code>test_suite = 'nose.collector' </code></pre> <p>in setup.py and run the tests just fine as</p> <pre><code>python setup.py ...
34
2009-05-14T18:30:15Z
7,328,089
<p>Perhaps this is a recent change, but for me, when I installed nosetests through pip, there was a nosetests executable installed in <code>.virtualenvs/&lt;env&gt;/bin</code>, which (unsurprisingly) operates correctly with the virtualenv.</p>
0
2011-09-07T01:55:32Z
[ "python", "virtualenv", "nose", "nosetests" ]
Problems using nose in a virtualenv
864,956
<p>I am unable to use nose (nosetests) in a virtualenv project - it can't seem to find the packages installed in the virtualenv environment.</p> <p>The odd thing is that i can set</p> <pre><code>test_suite = 'nose.collector' </code></pre> <p>in setup.py and run the tests just fine as</p> <pre><code>python setup.py ...
34
2009-05-14T18:30:15Z
16,968,277
<p>You might have a <code>nosetests</code> that is installed somewhere else in your <code>PATH</code> with higher priority than the one installed in your virtualenv. A quick way to give the <code>nose</code> module and associated <code>nosetests</code> script installed in your current virtualenv top priority is to edit...
0
2013-06-06T17:18:33Z
[ "python", "virtualenv", "nose", "nosetests" ]
Problems using nose in a virtualenv
864,956
<p>I am unable to use nose (nosetests) in a virtualenv project - it can't seem to find the packages installed in the virtualenv environment.</p> <p>The odd thing is that i can set</p> <pre><code>test_suite = 'nose.collector' </code></pre> <p>in setup.py and run the tests just fine as</p> <pre><code>python setup.py ...
34
2009-05-14T18:30:15Z
18,860,563
<p>In the same situation I needed to reload the <code>virtualenv</code> for the path to be correctly updated:</p> <pre><code>deactivate env/bin/activate </code></pre>
5
2013-09-17T21:54:09Z
[ "python", "virtualenv", "nose", "nosetests" ]
Problems using nose in a virtualenv
864,956
<p>I am unable to use nose (nosetests) in a virtualenv project - it can't seem to find the packages installed in the virtualenv environment.</p> <p>The odd thing is that i can set</p> <pre><code>test_suite = 'nose.collector' </code></pre> <p>in setup.py and run the tests just fine as</p> <pre><code>python setup.py ...
34
2009-05-14T18:30:15Z
18,971,267
<p>If all else fails, try installing nose in your venv, and/or run <code>nosetests-2.7</code>. I believe @andrea-zonca's answer has the same effect if your venv python is 2.7</p>
1
2013-09-24T00:51:41Z
[ "python", "virtualenv", "nose", "nosetests" ]
Python: Plugging wx.py.shell.Shell into a separate process
865,082
<p>I would like to create a shell which will control a separate process that I created with the multiprocessing module. Possible? How?</p> <p><strong>EDIT:</strong></p> <p>I have already achieved a way to send commands to the secondary process: I created a <code>code.InteractiveConsole</code> in that process, and att...
1
2009-05-14T18:56:26Z
865,875
<p>You can create a <code>Queue</code> which you pass to the separate process. From the <a href="http://docs.python.org/library/multiprocessing.html" rel="nofollow">Python Docs</a>:</p> <pre><code>from multiprocessing import Process, Queue def f(q): q.put([42, None, 'hello']) if __name__ == '__main__': q = Q...
0
2009-05-14T21:27:00Z
[ "python", "shell", "wxpython", "multiprocessing" ]
Python: Plugging wx.py.shell.Shell into a separate process
865,082
<p>I would like to create a shell which will control a separate process that I created with the multiprocessing module. Possible? How?</p> <p><strong>EDIT:</strong></p> <p>I have already achieved a way to send commands to the secondary process: I created a <code>code.InteractiveConsole</code> in that process, and att...
1
2009-05-14T18:56:26Z
892,646
<ol> <li>First create the shell </li> <li>Decouple the shell from your app by making its locals empty</li> <li>Create your code string</li> <li>Compile the code string and get a code object</li> <li>Execute the code object in the shell</li> </ol> <pre> from wx.py.shell import Shell frm = wx.Frame(None) sh...
1
2009-05-21T12:13:52Z
[ "python", "shell", "wxpython", "multiprocessing" ]
How do I correctly clean up a Python object?
865,115
<pre><code>class Package: def __init__(self): self.files = [] # ... def __del__(self): for file in self.files: os.unlink(file) </code></pre> <p><code>__del__(self)</code> above fails with an AttributeError exception. I understand <a href="http://docs.python.org/reference/data...
249
2009-05-14T19:04:12Z
865,138
<p>Just wrap your destructor with a try/except statement and it will not throw an exception if your globals are already disposed of.</p> <p><strong>Edit</strong></p> <p>Try this:</p> <pre><code>from weakref import proxy class MyList(list): pass class Package: def __init__(self): self.__del__.im_func.fi...
4
2009-05-14T19:08:42Z
[ "python", "destructor" ]
How do I correctly clean up a Python object?
865,115
<pre><code>class Package: def __init__(self): self.files = [] # ... def __del__(self): for file in self.files: os.unlink(file) </code></pre> <p><code>__del__(self)</code> above fails with an AttributeError exception. I understand <a href="http://docs.python.org/reference/data...
249
2009-05-14T19:04:12Z
865,140
<p>It seems that the idiomatic way to do this is to provide a <code>close()</code> method (or similar), and call it explicitely.</p>
3
2009-05-14T19:09:24Z
[ "python", "destructor" ]
How do I correctly clean up a Python object?
865,115
<pre><code>class Package: def __init__(self): self.files = [] # ... def __del__(self): for file in self.files: os.unlink(file) </code></pre> <p><code>__del__(self)</code> above fails with an AttributeError exception. I understand <a href="http://docs.python.org/reference/data...
249
2009-05-14T19:04:12Z
865,272
<p>I'd recommend using Python's <code>with</code> statement for managing resources that need to be cleaned up. The problem with using an explicit <code>close()</code> statement is that you have to worry about people forgetting to call it at all or forgetting to place it in a <code>finally</code> block to prevent a res...
337
2009-05-14T19:39:56Z
[ "python", "destructor" ]
How do I correctly clean up a Python object?
865,115
<pre><code>class Package: def __init__(self): self.files = [] # ... def __del__(self): for file in self.files: os.unlink(file) </code></pre> <p><code>__del__(self)</code> above fails with an AttributeError exception. I understand <a href="http://docs.python.org/reference/data...
249
2009-05-14T19:04:12Z
865,354
<p>I don't think that it's possible for instance members to be removed before <code>__del__</code> is called. My guess would be that the reason for your particular AttributeError is somewhere else (maybe you mistakenly remove self.file elsewhere).</p> <p>However, as the others pointed out, you should avoid using <code...
14
2009-05-14T19:51:55Z
[ "python", "destructor" ]
How do I correctly clean up a Python object?
865,115
<pre><code>class Package: def __init__(self): self.files = [] # ... def __del__(self): for file in self.files: os.unlink(file) </code></pre> <p><code>__del__(self)</code> above fails with an AttributeError exception. I understand <a href="http://docs.python.org/reference/data...
249
2009-05-14T19:04:12Z
13,621,521
<p>I think the problem could be in <code>__init__</code> if there is more code than shown?</p> <p><code>__del__</code> will be called even when <code>__init__</code> has not been executed properly or threw an exception.</p> <p><a href="http://www.algorithm.co.il/blogs/programming/python-gotchas-1-__del__-is-not-the-o...
8
2012-11-29T08:22:09Z
[ "python", "destructor" ]
How do I correctly clean up a Python object?
865,115
<pre><code>class Package: def __init__(self): self.files = [] # ... def __del__(self): for file in self.files: os.unlink(file) </code></pre> <p><code>__del__(self)</code> above fails with an AttributeError exception. I understand <a href="http://docs.python.org/reference/data...
249
2009-05-14T19:04:12Z
14,741,602
<p>Maybe, and I haven't tried this, if you really need to clean up the content of self.files then perhaps you can wrap each content in self.files in a class. The wrapper class containing a del method to delete itself.</p> <p>*shrug</p>
-4
2013-02-07T00:36:35Z
[ "python", "destructor" ]
How do I correctly clean up a Python object?
865,115
<pre><code>class Package: def __init__(self): self.files = [] # ... def __del__(self): for file in self.files: os.unlink(file) </code></pre> <p><code>__del__(self)</code> above fails with an AttributeError exception. I understand <a href="http://docs.python.org/reference/data...
249
2009-05-14T19:04:12Z
30,349,291
<p>As an appendix to <a href="http://stackoverflow.com/a/865272/321973">Clint's answer</a>, you can simplify <code>PackageResource</code> using <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" rel="nofollow"><code>contextlib.contextmanager</code></a>:</p> <pre><code>@contextlib.con...
12
2015-05-20T12:11:21Z
[ "python", "destructor" ]
How do you grep through code that lives in many different directories?
865,382
<p>I'm working on a Python program that makes heavy use of eggs (Plone). That means there are 198 directories full of Python code I might want to search through while debugging. Is there a good way to search only the .py files in only those directories, avoiding unrelated code and large binary files?</p>
14
2009-05-14T19:58:09Z
865,400
<pre><code>find DIRECTORY -name "*.py" | xargs grep PATTERN </code></pre> <p>By the way, since writing this, I have discovered <a href="http://beyondgrep.com/" rel="nofollow">ack</a>, which is a much better solution.</p>
16
2009-05-14T20:00:33Z
[ "python", "grep", "plone", "zope" ]
How do you grep through code that lives in many different directories?
865,382
<p>I'm working on a Python program that makes heavy use of eggs (Plone). That means there are 198 directories full of Python code I might want to search through while debugging. Is there a good way to search only the .py files in only those directories, avoiding unrelated code and large binary files?</p>
14
2009-05-14T19:58:09Z
865,421
<pre><code>grep -r -n "PATTERN" --include="*.py" DIRECTORY </code></pre>
5
2009-05-14T20:04:37Z
[ "python", "grep", "plone", "zope" ]
How do you grep through code that lives in many different directories?
865,382
<p>I'm working on a Python program that makes heavy use of eggs (Plone). That means there are 198 directories full of Python code I might want to search through while debugging. Is there a good way to search only the .py files in only those directories, avoiding unrelated code and large binary files?</p>
14
2009-05-14T19:58:09Z
865,422
<p>find &lt;directory&gt; -name '*.py' -exec grep &lt;pattern&gt; {} \;</p>
3
2009-05-14T20:04:42Z
[ "python", "grep", "plone", "zope" ]
How do you grep through code that lives in many different directories?
865,382
<p>I'm working on a Python program that makes heavy use of eggs (Plone). That means there are 198 directories full of Python code I might want to search through while debugging. Is there a good way to search only the .py files in only those directories, avoiding unrelated code and large binary files?</p>
14
2009-05-14T19:58:09Z
865,481
<p>I would strongly recommend <a href="http://betterthangrep.com/">ack</a>, a grep substitute, "aimed at programmers with large trees of heterogeneous source code" (from the website)</p>
18
2009-05-14T20:15:21Z
[ "python", "grep", "plone", "zope" ]
How do you grep through code that lives in many different directories?
865,382
<p>I'm working on a Python program that makes heavy use of eggs (Plone). That means there are 198 directories full of Python code I might want to search through while debugging. Is there a good way to search only the .py files in only those directories, avoiding unrelated code and large binary files?</p>
14
2009-05-14T19:58:09Z
1,001,943
<p>I also use ack a lot these days. I did tweak it a bit to find all the relevant file types:</p> <pre><code># Add zcml to the xml type: --type-add xml=.zcml # Add more files the plone type: --type-add plone=.dtml,.zpt,.kss,.vpy,.props # buildout config files --type-set buildout=.cfg # Include our page templates to...
6
2009-06-16T14:43:24Z
[ "python", "grep", "plone", "zope" ]
How do you grep through code that lives in many different directories?
865,382
<p>I'm working on a Python program that makes heavy use of eggs (Plone). That means there are 198 directories full of Python code I might want to search through while debugging. Is there a good way to search only the .py files in only those directories, avoiding unrelated code and large binary files?</p>
14
2009-05-14T19:58:09Z
1,441,324
<p>There's also <a href="http://www.gnu.org/software/idutils/" rel="nofollow" title="GNU idutils">GNU idutils</a> if you want to grep for identifiers in a large source tree very very quickly. It requires building a search database in advance, by running mkid (and tweaking its config file to not ignore .py files). <a ...
2
2009-09-17T20:59:42Z
[ "python", "grep", "plone", "zope" ]
How do you grep through code that lives in many different directories?
865,382
<p>I'm working on a Python program that makes heavy use of eggs (Plone). That means there are 198 directories full of Python code I might want to search through while debugging. Is there a good way to search only the .py files in only those directories, avoiding unrelated code and large binary files?</p>
14
2009-05-14T19:58:09Z
5,130,571
<p>My grepping life is way more satisfying since discovering Emacs' rgrep command.</p> <p>Say I want to find 'IPortletDataProvider' in Plone's source. I do:</p> <ol> <li><code>M-x rgrep</code></li> <li>Emacs prompts for the search string (IPortletDataProvider)</li> <li>... then which files to search (*.py)</li> <li>....
1
2011-02-27T00:03:30Z
[ "python", "grep", "plone", "zope" ]
How do you grep through code that lives in many different directories?
865,382
<p>I'm working on a Python program that makes heavy use of eggs (Plone). That means there are 198 directories full of Python code I might want to search through while debugging. Is there a good way to search only the .py files in only those directories, avoiding unrelated code and large binary files?</p>
14
2009-05-14T19:58:09Z
5,131,426
<p>Just in case you want a non-commandline OSS solution...</p> <p>I use pycharm. It has built in support for buildout. You point it at a buildout generated bin/instance and it sets the projects external dependencies to all the eggs used by the instance. Then all the IDE's introspection and code navigation work nicely....
1
2011-02-27T04:21:08Z
[ "python", "grep", "plone", "zope" ]
How do you grep through code that lives in many different directories?
865,382
<p>I'm working on a Python program that makes heavy use of eggs (Plone). That means there are 198 directories full of Python code I might want to search through while debugging. Is there a good way to search only the .py files in only those directories, avoiding unrelated code and large binary files?</p>
14
2009-05-14T19:58:09Z
5,131,554
<p>This problem was the motivation for the creation of collective.recipe.omelette. It is a buildout recipe which can symlink all the eggs from your working set into one directory structure, which you can point your favorite search utility at.</p>
4
2011-02-27T05:00:22Z
[ "python", "grep", "plone", "zope" ]
How do you grep through code that lives in many different directories?
865,382
<p>I'm working on a Python program that makes heavy use of eggs (Plone). That means there are 198 directories full of Python code I might want to search through while debugging. Is there a good way to search only the .py files in only those directories, avoiding unrelated code and large binary files?</p>
14
2009-05-14T19:58:09Z
5,140,059
<p>I recomend <a href="http://pypi.python.org/pypi/grin" rel="nofollow">grin</a> to search, <a href="http://pypi.python.org/pypi/collective.recipe.omelette" rel="nofollow">omelette</a> when working with plone and the pydev-feature 'Globals browser' (with eclipse or aptana studio).</p>
2
2011-02-28T09:19:30Z
[ "python", "grep", "plone", "zope" ]
How do you grep through code that lives in many different directories?
865,382
<p>I'm working on a Python program that makes heavy use of eggs (Plone). That means there are 198 directories full of Python code I might want to search through while debugging. Is there a good way to search only the .py files in only those directories, avoiding unrelated code and large binary files?</p>
14
2009-05-14T19:58:09Z
5,189,472
<p>And simply because there are not enough answers...</p> <p>If you're developing routinely, it's well worth the effort to install Eclipse with Pydev (or even easier, Aptana Studio - which is a modified Eclipse), in which case the find tools are right there.</p>
2
2011-03-04T03:56:29Z
[ "python", "grep", "plone", "zope" ]
How do you grep through code that lives in many different directories?
865,382
<p>I'm working on a Python program that makes heavy use of eggs (Plone). That means there are 198 directories full of Python code I might want to search through while debugging. Is there a good way to search only the .py files in only those directories, avoiding unrelated code and large binary files?</p>
14
2009-05-14T19:58:09Z
5,225,203
<p>OpenGrok is an excellent choice for source searching and navigation. Runs on Java, though.</p> <p>I really wish there was something like <a href="http://opengrok.plone.org/" rel="nofollow">http://opengrok.plone.org/</a></p>
1
2011-03-07T21:01:53Z
[ "python", "grep", "plone", "zope" ]
How can I get the name of a python class?
865,384
<p>When I have an object foo, I can get it's class object via</p> <pre><code>str(foo.__class__) </code></pre> <p>What I would need however is only the name of the class ("Foo" for example), the above would give me something along the lines of </p> <pre><code>"&lt;class 'my.package.Foo'&gt;" </code></pre> <p>I know ...
1
2009-05-14T19:58:27Z
865,414
<p>Try</p> <pre><code>__class__.__name__ </code></pre>
4
2009-05-14T20:02:59Z
[ "python", "reflection", "inspection" ]
How can I get the name of a python class?
865,384
<p>When I have an object foo, I can get it's class object via</p> <pre><code>str(foo.__class__) </code></pre> <p>What I would need however is only the name of the class ("Foo" for example), the above would give me something along the lines of </p> <pre><code>"&lt;class 'my.package.Foo'&gt;" </code></pre> <p>I know ...
1
2009-05-14T19:58:27Z
865,417
<p>foo.__class__.__name__ should give you result you need.</p>
3
2009-05-14T20:03:52Z
[ "python", "reflection", "inspection" ]
How can I get the name of a python class?
865,384
<p>When I have an object foo, I can get it's class object via</p> <pre><code>str(foo.__class__) </code></pre> <p>What I would need however is only the name of the class ("Foo" for example), the above would give me something along the lines of </p> <pre><code>"&lt;class 'my.package.Foo'&gt;" </code></pre> <p>I know ...
1
2009-05-14T19:58:27Z
865,431
<pre><code>Python 3.0.1 (r301:69561, Feb 13 2009, 20:04:18) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; class foo: ... x = 1 ... &gt;&gt;&gt; f = foo() &gt;&gt;&gt; f.__class__.__name__ 'foo' &gt;&gt;&gt; </code></pre>
1
2009-05-14T20:06:40Z
[ "python", "reflection", "inspection" ]
how to isinstance(x, module)?
865,503
<p>I need to test if a variable is a module or not. How to do this in the cleanest way?</p> <p>I need this for initializing some dispatcher function and I want that the function can accept either dict or module as an argument.</p>
11
2009-05-14T20:18:19Z
865,523
<pre><code>&gt;&gt;&gt; import os, types &gt;&gt;&gt; isinstance(os, types.ModuleType) True </code></pre> <p>(It also works for your own Python modules, as well as built-in ones like <code>os</code>.)</p>
21
2009-05-14T20:21:08Z
[ "python" ]
how to isinstance(x, module)?
865,503
<p>I need to test if a variable is a module or not. How to do this in the cleanest way?</p> <p>I need this for initializing some dispatcher function and I want that the function can accept either dict or module as an argument.</p>
11
2009-05-14T20:18:19Z
865,619
<p>I like to use this so you don't have to import the types module:</p> <pre><code>isinstance(amodule, __builtins__.__class__) </code></pre>
4
2009-05-14T20:37:35Z
[ "python" ]
How can I perform divison on a datetime.timedelta in python?
865,618
<p>I'd like to be able to do the following:</p> <pre><code>num_intervals = (cur_date - previous_date) / interval_length </code></pre> <p>or</p> <pre><code>print (datetime.now() - (datetime.now() - timedelta(days=5))) / timedelta(hours=12) # won't run, would like it to print '10' </code></pre> <p>but the divi...
19
2009-05-14T20:37:32Z
865,639
<p>Sure, just convert to a number of seconds (minutes, milliseconds, hours, take your pick of units) and do the division.</p> <p><em>EDIT</em> (again): so you can't assign to <code>timedelta.__div__</code>. Try this, then:</p> <pre><code>divtdi = datetime.timedelta.__div__ def divtd(td1, td2): if isinstance(td2, ...
7
2009-05-14T20:41:21Z
[ "python", "date", "datetime", "division", "timedelta" ]
How can I perform divison on a datetime.timedelta in python?
865,618
<p>I'd like to be able to do the following:</p> <pre><code>num_intervals = (cur_date - previous_date) / interval_length </code></pre> <p>or</p> <pre><code>print (datetime.now() - (datetime.now() - timedelta(days=5))) / timedelta(hours=12) # won't run, would like it to print '10' </code></pre> <p>but the divi...
19
2009-05-14T20:37:32Z
865,643
<p>You can override the division operator like this:</p> <pre><code>class MyTimeDelta(timedelta): def __div__(self, value): # Dome something about the object </code></pre>
2
2009-05-14T20:41:59Z
[ "python", "date", "datetime", "division", "timedelta" ]
How can I perform divison on a datetime.timedelta in python?
865,618
<p>I'd like to be able to do the following:</p> <pre><code>num_intervals = (cur_date - previous_date) / interval_length </code></pre> <p>or</p> <pre><code>print (datetime.now() - (datetime.now() - timedelta(days=5))) / timedelta(hours=12) # won't run, would like it to print '10' </code></pre> <p>but the divi...
19
2009-05-14T20:37:32Z
865,655
<p>Division and multiplication by integers seems to work <a href="http://docs.python.org/library/datetime.html#timedelta-objects">out of the box</a>:</p> <pre><code>&gt;&gt;&gt; from datetime import timedelta &gt;&gt;&gt; timedelta(hours=6) datetime.timedelta(0, 21600) &gt;&gt;&gt; timedelta(hours=6) / 2 datetime.time...
8
2009-05-14T20:44:46Z
[ "python", "date", "datetime", "division", "timedelta" ]
"else" considered harmful in Python?
865,741
<p>In an <a href="http://stackoverflow.com/questions/855759/python-try-else/855783#855783">answer</a> (by <a href="http://stackoverflow.com/users/10661/s-lott">S.Lott) </a>to a question about Python's <code>try...else</code> statement:</p> <blockquote> <p>Actually, even on an if-statement, the else: can be abused ...
11
2009-05-14T21:00:06Z
865,764
<p>S.Lott has obviously seen some bad code out there. Haven't we all? I do not consider else harmful, though I've seen it used to write bad code. In those cases, all the surrounding code has been bad as well, so why blame poor else?</p>
30
2009-05-14T21:04:53Z
[ "python", "if-statement" ]
"else" considered harmful in Python?
865,741
<p>In an <a href="http://stackoverflow.com/questions/855759/python-try-else/855783#855783">answer</a> (by <a href="http://stackoverflow.com/users/10661/s-lott">S.Lott) </a>to a question about Python's <code>try...else</code> statement:</p> <blockquote> <p>Actually, even on an if-statement, the else: can be abused ...
11
2009-05-14T21:00:06Z
865,768
<p>No it is not harmful, it is necessary.</p> <p>There should always be a catch-all statement. All switches should have a default. All pattern matching in an ML language should have a default.</p> <p>The argument that it is impossible to reason what is true after a series of if statements is a fact of life. The compu...
15
2009-05-14T21:06:57Z
[ "python", "if-statement" ]
"else" considered harmful in Python?
865,741
<p>In an <a href="http://stackoverflow.com/questions/855759/python-try-else/855783#855783">answer</a> (by <a href="http://stackoverflow.com/users/10661/s-lott">S.Lott) </a>to a question about Python's <code>try...else</code> statement:</p> <blockquote> <p>Actually, even on an if-statement, the else: can be abused ...
11
2009-05-14T21:00:06Z
865,775
<p>To me, the whole concept of certain popular language constructs being inherently bad is just plain wrong. Even <code>goto</code> has its place. I've seen very readable, maintainable code by the likes of Walter Bright and Linus Torvalds that uses it. It's much better to just teach programmers that readability coun...
6
2009-05-14T21:08:48Z
[ "python", "if-statement" ]
"else" considered harmful in Python?
865,741
<p>In an <a href="http://stackoverflow.com/questions/855759/python-try-else/855783#855783">answer</a> (by <a href="http://stackoverflow.com/users/10661/s-lott">S.Lott) </a>to a question about Python's <code>try...else</code> statement:</p> <blockquote> <p>Actually, even on an if-statement, the else: can be abused ...
11
2009-05-14T21:00:06Z
865,779
<p>Saying that else is considered harmful is a bit like saying that variables or classes are harmful. Heck, it's even like saying that goto is harmful. Sure, things can be misused. But at some point, you just have to trust programmers to be adults and be smart enough not to.</p> <p>What it comes down to is this: i...
7
2009-05-14T21:09:25Z
[ "python", "if-statement" ]
"else" considered harmful in Python?
865,741
<p>In an <a href="http://stackoverflow.com/questions/855759/python-try-else/855783#855783">answer</a> (by <a href="http://stackoverflow.com/users/10661/s-lott">S.Lott) </a>to a question about Python's <code>try...else</code> statement:</p> <blockquote> <p>Actually, even on an if-statement, the else: can be abused ...
11
2009-05-14T21:00:06Z
865,781
<p>I wouldn't say it is harmful, but there are times when the else statement can get you into trouble. For instance, if you need to do some processing based on an input value and there are only two valid input values. Only checking for one could introduce a bug. eg:</p> <pre><code>The only valid inputs are 1 and 2: ...
7
2009-05-14T21:09:31Z
[ "python", "if-statement" ]
"else" considered harmful in Python?
865,741
<p>In an <a href="http://stackoverflow.com/questions/855759/python-try-else/855783#855783">answer</a> (by <a href="http://stackoverflow.com/users/10661/s-lott">S.Lott) </a>to a question about Python's <code>try...else</code> statement:</p> <blockquote> <p>Actually, even on an if-statement, the else: can be abused ...
11
2009-05-14T21:00:06Z
865,790
<p>In the example posited of being hard to reason, it can be written explicitly, but the else is still necessary. E.g. </p> <pre><code>if a &lt; 10: # condition stated explicitly elif a &gt; 10 and b &lt; 10: # condition confusing but at least explicit else: # Exactly what is tru...
0
2009-05-14T21:11:30Z
[ "python", "if-statement" ]
"else" considered harmful in Python?
865,741
<p>In an <a href="http://stackoverflow.com/questions/855759/python-try-else/855783#855783">answer</a> (by <a href="http://stackoverflow.com/users/10661/s-lott">S.Lott) </a>to a question about Python's <code>try...else</code> statement:</p> <blockquote> <p>Actually, even on an if-statement, the else: can be abused ...
11
2009-05-14T21:00:06Z
865,791
<p><strong>Else</strong> is most useful when documenting assumptions about the code. It ensures that you have thought through both sides of an if statement.</p> <p>Always using an else clause with each if statement is even a recommended practice in "Code Complete".</p>
3
2009-05-14T21:11:31Z
[ "python", "if-statement" ]
"else" considered harmful in Python?
865,741
<p>In an <a href="http://stackoverflow.com/questions/855759/python-try-else/855783#855783">answer</a> (by <a href="http://stackoverflow.com/users/10661/s-lott">S.Lott) </a>to a question about Python's <code>try...else</code> statement:</p> <blockquote> <p>Actually, even on an if-statement, the else: can be abused ...
11
2009-05-14T21:00:06Z
865,796
<p>The rationale behind including the <code>else</code> statement (of <code>try...else</code>) in Python in the first place was to only catch the exceptions you really want to. Normally when you have a <code>try...except</code> block, there's some code that might raise an exception, and then there's some more code that...
2
2009-05-14T21:12:23Z
[ "python", "if-statement" ]
"else" considered harmful in Python?
865,741
<p>In an <a href="http://stackoverflow.com/questions/855759/python-try-else/855783#855783">answer</a> (by <a href="http://stackoverflow.com/users/10661/s-lott">S.Lott) </a>to a question about Python's <code>try...else</code> statement:</p> <blockquote> <p>Actually, even on an if-statement, the else: can be abused ...
11
2009-05-14T21:00:06Z
865,798
<p>Au contraire... In my opinion, there MUST be an else for every if. Granted, you can do stupid things, but you can abuse any construct if you try hard enough. You know the saying "a real programer can write FORTRAN in every language".</p> <p>What I do lots of time is to write the else part as a comment, describing w...
3
2009-05-14T21:12:24Z
[ "python", "if-statement" ]
"else" considered harmful in Python?
865,741
<p>In an <a href="http://stackoverflow.com/questions/855759/python-try-else/855783#855783">answer</a> (by <a href="http://stackoverflow.com/users/10661/s-lott">S.Lott) </a>to a question about Python's <code>try...else</code> statement:</p> <blockquote> <p>Actually, even on an if-statement, the else: can be abused ...
11
2009-05-14T21:00:06Z
865,800
<p>Seems to me that, for any language and any flow-control statement where there is a default scenario or side-effect, that scenario needs to have the same level of consideration. The logic in if or switch or while is only as good as the condition if(x) while(x) or for(...). Therefore the statement is not harmful but t...
1
2009-05-14T21:12:52Z
[ "python", "if-statement" ]
"else" considered harmful in Python?
865,741
<p>In an <a href="http://stackoverflow.com/questions/855759/python-try-else/855783#855783">answer</a> (by <a href="http://stackoverflow.com/users/10661/s-lott">S.Lott) </a>to a question about Python's <code>try...else</code> statement:</p> <blockquote> <p>Actually, even on an if-statement, the else: can be abused ...
11
2009-05-14T21:00:06Z
866,026
<p>I think the point with respect to <code>try...except...else</code> is that it is an easy mistake to use it to <em>create</em> inconsistent state rather than fix it. It is not that it should be avoided at all costs, but it can be counter-productive.</p> <p>Consider:</p> <pre><code>try: file = open('somefile','...
0
2009-05-14T21:50:38Z
[ "python", "if-statement" ]
"else" considered harmful in Python?
865,741
<p>In an <a href="http://stackoverflow.com/questions/855759/python-try-else/855783#855783">answer</a> (by <a href="http://stackoverflow.com/users/10661/s-lott">S.Lott) </a>to a question about Python's <code>try...else</code> statement:</p> <blockquote> <p>Actually, even on an if-statement, the else: can be abused ...
11
2009-05-14T21:00:06Z
866,309
<p>If you write:</p> <pre><code>if foo: # ... elif bar: # ... # ... </code></pre> <p>then the reader may be left wondering: what if neither <code>foo</code> nor <code>bar</code> is true? Perhaps you know, from your understanding of the code, that it must be the case that either <code>foo</code> or <code>bar<...
4
2009-05-14T23:02:38Z
[ "python", "if-statement" ]
"else" considered harmful in Python?
865,741
<p>In an <a href="http://stackoverflow.com/questions/855759/python-try-else/855783#855783">answer</a> (by <a href="http://stackoverflow.com/users/10661/s-lott">S.Lott) </a>to a question about Python's <code>try...else</code> statement:</p> <blockquote> <p>Actually, even on an if-statement, the else: can be abused ...
11
2009-05-14T21:00:06Z
871,073
<p>There is a so called "dangling else" problem which is encountered in C family languages as follows:</p> <pre><code>if (a==4) if (b==2) printf("here!"); else printf("which one"); </code></pre> <p>This innocent code can be understood in two ways:</p> <pre><code>if (a==4) if (b==2) printf("here!"); e...
1
2009-05-15T22:11:10Z
[ "python", "if-statement" ]
Is everything an object in python like ruby?
865,911
<p>A comment on another Stack Overflow question states that Python was just like Ruby, as it relates to "everything's an object," and everything in Python was an object, just like Ruby.</p> <p>Is this true? Is everything an object in python like ruby?</p> <p>How are the two different in this respect or are they real...
28
2009-05-14T21:33:02Z
865,963
<p><a href="http://www.diveintopython.net/getting_to_know_python/everything_is_an_object.html">DiveIntoPython - Everything Is an Object </a></p> <blockquote> <p>Everything in Python is an object, and almost everything has attributes and methods. All functions have a built-in attribute <code>__doc__</code>, which ret...
47
2009-05-14T21:40:38Z
[ "python", "ruby", "object" ]
Is everything an object in python like ruby?
865,911
<p>A comment on another Stack Overflow question states that Python was just like Ruby, as it relates to "everything's an object," and everything in Python was an object, just like Ruby.</p> <p>Is this true? Is everything an object in python like ruby?</p> <p>How are the two different in this respect or are they real...
28
2009-05-14T21:33:02Z
865,969
<p>Yep, as far as I know everything is an object in Python. Certainly the primitive and builtin types (int, long, str, float, etc.) can be subclassed - and in fact the types themselves are objects. Functions are objects, classes are objects, even code blocks are objects in a sense... I can't think of anything in Python...
1
2009-05-14T21:40:59Z
[ "python", "ruby", "object" ]
Is everything an object in python like ruby?
865,911
<p>A comment on another Stack Overflow question states that Python was just like Ruby, as it relates to "everything's an object," and everything in Python was an object, just like Ruby.</p> <p>Is this true? Is everything an object in python like ruby?</p> <p>How are the two different in this respect or are they real...
28
2009-05-14T21:33:02Z
866,039
<p>In answer to your second question, yes:</p> <pre><code>&gt;&gt;&gt; (1).__add__(2) 3 </code></pre>
13
2009-05-14T21:51:48Z
[ "python", "ruby", "object" ]
Is everything an object in python like ruby?
865,911
<p>A comment on another Stack Overflow question states that Python was just like Ruby, as it relates to "everything's an object," and everything in Python was an object, just like Ruby.</p> <p>Is this true? Is everything an object in python like ruby?</p> <p>How are the two different in this respect or are they real...
28
2009-05-14T21:33:02Z
866,083
<p>"everything" is a tad of an overbid, for both Python and Ruby -- for example, <code>if</code> is not "an object", rather it's a keyword used to start a conditional statement or (in Python) inside list comprehensions and generator expressions. The enthusiasm of finding out that functions, classes, methods, and all so...
12
2009-05-14T22:02:51Z
[ "python", "ruby", "object" ]
Is everything an object in python like ruby?
865,911
<p>A comment on another Stack Overflow question states that Python was just like Ruby, as it relates to "everything's an object," and everything in Python was an object, just like Ruby.</p> <p>Is this true? Is everything an object in python like ruby?</p> <p>How are the two different in this respect or are they real...
28
2009-05-14T21:33:02Z
866,085
<p>While everything is an object in Python, it differs from Ruby in its approach to resolving names and interacting with objects.</p> <p>For example, while Ruby provides you with a 'to_s' method on the Object base class, in order to expose that functionality, Python integrates it into the string type itself - you conv...
24
2009-05-14T22:03:28Z
[ "python", "ruby", "object" ]
Is everything an object in python like ruby?
865,911
<p>A comment on another Stack Overflow question states that Python was just like Ruby, as it relates to "everything's an object," and everything in Python was an object, just like Ruby.</p> <p>Is this true? Is everything an object in python like ruby?</p> <p>How are the two different in this respect or are they real...
28
2009-05-14T21:33:02Z
866,321
<p>To add a comment to other people's excellent answers: everything is an object, but some – notably strings and numeric types – are immutable. This means that these types behave the way they do in languages like C or Java (where integers, etc. are not objects) with respect to assignment, parameter passing, etc, a...
0
2009-05-14T23:08:33Z
[ "python", "ruby", "object" ]
Python: File IO - Disable incremental flush
865,957
<p>Kind of the opposite of <a href="http://stackoverflow.com/questions/608316/is-there-commit-analog-in-python-for-writing-into-a-file">this question</a>.</p> <p>Is there a way to tell Python "Do not write to disk until I tell you to." (by closing or flushing the file)? I'm writing to a file on the network, and would...
3
2009-05-14T21:39:42Z
866,007
<p>No, a glance at the python manual does not indicate an option to set the buffer size to infinity. </p> <p>Your current solution is basically the same concept.</p> <p>You <strong>could</strong> use Alex's idea, but I would hazard against it for the following reasons:</p> <ol> <li>The buffer size on open is limited...
3
2009-05-14T21:47:08Z
[ "python", "file-io" ]
Python: File IO - Disable incremental flush
865,957
<p>Kind of the opposite of <a href="http://stackoverflow.com/questions/608316/is-there-commit-analog-in-python-for-writing-into-a-file">this question</a>.</p> <p>Is there a way to tell Python "Do not write to disk until I tell you to." (by closing or flushing the file)? I'm writing to a file on the network, and would...
3
2009-05-14T21:39:42Z
866,019
<p>You can open your file with as large a buffer as you want. For example, to use up to a billion bytes for buffering, <code>x=open('/tmp/za', 'w', 1000*1000*1000)</code> -- if you have a hundred billion bytes of memory and want to use them all, just add another *100...;-). Memory will only be consumed in the amount ...
3
2009-05-14T21:49:20Z
[ "python", "file-io" ]
Python: File IO - Disable incremental flush
865,957
<p>Kind of the opposite of <a href="http://stackoverflow.com/questions/608316/is-there-commit-analog-in-python-for-writing-into-a-file">this question</a>.</p> <p>Is there a way to tell Python "Do not write to disk until I tell you to." (by closing or flushing the file)? I'm writing to a file on the network, and would...
3
2009-05-14T21:39:42Z
867,043
<p>I would say this partly depends on what you're trying to do. </p> <p>The case where I came across this issue was when my application was a bit slow creating a file that was used by another application, the other application would get incomplete versions of the file.</p> <p>I solved it by writing the file to a di...
1
2009-05-15T05:05:29Z
[ "python", "file-io" ]
Algorithm: How to Delete every other file
865,973
<p>I have a folder with thousands of images. I want to delete every other image. What is the most effective way to do this? Going through each one with i%2==0 is still O(n). Is there a fast way to do this (preferably in Python)?</p> <p>Thx</p>
1
2009-05-14T21:42:18Z
865,997
<p>To delete half the N images you <strong>cannot</strong> be faster than O(N)! You <em>do</em> know that the O() notation means (among other things) that constant multiplicative factors are irrelevant, yes?</p>
21
2009-05-14T21:45:49Z
[ "python", "algorithm" ]
Algorithm: How to Delete every other file
865,973
<p>I have a folder with thousands of images. I want to delete every other image. What is the most effective way to do this? Going through each one with i%2==0 is still O(n). Is there a fast way to do this (preferably in Python)?</p> <p>Thx</p>
1
2009-05-14T21:42:18Z
866,005
<p>I fail to see any conceivable way in which deleting <code>n/2</code> files could be faster than O(n), unless the filesystem has some special feature for deleting large numbers of files (but I don't think that actually exists in practice, if it's even possible)</p>
2
2009-05-14T21:46:46Z
[ "python", "algorithm" ]
Algorithm: How to Delete every other file
865,973
<p>I have a folder with thousands of images. I want to delete every other image. What is the most effective way to do this? Going through each one with i%2==0 is still O(n). Is there a fast way to do this (preferably in Python)?</p> <p>Thx</p>
1
2009-05-14T21:42:18Z
866,009
<p>If you wanted to delete Log(n) files, there would be... You can store images in a database, though ( MySQL has a "blob" type, among several others, that will store your images). Then you could do it in O(1) if you named them smartly.</p> <p>/edit i hate how i have to use shorthand and bad grammar to get my answers ...
1
2009-05-14T21:47:18Z
[ "python", "algorithm" ]
Algorithm: How to Delete every other file
865,973
<p>I have a folder with thousands of images. I want to delete every other image. What is the most effective way to do this? Going through each one with i%2==0 is still O(n). Is there a fast way to do this (preferably in Python)?</p> <p>Thx</p>
1
2009-05-14T21:42:18Z
866,018
<blockquote> <p>Going through each one with i%2==0 is still O(n). Is there a fast way to do this (preferably in Python)?</p> </blockquote> <p>The only way to be faster than O(n) is if your files are already sorted, and you only want to delete 1 file.</p> <p>You said i%2==0, this means you are deleting every "even" ...
3
2009-05-14T21:49:18Z
[ "python", "algorithm" ]
Algorithm: How to Delete every other file
865,973
<p>I have a folder with thousands of images. I want to delete every other image. What is the most effective way to do this? Going through each one with i%2==0 is still O(n). Is there a fast way to do this (preferably in Python)?</p> <p>Thx</p>
1
2009-05-14T21:42:18Z
866,030
<p>"Going through each one with i%2==0 is still O(n)"</p> <p>Increment by 2 instead of incrementing by 1?</p> <pre><code>for(i = 0; i &lt; numFiles; i += 2) { deleteFile(files[i]); } </code></pre> <p>Seriously though: iterating through a list of files probably isn't the slowest part of your file deletion algo. Th...
0
2009-05-14T21:50:54Z
[ "python", "algorithm" ]
Algorithm: How to Delete every other file
865,973
<p>I have a folder with thousands of images. I want to delete every other image. What is the most effective way to do this? Going through each one with i%2==0 is still O(n). Is there a fast way to do this (preferably in Python)?</p> <p>Thx</p>
1
2009-05-14T21:42:18Z
866,075
<p>You could use <code>islice</code> from the <code>itertools</code> module. Here goes your example:</p> <pre><code>import os, itertools dirContent = os.listdir('/some/dir/with/files') toBeDeleted = itertools.islice(dirContent, 0, len(dirContent), 2) # Now remove the files [os.unlink(file) for file in toBeDeleted] </c...
1
2009-05-14T22:01:43Z
[ "python", "algorithm" ]
Algorithm: How to Delete every other file
865,973
<p>I have a folder with thousands of images. I want to delete every other image. What is the most effective way to do this? Going through each one with i%2==0 is still O(n). Is there a fast way to do this (preferably in Python)?</p> <p>Thx</p>
1
2009-05-14T21:42:18Z
866,349
<pre><code>import os l = os.listdir('/some/dir/with/files') for n in l[::2]: os.unlink(n) </code></pre>
11
2009-05-14T23:18:38Z
[ "python", "algorithm" ]
Algorithm: How to Delete every other file
865,973
<p>I have a folder with thousands of images. I want to delete every other image. What is the most effective way to do this? Going through each one with i%2==0 is still O(n). Is there a fast way to do this (preferably in Python)?</p> <p>Thx</p>
1
2009-05-14T21:42:18Z
866,470
<p>I would try to use something operating-system specific like:</p> <p>linux:</p> <pre><code>@files = grep { -f "$dir/$_" &amp;&amp; /*.H$/ } unlink @files </code></pre> <p>Win:</p> <pre><code>$file_delete =~ /H$/; rm $file_delete </code></pre> <p>to see if your os can do it faster than iterating in python.</p> <...
0
2009-05-15T00:03:59Z
[ "python", "algorithm" ]
Using BeautifulSoup to find a HTML tag that contains certain text
866,000
<p>I'm trying to get the elements in an HTML doc that contain the following pattern of text: #\S{11}</p> <pre><code>&lt;h2&gt; this is cool #12345678901 &lt;/h2&gt; </code></pre> <p>So, the previous would match by using:</p> <pre><code>soup('h2',text=re.compile(r' #\S{11}')) </code></pre> <p>And the results would b...
33
2009-05-14T21:46:12Z
866,050
<pre><code>from BeautifulSoup import BeautifulSoup import re html_text = """ &lt;h2&gt;this is cool #12345678901&lt;/h2&gt; &lt;h2&gt;this is nothing&lt;/h2&gt; &lt;h1&gt;foo #126666678901&lt;/h1&gt; &lt;h2&gt;this is interesting #126666678901&lt;/h2&gt; &lt;h2&gt;this is blah #124445678901&lt;/h2&gt; """ soup = Beau...
40
2009-05-14T21:53:21Z
[ "python", "regex", "beautifulsoup", "html-content-extraction" ]
Using BeautifulSoup to find a HTML tag that contains certain text
866,000
<p>I'm trying to get the elements in an HTML doc that contain the following pattern of text: #\S{11}</p> <pre><code>&lt;h2&gt; this is cool #12345678901 &lt;/h2&gt; </code></pre> <p>So, the previous would match by using:</p> <pre><code>soup('h2',text=re.compile(r' #\S{11}')) </code></pre> <p>And the results would b...
33
2009-05-14T21:46:12Z
13,349,041
<p>BeautifulSoup search operations deliver [a list of] <code>BeautifulSoup.NavigableString</code> objects when <code>text=</code> is used as a criteria as opposed to <code>BeautifulSoup.Tag</code> in other cases. Check the object's <code>__dict__</code> to see the attributes made available to you. Of these attributes, ...
9
2012-11-12T18:05:50Z
[ "python", "regex", "beautifulsoup", "html-content-extraction" ]
python dealing with Nonetype before cast\addition
866,208
<p>I'm pulling a row from a db and adding up the fields (approx 15) to get a total. But some field values will be Null, which causes an error in the addition of the fields (<code>TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'</code>)</p> <p>Right now, with each field, I get the field value and set...
4
2009-05-14T22:33:10Z
866,230
<p>You can do it easily like this:</p> <pre><code>result = sum(field for field in row if field) </code></pre>
13
2009-05-14T22:38:11Z
[ "python", "types" ]
python dealing with Nonetype before cast\addition
866,208
<p>I'm pulling a row from a db and adding up the fields (approx 15) to get a total. But some field values will be Null, which causes an error in the addition of the fields (<code>TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'</code>)</p> <p>Right now, with each field, I get the field value and set...
4
2009-05-14T22:33:10Z
866,375
<p>Here's a clunkier version.</p> <pre><code>total = (a if a is not None else 0) + (b if b is not None else 0) + ... </code></pre> <p>Here's another choice.</p> <pre><code>def ifnull(col,replacement=0): return col if col is not None else replacement total = ifnull(a) + ifnull(b) + ifnull(c) + ... </code></pre> ...
0
2009-05-14T23:26:37Z
[ "python", "types" ]
python dealing with Nonetype before cast\addition
866,208
<p>I'm pulling a row from a db and adding up the fields (approx 15) to get a total. But some field values will be Null, which causes an error in the addition of the fields (<code>TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'</code>)</p> <p>Right now, with each field, I get the field value and set...
4
2009-05-14T22:33:10Z
866,800
<p>Another (better?) option is to do this in the database. You can alter your db query to map NULL to 0 using COALESCE.</p> <p>Say you have a table with integer columns named col1, col2, col3 that can accept NULLs.</p> <p>Option 1:</p> <pre><code>SELECT coalesce(col1, 0) as col1, coalesce(col2, 0) as col2, coalesce(...
1
2009-05-15T02:58:39Z
[ "python", "types" ]
python dealing with Nonetype before cast\addition
866,208
<p>I'm pulling a row from a db and adding up the fields (approx 15) to get a total. But some field values will be Null, which causes an error in the addition of the fields (<code>TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'</code>)</p> <p>Right now, with each field, I get the field value and set...
4
2009-05-14T22:33:10Z
867,519
<pre><code>total = 0.0 for f in fields: total += f or 0.0 </code></pre>
0
2009-05-15T08:09:52Z
[ "python", "types" ]
How can I build multiple submit buttons django form?
866,272
<p>I have form with one input for email and two submit buttons to subscribe and unsubscribe from newsletter:</p> <pre><code>&lt;form action="" method="post"&gt; {{ form_newsletter }} &lt;input type="submit" name="newsletter_sub" value="Subscribe" /&gt; &lt;input type="submit" name="newsletter_unsub" value="Unsubscribe...
101
2009-05-14T22:50:25Z
866,311
<p>You can use <code>self.data</code> in the <code>clean_email</code> method to access the POST data before validation. It should contain a key called <code>newsletter_sub</code> or <code>newsletter_unsub</code> depending on which button was pressed.</p> <pre><code># in the context of a django.forms form def clean(se...
58
2009-05-14T23:03:30Z
[ "python", "button", "django-forms", "submit" ]
How can I build multiple submit buttons django form?
866,272
<p>I have form with one input for email and two submit buttons to subscribe and unsubscribe from newsletter:</p> <pre><code>&lt;form action="" method="post"&gt; {{ form_newsletter }} &lt;input type="submit" name="newsletter_sub" value="Subscribe" /&gt; &lt;input type="submit" name="newsletter_unsub" value="Unsubscribe...
101
2009-05-14T22:50:25Z
2,011,023
<p>Eg:</p> <pre><code>if 'newsletter_sub' in request.POST: # do subscribe elif 'newsletter_unsub' in request.POST: # do unsubscribe </code></pre>
167
2010-01-06T04:50:40Z
[ "python", "button", "django-forms", "submit" ]
How can I build multiple submit buttons django form?
866,272
<p>I have form with one input for email and two submit buttons to subscribe and unsubscribe from newsletter:</p> <pre><code>&lt;form action="" method="post"&gt; {{ form_newsletter }} &lt;input type="submit" name="newsletter_sub" value="Subscribe" /&gt; &lt;input type="submit" name="newsletter_unsub" value="Unsubscribe...
101
2009-05-14T22:50:25Z
16,891,638
<p>You can also do like this,</p> <pre><code> &lt;form method='POST'&gt; {{form1.as_p}} &lt;button type="submit" name="btnform1"&gt;Save Changes&lt;/button&gt; &lt;/form&gt; &lt;form method='POST'&gt; {{form2.as_p}} &lt;button type="submit" name="btnform2"&gt;Save Changes&lt;/button&gt; &lt...
4
2013-06-03T07:09:47Z
[ "python", "button", "django-forms", "submit" ]
How can I build multiple submit buttons django form?
866,272
<p>I have form with one input for email and two submit buttons to subscribe and unsubscribe from newsletter:</p> <pre><code>&lt;form action="" method="post"&gt; {{ form_newsletter }} &lt;input type="submit" name="newsletter_sub" value="Subscribe" /&gt; &lt;input type="submit" name="newsletter_unsub" value="Unsubscribe...
101
2009-05-14T22:50:25Z
23,505,267
<p>It's an old question now, nevertheless I had the same issue and found a solution that works for me: I wrote MultiRedirectMixin.</p> <pre><code>from django.http import HttpResponseRedirect class MultiRedirectMixin(object): """ A mixin that supports submit-specific success redirection. Either specify on...
2
2014-05-06T22:00:44Z
[ "python", "button", "django-forms", "submit" ]