title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
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 obvious solution is to simply invert the dictionary every time I want a reverse-lookup: Inverting a dictionary is very easy, <a href="http://stackoverflow.com/questions/483666/python-reverse-inverse-a-mapping/483833">there's a recipe here but for a large dictionary it can be very slow</a>.</p>
<p>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. </p>
<p>So is there a better structure I can use?</p>
<ul>
<li>My application requires that this should be very fast and use as little as possible memory.</li>
<li>The structure must be mutable, and it's strongly desirable that mutating the object should not cause it to be slower (e.g. to force a complete re-index)</li>
<li>We can guarantee that either the key or the value (or both) will be an integer</li>
<li>It's likely that the structure will be needed to store thousands or possibly millions of items.</li>
<li>Keys & Valus are guaranteed to be unique, i.e. len(set(x)) == len(x) for for x in [D.keys(), D.valuies()]</li>
</ul>
| 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 references to the <strong>same objects</strong> as keys and values, then the memory spent would be just the dictionary structure. That's a lot less than <strong><em>twice</em></strong> and is a fixed ammount regardless of your data size.</p>
<p>What I mean is that the actual data wouldn't be copied. So you'd spend little extra memory.</p>
<p>Example:</p>
<pre><code>a = "some really really big text spending a lot of memory"
number_to_text = {1: a}
text_to_number = {a: 1}
</code></pre>
<p>Only a single copy of the "really big" string exists, so you end up spending just a little more memory. That's generally affordable.</p>
<p>I can't imagine a solution where you'd have the key lookup speed when looking by value, if you don't spend <em>at least</em> enough memory to store a reverse lookup hash table (which is exactly what's being done in your "unite two <code>dict</code>s" solution).</p>
| 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 obvious solution is to simply invert the dictionary every time I want a reverse-lookup: Inverting a dictionary is very easy, <a href="http://stackoverflow.com/questions/483666/python-reverse-inverse-a-mapping/483833">there's a recipe here but for a large dictionary it can be very slow</a>.</p>
<p>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. </p>
<p>So is there a better structure I can use?</p>
<ul>
<li>My application requires that this should be very fast and use as little as possible memory.</li>
<li>The structure must be mutable, and it's strongly desirable that mutating the object should not cause it to be slower (e.g. to force a complete re-index)</li>
<li>We can guarantee that either the key or the value (or both) will be an integer</li>
<li>It's likely that the structure will be needed to store thousands or possibly millions of items.</li>
<li>Keys & Valus are guaranteed to be unique, i.e. len(set(x)) == len(x) for for x in [D.keys(), D.valuies()]</li>
</ul>
| 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 replacing the target object with an integer value so you only have one copy referenced by an integer. This is a false economy. Just keep the target object. All Python objects are -- in effect -- references. Very little actual copying gets done.</p>
<p>Let's pretend that you simply have two integers and can do a lookup on either one of the pair. One way to do this is to use heap queues or the bisect module to maintain ordered lists of integer key-value tuples.</p>
<p>See <a href="http://docs.python.org/library/heapq.html#module-heapq" rel="nofollow">http://docs.python.org/library/heapq.html#module-heapq</a></p>
<p>See <a href="http://docs.python.org/library/bisect.html#module-bisect" rel="nofollow">http://docs.python.org/library/bisect.html#module-bisect</a></p>
<p>You have one heapq <code>(key,value)</code> tuples. Or, if your underlying object is more complex, the <code>(key,object</code>) tuples.</p>
<p>You have another heapq <code>(value,key)</code> tuples. Or, if your underlying object is more complex, <code>(otherkey,object)</code> tuples.</p>
<p>An "insert" becomes two inserts, one to each heapq-structured list.</p>
<p>A key lookup is in one queue; a value lookup is in the other queue. Do the lookups using <code>bisect(list,item)</code>. </p>
| 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 obvious solution is to simply invert the dictionary every time I want a reverse-lookup: Inverting a dictionary is very easy, <a href="http://stackoverflow.com/questions/483666/python-reverse-inverse-a-mapping/483833">there's a recipe here but for a large dictionary it can be very slow</a>.</p>
<p>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. </p>
<p>So is there a better structure I can use?</p>
<ul>
<li>My application requires that this should be very fast and use as little as possible memory.</li>
<li>The structure must be mutable, and it's strongly desirable that mutating the object should not cause it to be slower (e.g. to force a complete re-index)</li>
<li>We can guarantee that either the key or the value (or both) will be an integer</li>
<li>It's likely that the structure will be needed to store thousands or possibly millions of items.</li>
<li>Keys & Valus are guaranteed to be unique, i.e. len(set(x)) == len(x) for for x in [D.keys(), D.valuies()]</li>
</ul>
| 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 BiDict(list):
def __init__(self,*pairs):
super(list,self).__init__(pairs)
self._first_access = {}
self._second_access = {}
for pair in pairs:
self._first_access[pair[0]] = pair[1]
self._second_access[pair[1]] = pair[0]
self.append(pair)
def _get_by_first(self,key):
return self._first_access[key]
def _get_by_second(self,key):
return self._second_access[key]
# You'll have to do some overrides to make it mutable
# Methods such as append, __add__, __del__, __iadd__
# to name a few will have to maintain ._*_access
class Constants(BiDict):
# An implementation expecting an integer and a string
get_by_name = BiDict._get_by_second
get_by_number = BiDict._get_by_first
t = Constants(
( 1, 'foo'),
( 5, 'bar'),
( 8, 'baz'),
)
>>> print t.get_by_number(5)
bar
>>> print t.get_by_name('baz')
8
>>> print t
[(1, 'foo'), (5, 'bar'), (8, 'baz')]
</code></pre>
| 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 obvious solution is to simply invert the dictionary every time I want a reverse-lookup: Inverting a dictionary is very easy, <a href="http://stackoverflow.com/questions/483666/python-reverse-inverse-a-mapping/483833">there's a recipe here but for a large dictionary it can be very slow</a>.</p>
<p>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. </p>
<p>So is there a better structure I can use?</p>
<ul>
<li>My application requires that this should be very fast and use as little as possible memory.</li>
<li>The structure must be mutable, and it's strongly desirable that mutating the object should not cause it to be slower (e.g. to force a complete re-index)</li>
<li>We can guarantee that either the key or the value (or both) will be an integer</li>
<li>It's likely that the structure will be needed to store thousands or possibly millions of items.</li>
<li>Keys & Valus are guaranteed to be unique, i.e. len(set(x)) == len(x) for for x in [D.keys(), D.valuies()]</li>
</ul>
| 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 obvious solution is to simply invert the dictionary every time I want a reverse-lookup: Inverting a dictionary is very easy, <a href="http://stackoverflow.com/questions/483666/python-reverse-inverse-a-mapping/483833">there's a recipe here but for a large dictionary it can be very slow</a>.</p>
<p>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. </p>
<p>So is there a better structure I can use?</p>
<ul>
<li>My application requires that this should be very fast and use as little as possible memory.</li>
<li>The structure must be mutable, and it's strongly desirable that mutating the object should not cause it to be slower (e.g. to force a complete re-index)</li>
<li>We can guarantee that either the key or the value (or both) will be an integer</li>
<li>It's likely that the structure will be needed to store thousands or possibly millions of items.</li>
<li>Keys & Valus are guaranteed to be unique, i.e. len(set(x)) == len(x) for for x in [D.keys(), D.valuies()]</li>
</ul>
| 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 obvious solution is to simply invert the dictionary every time I want a reverse-lookup: Inverting a dictionary is very easy, <a href="http://stackoverflow.com/questions/483666/python-reverse-inverse-a-mapping/483833">there's a recipe here but for a large dictionary it can be very slow</a>.</p>
<p>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. </p>
<p>So is there a better structure I can use?</p>
<ul>
<li>My application requires that this should be very fast and use as little as possible memory.</li>
<li>The structure must be mutable, and it's strongly desirable that mutating the object should not cause it to be slower (e.g. to force a complete re-index)</li>
<li>We can guarantee that either the key or the value (or both) will be an integer</li>
<li>It's likely that the structure will be needed to store thousands or possibly millions of items.</li>
<li>Keys & Valus are guaranteed to be unique, i.e. len(set(x)) == len(x) for for x in [D.keys(), D.valuies()]</li>
</ul>
| 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>partner</code>.</p>
<p><code>OneToOneDict</code> subclasses from <code>dict</code> - I know that <a href="http://stackoverflow.com/questions/1392396/advantages-of-userdict-class-in-python/1394572#1394572">isn't generally recommended</a>, but I think I have the common use cases covered. The backend is pretty simple, it (<code>dict1</code>) keeps a weakref to a 'partner' <code>OneToOneDict</code> (<code>dict2</code>) which is its inverse. When <code>dict1</code> is modified <code>dict2</code> is updated accordingly as well and vice versa.</p>
<p>From the docstring:</p>
<pre><code>>>> dict1 = OneToOneDict()
>>> dict2 = OneToOneDict()
>>> dict1.partner = dict2
>>> assert(dict1 is dict2.partner)
>>> assert(dict2 is dict1.partner)
>>> dict1['one'] = '1'
>>> dict2['2'] = '1'
>>> dict1['one'] = 'wow'
>>> assert(dict1 == dict((v,k) for k,v in dict2.items()))
>>> dict1['one'] = '1'
>>> assert(dict1 == dict((v,k) for k,v in dict2.items()))
>>> dict1.update({'three': '3', 'four': '4'})
>>> assert(dict1 == dict((v,k) for k,v in dict2.items()))
>>> dict3 = OneToOneDict({'4':'four'})
>>> assert(dict3.partner is None)
>>> assert(dict3 == {'4':'four'})
>>> dict1.partner = dict3
>>> assert(dict1.partner is not dict2)
>>> assert(dict2.partner is None)
>>> assert(dict1.partner is dict3)
>>> assert(dict3.partner is dict1)
>>> dict1.setdefault('five', '5')
>>> dict1['five']
'5'
>>> dict1.setdefault('five', '0')
>>> dict1['five']
'5'
</code></pre>
<p>When I get some free time, I intend to make a version that doesn't store things twice. No clue when that'll be though :)</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 open, possible states are CLOSED, CANCELED
...
if foo.state == STATES.PENDING: #if foo is pending, possible states are OPEN,CANCELED
...
</code></pre>
<p>As a result, when foo.state changes to a new state, its set of possible choices changes also.</p>
<p>How can I implement this functionality on Admin add/change pages?</p>
| 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 open, possible states are CLOSED, CANCELED
...
if foo.state == STATES.PENDING: #if foo is pending, possible states are OPEN,CANCELED
...
</code></pre>
<p>As a result, when foo.state changes to a new state, its set of possible choices changes also.</p>
<p>How can I implement this functionality on Admin add/change pages?</p>
| 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.ModelForm):
class Meta:
model = Foo
def __init__(self, *args, **kwargs):
super(FooForm, self).__init__(*args, **kwargs)
current_state = self.instance.state
...construct available_choices based on current state...
self.fields['state'].choices = available_choices
</code></pre>
<p>You'd use it like this:</p>
<pre><code>class FooAdmin(admin.ModelAdmin):
form = FooForm
</code></pre>
| 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 open, possible states are CLOSED, CANCELED
...
if foo.state == STATES.PENDING: #if foo is pending, possible states are OPEN,CANCELED
...
</code></pre>
<p>As a result, when foo.state changes to a new state, its set of possible choices changes also.</p>
<p>How can I implement this functionality on Admin add/change pages?</p>
| 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 javascript.</p>
<p>You can load custom javascript in a model's admin page by using the ModelAdmin's Media class, documented <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#modeladmin-media-definitions" rel="nofollow">here</a>. </p>
| 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 open, possible states are CLOSED, CANCELED
...
if foo.state == STATES.PENDING: #if foo is pending, possible states are OPEN,CANCELED
...
</code></pre>
<p>As a result, when foo.state changes to a new state, its set of possible choices changes also.</p>
<p>How can I implement this functionality on Admin add/change pages?</p>
| 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>class MyModelAdmin(admin.ModelAdmin):
def formfield_for_choice_field(self, db_field, request, **kwargs):
if db_field.name == "status":
kwargs['choices'] = (
('accepted', 'Accepted'),
('denied', 'Denied'),
)
if request.user.is_superuser:
kwargs['choices'] += (('ready', 'Ready for deployment'),)
return super(MyModelAdmin, self).formfield_for_choice_field(db_field, request, **kwargs)
</code></pre>
<p>But you can also override choices for <a href="https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_for_foreignkey">ForeignKey</a> and <a href="https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_for_manytomany">Many to Many</a> relationships.</p>
| 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 < 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 < 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>>>> foo = [0, 1, 2]
>>> for bar in foo:
if bar % 2: # append to foo for every odd number
foo.append(len(foo))
print bar
0
1
2
3
4
</code></pre>
<p>If you need to know how "far" into the list you are, you can use <code>enumerate</code>:</p>
<pre><code>>>> foo = ["wibble", "wobble", "wubble"]
>>> for i, bar in enumerate(foo):
if i % 2: # append to foo for every odd number
foo.append("appended")
print bar
wibble
wobble
wubble
appended
appended
</code></pre>
| 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)
</code></pre>
<p>Then I know I can get the derived object by calling</p>
<pre><code>base = BaseClass.objects.get(pk=3)
my_obj= base.someclass
</code></pre>
<p>Now the problem arises that I have multiple subclasses, and all I have is an instance of the base class. How can I get to the subclassed object without knowing it's class in advance?</p>
<p><hr /></p>
<p>The idea is to load a corresponding view and let that do the stuff. My project features only have a limited set of default actions for these models, like view, edit, delete etc. What I don't want is to expose the type of the given object via URL, so the "normal way" is not available</p>
| 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 a corresponding view and let that do the stuff. My project features only have a limited set of default actions for these models, like view, edit, delete etc. What I don't want is to expose the type of the given object via URL, so the "normal way" is not available</p>
</blockquote>
<p>If you know the set of model subclasses ahead of time, or are willing to register them with a central view list, you can do something like this:</p>
<pre><code>VIEWS = [('subclass_a', a_views), ('subclass_b', b_views)]
def edit(request):
base = (get base somehow)
for attrname, views in VIEWS:
if getattr(base, attrname) is not None:
return views['edit']
</code></pre>
<p>Depending on how many different kinds of views you have, you might abstract the search out into a separate function, so the end view is something like:</p>
<pre><code>def edit(request):
return generic_base_view(request, 'edit')
</code></pre>
| 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)
</code></pre>
<p>Then I know I can get the derived object by calling</p>
<pre><code>base = BaseClass.objects.get(pk=3)
my_obj= base.someclass
</code></pre>
<p>Now the problem arises that I have multiple subclasses, and all I have is an instance of the base class. How can I get to the subclassed object without knowing it's class in advance?</p>
<p><hr /></p>
<p>The idea is to load a corresponding view and let that do the stuff. My project features only have a limited set of default actions for these models, like view, edit, delete etc. What I don't want is to expose the type of the given object via URL, so the "normal way" is not available</p>
| 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 returns the actual derived object.</p>
| 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)
</code></pre>
<p>Then I know I can get the derived object by calling</p>
<pre><code>base = BaseClass.objects.get(pk=3)
my_obj= base.someclass
</code></pre>
<p>Now the problem arises that I have multiple subclasses, and all I have is an instance of the base class. How can I get to the subclassed object without knowing it's class in advance?</p>
<p><hr /></p>
<p>The idea is to load a corresponding view and let that do the stuff. My project features only have a limited set of default actions for these models, like view, edit, delete etc. What I don't want is to expose the type of the given object via URL, so the "normal way" is not available</p>
| 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 multi table inheritance</a></p>
<p>look at the example of places and restaurants. The base object is a place, and the subclass is a restaurant. You can get the subclass by place.restaurant which gives an exception you can catch if the place is not a restaurant.
I add this because the answer accepted might be a bit outdated and led me to the wrong track.</p>
| 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)
</code></pre>
<p>Then I know I can get the derived object by calling</p>
<pre><code>base = BaseClass.objects.get(pk=3)
my_obj= base.someclass
</code></pre>
<p>Now the problem arises that I have multiple subclasses, and all I have is an instance of the base class. How can I get to the subclassed object without knowing it's class in advance?</p>
<p><hr /></p>
<p>The idea is to load a corresponding view and let that do the stuff. My project features only have a limited set of default actions for these models, like view, edit, delete etc. What I don't want is to expose the type of the given object via URL, so the "normal way" is not available</p>
| 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/latest/managers.html#inheritancemanager</a></p>
| 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?"
</code></pre>
| 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.write(fd,"password\n")
c = os.read(fd, 1)
while c:
c = os.read(fd, 1)
sys.stdout.write(c)
</code></pre>
| 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) converting the individual values?</p>
<p>I guess I should clarify, that it needn't look like a matrix, just the associated values in an easy to parse list, as I will be reading in later. All on one line may actually make this easier!</p>
| 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) converting the individual values?</p>
<p>I guess I should clarify, that it needn't look like a matrix, just the associated values in an easy to parse list, as I will be reading in later. All on one line may actually make this easier!</p>
| 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) converting the individual values?</p>
<p>I guess I should clarify, that it needn't look like a matrix, just the associated values in an easy to parse list, as I will be reading in later. All on one line may actually make this easier!</p>
| 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) converting the individual values?</p>
<p>I guess I should clarify, that it needn't look like a matrix, just the associated values in an easy to parse list, as I will be reading in later. All on one line may actually make this easier!</p>
| 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 (lp0
2 S'hello'
3 p1
4 aS'world'
5 p2
6 a.
</code></pre>
| 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) converting the individual values?</p>
<p>I guess I should clarify, that it needn't look like a matrix, just the associated values in an easy to parse list, as I will be reading in later. All on one line may actually make this easier!</p>
| 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 PyCe which I think is what I would need to get started on the app? Can anyone with some experience in this area point me in the right direction? What to download to get started, what lightweight database I could use, etc?</p>
<p>Thanks in advance!</p>
| 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 test
</code></pre>
<p>but when running nosetests straight, there are all sorts of import errors.</p>
<p>I've tried it with both a system-wide installation of nose and a virtualenv nose package and no luck.</p>
<p>Any thoughts?</p>
<p>Thanks!!</p>
| 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 test
</code></pre>
<p>but when running nosetests straight, there are all sorts of import errors.</p>
<p>I've tried it with both a system-wide installation of nose and a virtualenv nose package and no luck.</p>
<p>Any thoughts?</p>
<p>Thanks!!</p>
| 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_install nose # install nose package into "env1"
</code></pre>
<p>I created a really basic package <code>slither</code> that had, in its <code>setup.py</code>, same <code>test_suite</code> attribute as you mentioned above. Then I placed the package source under <code>env1/src</code>.</p>
<p>If you looked inside <code>env1/src</code>, you'd see:</p>
<pre><code>slither/setup.py
slither/slither/__init__.py
slither/slither/impl.py # has some very silly code to be tested
slither/slither/tests.py # has test-cases
</code></pre>
<p>I can run the tests using <code>test</code> subcommand:</p>
<pre><code>(env1)$ pushd src/slither
(env1)$ python setup.py test
# ... output elided ...
test_ctor (slither.tests.SnakeTests) ... ok
test_division_by_zero (slither.tests.SnakeTests) ... ok
Ran 2 tests in 0.009s
OK
(env1)$ popd
</code></pre>
<p>Or, I can run the same tests with <code>nosetests</code>:</p>
<pre><code>(env1)$ pushd src
(env1)$ nosetests slither/
..
Ran 2 tests in 0.007s
OK
(env1)$ popd
</code></pre>
<p>Also note that <code>nosetests</code> can be picky about executables. You can pass <code>--exe</code> if you want it to discover tests in python modules that are executable.</p>
| 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 test
</code></pre>
<p>but when running nosetests straight, there are all sorts of import errors.</p>
<p>I've tried it with both a system-wide installation of nose and a virtualenv nose package and no luck.</p>
<p>Any thoughts?</p>
<p>Thanks!!</p>
| 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 test
</code></pre>
<p>but when running nosetests straight, there are all sorts of import errors.</p>
<p>I've tried it with both a system-wide installation of nose and a virtualenv nose package and no luck.</p>
<p>Any thoughts?</p>
<p>Thanks!!</p>
| 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>From then on you can just run <code>nosetests</code> as usual.</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 test
</code></pre>
<p>but when running nosetests straight, there are all sorts of import errors.</p>
<p>I've tried it with both a system-wide installation of nose and a virtualenv nose package and no luck.</p>
<p>Any thoughts?</p>
<p>Thanks!!</p>
| 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/<env>/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 test
</code></pre>
<p>but when running nosetests straight, there are all sorts of import errors.</p>
<p>I've tried it with both a system-wide installation of nose and a virtualenv nose package and no luck.</p>
<p>Any thoughts?</p>
<p>Thanks!!</p>
| 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 your <code>PATH</code>:</p>
<pre><code>export PATH=/path/to/current/virtualenv/bin:$PATH
</code></pre>
| 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 test
</code></pre>
<p>but when running nosetests straight, there are all sorts of import errors.</p>
<p>I've tried it with both a system-wide installation of nose and a virtualenv nose package and no luck.</p>
<p>Any thoughts?</p>
<p>Thanks!!</p>
| 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 test
</code></pre>
<p>but when running nosetests straight, there are all sorts of import errors.</p>
<p>I've tried it with both a system-wide installation of nose and a virtualenv nose package and no luck.</p>
<p>Any thoughts?</p>
<p>Thanks!!</p>
| 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 attached it to an input queue and an output queue, so I can command the console from my main process. But I want it in a shell, probably a <code>wx.py.shell.Shell</code>, so a user of the program could use it.</p>
| 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 = Queue()
p = Process(target=f, args=(q,))
p.start()
print q.get() # prints "[42, None, 'hello']"
p.join()
</code></pre>
<p><strong>EXAMPLE:</strong> In the <a href="http://www.wxpython.org/docs/api/wx.py.shell.Shell-class.html#%5F%5Finit%5F%5F" rel="nofollow">wx.py.shell.Shell Docs</a> the constructur parameters are given as</p>
<pre><code>__init__(self, parent, id, pos, size, style, introText, locals,
InterpClass, startupScript, execStartupScript, *args, **kwds)
</code></pre>
<p>I have not tried it, but <code>locals</code> might be a dictionary of local variables, which you can pass to the shell. So, I would try the following:</p>
<pre><code>def f(cmd_queue):
shell = wx.py.shell.Shell(parent, id, pos, size, style, introText, locals(),
...)
q = Queue()
p = Process(target=f, args=(q,))
p.start()
</code></pre>
<p>Inside the shell, you should then be able to put your commands into <code>cmd_queue</code> which have then to be read in the parent process to be executed.</p>
| 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 attached it to an input queue and an output queue, so I can command the console from my main process. But I want it in a shell, probably a <code>wx.py.shell.Shell</code>, so a user of the program could use it.</p>
| 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 = Shell(frm)
frm.Show()
sh.interp.locals = {}
codeStr = """
from multiprocessing import Process, Queue
def f(q):
q.put([42, None, 'hello'])
q = Queue()
p = Process(target=f, args=(q,))
p.start()
print q.get() # prints "[42, None, 'hello']"
p.join()
"""
code = compile(codeStr, '', 'exec')
sh.interp.runcode(code)
</pre>
<p>Note:
The codeStr I stole from the first poster may not work here due to some pickling issues. But the point is you can execute your own codeStr remotely in a shell.</p>
| 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/datamodel.html#customization">Python doesn't guarantee</a> the existence of "global variables" (member data in this context?) when <code>__del__()</code> is invoked. If that is the case and this is the reason for the exception, how do I make sure the object destructs properly?</p>
| 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.files = MyList([1,2,3,4])
self.files = proxy(self.__del__.im_func.files)
def __del__(self):
print self.__del__.im_func.files
</code></pre>
<p>It will stuff the file list in the <strong>del</strong> function that is guaranteed to exist at the time of call. The weakref proxy is to prevent Python, or yourself from deleting the self.files variable somehow (if it is deleted, then it will not affect the original file list). If it is not the case that this is being deleted even though there are more references to the variable, then you can remove the proxy encapsulation.</p>
| 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/datamodel.html#customization">Python doesn't guarantee</a> the existence of "global variables" (member data in this context?) when <code>__del__()</code> is invoked. If that is the case and this is the reason for the exception, how do I make sure the object destructs properly?</p>
| 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/datamodel.html#customization">Python doesn't guarantee</a> the existence of "global variables" (member data in this context?) when <code>__del__()</code> is invoked. If that is the case and this is the reason for the exception, how do I make sure the object destructs properly?</p>
| 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 resource leak when an exception occurs.</p>
<p>To use the <code>with</code> statement, create a class with the following methods:</p>
<pre><code> def __enter__(self)
def __exit__(self, exc_type, exc_value, traceback)
</code></pre>
<p>In your example above, you'd use </p>
<pre><code>class Package:
def __init__(self):
self.files = []
def __enter__(self):
return self
# ...
def __exit__(self, exc_type, exc_value, traceback):
for file in self.files:
os.unlink(file)
</code></pre>
<p>Then, when someone wanted to use your class, they'd do the following:</p>
<pre><code>with Package() as package_obj:
# use package_obj
</code></pre>
<p>The variable package_obj will be an instance of type Package (it's the value returned by the <code>__enter__</code> method). Its <code>__exit__</code> method will automatically be called, regardless of whether or not an exception occurs.</p>
<p>You could even take this approach a step further. In the example above, someone could still instantiate Package using its constructor without using the <code>with</code> clause. You don't want that to happen. You can fix this by creating a PackageResource class that defines the <code>__enter__</code> and <code>__exit__</code> methods. Then, the Package class would be defined strictly inside the <code>__enter__</code> method and returned. That way, the caller never could instantiate the Package class without using a <code>with</code> statement:</p>
<pre><code>class PackageResource:
def __enter__(self):
class Package:
...
self.package_obj = Package()
return self.package_obj
def __exit__(self, exc_type, exc_value, traceback):
self.package_obj.cleanup()
</code></pre>
<p>You'd use this as follows:</p>
<pre><code>with PackageResource() as package_obj:
# use package_obj
</code></pre>
| 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/datamodel.html#customization">Python doesn't guarantee</a> the existence of "global variables" (member data in this context?) when <code>__del__()</code> is invoked. If that is the case and this is the reason for the exception, how do I make sure the object destructs properly?</p>
| 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>__del__</code>. The main reason for this is that instances with <code>__del__</code> will not be garbage collected (they will only be freed when their refcount reaches 0). Therefore, if your instances are involved in circular references, they will live in memory for as long as the application run. (I may be mistaken about all this though, I'd have to read the gc docs again, but I'm rather sure it works like this).</p>
| 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/datamodel.html#customization">Python doesn't guarantee</a> the existence of "global variables" (member data in this context?) when <code>__del__()</code> is invoked. If that is the case and this is the reason for the exception, how do I make sure the object destructs properly?</p>
| 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-opposite-of-__init__/" rel="nofollow">Source</a></p>
| 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/datamodel.html#customization">Python doesn't guarantee</a> the existence of "global variables" (member data in this context?) when <code>__del__()</code> is invoked. If that is the case and this is the reason for the exception, how do I make sure the object destructs properly?</p>
| 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/datamodel.html#customization">Python doesn't guarantee</a> the existence of "global variables" (member data in this context?) when <code>__del__()</code> is invoked. If that is the case and this is the reason for the exception, how do I make sure the object destructs properly?</p>
| 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.contextmanager
def packageResource():
class Package:
...
package = Package()
yield package
package.cleanup()
</code></pre>
<p>Alternatively, though probably not as Pythonic, you can override <code>Package.__new__</code>:</p>
<pre><code>class Package(object):
def __new__(cls, *args, **kwargs):
@contextlib.contextmanager
def packageResource():
# adapt arguments if superclass takes some!
package = super(Package, cls).__new__(cls)
package.__init__(*args, **kwargs)
yield package
package.cleanup()
def __init__(self, *args, **kwargs):
...
</code></pre>
<p>and simply use <code>with Package(...) as package</code>.</p>
<p>To get things shorter, name your cleanup function <code>close</code> and use <a href="https://docs.python.org/3/library/contextlib.html#contextlib.closing" rel="nofollow"><code>contextlib.closing</code></a>, in which case you can either use the unmodified <code>Package</code> class via <code>with contextlib.closing(Package(...))</code> or override its <code>__new__</code> to the simpler</p>
<pre><code>class Package(object):
def __new__(cls, *args, **kwargs):
package = super(Package, cls).__new__(cls)
package.__init__(*args, **kwargs)
return contextlib.closing(package)
</code></pre>
<p>And this constructor is inherited, so you can simply inherit, e.g.</p>
<pre><code>class SubPackage(Package):
def close(self):
pass
</code></pre>
| 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 <directory> -name '*.py' -exec grep <pattern> {} \;</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 the html type so we can limit our search:
--type-add
html=.pt,.zpt
# Create txt file type:
--type-set
txt=.txt,.rst
# Define i18n file types:
--type-set
i18n=.pot,.po
# More options
--follow
--ignore-case
--nogroup
</code></pre>
<p>Important to remember is that ack won't find files if the extension isn't in its configuration. See "ack --help-types" for all the available types.</p>
<p>I also assume you are using <a href="http://pypi.python.org/pypi/collective.recipe.omelette" rel="nofollow" title="omelette">omelette</a> so you can grep/ack/find all the related files?</p>
| 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 href="http://pypi.python.org/pypi/z3c.recipe.tag" rel="nofollow">z3c.recipe.tag</a> takes care of that, if you use buildout.</p>
| 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>... then which directory (~/Plone/buildout-cache/eggs). If I'm already editing a file, this defaults to that file's directory, which is usually exactly what I want.</li>
</ol>
<p>The results appear in a new buffer. At the top is the <code>find | xargs grep</code> command Emacs ran. All matches are highlighted. I can search the buffer using the standard text search commands. Best of all, I can hit Enter (or click) on a match to open that file.</p>
<p>It's a pretty nice way to work. I like that I don't have to remember <code>find | xargs grep</code> argument sequences, but that all that power is there if I need it. </p>
<p><a href="http://i.stack.imgur.com/r6Jle.png" rel="nofollow" title="Emacs rgrep example">
<img src="http://i.stack.imgur.com/r6Jle.png" alt="Emacs rgrep example">
</a></p>
| 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. Goto definition, goto instances, refactoring support and of course search.</p>
| 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>"<class 'my.package.Foo'>"
</code></pre>
<p>I know I can get it quite easily with a regexp, but I would like to know if there's a more "clean" way.</p>
| 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>"<class 'my.package.Foo'>"
</code></pre>
<p>I know I can get it quite easily with a regexp, but I would like to know if there's a more "clean" way.</p>
| 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>"<class 'my.package.Foo'>"
</code></pre>
<p>I know I can get it quite easily with a regexp, but I would like to know if there's a more "clean" way.</p>
| 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.
>>> class foo:
... x = 1
...
>>> f = foo()
>>> f.__class__.__name__
'foo'
>>>
</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>>>> import os, types
>>> 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 division operation is unsupported on timedeltas. Is there a way that I can implement divison for timedeltas?</p>
<p><strong>Edit:</strong> Looks like this was added to Python 3.2 (thanks rincewind!): <a href="http://bugs.python.org/issue2706">http://bugs.python.org/issue2706</a></p>
| 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, (int, long)):
return divtdi(td1, td2)
us1 = td1.microseconds + 1000000 * (td1.seconds + 86400 * td1.days)
us2 = td2.microseconds + 1000000 * (td2.seconds + 86400 * td2.days)
return us1 / us2 # this does integer division, use float(us1) / us2 for fp division
</code></pre>
<p>And to incorporate this into nadia's suggestion:</p>
<pre><code>class MyTimeDelta:
__div__ = divtd
</code></pre>
<p>Example usage:</p>
<pre><code>>>> divtd(datetime.timedelta(hours = 12), datetime.timedelta(hours = 2))
6
>>> divtd(datetime.timedelta(hours = 12), 2)
datetime.timedelta(0, 21600)
>>> MyTimeDelta(hours = 12) / MyTimeDelta(hours = 2)
6
</code></pre>
<p>etc. Of course you could even name (or alias) your custom class <code>timedelta</code> so it gets used in place of the real <code>timedelta</code>, at least in your code.</p>
| 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 division operation is unsupported on timedeltas. Is there a way that I can implement divison for timedeltas?</p>
<p><strong>Edit:</strong> Looks like this was added to Python 3.2 (thanks rincewind!): <a href="http://bugs.python.org/issue2706">http://bugs.python.org/issue2706</a></p>
| 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 division operation is unsupported on timedeltas. Is there a way that I can implement divison for timedeltas?</p>
<p><strong>Edit:</strong> Looks like this was added to Python 3.2 (thanks rincewind!): <a href="http://bugs.python.org/issue2706">http://bugs.python.org/issue2706</a></p>
| 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>>>> from datetime import timedelta
>>> timedelta(hours=6)
datetime.timedelta(0, 21600)
>>> timedelta(hours=6) / 2
datetime.timedelta(0, 10800)
</code></pre>
| 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 in truly terrible
ways creating bugs that are very hard
to find. [...]</p>
<p>Think twice about else:. It is
generally a problem. Avoid it except
in an if-statement and even then
consider documenting the else-
condition to make it explicit.</p>
</blockquote>
<p><strong>Is this a widely held opinion? Is <code>else</code> <a href="http://meyerweb.com/eric/comment/chech.html">considered harmful</a>?</strong></p>
<p>Of course you can write confusing code with it but that's true of any other language construct. Even Python's <code>for...else</code> seems to me a very handy thing to have (less so for <code>try...else</code>). </p>
| 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 in truly terrible
ways creating bugs that are very hard
to find. [...]</p>
<p>Think twice about else:. It is
generally a problem. Avoid it except
in an if-statement and even then
consider documenting the else-
condition to make it explicit.</p>
</blockquote>
<p><strong>Is this a widely held opinion? Is <code>else</code> <a href="http://meyerweb.com/eric/comment/chech.html">considered harmful</a>?</strong></p>
<p>Of course you can write confusing code with it but that's true of any other language construct. Even Python's <code>for...else</code> seems to me a very handy thing to have (less so for <code>try...else</code>). </p>
| 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 computer is the biggest finite state machine out there, and it is silly to enumerate every single possibility in every situation.</p>
<p>If you are really afraid that unknown errors go unnoticed in else statements, is it really that hard to raise an exception there?</p>
| 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 in truly terrible
ways creating bugs that are very hard
to find. [...]</p>
<p>Think twice about else:. It is
generally a problem. Avoid it except
in an if-statement and even then
consider documenting the else-
condition to make it explicit.</p>
</blockquote>
<p><strong>Is this a widely held opinion? Is <code>else</code> <a href="http://meyerweb.com/eric/comment/chech.html">considered harmful</a>?</strong></p>
<p>Of course you can write confusing code with it but that's true of any other language construct. Even Python's <code>for...else</code> seems to me a very handy thing to have (less so for <code>try...else</code>). </p>
| 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 counts and to use common sense than to arbitrarily declare certain constructs "harmful".</p>
| 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 in truly terrible
ways creating bugs that are very hard
to find. [...]</p>
<p>Think twice about else:. It is
generally a problem. Avoid it except
in an if-statement and even then
consider documenting the else-
condition to make it explicit.</p>
</blockquote>
<p><strong>Is this a widely held opinion? Is <code>else</code> <a href="http://meyerweb.com/eric/comment/chech.html">considered harmful</a>?</strong></p>
<p>Of course you can write confusing code with it but that's true of any other language construct. Even Python's <code>for...else</code> seems to me a very handy thing to have (less so for <code>try...else</code>). </p>
| 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: if you're willing to not use something because an answer on SO or a blog post or even a famous paper by Dijkstra told you not to, you need to consider if programming is the right profession for you.</p>
| 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 in truly terrible
ways creating bugs that are very hard
to find. [...]</p>
<p>Think twice about else:. It is
generally a problem. Avoid it except
in an if-statement and even then
consider documenting the else-
condition to make it explicit.</p>
</blockquote>
<p><strong>Is this a widely held opinion? Is <code>else</code> <a href="http://meyerweb.com/eric/comment/chech.html">considered harmful</a>?</strong></p>
<p>Of course you can write confusing code with it but that's true of any other language construct. Even Python's <code>for...else</code> seems to me a very handy thing to have (less so for <code>try...else</code>). </p>
| 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:
if(input == 1)
{
//do processing
...
}
else
{
//do processing
...
}
</code></pre>
<p>In this case, using the else would allow all values other than 1 to be processed when it should only be for values 1 and 2.</p>
| 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 in truly terrible
ways creating bugs that are very hard
to find. [...]</p>
<p>Think twice about else:. It is
generally a problem. Avoid it except
in an if-statement and even then
consider documenting the else-
condition to make it explicit.</p>
</blockquote>
<p><strong>Is this a widely held opinion? Is <code>else</code> <a href="http://meyerweb.com/eric/comment/chech.html">considered harmful</a>?</strong></p>
<p>Of course you can write confusing code with it but that's true of any other language construct. Even Python's <code>for...else</code> seems to me a very handy thing to have (less so for <code>try...else</code>). </p>
| 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 < 10:
# condition stated explicitly
elif a > 10 and b < 10:
# condition confusing but at least explicit
else:
# Exactly what is true here?
# Can be hard to reason out what condition is true
</code></pre>
<p>Can be written</p>
<pre><code>if a < 10:
# condition stated explicitly
elif a > 10 and b < 10:
# condition confusing but at least explicit
elif a > 10 and b >=10:
# else condition
else:
# Handle edge case with error?
</code></pre>
| 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 in truly terrible
ways creating bugs that are very hard
to find. [...]</p>
<p>Think twice about else:. It is
generally a problem. Avoid it except
in an if-statement and even then
consider documenting the else-
condition to make it explicit.</p>
</blockquote>
<p><strong>Is this a widely held opinion? Is <code>else</code> <a href="http://meyerweb.com/eric/comment/chech.html">considered harmful</a>?</strong></p>
<p>Of course you can write confusing code with it but that's true of any other language construct. Even Python's <code>for...else</code> seems to me a very handy thing to have (less so for <code>try...else</code>). </p>
| 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 in truly terrible
ways creating bugs that are very hard
to find. [...]</p>
<p>Think twice about else:. It is
generally a problem. Avoid it except
in an if-statement and even then
consider documenting the else-
condition to make it explicit.</p>
</blockquote>
<p><strong>Is this a widely held opinion? Is <code>else</code> <a href="http://meyerweb.com/eric/comment/chech.html">considered harmful</a>?</strong></p>
<p>Of course you can write confusing code with it but that's true of any other language construct. Even Python's <code>for...else</code> seems to me a very handy thing to have (less so for <code>try...else</code>). </p>
| 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 should only run if the previous code was successful. Without an <code>else</code> block, you'd have to put all that code in the <code>try</code> block:</p>
<pre><code>try:
something_that_might_raise_error()
do_this_only_if_that_was_ok()
except ValueError:
# whatever
</code></pre>
<p>The issue is, what if <code>do_this_only_if_that_was_ok()</code> raises a <code>ValueError</code>? It would get caught by the <code>except</code> statement, when you might not have wanted it to. That's the purpose of the <code>else</code> block:</p>
<pre><code>try:
something_that_might_raise_error()
except ValueError:
# whatever
else:
do_this_only_if_that_was_ok()
</code></pre>
<p>I guess it's a matter of opinion to some extent, but I personally think this is a great idea, even though I use it very rarely. When I do use it, it just feels very appropriate (and besides, I think it helps clarify the code flow a bit)</p>
| 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 in truly terrible
ways creating bugs that are very hard
to find. [...]</p>
<p>Think twice about else:. It is
generally a problem. Avoid it except
in an if-statement and even then
consider documenting the else-
condition to make it explicit.</p>
</blockquote>
<p><strong>Is this a widely held opinion? Is <code>else</code> <a href="http://meyerweb.com/eric/comment/chech.html">considered harmful</a>?</strong></p>
<p>Of course you can write confusing code with it but that's true of any other language construct. Even Python's <code>for...else</code> seems to me a very handy thing to have (less so for <code>try...else</code>). </p>
| 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 why there's nothing to be done.</p>
| 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 in truly terrible
ways creating bugs that are very hard
to find. [...]</p>
<p>Think twice about else:. It is
generally a problem. Avoid it except
in an if-statement and even then
consider documenting the else-
condition to make it explicit.</p>
</blockquote>
<p><strong>Is this a widely held opinion? Is <code>else</code> <a href="http://meyerweb.com/eric/comment/chech.html">considered harmful</a>?</strong></p>
<p>Of course you can write confusing code with it but that's true of any other language construct. Even Python's <code>for...else</code> seems to me a very handy thing to have (less so for <code>try...else</code>). </p>
| 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 the logic in their condition is.</p>
<p>Therefore, as developers it is our responsibility to code with the wide scope of the else in-mind. Too many developers treat it as a 'if not the above' when in-fact it can ignore all common sense because the only logic in it is the negation of the preceding logic, which is often incomplete. (an algorithm design error itself)</p>
<p>I don't then consider 'else' any more harmful than off-by-ones in a for() loop or bad memory management. It's all about the algorithms. If your automata is complete in its scope and possible branches, and all are concrete and understood then there is no danger. The danger is misuse of the logic behind the expressions by people not realizing the impact of wide-scope logic. <strong>Computers are stupid, they do what they are told by their operator</strong>(in theory)</p>
<p>I do consider the <strong>try</strong> and <strong>catch</strong> to be dangerous because it can negate handling to an unknown quantity of code. Branching above the <strong>raise</strong> may contain a bug, highlighted by the <strong>raise</strong> itself. This is can be non-obvious. It is like turning a sequential set of instructions into a tree or graph of error handling, where each component is dependent on the branches in the parent. Odd. Mind you, I love C.</p>
| 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 in truly terrible
ways creating bugs that are very hard
to find. [...]</p>
<p>Think twice about else:. It is
generally a problem. Avoid it except
in an if-statement and even then
consider documenting the else-
condition to make it explicit.</p>
</blockquote>
<p><strong>Is this a widely held opinion? Is <code>else</code> <a href="http://meyerweb.com/eric/comment/chech.html">considered harmful</a>?</strong></p>
<p>Of course you can write confusing code with it but that's true of any other language construct. Even Python's <code>for...else</code> seems to me a very handy thing to have (less so for <code>try...else</code>). </p>
| 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','r')
except IOError:
logger.error("File not found!")
else:
# Some file operations
file.close()
# Some code that no longer explicitly references 'file'
</code></pre>
<p>It would be real nice to say that the above block prevented code from trying to access a file that didn't exist, or a directory for which the user has no permissions, and to say that everything is encapsulated because it is within a <code>try...except...else</code> block. But in reality, a lot of code in the above form really should look like this:</p>
<pre><code>try:
file = open('somefile','r')
except IOError:
logger.error("File not found!")
return False
# Some file operations
file.close()
# Some code that no longer explicitly references 'file'
</code></pre>
<p>You are often fooling yourself by saying that because <code>file</code> is no longer referenced in scope, it's okay to go on coding after the block, but in many cases something will come up where it just isn't okay. Or maybe a variable will later be created within the <code>else</code> block that isn't created in the <code>except</code> block.</p>
<p>This is how I would differentiate the <code>if...else</code> from <code>try...except...else</code>. In both cases, one must make the blocks parallel in most cases (variables and state set in one ought to be set in the other) but in the latter, coders often don't, likely because it's impossible or irrelevant. In such cases, it often will make a whole lot more sense to return to the caller than to try and keep working around what you think you will have in the best case scenario.</p>
| 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 in truly terrible
ways creating bugs that are very hard
to find. [...]</p>
<p>Think twice about else:. It is
generally a problem. Avoid it except
in an if-statement and even then
consider documenting the else-
condition to make it explicit.</p>
</blockquote>
<p><strong>Is this a widely held opinion? Is <code>else</code> <a href="http://meyerweb.com/eric/comment/chech.html">considered harmful</a>?</strong></p>
<p>Of course you can write confusing code with it but that's true of any other language construct. Even Python's <code>for...else</code> seems to me a very handy thing to have (less so for <code>try...else</code>). </p>
| 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</code>. I would prefer to see:</p>
<pre><code>if foo:
# ...
else:
# at this point, we know that bar is true.
# ...
# ...
</code></pre>
<p>or:</p>
<pre><code>if foo:
# ...
else:
assert bar
# ...
# ...
</code></pre>
<p>This makes it clear to the reader how you expect control to flow, without requiring the reader to have intimate knowledge of where <code>foo</code> and <code>bar</code> come from.</p>
<p>(in the original case, you could still write a comment explaining what is happening, but I think I would then wonder: "Why not just use an <code>else:</code> clause?")</p>
<p>I think the point is not that you shouldn't use <code>else:</code>; rather, that <strong>an <code>else:</code> clause can allow you to write unclear code</strong> and you should try to recognise when this happens and add a little comment to help out any readers.</p>
<p>Which is true about most things in programming languages, really :-)</p>
| 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 in truly terrible
ways creating bugs that are very hard
to find. [...]</p>
<p>Think twice about else:. It is
generally a problem. Avoid it except
in an if-statement and even then
consider documenting the else-
condition to make it explicit.</p>
</blockquote>
<p><strong>Is this a widely held opinion? Is <code>else</code> <a href="http://meyerweb.com/eric/comment/chech.html">considered harmful</a>?</strong></p>
<p>Of course you can write confusing code with it but that's true of any other language construct. Even Python's <code>for...else</code> seems to me a very handy thing to have (less so for <code>try...else</code>). </p>
| 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!");
else
printf("which one");
</code></pre>
<p>or</p>
<pre><code>if (a==4)
if (b==2)
printf("here!");
else
printf("which one");
</code></pre>
<p>The problem is that the "else" is "dangling", one can confuse the owner of the else. Of course the compiler will not make this confusion, but it is valid for mortals.</p>
<p>Thanks to Python, we can not have a dangling else problem in Python since we have to write either</p>
<pre><code>if a==4:
if b==2:
print "here!"
else:
print "which one"
</code></pre>
<p>or</p>
<pre><code>if a==4:
if b==2:
print "here!"
else:
print "which one"
</code></pre>
<p>So that human eye catches it. And, nope, I do not think "else" is harmful, it is as harmful as "if".</p>
| 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 really the same? For example, can you take a number and do the ruby stuff I've seen like:</p>
<pre><code>y = 5.plus 6
</code></pre>
<p>Can that be done the same way in Python?</p>
| 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 returns the doc string defined in the function's source code. The sys module is an object which has (among other things) an attribute called path. And so forth.</p>
<p>Still, this begs the question. What is an object? Different programming languages define âobjectâ in different ways. In some, it means that all objects must have attributes and methods; in others, it means that all objects are subclassable. In Python, the definition is looser; some objects have neither attributes nor methods (more on this in Chapter 3), and not all objects are subclassable (more on this in Chapter 5). But everything is an object in the sense that it can be assigned to a variable or passed as an argument to a function (more in this in Chapter 4). </p>
</blockquote>
<p><a href="http://www.ruby-lang.org/en/documentation/ruby-from-other-languages/to-ruby-from-python/">Ruby Docs - To Ruby From Python</a></p>
<blockquote>
<p>As with Python, in Ruby,... Everything is an object</p>
</blockquote>
<p>So there you have it from Ruby's own website: in Python everything is an object.</p>
| 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 really the same? For example, can you take a number and do the ruby stuff I've seen like:</p>
<pre><code>y = 5.plus 6
</code></pre>
<p>Can that be done the same way in Python?</p>
| 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 that can't be treated as an object.</p>
| 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 really the same? For example, can you take a number and do the ruby stuff I've seen like:</p>
<pre><code>y = 5.plus 6
</code></pre>
<p>Can that be done the same way in Python?</p>
| 28 | 2009-05-14T21:33:02Z | 866,039 | <p>In answer to your second question, yes:</p>
<pre><code>>>> (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 really the same? For example, can you take a number and do the ruby stuff I've seen like:</p>
<pre><code>y = 5.plus 6
</code></pre>
<p>Can that be done the same way in Python?</p>
| 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 sort of such things that aren't really objects in (say) C++, are objects in Ruby or Python, causes such enthusiasm. Other things may be objects in Ruby but not Python or viceversa (code blocks, regular expressions, ...).</p>
| 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 really the same? For example, can you take a number and do the ruby stuff I've seen like:</p>
<pre><code>y = 5.plus 6
</code></pre>
<p>Can that be done the same way in Python?</p>
| 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 convert a type to a string by constructing a string from it. Instead of <code>5.to_s</code>, you have <code>str(5)</code>.</p>
<p>Don't be fooled, though. There's still a method behind the scenes - which is why this code works:</p>
<pre><code>(5).__str__()
</code></pre>
<p>So in practice, the two are fundamentally similar, but you use them differently. Length for sequences like lists and tuples in Python is another example of this principle at work - the actual feature is built upon methods with special names, but exposed through a simpler, easier-to-use interface (the <code>len</code> function).</p>
<p>The python equivalent to what you wrote in your question would thus be:</p>
<pre><code>(5).__add__(6)
</code></pre>
<p>The other difference that's important is how global functions are implemented. In python, globals are represented by a dictionary (as are locals). This means that the following:</p>
<pre><code>foo(5)
</code></pre>
<p>Is equivalent to this in python:</p>
<pre><code>globals()["foo"].__call__(5)
</code></pre>
<p>While ruby effectively does this:</p>
<pre><code>Object.foo(5)
</code></pre>
<p>This has a large impact on the approach used when writing code in both languages. Ruby libraries tend to grow through the addition of methods to existing types like Object, while Python libraries tend to grow through the addition of global functions to a given module.</p>
| 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 really the same? For example, can you take a number and do the ruby stuff I've seen like:</p>
<pre><code>y = 5.plus 6
</code></pre>
<p>Can that be done the same way in Python?</p>
| 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, and you never have to worry about traps caused by pass-by-reference. It's rather a good solution :-)</p>
| 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 rather write the entire file at once.</p>
<p>In the meantime, I'm writing to a StringIO buffer, and then writing that to the disk at the end.</p>
| 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 to 2^31-1 or 2 gigs. Any larger will result in "OverflowError: long int too large to convert to int"</li>
<li><p>It doesn't seem to work:</p>
<pre><code>a = open("blah.txt", "w", 2 ** 31 - 1)
for i in xrange(10000):
a.write("a")
</code></pre></li>
</ol>
<p>Open up the file without closing python, and you will see the text</p>
| 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 rather write the entire file at once.</p>
<p>In the meantime, I'm writing to a StringIO buffer, and then writing that to the disk at the end.</p>
| 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 actually needed, so, no worry...</p>
| 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 rather write the entire file at once.</p>
<p>In the meantime, I'm writing to a StringIO buffer, and then writing that to the disk at the end.</p>
| 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 different place, then renaming it into the correct
place once I'd finished writing. </p>
<p>If you want this for other reasons then maybe that doesn't help.</p>
| 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 in quickly!!!</p>
<p>if you're looking for a python equivalent of rm -rf *2.img *4.img *6.img *8.img *0.img, know that the computer still has to go through the entire list of files</p>
| 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" file. O(n/2) is still O(n)</p>
| 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 < 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. The actual deletion likely takes several orders of magnitude more time.</p>
| 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]
</code></pre>
<p>This is another form of doing what you want, although I'm not sure if it'll be faster. Hope this helps.</p>
| 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/$_" && /*.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>
<p>use os.system(...) or subprocess.call(...) to run these from 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><h2> this is cool #12345678901 </h2>
</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 be something like:</p>
<pre><code>[u'blahblah #223409823523', u'thisisinteresting #293845023984']
</code></pre>
<p>I'm able to get all the text that matches (see line above). But I want the parent element of the text to match, so I can use that as a starting point for traversing the document tree. In this case, I'd want all the h2 elements to return, not the text matches.</p>
<p>Ideas?</p>
| 33 | 2009-05-14T21:46:12Z | 866,050 | <pre><code>from BeautifulSoup import BeautifulSoup
import re
html_text = """
<h2>this is cool #12345678901</h2>
<h2>this is nothing</h2>
<h1>foo #126666678901</h1>
<h2>this is interesting #126666678901</h2>
<h2>this is blah #124445678901</h2>
"""
soup = BeautifulSoup(html_text)
for elem in soup(text=re.compile(r' #\S{11}')):
print elem.parent
</code></pre>
<p>Prints:</p>
<pre><code><h2>this is cool #12345678901</h2>
<h2>this is interesting #126666678901</h2>
<h2>this is blah #124445678901</h2>
</code></pre>
| 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><h2> this is cool #12345678901 </h2>
</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 be something like:</p>
<pre><code>[u'blahblah #223409823523', u'thisisinteresting #293845023984']
</code></pre>
<p>I'm able to get all the text that matches (see line above). But I want the parent element of the text to match, so I can use that as a starting point for traversing the document tree. In this case, I'd want all the h2 elements to return, not the text matches.</p>
<p>Ideas?</p>
| 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, <code>parent</code> is favored over <code>previous</code> because of <a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/#method-names">changes in BS4</a>.</p>
<pre><code>from BeautifulSoup import BeautifulSoup
from pprint import pprint
import re
html_text = """
<h2>this is cool #12345678901</h2>
<h2>this is nothing</h2>
<h2>this is interesting #126666678901</h2>
<h2>this is blah #124445678901</h2>
"""
soup = BeautifulSoup(html_text)
# Even though the OP was not looking for 'cool', it's more understandable to work with item zero.
pattern = re.compile(r'cool')
pprint(soup.find(text=pattern).__dict__)
#>> {'next': u'\n',
#>> 'nextSibling': None,
#>> 'parent': <h2>this is cool #12345678901</h2>,
#>> 'previous': <h2>this is cool #12345678901</h2>,
#>> 'previousSibling': None}
print soup.find('h2')
#>> <h2>this is cool #12345678901</h2>
print soup.find('h2', text=pattern)
#>> this is cool #12345678901
print soup.find('h2', text=pattern).parent
#>> <h2>this is cool #12345678901</h2>
print soup.find('h2', text=pattern) == soup.find('h2')
#>> False
print soup.find('h2', text=pattern) == soup.find('h2').text
#>> True
print soup.find('h2', text=pattern).parent == soup.find('h2')
#>> True
</code></pre>
| 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 it to 'x#', then check if it is None and if so set 'x#' to 0. </p>
<p>Not very elegant...any advice on a better way to deal with this in python?</p>
<p>cc</p>
| 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 it to 'x#', then check if it is None and if so set 'x#' to 0. </p>
<p>Not very elegant...any advice on a better way to deal with this in python?</p>
<p>cc</p>
| 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>
<p>Here's another choice.</p>
<pre><code>def non_null( *fields ):
for f in fields:
if f is not None:
yield f
total = sum( non_null( a, b, c, d, e, f, g ) )
</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 it to 'x#', then check if it is None and if so set 'x#' to 0. </p>
<p>Not very elegant...any advice on a better way to deal with this in python?</p>
<p>cc</p>
| 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(col3, 0) as col3
FROM your_table;
</code></pre>
<p>Then use sum() in Python on the returned row without having to worry about the presence of None.</p>
<p>Option 2:
Sum the columns in the database and return the total in the query:</p>
<pre><code>SELECT coalesce(col1, 0) + coalesce(col2, 0) + coalesce(col3, 0) as total
FROM your_table;
</code></pre>
<p>Nothing more to do in Python. One advantage of the second option is that you can select other columns in your query that are not part of your sum (you probably have other columns in your table and are making multiple queries to get different columns of the table?)</p>
| 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 it to 'x#', then check if it is None and if so set 'x#' to 0. </p>
<p>Not very elegant...any advice on a better way to deal with this in python?</p>
<p>cc</p>
| 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><form action="" method="post">
{{ form_newsletter }}
<input type="submit" name="newsletter_sub" value="Subscribe" />
<input type="submit" name="newsletter_unsub" value="Unsubscribe" />
</form>
</code></pre>
<p>I have also class form:</p>
<pre><code>class NewsletterForm(forms.ModelForm):
class Meta:
model = Newsletter
fields = ('email',)
</code></pre>
<p>I must write my own clean_email method and I need to know by which button was form submited. But the value of submit buttons aren't in <code>self.cleaned_data</code> dictionary.
Could I get values of buttons otherwise?</p>
| 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(self):
if 'newsletter_sub' in self.data:
# do subscribe
elif 'newsletter_unsub' in self.data:
# do unsubscribe
</code></pre>
| 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><form action="" method="post">
{{ form_newsletter }}
<input type="submit" name="newsletter_sub" value="Subscribe" />
<input type="submit" name="newsletter_unsub" value="Unsubscribe" />
</form>
</code></pre>
<p>I have also class form:</p>
<pre><code>class NewsletterForm(forms.ModelForm):
class Meta:
model = Newsletter
fields = ('email',)
</code></pre>
<p>I must write my own clean_email method and I need to know by which button was form submited. But the value of submit buttons aren't in <code>self.cleaned_data</code> dictionary.
Could I get values of buttons otherwise?</p>
| 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><form action="" method="post">
{{ form_newsletter }}
<input type="submit" name="newsletter_sub" value="Subscribe" />
<input type="submit" name="newsletter_unsub" value="Unsubscribe" />
</form>
</code></pre>
<p>I have also class form:</p>
<pre><code>class NewsletterForm(forms.ModelForm):
class Meta:
model = Newsletter
fields = ('email',)
</code></pre>
<p>I must write my own clean_email method and I need to know by which button was form submited. But the value of submit buttons aren't in <code>self.cleaned_data</code> dictionary.
Could I get values of buttons otherwise?</p>
| 101 | 2009-05-14T22:50:25Z | 16,891,638 | <p>You can also do like this,</p>
<pre><code> <form method='POST'>
{{form1.as_p}}
<button type="submit" name="btnform1">Save Changes</button>
</form>
<form method='POST'>
{{form2.as_p}}
<button type="submit" name="btnform2">Save Changes</button>
</form>
</code></pre>
<p><em><strong>CODE</em></strong> <br></p>
<pre><code>if request.method=='POST' and 'btnform1' in request.POST:
do something...
if request.method=='POST' and 'btnform2' in request.POST:
do something...
</code></pre>
| 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><form action="" method="post">
{{ form_newsletter }}
<input type="submit" name="newsletter_sub" value="Subscribe" />
<input type="submit" name="newsletter_unsub" value="Unsubscribe" />
</form>
</code></pre>
<p>I have also class form:</p>
<pre><code>class NewsletterForm(forms.ModelForm):
class Meta:
model = Newsletter
fields = ('email',)
</code></pre>
<p>I must write my own clean_email method and I need to know by which button was form submited. But the value of submit buttons aren't in <code>self.cleaned_data</code> dictionary.
Could I get values of buttons otherwise?</p>
| 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 one success_url, or provide dict with names of
submit actions given in template as keys
Example:
In template:
<input type="submit" name="create_new" value="Create"/>
<input type="submit" name="delete" value="Delete"/>
View:
MyMultiSubmitView(MultiRedirectMixin, forms.FormView):
success_urls = {"create_new": reverse_lazy('create'),
"delete": reverse_lazy('delete')}
"""
success_urls = {}
def form_valid(self, form):
""" Form is valid: Pick the url and redirect.
"""
for name in self.success_urls:
if name in form.data:
self.success_url = self.success_urls[name]
break
return HttpResponseRedirect(self.get_success_url())
def get_success_url(self):
"""
Returns the supplied success URL.
"""
if self.success_url:
# Forcing possible reverse_lazy evaluation
url = force_text(self.success_url)
else:
raise ImproperlyConfigured(
_("No URL to redirect to. Provide a success_url."))
return url
</code></pre>
| 2 | 2014-05-06T22:00:44Z | [
"python",
"button",
"django-forms",
"submit"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.