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 |
|---|---|---|---|---|---|---|---|---|---|
Django forms, inheritance and order of form fields | 913,589 | <p>I'm using Django forms in my website and would like to control the order of the fields.</p>
<p>Here's how I define my forms:</p>
<pre><code>class edit_form(forms.Form):
summary = forms.CharField()
description = forms.CharField(widget=forms.TextArea)
class create_form(edit_form):
name = forms.CharField()
</code></pre>
<p>The name is immutable and should only be listed when the entity is created. I use inheritance to add consistency and DRY principles. What happens which is not erroneous, in fact totally expected, is that the name field is listed last in the view/html but I'd like the name field to be on top of summary and description. I do realize that I could easily fix it by copying summary and description into create_form and loose the inheritance but I'd like to know if this is possible. </p>
<p><strong>Why?</strong> Imagine you've got 100 fields in edit_form and have to add 10 fields on the top in create_form - copying and maintaining the two forms wouldn't look so sexy then. (This is <em>not</em> my case, I'm just making up an example)</p>
<p>So, how can I override this behavior?</p>
<p><strong>Edit:</strong></p>
<p>Apparently there's no proper way to do this without going through nasty hacks (fiddling with .field attribute). The .field attribute is a SortedDict (one of Django's internal datastructures) which doesn't provide any way to reorder key:value pairs. It does how-ever provide a way to insert items at a given index but that would move the items from the class members and into the constructor. This method would work, but make the code less readable. The only other way I see fit is to modify the framework itself which is less-than-optimal in most situations.</p>
<p>In short the code would become something like this:</p>
<pre><code>class edit_form(forms.Form):
summary = forms.CharField()
description = forms.CharField(widget=forms.TextArea)
class create_form(edit_form):
def __init__(self,*args,**kwargs):
forms.Form.__init__(self,*args,**kwargs)
self.fields.insert(0,'name',forms.CharField())
</code></pre>
<p>That shut me up :) </p>
| 53 | 2009-05-27T01:46:50Z | 2,619,586 | <p>I used the solution posted by Selene but found that it removed all fields which weren't assigned to keyOrder. The form that I'm subclassing has a lot of fields so this didn't work very well for me. I coded up this function to solve the problem using akaihola's answer, but if you want it to work like Selene's all you need to do is set <code>throw_away</code> to <code>True</code>.</p>
<pre><code>def order_fields(form, field_list, throw_away=False):
"""
Accepts a form and a list of dictionary keys which map to the
form's fields. After running the form's fields list will begin
with the fields in field_list. If throw_away is set to true only
the fields in the field_list will remain in the form.
example use:
field_list = ['first_name', 'last_name']
order_fields(self, field_list)
"""
if throw_away:
form.fields.keyOrder = field_list
else:
for field in field_list[::-1]:
form.fields.insert(0, field, form.fields.pop(field))
</code></pre>
<p>This is how I'm using it in my own code:</p>
<pre><code>class NestableCommentForm(ExtendedCommentSecurityForm):
# TODO: Have min and max length be determined through settings.
comment = forms.CharField(widget=forms.Textarea, max_length=100)
parent_id = forms.IntegerField(widget=forms.HiddenInput, required=False)
def __init__(self, *args, **kwargs):
super(NestableCommentForm, self).__init__(*args, **kwargs)
order_fields(self, ['comment', 'captcha'])
</code></pre>
| 11 | 2010-04-12T02:38:58Z | [
"python",
"django",
"django-forms"
] |
Django forms, inheritance and order of form fields | 913,589 | <p>I'm using Django forms in my website and would like to control the order of the fields.</p>
<p>Here's how I define my forms:</p>
<pre><code>class edit_form(forms.Form):
summary = forms.CharField()
description = forms.CharField(widget=forms.TextArea)
class create_form(edit_form):
name = forms.CharField()
</code></pre>
<p>The name is immutable and should only be listed when the entity is created. I use inheritance to add consistency and DRY principles. What happens which is not erroneous, in fact totally expected, is that the name field is listed last in the view/html but I'd like the name field to be on top of summary and description. I do realize that I could easily fix it by copying summary and description into create_form and loose the inheritance but I'd like to know if this is possible. </p>
<p><strong>Why?</strong> Imagine you've got 100 fields in edit_form and have to add 10 fields on the top in create_form - copying and maintaining the two forms wouldn't look so sexy then. (This is <em>not</em> my case, I'm just making up an example)</p>
<p>So, how can I override this behavior?</p>
<p><strong>Edit:</strong></p>
<p>Apparently there's no proper way to do this without going through nasty hacks (fiddling with .field attribute). The .field attribute is a SortedDict (one of Django's internal datastructures) which doesn't provide any way to reorder key:value pairs. It does how-ever provide a way to insert items at a given index but that would move the items from the class members and into the constructor. This method would work, but make the code less readable. The only other way I see fit is to modify the framework itself which is less-than-optimal in most situations.</p>
<p>In short the code would become something like this:</p>
<pre><code>class edit_form(forms.Form):
summary = forms.CharField()
description = forms.CharField(widget=forms.TextArea)
class create_form(edit_form):
def __init__(self,*args,**kwargs):
forms.Form.__init__(self,*args,**kwargs)
self.fields.insert(0,'name',forms.CharField())
</code></pre>
<p>That shut me up :) </p>
| 53 | 2009-05-27T01:46:50Z | 8,476,642 | <p>You could also create a decorator to order fields (inspired by Joshua's solution):</p>
<pre><code>def order_fields(*field_list):
def decorator(form):
original_init = form.__init__
def init(self, *args, **kwargs):
original_init(self, *args, **kwargs)
for field in field_list[::-1]:
self.fields.insert(0, field, self.fields.pop(field))
form.__init__ = init
return form
return decorator
</code></pre>
<p>This will ensure that all the fields passed to the decorator come first.
You can use it like this:</p>
<pre><code>@order_fields('name')
class CreateForm(EditForm):
name = forms.CharField()
</code></pre>
| 7 | 2011-12-12T15:26:51Z | [
"python",
"django",
"django-forms"
] |
Django forms, inheritance and order of form fields | 913,589 | <p>I'm using Django forms in my website and would like to control the order of the fields.</p>
<p>Here's how I define my forms:</p>
<pre><code>class edit_form(forms.Form):
summary = forms.CharField()
description = forms.CharField(widget=forms.TextArea)
class create_form(edit_form):
name = forms.CharField()
</code></pre>
<p>The name is immutable and should only be listed when the entity is created. I use inheritance to add consistency and DRY principles. What happens which is not erroneous, in fact totally expected, is that the name field is listed last in the view/html but I'd like the name field to be on top of summary and description. I do realize that I could easily fix it by copying summary and description into create_form and loose the inheritance but I'd like to know if this is possible. </p>
<p><strong>Why?</strong> Imagine you've got 100 fields in edit_form and have to add 10 fields on the top in create_form - copying and maintaining the two forms wouldn't look so sexy then. (This is <em>not</em> my case, I'm just making up an example)</p>
<p>So, how can I override this behavior?</p>
<p><strong>Edit:</strong></p>
<p>Apparently there's no proper way to do this without going through nasty hacks (fiddling with .field attribute). The .field attribute is a SortedDict (one of Django's internal datastructures) which doesn't provide any way to reorder key:value pairs. It does how-ever provide a way to insert items at a given index but that would move the items from the class members and into the constructor. This method would work, but make the code less readable. The only other way I see fit is to modify the framework itself which is less-than-optimal in most situations.</p>
<p>In short the code would become something like this:</p>
<pre><code>class edit_form(forms.Form):
summary = forms.CharField()
description = forms.CharField(widget=forms.TextArea)
class create_form(edit_form):
def __init__(self,*args,**kwargs):
forms.Form.__init__(self,*args,**kwargs)
self.fields.insert(0,'name',forms.CharField())
</code></pre>
<p>That shut me up :) </p>
| 53 | 2009-05-27T01:46:50Z | 12,463,656 | <p>Based on an answer by @akaihola and updated to work with latest Django 1.5 as <code>self.fields.insert</code> is being <a href="https://github.com/django/django/blob/master/django/utils/datastructures.py#L227" rel="nofollow">depreciated</a>. </p>
<pre><code>from easycontactus.forms import *
from django import forms
class CustomEasyContactUsForm(EasyContactUsForm):
### form settings and configuration
CAPTHCA_PHRASE = 'igolf'
### native methods
def __init__(self, *args, **kwargs):
super(CustomEasyContactUsForm, self).__init__(*args, **kwargs)
# re-order placement of added attachment field
self.fields.keyOrder.insert(self.fields.keyOrder.index('captcha'),
self.fields.keyOrder.pop(self.fields.keyOrder.index('attachment'))
)
### field defintitions
attachment = forms.FileField()
</code></pre>
<p>In the above we are extending an EasyContactUsForm base class as it is defined in <a href="https://github.com/danielsokolowski/django-easycontactus" rel="nofollow">django-easycontactus</a> package. </p>
| 1 | 2012-09-17T16:40:49Z | [
"python",
"django",
"django-forms"
] |
Django forms, inheritance and order of form fields | 913,589 | <p>I'm using Django forms in my website and would like to control the order of the fields.</p>
<p>Here's how I define my forms:</p>
<pre><code>class edit_form(forms.Form):
summary = forms.CharField()
description = forms.CharField(widget=forms.TextArea)
class create_form(edit_form):
name = forms.CharField()
</code></pre>
<p>The name is immutable and should only be listed when the entity is created. I use inheritance to add consistency and DRY principles. What happens which is not erroneous, in fact totally expected, is that the name field is listed last in the view/html but I'd like the name field to be on top of summary and description. I do realize that I could easily fix it by copying summary and description into create_form and loose the inheritance but I'd like to know if this is possible. </p>
<p><strong>Why?</strong> Imagine you've got 100 fields in edit_form and have to add 10 fields on the top in create_form - copying and maintaining the two forms wouldn't look so sexy then. (This is <em>not</em> my case, I'm just making up an example)</p>
<p>So, how can I override this behavior?</p>
<p><strong>Edit:</strong></p>
<p>Apparently there's no proper way to do this without going through nasty hacks (fiddling with .field attribute). The .field attribute is a SortedDict (one of Django's internal datastructures) which doesn't provide any way to reorder key:value pairs. It does how-ever provide a way to insert items at a given index but that would move the items from the class members and into the constructor. This method would work, but make the code less readable. The only other way I see fit is to modify the framework itself which is less-than-optimal in most situations.</p>
<p>In short the code would become something like this:</p>
<pre><code>class edit_form(forms.Form):
summary = forms.CharField()
description = forms.CharField(widget=forms.TextArea)
class create_form(edit_form):
def __init__(self,*args,**kwargs):
forms.Form.__init__(self,*args,**kwargs)
self.fields.insert(0,'name',forms.CharField())
</code></pre>
<p>That shut me up :) </p>
| 53 | 2009-05-27T01:46:50Z | 23,615,361 | <p>It appears that at some point the underlying structure of field order was changed from a django specific <code>SordedDict</code> to a python standard <code>OrderedDict</code></p>
<p>Thus, in 1.7 I had to do the following:</p>
<pre><code>from collections import OrderedDict
class MyForm(forms.Form):
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
original_fields = self.fields
new_order = OrderedDict()
for key in ['first', 'second', ... 'last']:
new_order[key] = original_fields[key]
self.fields = new_order
</code></pre>
<p>I'm sure someone could golf that into two or three lines, but for S.O. purposes I think clearly showing how it works is better than cleaver.</p>
| 9 | 2014-05-12T17:35:17Z | [
"python",
"django",
"django-forms"
] |
Django forms, inheritance and order of form fields | 913,589 | <p>I'm using Django forms in my website and would like to control the order of the fields.</p>
<p>Here's how I define my forms:</p>
<pre><code>class edit_form(forms.Form):
summary = forms.CharField()
description = forms.CharField(widget=forms.TextArea)
class create_form(edit_form):
name = forms.CharField()
</code></pre>
<p>The name is immutable and should only be listed when the entity is created. I use inheritance to add consistency and DRY principles. What happens which is not erroneous, in fact totally expected, is that the name field is listed last in the view/html but I'd like the name field to be on top of summary and description. I do realize that I could easily fix it by copying summary and description into create_form and loose the inheritance but I'd like to know if this is possible. </p>
<p><strong>Why?</strong> Imagine you've got 100 fields in edit_form and have to add 10 fields on the top in create_form - copying and maintaining the two forms wouldn't look so sexy then. (This is <em>not</em> my case, I'm just making up an example)</p>
<p>So, how can I override this behavior?</p>
<p><strong>Edit:</strong></p>
<p>Apparently there's no proper way to do this without going through nasty hacks (fiddling with .field attribute). The .field attribute is a SortedDict (one of Django's internal datastructures) which doesn't provide any way to reorder key:value pairs. It does how-ever provide a way to insert items at a given index but that would move the items from the class members and into the constructor. This method would work, but make the code less readable. The only other way I see fit is to modify the framework itself which is less-than-optimal in most situations.</p>
<p>In short the code would become something like this:</p>
<pre><code>class edit_form(forms.Form):
summary = forms.CharField()
description = forms.CharField(widget=forms.TextArea)
class create_form(edit_form):
def __init__(self,*args,**kwargs):
forms.Form.__init__(self,*args,**kwargs)
self.fields.insert(0,'name',forms.CharField())
</code></pre>
<p>That shut me up :) </p>
| 53 | 2009-05-27T01:46:50Z | 27,493,844 | <p>The accepted answer's approach makes use of an internal Django forms API that was changed in Django 1.7. <a href="https://code.djangoproject.com/timeline?from=2014-09-07T19%3A47%3A59%2B01%3A00&precision=second" rel="nofollow">The project team's opinion is that it should never have been used in the first place.</a> I now use this function to reorder my forms. This code makes use of an <code>OrderedDict</code>:</p>
<pre><code>def reorder_fields(fields, order):
"""Reorder form fields by order, removing items not in order.
>>> reorder_fields(
... OrderedDict([('a', 1), ('b', 2), ('c', 3)]),
... ['b', 'c', 'a'])
OrderedDict([('b', 2), ('c', 3), ('a', 1)])
"""
for key, v in fields.items():
if key not in order:
del fields[key]
return OrderedDict(sorted(fields.items(), key=lambda k: order.index(k[0])))
</code></pre>
<p>Which I use in classes like this:</p>
<pre><code>class ChangeOpenQuestion(ChangeMultipleChoice):
def __init__(self, *args, **kwargs):
super(ChangeOpenQuestion, self).__init__(*args, **kwargs)
key_order = ['title',
'question',
'answer',
'correct_answer',
'incorrect_answer']
self.fields = reorder_fields(self.fields, key_order)
</code></pre>
| 4 | 2014-12-15T21:53:46Z | [
"python",
"django",
"django-forms"
] |
Django forms, inheritance and order of form fields | 913,589 | <p>I'm using Django forms in my website and would like to control the order of the fields.</p>
<p>Here's how I define my forms:</p>
<pre><code>class edit_form(forms.Form):
summary = forms.CharField()
description = forms.CharField(widget=forms.TextArea)
class create_form(edit_form):
name = forms.CharField()
</code></pre>
<p>The name is immutable and should only be listed when the entity is created. I use inheritance to add consistency and DRY principles. What happens which is not erroneous, in fact totally expected, is that the name field is listed last in the view/html but I'd like the name field to be on top of summary and description. I do realize that I could easily fix it by copying summary and description into create_form and loose the inheritance but I'd like to know if this is possible. </p>
<p><strong>Why?</strong> Imagine you've got 100 fields in edit_form and have to add 10 fields on the top in create_form - copying and maintaining the two forms wouldn't look so sexy then. (This is <em>not</em> my case, I'm just making up an example)</p>
<p>So, how can I override this behavior?</p>
<p><strong>Edit:</strong></p>
<p>Apparently there's no proper way to do this without going through nasty hacks (fiddling with .field attribute). The .field attribute is a SortedDict (one of Django's internal datastructures) which doesn't provide any way to reorder key:value pairs. It does how-ever provide a way to insert items at a given index but that would move the items from the class members and into the constructor. This method would work, but make the code less readable. The only other way I see fit is to modify the framework itself which is less-than-optimal in most situations.</p>
<p>In short the code would become something like this:</p>
<pre><code>class edit_form(forms.Form):
summary = forms.CharField()
description = forms.CharField(widget=forms.TextArea)
class create_form(edit_form):
def __init__(self,*args,**kwargs):
forms.Form.__init__(self,*args,**kwargs)
self.fields.insert(0,'name',forms.CharField())
</code></pre>
<p>That shut me up :) </p>
| 53 | 2009-05-27T01:46:50Z | 30,794,861 | <p>Django 1.9 will support this by default on the form with <code>field_order</code>:</p>
<pre><code>class MyForm(forms.Form):
...
field_order = ['field_1', 'field_2']
...
</code></pre>
<p><a href="https://github.com/django/django/commit/28986da4ca167ae257abcaf7caea230eca2bcd80">https://github.com/django/django/commit/28986da4ca167ae257abcaf7caea230eca2bcd80</a></p>
| 6 | 2015-06-12T03:27:41Z | [
"python",
"django",
"django-forms"
] |
Django forms, inheritance and order of form fields | 913,589 | <p>I'm using Django forms in my website and would like to control the order of the fields.</p>
<p>Here's how I define my forms:</p>
<pre><code>class edit_form(forms.Form):
summary = forms.CharField()
description = forms.CharField(widget=forms.TextArea)
class create_form(edit_form):
name = forms.CharField()
</code></pre>
<p>The name is immutable and should only be listed when the entity is created. I use inheritance to add consistency and DRY principles. What happens which is not erroneous, in fact totally expected, is that the name field is listed last in the view/html but I'd like the name field to be on top of summary and description. I do realize that I could easily fix it by copying summary and description into create_form and loose the inheritance but I'd like to know if this is possible. </p>
<p><strong>Why?</strong> Imagine you've got 100 fields in edit_form and have to add 10 fields on the top in create_form - copying and maintaining the two forms wouldn't look so sexy then. (This is <em>not</em> my case, I'm just making up an example)</p>
<p>So, how can I override this behavior?</p>
<p><strong>Edit:</strong></p>
<p>Apparently there's no proper way to do this without going through nasty hacks (fiddling with .field attribute). The .field attribute is a SortedDict (one of Django's internal datastructures) which doesn't provide any way to reorder key:value pairs. It does how-ever provide a way to insert items at a given index but that would move the items from the class members and into the constructor. This method would work, but make the code less readable. The only other way I see fit is to modify the framework itself which is less-than-optimal in most situations.</p>
<p>In short the code would become something like this:</p>
<pre><code>class edit_form(forms.Form):
summary = forms.CharField()
description = forms.CharField(widget=forms.TextArea)
class create_form(edit_form):
def __init__(self,*args,**kwargs):
forms.Form.__init__(self,*args,**kwargs)
self.fields.insert(0,'name',forms.CharField())
</code></pre>
<p>That shut me up :) </p>
| 53 | 2009-05-27T01:46:50Z | 33,034,723 | <p>I built a form 'ExRegistrationForm' inherited from the 'RegistrationForm' from Django-Registration-Redux. I faced two issues, one of which was reordering the fields on the html output page once the new form had been created.</p>
<p>I solved them as follows:</p>
<p><strong>1. ISSUE 1: Remove Username from the Registration Form: In my_app.forms.py</strong></p>
<pre><code> class ExRegistrationForm(RegistrationForm):
#Below 2 lines extend the RegistrationForm with 2 new fields firstname & lastname
first_name = forms.CharField(label=(u'First Name'))
last_name = forms.CharField(label=(u'Last Name'))
#Below 3 lines removes the username from the fields shown in the output of the this form
def __init__(self, *args, **kwargs):
super(ExRegistrationForm, self).__init__(*args, **kwargs)
self.fields.pop('username')
</code></pre>
<p><strong>2. ISSUE 2: Make FirstName and LastName appear on top: In templates/registration/registration_form.html</strong></p>
<p>You can individually display the fields in the order that you want. This would help in case the number of fields are less, but not if you have a large number of fields where it becomes practically impossible to actually write them in the form.</p>
<pre><code> {% extends "base.html" %}
{% load i18n %}
{% block content %}
<form method="post" action=".">
{% csrf_token %}
#The Default html is: {{ form.as_p }} , which can be broken down into individual elements as below for re-ordering.
<p>First Name: {{ form.first_name }}</p>
<p>Last Name: {{ form.last_name }}</p>
<p>Email: {{ form.email }}</p>
<p>Password: {{ form.password1 }}</p>
<p>Confirm Password: {{ form.password2 }}</p>
<input type="submit" value="{% trans 'Submit' %}" />
</form>
{% endblock %}
</code></pre>
| 0 | 2015-10-09T09:31:11Z | [
"python",
"django",
"django-forms"
] |
django error 'too many values to unpack' | 913,590 | <p>I'm learning Django by building a simple recipes app. I have a 1 table model using the 'choices' field option for recipe categories rather than using a 2nd 'categories' table and a foreign key relationship. So i created db table via syncdb and then loaded table with test data. When i go to admin and click on the 'Recipes' link in an attempt to view recipes i get the following error:</p>
<pre><code>Template error
In template /var/lib/python-support/python2.6/django/contrib/admin/templates/admin/change_list.html, error at line 34
Caught an exception while rendering: too many values to unpack
</code></pre>
<p>If anyone can shed light on this cryptic error that would be great. Db is Sqlite. Django version is 1.0. The model is listed below:</p>
<pre><code>from django.db import models
class Recipe(models.Model):
CATEGORY_CHOICES = (
(1, u'Appetizer'),
(2, u'Bread'),
(3, u'Dessert'),
(4, u'Drinks'),
(5, u'Main Course'),
(6, u'Salad'),
(7, u'Side Dish'),
(8, u'Soup'),
(9, u'Sauce/Marinade'),
(10, u'Other'),
)
name = models.CharField(max_length=255)
submitter = models.CharField(max_length=40)
date = models.DateTimeField()
category = models.SmallIntegerField(choices=CATEGORY_CHOICES)
ingredients = models.TextField()
directions = models.TextField()
comments = models.TextField(null=True, blank=True)
</code></pre>
| 13 | 2009-05-27T01:46:50Z | 913,605 | <p>If I had to guess, it's because whatever is in the administrative template expects a list of tuples, but you've instead supplied a tuple of tuples (hence the "too many values"). Try replacing with a list instead:</p>
<pre><code>CATEGORY_CHOICES = [ # Note square brackets.
(1, u'Appetizer'),
(2, u'Bread'),
(3, u'Dessert'),
(4, u'Drinks'),
(5, u'Main Course'),
(6, u'Salad'),
(7, u'Side Dish'),
(8, u'Soup'),
(9, u'Sauce/Marinade'),
(10, u'Other'),
]
</code></pre>
| 1 | 2009-05-27T01:53:35Z | [
"python",
"django",
"sqlite"
] |
django error 'too many values to unpack' | 913,590 | <p>I'm learning Django by building a simple recipes app. I have a 1 table model using the 'choices' field option for recipe categories rather than using a 2nd 'categories' table and a foreign key relationship. So i created db table via syncdb and then loaded table with test data. When i go to admin and click on the 'Recipes' link in an attempt to view recipes i get the following error:</p>
<pre><code>Template error
In template /var/lib/python-support/python2.6/django/contrib/admin/templates/admin/change_list.html, error at line 34
Caught an exception while rendering: too many values to unpack
</code></pre>
<p>If anyone can shed light on this cryptic error that would be great. Db is Sqlite. Django version is 1.0. The model is listed below:</p>
<pre><code>from django.db import models
class Recipe(models.Model):
CATEGORY_CHOICES = (
(1, u'Appetizer'),
(2, u'Bread'),
(3, u'Dessert'),
(4, u'Drinks'),
(5, u'Main Course'),
(6, u'Salad'),
(7, u'Side Dish'),
(8, u'Soup'),
(9, u'Sauce/Marinade'),
(10, u'Other'),
)
name = models.CharField(max_length=255)
submitter = models.CharField(max_length=40)
date = models.DateTimeField()
category = models.SmallIntegerField(choices=CATEGORY_CHOICES)
ingredients = models.TextField()
directions = models.TextField()
comments = models.TextField(null=True, blank=True)
</code></pre>
| 13 | 2009-05-27T01:46:50Z | 913,660 | <p>Per <a href="http://code.djangoproject.com/ticket/972" rel="nofollow">http://code.djangoproject.com/ticket/972</a> , you need to move the assignment <code>CATEGORY_CHOICES = ...</code> <em>outside</em> the <code>class</code> statement.</p>
| 1 | 2009-05-27T02:22:04Z | [
"python",
"django",
"sqlite"
] |
django error 'too many values to unpack' | 913,590 | <p>I'm learning Django by building a simple recipes app. I have a 1 table model using the 'choices' field option for recipe categories rather than using a 2nd 'categories' table and a foreign key relationship. So i created db table via syncdb and then loaded table with test data. When i go to admin and click on the 'Recipes' link in an attempt to view recipes i get the following error:</p>
<pre><code>Template error
In template /var/lib/python-support/python2.6/django/contrib/admin/templates/admin/change_list.html, error at line 34
Caught an exception while rendering: too many values to unpack
</code></pre>
<p>If anyone can shed light on this cryptic error that would be great. Db is Sqlite. Django version is 1.0. The model is listed below:</p>
<pre><code>from django.db import models
class Recipe(models.Model):
CATEGORY_CHOICES = (
(1, u'Appetizer'),
(2, u'Bread'),
(3, u'Dessert'),
(4, u'Drinks'),
(5, u'Main Course'),
(6, u'Salad'),
(7, u'Side Dish'),
(8, u'Soup'),
(9, u'Sauce/Marinade'),
(10, u'Other'),
)
name = models.CharField(max_length=255)
submitter = models.CharField(max_length=40)
date = models.DateTimeField()
category = models.SmallIntegerField(choices=CATEGORY_CHOICES)
ingredients = models.TextField()
directions = models.TextField()
comments = models.TextField(null=True, blank=True)
</code></pre>
| 13 | 2009-05-27T01:46:50Z | 913,705 | <p>I got it working. Most of the 'too many values to unpack' errors that i came across while googling were Value Error types. My error was a Template Syntax type. To load my recipe table i had imported a csv file. I was thinking maybe there was a problem somewhere in the data that sqlite allowed on import. So i deleted all data and then added 2 recipes manually via django admin form. The list of recipes loaded after that.</p>
<p>thanks.</p>
| 0 | 2009-05-27T02:37:17Z | [
"python",
"django",
"sqlite"
] |
django error 'too many values to unpack' | 913,590 | <p>I'm learning Django by building a simple recipes app. I have a 1 table model using the 'choices' field option for recipe categories rather than using a 2nd 'categories' table and a foreign key relationship. So i created db table via syncdb and then loaded table with test data. When i go to admin and click on the 'Recipes' link in an attempt to view recipes i get the following error:</p>
<pre><code>Template error
In template /var/lib/python-support/python2.6/django/contrib/admin/templates/admin/change_list.html, error at line 34
Caught an exception while rendering: too many values to unpack
</code></pre>
<p>If anyone can shed light on this cryptic error that would be great. Db is Sqlite. Django version is 1.0. The model is listed below:</p>
<pre><code>from django.db import models
class Recipe(models.Model):
CATEGORY_CHOICES = (
(1, u'Appetizer'),
(2, u'Bread'),
(3, u'Dessert'),
(4, u'Drinks'),
(5, u'Main Course'),
(6, u'Salad'),
(7, u'Side Dish'),
(8, u'Soup'),
(9, u'Sauce/Marinade'),
(10, u'Other'),
)
name = models.CharField(max_length=255)
submitter = models.CharField(max_length=40)
date = models.DateTimeField()
category = models.SmallIntegerField(choices=CATEGORY_CHOICES)
ingredients = models.TextField()
directions = models.TextField()
comments = models.TextField(null=True, blank=True)
</code></pre>
| 13 | 2009-05-27T01:46:50Z | 2,777,895 | <p>I just had the same problem... my cvs file came from ms excel and the date fields gotten the wrong format at saving time. I change the format to something like '2010-05-04 13:05:46.790454' (excel gave me 5/5/2010 10:05:47) and voilaaaa no more 'too many values to unpackâ</p>
| 0 | 2010-05-06T01:37:56Z | [
"python",
"django",
"sqlite"
] |
django error 'too many values to unpack' | 913,590 | <p>I'm learning Django by building a simple recipes app. I have a 1 table model using the 'choices' field option for recipe categories rather than using a 2nd 'categories' table and a foreign key relationship. So i created db table via syncdb and then loaded table with test data. When i go to admin and click on the 'Recipes' link in an attempt to view recipes i get the following error:</p>
<pre><code>Template error
In template /var/lib/python-support/python2.6/django/contrib/admin/templates/admin/change_list.html, error at line 34
Caught an exception while rendering: too many values to unpack
</code></pre>
<p>If anyone can shed light on this cryptic error that would be great. Db is Sqlite. Django version is 1.0. The model is listed below:</p>
<pre><code>from django.db import models
class Recipe(models.Model):
CATEGORY_CHOICES = (
(1, u'Appetizer'),
(2, u'Bread'),
(3, u'Dessert'),
(4, u'Drinks'),
(5, u'Main Course'),
(6, u'Salad'),
(7, u'Side Dish'),
(8, u'Soup'),
(9, u'Sauce/Marinade'),
(10, u'Other'),
)
name = models.CharField(max_length=255)
submitter = models.CharField(max_length=40)
date = models.DateTimeField()
category = models.SmallIntegerField(choices=CATEGORY_CHOICES)
ingredients = models.TextField()
directions = models.TextField()
comments = models.TextField(null=True, blank=True)
</code></pre>
| 13 | 2009-05-27T01:46:50Z | 5,990,777 | <p>You should use a <code>ChoiceField</code> instead of <code>SmallIntegerField</code></p>
| 2 | 2011-05-13T10:45:47Z | [
"python",
"django",
"sqlite"
] |
django error 'too many values to unpack' | 913,590 | <p>I'm learning Django by building a simple recipes app. I have a 1 table model using the 'choices' field option for recipe categories rather than using a 2nd 'categories' table and a foreign key relationship. So i created db table via syncdb and then loaded table with test data. When i go to admin and click on the 'Recipes' link in an attempt to view recipes i get the following error:</p>
<pre><code>Template error
In template /var/lib/python-support/python2.6/django/contrib/admin/templates/admin/change_list.html, error at line 34
Caught an exception while rendering: too many values to unpack
</code></pre>
<p>If anyone can shed light on this cryptic error that would be great. Db is Sqlite. Django version is 1.0. The model is listed below:</p>
<pre><code>from django.db import models
class Recipe(models.Model):
CATEGORY_CHOICES = (
(1, u'Appetizer'),
(2, u'Bread'),
(3, u'Dessert'),
(4, u'Drinks'),
(5, u'Main Course'),
(6, u'Salad'),
(7, u'Side Dish'),
(8, u'Soup'),
(9, u'Sauce/Marinade'),
(10, u'Other'),
)
name = models.CharField(max_length=255)
submitter = models.CharField(max_length=40)
date = models.DateTimeField()
category = models.SmallIntegerField(choices=CATEGORY_CHOICES)
ingredients = models.TextField()
directions = models.TextField()
comments = models.TextField(null=True, blank=True)
</code></pre>
| 13 | 2009-05-27T01:46:50Z | 8,206,621 | <p><strong>Edit: Updated in light of kibibu's correction.</strong></p>
<p>I have encountered what I believe is this same error, producing the message:</p>
<pre><code>Caught ValueError while rendering: too many values to unpack
</code></pre>
<p>My form class was as follows:</p>
<pre><code>class CalcForm(forms.Form):
item = forms.ChoiceField(choices=(('17815', '17816')))
</code></pre>
<p>Note that my <code>choices</code> type here a tuple. Django official documentation reads as follows for the <code>choices</code> arg:</p>
<blockquote>
<p>An iterable (e.g., a list or tuple) of 2-tuples to use as choices for
this field. This argument accepts the same formats as the choices
argument to a model field.</p>
</blockquote>
<p>src: <a href="https://docs.djangoproject.com/en/1.3/ref/forms/fields/#django.forms.ChoiceField.choices" rel="nofollow">https://docs.djangoproject.com/en/1.3/ref/forms/fields/#django.forms.ChoiceField.choices</a></p>
<p>This problem was solved by my observing the documentation and using a <strong>list of tuples:</strong></p>
<pre><code>class CalcForm(forms.Form):
item = forms.ChoiceField(choices=[('17815', '17816')])
</code></pre>
<p>Do note that while the docs state any iterable of the correct form can be used, a tuple of 2-tuples did not work:</p>
<pre><code>item = forms.ChoiceField(choices=(('17815', '17816'), ('123', '456')))
</code></pre>
<p>This produced the same error as before.</p>
<p>Lesson: bugs happen.</p>
| 12 | 2011-11-21T02:24:40Z | [
"python",
"django",
"sqlite"
] |
django error 'too many values to unpack' | 913,590 | <p>I'm learning Django by building a simple recipes app. I have a 1 table model using the 'choices' field option for recipe categories rather than using a 2nd 'categories' table and a foreign key relationship. So i created db table via syncdb and then loaded table with test data. When i go to admin and click on the 'Recipes' link in an attempt to view recipes i get the following error:</p>
<pre><code>Template error
In template /var/lib/python-support/python2.6/django/contrib/admin/templates/admin/change_list.html, error at line 34
Caught an exception while rendering: too many values to unpack
</code></pre>
<p>If anyone can shed light on this cryptic error that would be great. Db is Sqlite. Django version is 1.0. The model is listed below:</p>
<pre><code>from django.db import models
class Recipe(models.Model):
CATEGORY_CHOICES = (
(1, u'Appetizer'),
(2, u'Bread'),
(3, u'Dessert'),
(4, u'Drinks'),
(5, u'Main Course'),
(6, u'Salad'),
(7, u'Side Dish'),
(8, u'Soup'),
(9, u'Sauce/Marinade'),
(10, u'Other'),
)
name = models.CharField(max_length=255)
submitter = models.CharField(max_length=40)
date = models.DateTimeField()
category = models.SmallIntegerField(choices=CATEGORY_CHOICES)
ingredients = models.TextField()
directions = models.TextField()
comments = models.TextField(null=True, blank=True)
</code></pre>
| 13 | 2009-05-27T01:46:50Z | 19,302,943 | <p>kibibu's comment to Kreychek's answer is correct. This isn't a Django issue but rather an interesting aspect of Python. To summarize:</p>
<p>In Python, round parentheses are used for both order of operations and tuples. So:</p>
<pre><code>foo = (2+2)
</code></pre>
<p>will result in foo being 4, not a tuple who's first and only element is 4: 4</p>
<pre><code>foo = (2+2, 3+3)
</code></pre>
<p>will result in foo being a two-dimensional tuple: (4,6)</p>
<p>To tell Python that you want to create a one-dimensional tuple instead of just denoting the order of operations, use a trailing comma:</p>
<pre><code>foo = (2+2,)
</code></pre>
<p>will result in foo being a one-dimensional tuple who's first and only element is 4: (4,)</p>
<p>So for your scenario:</p>
<pre><code>class CalcForm(forms.Form):
item = forms.ChoiceField(choices=(('17815', '17816'),))
</code></pre>
<p>would give what you want. Using a list is a great solution too (more Pythonic in my opinion), but hopefully this answer is informative since this can come up in other cases. </p>
<p>For example: </p>
<pre><code>print("foo: %s" % (foo))
</code></pre>
<p>may give an error if foo is an iterable, but:</p>
<pre><code>print("foo: %s" % (foo,))
</code></pre>
<p>or:</p>
<pre><code>print("foo: %s" % [foo])
</code></pre>
<p>will properly convert foo to a string whether it's an iterable or not.</p>
<p>Documentation: <a href="http://docs.python.org/2/tutorial/datastructures.html#tuples-and-sequences" rel="nofollow">http://docs.python.org/2/tutorial/datastructures.html#tuples-and-sequences</a></p>
| 0 | 2013-10-10T18:01:42Z | [
"python",
"django",
"sqlite"
] |
How does one debug a fastcgi application? | 913,817 | <p>How does one debug a FastCGI application? I've got an app that's dying but I can't figure out why, even though it's likely throwing a stack trace on stderr. Running it from the commandline results in an error saying: </p>
<pre><code>RuntimeError: No FastCGI Environment: 88 - Socket operation on non-socket
</code></pre>
<p>How do I set up a 'FastCGI Environtment' for debugging purposes? It's not my app - it's a 3rd party open source app - so I'd rather avoid adding in a bunch of logging to figure out what's going wrong.</p>
<p>If it matters, the app is Python, but FastCGI is FastCGI, right? Is there a shim or something to let you invoke a fastcgi program from the commandline and hook it up to the terminal so you can see its stdout/stderr?</p>
| 3 | 2009-05-27T03:32:40Z | 1,005,007 | <p>It does matter that the application is Python; your question is really "how do I debug Python when I'm not starting the script myself".</p>
<p>You want to use a remote debugger. The excellent WinPDB has <a href="http://winpdb.org/docs/embedded-debugging/" rel="nofollow">some documentation on embedded debugging</a> which you should be able to use to attach to your FastCGI application and step through it.</p>
| 2 | 2009-06-17T03:43:01Z | [
"python",
"debugging",
"web-applications",
"fastcgi"
] |
Using poll on file-like object returned by urllib2.urlopen()? | 913,913 | <p>I've run into the bug described at <a href="http://bugs.python.org/issue1327971" rel="nofollow">http://bugs.python.org/issue1327971</a> while trying to poll a file-like object returned by urllib2.urlopen(). </p>
<p>Unfortunately, being relatively new to Python, I can't actually determine from the responses how to get around the issue as they seem mostly geared towards fixing the bug, rather than hacking the code that triggers it to work.</p>
<p>Here is a distilled version of my code that throws the error:</p>
<pre><code>import urllib2, select
if __name__ == "__main__":
p = select.poll()
url = "http://localhost/"
fd = urllib2.urlopen(url)
p.register(fd, select.POLLIN | select.POLLERR | select.POLLHUP | select.POLLNVAL)
result = p.poll()
for fd, event in result:
if event == select.POLLIN:
while 1:
buf = fd.read(4096)
if not buf:
break
print buf
</code></pre>
<p>And the error which is raised when I run it on python 2.6:</p>
<pre><code>Traceback (most recent call last):
File "/home/shab/py/test.py", line 9, in <module>
p.register(fd, select.POLLIN | select.POLLERR | select.POLLHUP | select.POLLNVAL)
File "/usr/lib/python2.6/socket.py", line 287, in fileno
return self._sock.fileno()
AttributeError: HTTPResponse instance has no attribute 'fileno'
</code></pre>
<p>Update: I do not want to modify the system libraries.</p>
| 0 | 2009-05-27T04:22:12Z | 913,925 | <p>It looks like you want to modify urllib with <a href="http://bugs.python.org/file13033/urllib%5Ffileno%5F2.diff" rel="nofollow">this patch</a>. Keep in mind, there's a reason this code hasn't been released. It hasn't been completely reviewed.</p>
<p>EDIT: Actually, I think you want to modify httplib with <a href="http://bugs.python.org/file13032/httplib%5Ffileno%5F2.diff" rel="nofollow">the other patch</a>.</p>
| 0 | 2009-05-27T04:29:08Z | [
"python",
"python-2.6"
] |
Using poll on file-like object returned by urllib2.urlopen()? | 913,913 | <p>I've run into the bug described at <a href="http://bugs.python.org/issue1327971" rel="nofollow">http://bugs.python.org/issue1327971</a> while trying to poll a file-like object returned by urllib2.urlopen(). </p>
<p>Unfortunately, being relatively new to Python, I can't actually determine from the responses how to get around the issue as they seem mostly geared towards fixing the bug, rather than hacking the code that triggers it to work.</p>
<p>Here is a distilled version of my code that throws the error:</p>
<pre><code>import urllib2, select
if __name__ == "__main__":
p = select.poll()
url = "http://localhost/"
fd = urllib2.urlopen(url)
p.register(fd, select.POLLIN | select.POLLERR | select.POLLHUP | select.POLLNVAL)
result = p.poll()
for fd, event in result:
if event == select.POLLIN:
while 1:
buf = fd.read(4096)
if not buf:
break
print buf
</code></pre>
<p>And the error which is raised when I run it on python 2.6:</p>
<pre><code>Traceback (most recent call last):
File "/home/shab/py/test.py", line 9, in <module>
p.register(fd, select.POLLIN | select.POLLERR | select.POLLHUP | select.POLLNVAL)
File "/usr/lib/python2.6/socket.py", line 287, in fileno
return self._sock.fileno()
AttributeError: HTTPResponse instance has no attribute 'fileno'
</code></pre>
<p>Update: I do not want to modify the system libraries.</p>
| 0 | 2009-05-27T04:22:12Z | 914,011 | <p>If you don't want to modify you system libraries you also can patch <code>httplib</code> on the fly to match the patch in the bug report:</p>
<pre><code>import httplib
@property
def http_fileno(self):
return self.fp.fileno
@http_fileno.setter
def http_fileno(self, value):
self.fp.fileno = value
httplib.HTTPResponse.fileno = http_fileno
# and now on with the previous code
# ...
</code></pre>
<p>You then get an error on <code>fd.read(4096)</code> because the <code>fd</code> returned by <code>poll</code> is a raw file descriptor value, not a file-like object. You probably need to use the original file object to read the data, not the value returned by poll.</p>
| 1 | 2009-05-27T04:56:09Z | [
"python",
"python-2.6"
] |
Decoding html encoded strings in python | 913,933 | <p>I have the following string...</p>
<pre><code>"Scam, hoax, or the real deal, he&#8217;s gonna work his way to the bottom of the sordid tale, and hopefully end up with an arcade game in the process."
</code></pre>
<p>I need to turn it into this string...</p>
<blockquote>
<p>Scam, hoax, or the real deal,
he’s gonna work his way to the
bottom of the sordid tale, and
hopefully end up with an arcade game
in the process.</p>
</blockquote>
<p>This is pretty standard HTML encoding and I can't for the life of me figure out how to convert it in python.</p>
<p>I found this:
<a href="http://github.com/sku/python-twitter-ircbot/blob/321d94e0e40d0acc92f5bf57d126b57369da70de/html_decode.py" rel="nofollow">GitHub</a></p>
<p>And it's very close to working, however it does not output an apostrophe but instead some off unicode character.</p>
<p>Here is an example of the output from the GitHub script...</p>
<blockquote>
<p>Scam, hoax, or the real deal, heâs
gonna work his way to the bottom of
the sordid tale, and hopefully end up
with an arcade game in the process.</p>
</blockquote>
| 1 | 2009-05-27T04:32:50Z | 913,989 | <p>What's you're trying to do is called "HTML entity decoding" and it's covered in a number of past Stack Overflow questions, for example:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/816272/how-to-unescape-apostrophes-and-such-in-python">How to unescape apostrophes and such in Python?</a></li>
<li><a href="http://stackoverflow.com/questions/628332/decoding-html-entities-with-python">Decoding HTML Entities With Python</a></li>
</ul>
<p>Here's a code snippet using the <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a> HTML parsing library to decode your example:</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from BeautifulSoup import BeautifulSoup
string = "Scam, hoax, or the real deal, he&#8217;s gonna work his way to the bottom of the sordid tale, and hopefully end up with an arcade game in the process."
s = BeautifulSoup(string,convertEntities=BeautifulSoup.HTML_ENTITIES).contents[0]
print s
</code></pre>
<p>Here's the output:</p>
<blockquote>
<p>Scam, hoax, or the real deal, heâs
gonna work his way to the bottom of
the sordid tale, and hopefully end up
with an arcade game in the process.</p>
</blockquote>
| 4 | 2009-05-27T04:49:52Z | [
"python",
"html",
"xml"
] |
Python script embedded in Windows Registry | 914,106 | <p>We all know that windows has the feature that you can right click on a file and numerous options are shown. Well you can add a value to this menu. I followed this guide : jfitz.com/tips/rclick_custom.html</p>
<p>Basically I have a script that runs when I right click on a certain file type.
Alright, so everything is going flawlessly, however when I finish and try to test it out Windows tells me that it only accepts .exe's. </p>
<p>Is their a way around this without having to use py2exe or something similar?</p>
<p>**EDIT
Ok , so if my script takes the first argument as it's parameter how would I put this into the registry?</p>
<p>"C:\Python26\pythonw.exe C:\Users\daved\Documents\Python\backup.py "%1""
?</p>
| 0 | 2009-05-27T05:30:49Z | 914,117 | <p>yes, call pythonw.exe and pass the script path as a parameter</p>
<pre><code>"C:\Python26\pythonw.exe" "C:\Users\daved\Documents\Python\backup.py" "%1"
</code></pre>
<p>It's also recommended (but not required) to use the extension .pyw when your script doesn't run in a console.</p>
| 2 | 2009-05-27T05:32:57Z | [
"python",
"winapi"
] |
What is the underlying data structure for Python lists? | 914,233 | <p>What is the typical underlying data structure used to implement Python's built-in list data type?</p>
| 44 | 2009-05-27T06:22:56Z | 914,248 | <p>CPython:</p>
<pre><code>typedef struct {
PyObject_VAR_HEAD
/* Vector of pointers to list elements. list[0] is ob_item[0], etc. */
PyObject **ob_item;
/* ob_item contains space for 'allocated' elements. The number
* currently in use is ob_size.
* Invariants:
* 0 <= ob_size <= allocated
* len(list) == ob_size
* ob_item == NULL implies ob_size == allocated == 0
* list.sort() temporarily sets allocated to -1 to detect mutations.
*
* Items must normally not be NULL, except during construction when
* the list is not yet visible outside the function that builds it.
*/
Py_ssize_t allocated;
} PyListObject;
</code></pre>
<p>As can be seen on the following line, the list is declared as an array of pointers to <code>PyObjects</code>.</p>
<pre><code>PyObject **ob_item;
</code></pre>
| 21 | 2009-05-27T06:29:28Z | [
"python",
"list",
"data-structures"
] |
What is the underlying data structure for Python lists? | 914,233 | <p>What is the typical underlying data structure used to implement Python's built-in list data type?</p>
| 44 | 2009-05-27T06:22:56Z | 914,271 | <p>In the <a href="http://fisheye3.atlassian.com/browse/jython/trunk/jython/src/org/python/core/PyList.java?r1=6244&r2=6257&u=-1&ignore=&k=">Jython implementation</a>, it's an <code>ArrayList<PyObject></code>.</p>
| 9 | 2009-05-27T06:35:03Z | [
"python",
"list",
"data-structures"
] |
What is the underlying data structure for Python lists? | 914,233 | <p>What is the typical underlying data structure used to implement Python's built-in list data type?</p>
| 44 | 2009-05-27T06:22:56Z | 915,593 | <blockquote>
<p>List objects are implemented as
arrays. They are optimized for fast
fixed-length operations and incur O(n)
memory movement costs for pop(0) and
insert(0, v) operations which change
both the size and position of the
underlying data representation.</p>
</blockquote>
<p>See also:
<a href="http://docs.python.org/library/collections.html#collections.deque">http://docs.python.org/library/collections.html#collections.deque</a></p>
<p>Btw, I find it interesting that the Python tutorial on data structures recommends using pop(0) to simulate a queue but does not mention O(n) or the deque option.</p>
<p><a href="http://docs.python.org/tutorial/datastructures.html#using-lists-as-queues">http://docs.python.org/tutorial/datastructures.html#using-lists-as-queues</a></p>
| 34 | 2009-05-27T13:04:07Z | [
"python",
"list",
"data-structures"
] |
capture stderr from python subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE) | 914,320 | <p>I have seen this posted so many times here; yet failed to capture intentional errors from command. Best partial work I have found so far..</p>
<pre><code>from Tkinter import *
import os
import Image, ImageTk
import subprocess as sub
p = sub.Popen('datdsade',stdout=sub.PIPE,stderr=sub.PIPE)
output, errors = p.communicate()
root = Tk()
text = Text(root)
text.pack()
text.insert(END, output+ "Error: " + errors )
root.mainloop()
</code></pre>
| 4 | 2009-05-27T06:51:33Z | 914,328 | <p>Are you 100% sure 'datdsade' actually writes to stderr? If so then possibly it's buffering its stderr, or blocking on it.</p>
<p>EDIT: I'd suggest running 'datdsade' (your program) in bash (assuming you have linux, you can dl sh.exe for windows) and seeing if you can capture your stderr to a file datdsade 2> errors.txt. Be aware that <strong>if you are on Windows stderr will not output in a DOS window</strong>. You may have more luck writing to a log file first and reading it back or having python store it in a variable.</p>
<p>Alternatively stderr=sub.STDOUT will merge your errors with the stdout.</p>
<p>EDIT AGAIN: Ignore the above, since communicate() is capturing all of this. I would say the problem is definately that program you chose never writes to stderr or you aren't actually triggering an error. This is just the way the program was written. What is the program?</p>
| 2 | 2009-05-27T06:56:31Z | [
"python",
"subprocess"
] |
capture stderr from python subprocess.Popen(command, stderr=subprocess.PIPE, stdout=subprocess.PIPE) | 914,320 | <p>I have seen this posted so many times here; yet failed to capture intentional errors from command. Best partial work I have found so far..</p>
<pre><code>from Tkinter import *
import os
import Image, ImageTk
import subprocess as sub
p = sub.Popen('datdsade',stdout=sub.PIPE,stderr=sub.PIPE)
output, errors = p.communicate()
root = Tk()
text = Text(root)
text.pack()
text.insert(END, output+ "Error: " + errors )
root.mainloop()
</code></pre>
| 4 | 2009-05-27T06:51:33Z | 24,171,613 | <p>This works perfectly for me: </p>
<pre><code>import subprocess
try:
#prints results
result = subprocess.check_output("echo %USERNAME%", stderr=subprocess.STDOUT, shell=True)
print result
#causes error
result = subprocess.check_output("copy testfds", stderr=subprocess.STDOUT, shell=True)
except subprocess.CalledProcessError, ex:
print "--------error------"
print ex.cmd
print ex.message
print ex.returncode
print ex.output
</code></pre>
| 4 | 2014-06-11T20:03:47Z | [
"python",
"subprocess"
] |
How can I count unique terms in a plaintext file case-insensitively? | 914,382 | <p>This can be in any high-level language that is likely to be available on a typical unix-like system (Python, Perl, awk, standard unix utils {sort, uniq}, etc). Hopefully it's fast enough to report the total number of unique terms for a 2MB text file.</p>
<p>I only need this for quick sanity-checking, so it doesn't need to be well-engineered.</p>
<p>Remember, case-insensitve.</p>
<p>Thank you guys very much.</p>
<p>Side note: If you use Python, please don't use version 3-only code. The system I'm running it on only has 2.4.4.</p>
| 2 | 2009-05-27T07:18:15Z | 914,390 | <p>In Python 2.4 (possibly it works on earlier systems as well):</p>
<pre><code>#! /usr/bin/python2.4
import sys
h = set()
for line in sys.stdin.xreadlines():
for term in line.split():
h.add(term)
print len(h)
</code></pre>
<p>In Perl:</p>
<pre><code>$ perl -ne 'for (split(" ", $_)) { $H{$_} = 1 } END { print scalar(keys%H), "\n" }' <file.txt
</code></pre>
| 4 | 2009-05-27T07:19:54Z | [
"python",
"perl",
"unix",
"count",
"awk"
] |
How can I count unique terms in a plaintext file case-insensitively? | 914,382 | <p>This can be in any high-level language that is likely to be available on a typical unix-like system (Python, Perl, awk, standard unix utils {sort, uniq}, etc). Hopefully it's fast enough to report the total number of unique terms for a 2MB text file.</p>
<p>I only need this for quick sanity-checking, so it doesn't need to be well-engineered.</p>
<p>Remember, case-insensitve.</p>
<p>Thank you guys very much.</p>
<p>Side note: If you use Python, please don't use version 3-only code. The system I'm running it on only has 2.4.4.</p>
| 2 | 2009-05-27T07:18:15Z | 914,415 | <p>Using bash/UNIX commands:</p>
<pre><code>sed -e 's/[[:space:]]\+/\n/g' $FILE | sort -fu | wc -l
</code></pre>
| 5 | 2009-05-27T07:34:19Z | [
"python",
"perl",
"unix",
"count",
"awk"
] |
How can I count unique terms in a plaintext file case-insensitively? | 914,382 | <p>This can be in any high-level language that is likely to be available on a typical unix-like system (Python, Perl, awk, standard unix utils {sort, uniq}, etc). Hopefully it's fast enough to report the total number of unique terms for a 2MB text file.</p>
<p>I only need this for quick sanity-checking, so it doesn't need to be well-engineered.</p>
<p>Remember, case-insensitve.</p>
<p>Thank you guys very much.</p>
<p>Side note: If you use Python, please don't use version 3-only code. The system I'm running it on only has 2.4.4.</p>
| 2 | 2009-05-27T07:18:15Z | 914,419 | <p>Using just standard Unix utilities:</p>
<pre><code>< somefile tr 'A-Z[:blank:][:punct:]' 'a-z\n' | sort | uniq -c
</code></pre>
<p>If you're on a system without Gnu <code>tr</code>, you'll need to replace "<code>[:blank:][:punct:]</code>" with a list of all the whitespace and punctuation characters you'd like to consider to be separators of words, rather than part of a word, e.g., "<code> \t.,;</code>".</p>
<p>If you want the output sorted in descending order of frequency, you can append "<code>| sort -r -n</code>" to the end of this.</p>
<p>Note that this will produce an irrelevant count of whitespace tokens as well; if you're concerned about this, after the <code>tr</code> you can use sed to filter out the empty lines.</p>
| 4 | 2009-05-27T07:34:47Z | [
"python",
"perl",
"unix",
"count",
"awk"
] |
How can I count unique terms in a plaintext file case-insensitively? | 914,382 | <p>This can be in any high-level language that is likely to be available on a typical unix-like system (Python, Perl, awk, standard unix utils {sort, uniq}, etc). Hopefully it's fast enough to report the total number of unique terms for a 2MB text file.</p>
<p>I only need this for quick sanity-checking, so it doesn't need to be well-engineered.</p>
<p>Remember, case-insensitve.</p>
<p>Thank you guys very much.</p>
<p>Side note: If you use Python, please don't use version 3-only code. The system I'm running it on only has 2.4.4.</p>
| 2 | 2009-05-27T07:18:15Z | 914,430 | <p>In Perl:</p>
<pre><code>my %words;
while (<>) {
map { $words{lc $_} = 1 } split /\s/);
}
print scalar keys %words, "\n";
</code></pre>
| 6 | 2009-05-27T07:38:23Z | [
"python",
"perl",
"unix",
"count",
"awk"
] |
How can I count unique terms in a plaintext file case-insensitively? | 914,382 | <p>This can be in any high-level language that is likely to be available on a typical unix-like system (Python, Perl, awk, standard unix utils {sort, uniq}, etc). Hopefully it's fast enough to report the total number of unique terms for a 2MB text file.</p>
<p>I only need this for quick sanity-checking, so it doesn't need to be well-engineered.</p>
<p>Remember, case-insensitve.</p>
<p>Thank you guys very much.</p>
<p>Side note: If you use Python, please don't use version 3-only code. The system I'm running it on only has 2.4.4.</p>
| 2 | 2009-05-27T07:18:15Z | 914,787 | <p>Simply (52 strokes):</p>
<pre><code>perl -nE'@w{map lc,split/\W+/}=();END{say 0+keys%w}'
</code></pre>
<p>For older perl versions (55 strokes):</p>
<pre><code>perl -lne'@w{map lc,split/\W+/}=();END{print 0+keys%w}'
</code></pre>
| 3 | 2009-05-27T09:19:37Z | [
"python",
"perl",
"unix",
"count",
"awk"
] |
How can I count unique terms in a plaintext file case-insensitively? | 914,382 | <p>This can be in any high-level language that is likely to be available on a typical unix-like system (Python, Perl, awk, standard unix utils {sort, uniq}, etc). Hopefully it's fast enough to report the total number of unique terms for a 2MB text file.</p>
<p>I only need this for quick sanity-checking, so it doesn't need to be well-engineered.</p>
<p>Remember, case-insensitve.</p>
<p>Thank you guys very much.</p>
<p>Side note: If you use Python, please don't use version 3-only code. The system I'm running it on only has 2.4.4.</p>
| 2 | 2009-05-27T07:18:15Z | 914,907 | <p>Here is a Perl one-liner:</p>
<pre><code>perl -lne '$h{lc $_}++ for split /[\s.,]+/; END{print scalar keys %h}' file.txt
</code></pre>
<p>Or to list the count for each item:</p>
<pre><code>perl -lne '$h{lc $_}++ for split /[\s.,]+/; END{printf "%-12s %d\n", $_, $h{$_} for sort keys %h}' file.txt
</code></pre>
<p>This makes an attempt to handle punctuation so that "foo." is counted with "foo" while "don't" is treated as a single word, but you can adjust the regex to suit your needs. </p>
| 4 | 2009-05-27T09:55:37Z | [
"python",
"perl",
"unix",
"count",
"awk"
] |
How can I count unique terms in a plaintext file case-insensitively? | 914,382 | <p>This can be in any high-level language that is likely to be available on a typical unix-like system (Python, Perl, awk, standard unix utils {sort, uniq}, etc). Hopefully it's fast enough to report the total number of unique terms for a 2MB text file.</p>
<p>I only need this for quick sanity-checking, so it doesn't need to be well-engineered.</p>
<p>Remember, case-insensitve.</p>
<p>Thank you guys very much.</p>
<p>Side note: If you use Python, please don't use version 3-only code. The system I'm running it on only has 2.4.4.</p>
| 2 | 2009-05-27T07:18:15Z | 915,110 | <p>Here is an awk oneliner.</p>
<pre><code>$ gawk -v RS='[[:space:]]' 'NF&&!a[toupper($0)]++{i++}END{print i}' somefile
</code></pre>
<ul>
<li>'NF' means 'if there is a charactor'.</li>
<li>'!a[topuuer[$0]++]' means 'show only
uniq words'.</li>
</ul>
| 0 | 2009-05-27T10:53:51Z | [
"python",
"perl",
"unix",
"count",
"awk"
] |
How can I count unique terms in a plaintext file case-insensitively? | 914,382 | <p>This can be in any high-level language that is likely to be available on a typical unix-like system (Python, Perl, awk, standard unix utils {sort, uniq}, etc). Hopefully it's fast enough to report the total number of unique terms for a 2MB text file.</p>
<p>I only need this for quick sanity-checking, so it doesn't need to be well-engineered.</p>
<p>Remember, case-insensitve.</p>
<p>Thank you guys very much.</p>
<p>Side note: If you use Python, please don't use version 3-only code. The system I'm running it on only has 2.4.4.</p>
| 2 | 2009-05-27T07:18:15Z | 930,185 | <p>A shorter version in Python:</p>
<pre><code>print len(set(w.lower() for w in open('filename.dat').read().split()))
</code></pre>
<p>Reads the entire file into memory, splits it into words using whitespace, converts each word to lower case, creates a (unique) set from the lowercase words, counts them and prints the output.</p>
<p>Also possible using a one liner:</p>
<pre><code>python -c "print len(set(w.lower() for w in open('filename.dat').read().split()))"
</code></pre>
| 3 | 2009-05-30T17:40:52Z | [
"python",
"perl",
"unix",
"count",
"awk"
] |
How to save indention format of file in Python | 914,626 | <p>I am saving all the words from a file like so:</p>
<pre><code> sentence = " "
fileName = sys.argv[1]
fileIn = open(sys.argv[1],"r")
for line in open(sys.argv[1]):
for word in line.split(" "):
sentence += word
</code></pre>
<p>Everything works okay when outputting it except the formatting.
I am moving source code, is there any way I can save the indention?</p>
| 1 | 2009-05-27T08:37:48Z | 914,651 | <p>Since you state, that you want to <em>move source code files</em>, why not just copy/move them?</p>
<pre><code>import shutil
shutil.move(src, dest)
</code></pre>
<p>If you read source file, </p>
<pre><code>fh = open("yourfilename", "r")
content = fh.read()
</code></pre>
<p>should load your file as it is (with indention), or not? </p>
| 3 | 2009-05-27T08:43:44Z | [
"python"
] |
How to save indention format of file in Python | 914,626 | <p>I am saving all the words from a file like so:</p>
<pre><code> sentence = " "
fileName = sys.argv[1]
fileIn = open(sys.argv[1],"r")
for line in open(sys.argv[1]):
for word in line.split(" "):
sentence += word
</code></pre>
<p>Everything works okay when outputting it except the formatting.
I am moving source code, is there any way I can save the indention?</p>
| 1 | 2009-05-27T08:37:48Z | 914,702 | <p>Split removes all spaces:</p>
<pre><code>>>> a=" a b c"
>>> a.split(" ")
['', '', '', 'a', 'b', '', '', 'c']
</code></pre>
<p>As you can see, the resulting array doesn't contain any spaces anymore. But you can see these strange empty strings (''). They denote that there has been a space. To revert the effect of split, use <code>join(" ")</code>:</p>
<pre><code>>>> l=a.split(" ")
>>> " ".join(l)
' a b c'
</code></pre>
<p>or in your code:</p>
<pre><code>sentence += " " + word
</code></pre>
<p>Or you can use a regular expression to get all spaces at the start of the line:</p>
<pre><code>>>> import re
>>> re.match(r'^\s*', " a b c").group(0)
' '
</code></pre>
| 1 | 2009-05-27T08:57:57Z | [
"python"
] |
How to save indention format of file in Python | 914,626 | <p>I am saving all the words from a file like so:</p>
<pre><code> sentence = " "
fileName = sys.argv[1]
fileIn = open(sys.argv[1],"r")
for line in open(sys.argv[1]):
for word in line.split(" "):
sentence += word
</code></pre>
<p>Everything works okay when outputting it except the formatting.
I am moving source code, is there any way I can save the indention?</p>
| 1 | 2009-05-27T08:37:48Z | 914,709 | <p>When you invoke <code>line.split()</code>, you remove all leading spaces.</p>
<p>What's wrong with just reading the file into a single string?</p>
<pre><code>textWithIndentation = open(sys.argv[1], "r").read()
</code></pre>
| 2 | 2009-05-27T08:59:02Z | [
"python"
] |
best practice for user preferences in $HOME in Python | 914,675 | <p>For some small programs in Python, I would like to set, store and retrieve user preferences in a file in a portable (multi-platform) way.</p>
<p>I am thinking about a very simple ConfigParser file like "~/.program" or "~/.program/program.cfg".</p>
<p>Is <code>os.path.expanduser()</code> the best way for achieving this or is there something more easy/straightforward?</p>
| 3 | 2009-05-27T08:49:25Z | 914,812 | <pre><code>os.path.expanduser("~")
</code></pre>
<p>is more portable than </p>
<pre><code>os.environ['HOME']
</code></pre>
<p>so it should be ok to use the first.</p>
| 8 | 2009-05-27T09:26:06Z | [
"python",
"preferences"
] |
best practice for user preferences in $HOME in Python | 914,675 | <p>For some small programs in Python, I would like to set, store and retrieve user preferences in a file in a portable (multi-platform) way.</p>
<p>I am thinking about a very simple ConfigParser file like "~/.program" or "~/.program/program.cfg".</p>
<p>Is <code>os.path.expanduser()</code> the best way for achieving this or is there something more easy/straightforward?</p>
| 3 | 2009-05-27T08:49:25Z | 914,818 | <p>You can use os.environ:</p>
<pre><code>import os
print os.environ["HOME"]
</code></pre>
| 0 | 2009-05-27T09:27:44Z | [
"python",
"preferences"
] |
Python: Looping through all but the last item of a list | 914,715 | <p>I would like to loop through a list checking each item against the one following it.</p>
<p>Is there a way I can loop through all but the last item using for x in y? I would prefer to do it without using indexes if I can.</p>
<p><strong>Note</strong></p>
<p>freespace answered my actual question, which is why I accepted the answer, but SilentGhost answered the question I should have asked.</p>
<p>Apologies for the confusion.</p>
| 61 | 2009-05-27T08:59:35Z | 914,733 | <pre><code>for x in y[:-1]
</code></pre>
<p>If <code>y</code> is a generator, then the above will not work.</p>
| 136 | 2009-05-27T09:04:36Z | [
"python"
] |
Python: Looping through all but the last item of a list | 914,715 | <p>I would like to loop through a list checking each item against the one following it.</p>
<p>Is there a way I can loop through all but the last item using for x in y? I would prefer to do it without using indexes if I can.</p>
<p><strong>Note</strong></p>
<p>freespace answered my actual question, which is why I accepted the answer, but SilentGhost answered the question I should have asked.</p>
<p>Apologies for the confusion.</p>
| 61 | 2009-05-27T08:59:35Z | 914,786 | <p>If you want to get all the elements in the sequence pair wise, use this approach (the pairwise function is from the examples in the itertools module).</p>
<pre><code>from itertools import tee, izip, chain
def pairwise(seq):
a,b = tee(seq)
b.next()
return izip(a,b)
for current_item, next_item in pairwise(y):
if compare(current_item, next_item):
# do what you have to do
</code></pre>
<p>If you need to compare the last value to some special value, chain that value to the end</p>
<pre><code>for current, next_item in pairwise(chain(y, [None])):
</code></pre>
| 15 | 2009-05-27T09:18:47Z | [
"python"
] |
Python: Looping through all but the last item of a list | 914,715 | <p>I would like to loop through a list checking each item against the one following it.</p>
<p>Is there a way I can loop through all but the last item using for x in y? I would prefer to do it without using indexes if I can.</p>
<p><strong>Note</strong></p>
<p>freespace answered my actual question, which is why I accepted the answer, but SilentGhost answered the question I should have asked.</p>
<p>Apologies for the confusion.</p>
| 61 | 2009-05-27T08:59:35Z | 914,813 | <p>if you meant comparing nth item with n+1 th item in the list you could also do with</p>
<pre><code>>>> for i in range(len(list[:-1])):
... print list[i]>list[i+1]
</code></pre>
<p>note there is no hard coding going on there. This should be ok unless you feel otherwise.</p>
| 3 | 2009-05-27T09:26:25Z | [
"python"
] |
Python: Looping through all but the last item of a list | 914,715 | <p>I would like to loop through a list checking each item against the one following it.</p>
<p>Is there a way I can loop through all but the last item using for x in y? I would prefer to do it without using indexes if I can.</p>
<p><strong>Note</strong></p>
<p>freespace answered my actual question, which is why I accepted the answer, but SilentGhost answered the question I should have asked.</p>
<p>Apologies for the confusion.</p>
| 61 | 2009-05-27T08:59:35Z | 914,815 | <p>the easiest way to compare the sequence item with the following:</p>
<pre><code>for i, j in zip(a, a[1:]):
# compare i (the current) to j (the following)
</code></pre>
| 32 | 2009-05-27T09:26:29Z | [
"python"
] |
Python: Looping through all but the last item of a list | 914,715 | <p>I would like to loop through a list checking each item against the one following it.</p>
<p>Is there a way I can loop through all but the last item using for x in y? I would prefer to do it without using indexes if I can.</p>
<p><strong>Note</strong></p>
<p>freespace answered my actual question, which is why I accepted the answer, but SilentGhost answered the question I should have asked.</p>
<p>Apologies for the confusion.</p>
| 61 | 2009-05-27T08:59:35Z | 914,944 | <p>To compare each item with the next one in an iterator without instantiating a list:</p>
<pre><code>import itertools
it = (x for x in range(10))
data1, data2 = itertools.tee(it)
data2.next()
for a, b in itertools.izip(data1, data2):
print a, b
</code></pre>
| 0 | 2009-05-27T10:07:46Z | [
"python"
] |
producer/consumer problem with python multiprocessing | 914,821 | <p>I am writing a server program with one producer and multiple consumers,
what confuses me is only the first task producer put into the queue gets
consumed, after which tasks enqueued no longer get consumed, they remain
in the queue forever.</p>
<pre><code>from multiprocessing import Process, Queue, cpu_count
from http import httpserv
import time
def work(queue):
while True:
task = queue.get()
if task is None:
break
time.sleep(5)
print "task done:", task
queue.put(None)
class Manager:
def __init__(self):
self.queue = Queue()
self.NUMBER_OF_PROCESSES = cpu_count()
def start(self):
self.workers = [Process(target=work, args=(self.queue,))
for i in xrange(self.NUMBER_OF_PROCESSES)]
for w in self.workers:
w.start()
httpserv(self.queue)
def stop(self):
self.queue.put(None)
for i in range(self.NUMBER_OF_PROCESSES):
self.workers[i].join()
queue.close()
Manager().start()
</code></pre>
<p>The producer is a HTTP server which put a task in the queue once receive
a request from the user. It seems that consumer processes are still
blocked when there are new tasks in the queue, which is weird.</p>
<p>P.S. Another two questions not relating to the above, I am not sure if
it's better to put HTTP server in its own process other than the main
process, if yes how can I make the main process keep running before all
children processes end. Second question, what's the best way to stop the
HTTP server gracefully?</p>
<p><strong>Edit</strong>: add producer code, it's just a simple python wsgi server:</p>
<pre><code>import fapws._evwsgi as evwsgi
from fapws import base
def httpserv(queue):
evwsgi.start("0.0.0.0", 8080)
evwsgi.set_base_module(base)
def request_1(environ, start_response):
start_response('200 OK', [('Content-Type','text/html')])
queue.put('task_1')
return ["request 1!"]
def request_2(environ, start_response):
start_response('200 OK', [('Content-Type','text/html')])
queue.put('task_2')
return ["request 2!!"]
evwsgi.wsgi_cb(("/request_1", request_1))
evwsgi.wsgi_cb(("/request_2", request_2))
evwsgi.run()
</code></pre>
| 10 | 2009-05-27T09:28:56Z | 915,616 | <p>I think there must be something wrong with the web server part, as this works perfectly:</p>
<pre><code>from multiprocessing import Process, Queue, cpu_count
import random
import time
def serve(queue):
works = ["task_1", "task_2"]
while True:
time.sleep(0.01)
queue.put(random.choice(works))
def work(id, queue):
while True:
task = queue.get()
if task is None:
break
time.sleep(0.05)
print "%d task:" % id, task
queue.put(None)
class Manager:
def __init__(self):
self.queue = Queue()
self.NUMBER_OF_PROCESSES = cpu_count()
def start(self):
print "starting %d workers" % self.NUMBER_OF_PROCESSES
self.workers = [Process(target=work, args=(i, self.queue,))
for i in xrange(self.NUMBER_OF_PROCESSES)]
for w in self.workers:
w.start()
serve(self.queue)
def stop(self):
self.queue.put(None)
for i in range(self.NUMBER_OF_PROCESS):
self.workers[i].join()
queue.close()
Manager().start()
</code></pre>
<p>Sample output:</p>
<pre><code>starting 2 workers
0 task: task_1
1 task: task_2
0 task: task_2
1 task: task_1
0 task: task_1
</code></pre>
| 3 | 2009-05-27T13:08:41Z | [
"python",
"multiprocessing"
] |
producer/consumer problem with python multiprocessing | 914,821 | <p>I am writing a server program with one producer and multiple consumers,
what confuses me is only the first task producer put into the queue gets
consumed, after which tasks enqueued no longer get consumed, they remain
in the queue forever.</p>
<pre><code>from multiprocessing import Process, Queue, cpu_count
from http import httpserv
import time
def work(queue):
while True:
task = queue.get()
if task is None:
break
time.sleep(5)
print "task done:", task
queue.put(None)
class Manager:
def __init__(self):
self.queue = Queue()
self.NUMBER_OF_PROCESSES = cpu_count()
def start(self):
self.workers = [Process(target=work, args=(self.queue,))
for i in xrange(self.NUMBER_OF_PROCESSES)]
for w in self.workers:
w.start()
httpserv(self.queue)
def stop(self):
self.queue.put(None)
for i in range(self.NUMBER_OF_PROCESSES):
self.workers[i].join()
queue.close()
Manager().start()
</code></pre>
<p>The producer is a HTTP server which put a task in the queue once receive
a request from the user. It seems that consumer processes are still
blocked when there are new tasks in the queue, which is weird.</p>
<p>P.S. Another two questions not relating to the above, I am not sure if
it's better to put HTTP server in its own process other than the main
process, if yes how can I make the main process keep running before all
children processes end. Second question, what's the best way to stop the
HTTP server gracefully?</p>
<p><strong>Edit</strong>: add producer code, it's just a simple python wsgi server:</p>
<pre><code>import fapws._evwsgi as evwsgi
from fapws import base
def httpserv(queue):
evwsgi.start("0.0.0.0", 8080)
evwsgi.set_base_module(base)
def request_1(environ, start_response):
start_response('200 OK', [('Content-Type','text/html')])
queue.put('task_1')
return ["request 1!"]
def request_2(environ, start_response):
start_response('200 OK', [('Content-Type','text/html')])
queue.put('task_2')
return ["request 2!!"]
evwsgi.wsgi_cb(("/request_1", request_1))
evwsgi.wsgi_cb(("/request_2", request_2))
evwsgi.run()
</code></pre>
| 10 | 2009-05-27T09:28:56Z | 915,958 | <p><strong>"Second question, what's the best way to stop the HTTP server gracefully?"</strong></p>
<p>This is hard.</p>
<p>You have two choices for Interprocess Communication:</p>
<ul>
<li><p>Out-of-band controls. The server has another mechanism for communication. Another socket, a Unix Signal, or something else. The something else could be a "stop-now" file in the server's local directory. Seems odd, but it does work well and is simpler than introducing a select loop to listen on multiple sockets or a signal handler to catch a Unis signal.</p>
<p>The "stop-now" file is easy to implement. The <code>evwsgi.run()</code> loop merely checks for this file after each request. To make the server stop, you create the file, execute a <code>/control</code> request (which will get a 500 error or something, it doesn't really matter) and the server should grind to a halt. Remember to delete the stop-now file, otherwise your server won't restart.</p></li>
<li><p>In-band controls. The server has another URL (<code>/stop</code>) which will stop it. Superficially, this seems like a security nightmare, but it depends entirely on where and how this server will be used. Since it appears to be a simple wrapper around an internal request queue, this extra URL works well.</p>
<p>To make this work, you need to write your own version of <code>evwsgi.run()</code> that can be terminated by setting some variable in a way that will break out of the loop.</p></li>
</ul>
<p><strong>Edit</strong></p>
<p>You probably don't want to terminate your server, since you don't know the state of it's worker threads. You need to signal the server and then you just have to wait until it finishes things normally.</p>
<p>If you want to forcibly kill the server, then <code>os.kill()</code> (or <code>multiprocessing.terminate</code>) will work. Except, of course, you don't know what the child threads were doing.</p>
| 3 | 2009-05-27T14:16:14Z | [
"python",
"multiprocessing"
] |
producer/consumer problem with python multiprocessing | 914,821 | <p>I am writing a server program with one producer and multiple consumers,
what confuses me is only the first task producer put into the queue gets
consumed, after which tasks enqueued no longer get consumed, they remain
in the queue forever.</p>
<pre><code>from multiprocessing import Process, Queue, cpu_count
from http import httpserv
import time
def work(queue):
while True:
task = queue.get()
if task is None:
break
time.sleep(5)
print "task done:", task
queue.put(None)
class Manager:
def __init__(self):
self.queue = Queue()
self.NUMBER_OF_PROCESSES = cpu_count()
def start(self):
self.workers = [Process(target=work, args=(self.queue,))
for i in xrange(self.NUMBER_OF_PROCESSES)]
for w in self.workers:
w.start()
httpserv(self.queue)
def stop(self):
self.queue.put(None)
for i in range(self.NUMBER_OF_PROCESSES):
self.workers[i].join()
queue.close()
Manager().start()
</code></pre>
<p>The producer is a HTTP server which put a task in the queue once receive
a request from the user. It seems that consumer processes are still
blocked when there are new tasks in the queue, which is weird.</p>
<p>P.S. Another two questions not relating to the above, I am not sure if
it's better to put HTTP server in its own process other than the main
process, if yes how can I make the main process keep running before all
children processes end. Second question, what's the best way to stop the
HTTP server gracefully?</p>
<p><strong>Edit</strong>: add producer code, it's just a simple python wsgi server:</p>
<pre><code>import fapws._evwsgi as evwsgi
from fapws import base
def httpserv(queue):
evwsgi.start("0.0.0.0", 8080)
evwsgi.set_base_module(base)
def request_1(environ, start_response):
start_response('200 OK', [('Content-Type','text/html')])
queue.put('task_1')
return ["request 1!"]
def request_2(environ, start_response):
start_response('200 OK', [('Content-Type','text/html')])
queue.put('task_2')
return ["request 2!!"]
evwsgi.wsgi_cb(("/request_1", request_1))
evwsgi.wsgi_cb(("/request_2", request_2))
evwsgi.run()
</code></pre>
| 10 | 2009-05-27T09:28:56Z | 5,132,614 | <p>This can help:
<a href="http://www.rsdcbabu.com/2011/02/multiprocessing-with-python.html" rel="nofollow">http://www.rsdcbabu.com/2011/02/multiprocessing-with-python.html</a></p>
| 1 | 2011-02-27T10:18:38Z | [
"python",
"multiprocessing"
] |
Regular Expression for Stripping Strings from Source Code | 914,913 | <p>I'm looking for a regular expression that will replace strings in an input source code with some constant string value such as "string", and that will also take into account escaping the string-start character that is denoted by a double string-start character (e.g. "he said ""hello"""). </p>
<p>To clarify, I will provide some examples of input and expected output:</p>
<pre><code>input: print("hello world, how are you?")
output: print("string")
input: print("hello" + "world")
output: print("string" + "string")
# here's the tricky part:
input: print("He told her ""how you doin?"", and she said ""I'm fine, thanks""")
output: print("string")
</code></pre>
<p>I'm working in Python, but I guess this is language agnostic. </p>
<p>EDIT: According to one of the answers, this requirement may not be fit for a regular expression. I'm not sure that's true but I'm not an expert. If I try to phrase my requirement with words, what I'm looking for is to find sets of characters that are between double quotes, wherein even groups of adjacent double quotes should be disregarded, and that sounds to me like it can be figured by a DFA.</p>
<p>Thanks.</p>
| 0 | 2009-05-27T09:57:29Z | 914,965 | <p>Maybe:</p>
<pre><code>re.sub(r"[^\"]\"[^\"].*[^\"]\"[^\"]",'"string"',input)
</code></pre>
<p>EDIT:</p>
<p>No that won't work for the final example.</p>
<p>I don't think your requirements are regular: they can't be matched by a regular expression. This is because at the heart of the matter, you need to match any odd number of <code>"</code> grouped together, as that is your delimiter.</p>
<p>I think you'll have to do it manually, counting <code>"</code>s.</p>
| 0 | 2009-05-27T10:13:18Z | [
"python",
"regex",
"string"
] |
Regular Expression for Stripping Strings from Source Code | 914,913 | <p>I'm looking for a regular expression that will replace strings in an input source code with some constant string value such as "string", and that will also take into account escaping the string-start character that is denoted by a double string-start character (e.g. "he said ""hello"""). </p>
<p>To clarify, I will provide some examples of input and expected output:</p>
<pre><code>input: print("hello world, how are you?")
output: print("string")
input: print("hello" + "world")
output: print("string" + "string")
# here's the tricky part:
input: print("He told her ""how you doin?"", and she said ""I'm fine, thanks""")
output: print("string")
</code></pre>
<p>I'm working in Python, but I guess this is language agnostic. </p>
<p>EDIT: According to one of the answers, this requirement may not be fit for a regular expression. I'm not sure that's true but I'm not an expert. If I try to phrase my requirement with words, what I'm looking for is to find sets of characters that are between double quotes, wherein even groups of adjacent double quotes should be disregarded, and that sounds to me like it can be figured by a DFA.</p>
<p>Thanks.</p>
| 0 | 2009-05-27T09:57:29Z | 916,022 | <p>There's a very good <a href="http://code.activestate.com/recipes/475109/" rel="nofollow">string-matching regular expression</a> over at ActiveState. If it doesn't work straight out for your last example it should be a fairly trivial repeat to group adjacent quoted strings together.</p>
| 0 | 2009-05-27T14:28:38Z | [
"python",
"regex",
"string"
] |
Regular Expression for Stripping Strings from Source Code | 914,913 | <p>I'm looking for a regular expression that will replace strings in an input source code with some constant string value such as "string", and that will also take into account escaping the string-start character that is denoted by a double string-start character (e.g. "he said ""hello"""). </p>
<p>To clarify, I will provide some examples of input and expected output:</p>
<pre><code>input: print("hello world, how are you?")
output: print("string")
input: print("hello" + "world")
output: print("string" + "string")
# here's the tricky part:
input: print("He told her ""how you doin?"", and she said ""I'm fine, thanks""")
output: print("string")
</code></pre>
<p>I'm working in Python, but I guess this is language agnostic. </p>
<p>EDIT: According to one of the answers, this requirement may not be fit for a regular expression. I'm not sure that's true but I'm not an expert. If I try to phrase my requirement with words, what I'm looking for is to find sets of characters that are between double quotes, wherein even groups of adjacent double quotes should be disregarded, and that sounds to me like it can be figured by a DFA.</p>
<p>Thanks.</p>
| 0 | 2009-05-27T09:57:29Z | 916,277 | <p>If you're parsing Python code, save yourself the hassle and let the standard library's <a href="http://docs.python.org/library/parser.html" rel="nofollow">parser module</a> do the heavy lifting.</p>
<p>If you're writing your own parser for some custom language, it's awfully tempting to start out by just hacking together a bunch of regexes, but don't do it. You'll dig yourself into an unmaintainable mess. Read up on parsing techniques and do it right (wikipedia <a href="http://en.wikipedia.org/wiki/LR%5Fparser" rel="nofollow">can</a> <a href="http://en.wikipedia.org/wiki/Recursive%5Fdescent%5Fparser" rel="nofollow">help</a>).</p>
<p>This regex does the trick for all three of your examples:</p>
<pre><code>re.sub(r'"(?:""|[^"])+"', '"string"', original)
</code></pre>
| 3 | 2009-05-27T15:04:10Z | [
"python",
"regex",
"string"
] |
Migrating from python 2.4 to python 2.6 | 915,135 | <p>I'm migrating a legacy codebase at work from python 2.4 to python 2.6. This is being done as part of a push to remove the 'legacy' tag and make a maintainable, extensible foundation for active development, so I'm getting a chance to "do things right", including refactoring to use new 2.6 features if that leads to cleaner, more robust code. (I'm already in raptures over the 'with' statement :)). Any good tips for the migration? Best practices, design patterns, etc? I'm mostly a ruby programmer; I've learnt some python 2.4 while working with this code but know nothing about modern python design principles, so feel free to suggest things that you might think are obvious.</p>
| 4 | 2009-05-27T11:03:02Z | 915,182 | <p>I guess you have already found them, but reference and for others, here are the lists of new features in those two versions:</p>
<ul>
<li><a href="http://docs.python.org/whatsnew/2.5.html" rel="nofollow">http://docs.python.org/whatsnew/2.5.html</a></li>
<li><a href="http://docs.python.org/whatsnew/2.6.html" rel="nofollow">http://docs.python.org/whatsnew/2.6.html</a></li>
</ul>
<p>Apart from picking features from those documents, I suggest using the opportunity (if needed) to make the code conform to the standard Python code style in <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP 8</a>.</p>
<p>There are some automated tools that can help you getting the Python style right: <a href="http://svn.browsershots.org/trunk/devtools/pep8/pep8.py" rel="nofollow">pep8.py</a> implements the PEP 8 checks and <a href="http://svn.browsershots.org/trunk/devtools/pep8/pep8.py" rel="nofollow">pylint</a> gives a larger report that also includes things like undefined variables, unused imports, etc. <a href="http://divmod.org/trac/wiki/DivmodPyflakes" rel="nofollow">pyflakes</a> is a smaller and faster pylint.</p>
| 2 | 2009-05-27T11:18:06Z | [
"python",
"design"
] |
Migrating from python 2.4 to python 2.6 | 915,135 | <p>I'm migrating a legacy codebase at work from python 2.4 to python 2.6. This is being done as part of a push to remove the 'legacy' tag and make a maintainable, extensible foundation for active development, so I'm getting a chance to "do things right", including refactoring to use new 2.6 features if that leads to cleaner, more robust code. (I'm already in raptures over the 'with' statement :)). Any good tips for the migration? Best practices, design patterns, etc? I'm mostly a ruby programmer; I've learnt some python 2.4 while working with this code but know nothing about modern python design principles, so feel free to suggest things that you might think are obvious.</p>
| 4 | 2009-05-27T11:03:02Z | 915,195 | <p>Read the Python 3.0 changes. The point of 2.6 is to aim for 3.0.</p>
<p>From 2.4 to 2.6 you gained a lot of things. These are the the most important. I'm making this answer community wiki so other folks can edit it.</p>
<ol>
<li><p>Generator functions and the yield statement.</p></li>
<li><p>More consistent use of various types like <code>list</code> and <code>dict</code> -- they can be extended directly.</p></li>
<li><p><code>from __future__ import with_statement</code></p></li>
<li><p><code>from __future__ import print_function</code></p></li>
<li><p>Exceptions are new style classes, and there's more consistent exception handling. String exceptions have been removed. Attempting to use them raises a TypeError</p></li>
</ol>
| 5 | 2009-05-27T11:22:46Z | [
"python",
"design"
] |
How to convert specific character sequences in a string to upper case using Python? | 915,391 | <p>I am looking to accomplish the following and am wondering if anyone has a suggestion as to how best go about it.</p>
<p>I have a string, say 'this-is,-toronto.-and-this-is,-boston', and I would like to convert all occurrences of ',-[a-z]' to ',-[A-Z]'. In this case the result of the conversion would be 'this-is,-Toronto.-and-this-is,-Boston'.</p>
<p>I've been trying to get something working with re.sub(), but as yet haven't figured out how how</p>
<pre><code>testString = 'this-is,-toronto.-and-this-is,-boston'
re.sub(r',_([a-z])', r',_??', testString)
</code></pre>
<p>Thanks!</p>
| 2 | 2009-05-27T12:16:37Z | 915,460 | <p>re.sub can take a function which returns the replacement string:</p>
<pre><code>import re
s = 'this-is,-toronto.-and-this-is,-boston'
t = re.sub(',-[a-z]', lambda x: x.group(0).upper(), s)
print t
</code></pre>
<p>prints</p>
<pre><code>this-is,-Toronto.-and-this-is,-Boston
</code></pre>
| 11 | 2009-05-27T12:29:50Z | [
"python"
] |
Please point me to (good) documentation about QT layouts for plasma development | 915,633 | <p>I am trying to develop a plasmoid in python. I got some good tutorials here (techbase.kde.org/Development/Tutorials/Plasma) and they are really helpful, but they don't have documentation or examples about QT layouts and their usage.</p>
<p>I haven't programmed with QT, but I know C++ well. So, the resources shouldn't be necessarily python apis. </p>
<p>To be specific, I want a layout with two rows, the first containing two columns and the second with 3 rows.</p>
<p>thanks & ragards.</p>
| 1 | 2009-05-27T13:14:10Z | 915,666 | <p>Perhaps a good place to start would be the <a href="http://doc.qtsoftware.com/4.5/qlayout.html#details" rel="nofollow">Qt documentation</a>?</p>
| 1 | 2009-05-27T13:23:55Z | [
"python",
"qt",
"kde4",
"plasma",
"plasmoid"
] |
Please point me to (good) documentation about QT layouts for plasma development | 915,633 | <p>I am trying to develop a plasmoid in python. I got some good tutorials here (techbase.kde.org/Development/Tutorials/Plasma) and they are really helpful, but they don't have documentation or examples about QT layouts and their usage.</p>
<p>I haven't programmed with QT, but I know C++ well. So, the resources shouldn't be necessarily python apis. </p>
<p>To be specific, I want a layout with two rows, the first containing two columns and the second with 3 rows.</p>
<p>thanks & ragards.</p>
| 1 | 2009-05-27T13:14:10Z | 916,001 | <p>Plasma works as a big QGraphicsView, and applets are QGraphicsWidget items, meaning it's the documentation for <a href="http://doc.qtsoftware.com/4.5/qgraphicslayout.html" rel="nofollow">QGraphicsLayout</a> that you should be looking at, not QLayout as suggested.</p>
<p>For a grid layout you want to use <a href="http://doc.qtsoftware.com/4.5/qgraphicsgridlayout.html" rel="nofollow">QGraphicsGridLayout</a>. Have a look at the <a href="http://doc.qtsoftware.com/4.5/qgraphicsgridlayout.html#addItem" rel="nofollow">addItem</a> method in particular.</p>
| 3 | 2009-05-27T14:25:24Z | [
"python",
"qt",
"kde4",
"plasma",
"plasmoid"
] |
Reporting charts and data for MS-Office users | 915,726 | <p>We have lots of data and some charts repesenting one logical item. Charts and data is stored in various files. As a result, most users can easily access and re-use the information in their applications.</p>
<p>However, this not exactly a good way of storing data. Amongst other reasons, charts belong to some data, the charts and data have some meta-information that is not reflected in the file system, there are a lot of files, etc.</p>
<p>Ideally, we want</p>
<ol>
<li><p>one big "file" that can store all
information (text, data and charts)</p></li>
<li><p>the "file" is human readable,
portable and accessible by
non-technical users</p></li>
<li><p>allows typical office applications
like MS Word or MS Excel to extract
text, data and charts easily.</p></li>
<li><p>light-weight, easy solution. Quick
and dirty is sufficient. Not many
users.</p></li>
</ol>
<p>I am happy to use some scripting language like Python to generate the "file", third-party tools (ideally free as in beer), and everything that you find on a typical Windows-centric office computer.</p>
<p>Some ideas that we currently ponder:</p>
<ul>
<li><p>using VB or pywin32 to script MS Word or Excel </p></li>
<li><p>creating html and publish it on a RESTful web server</p></li>
</ul>
<p>Could you expand on the ideas above? Do you have any other ideas? What should we consider?</p>
| 2 | 2009-05-27T13:34:06Z | 920,669 | <p>Instead of using one big file, You should use a database. Yes, You can store various types of files like gifs in the database if You like to.</p>
<p>The file would not be human readable or accessible by non-technical users, but this is good.</p>
<p>The database would have a website that Your non-technical users would use to insert, update and get data from. They would be able to display it on the page or export it to csv (or even xls - it's not that hard, I've seen some csv->xls converters). You could look into some open standard document formats, I think it should be quite easy to output data with in it. Do not try to output in "doc" format (but You could try "docx"). You should be able to easily teach the users how to export their data to a CSV and upload it to the site, or they could use the web interface to insert the data if they like to.</p>
<p>If You will allow Your users to mess with the raw data, they will break it (i have tried that, You have no idea how those guys could do that). The only way to prevent it is to make a web form that only allows them to perform certain actions that You exactly know how that they should suppose to perform.</p>
<p>The database + web page solution is the good one. Using VB or pywin32 to script MSOffice will get You in so much trouble I cannot even imagine.</p>
<p>You could use gnuplot or some other graphics library to draw (pretty straightforward to implement, it does all the hard work for You).</p>
<p>I am afraid that the "quick" and dirty solution is tempting, but I only can say one thing: it will not be quick. In a few weeks You will find that hacking around with MSOffice scripting is messy, buggy and unreliable and the non-technical guys will hate it and say that in other companies they used to have a simple web panel that did that. Then You will find that You will not be able to ask about the scripting because everyone uses the web interfaces nowadays, as they are quite easy to implement and maintain.</p>
<p>This is not a small project, it's a medium sized one, You need to remember this while writing it. It will take some time to do it and test it and You will have to add new features as the non-technical guys will start using it. I knew some passionate php teenagers who would be able to write this panel in a week, but as I understand You have some better resources so I hope You will come with a really reliable, modular, extensible solution with good usability and happy users.<br />
Good luck!</p>
| 1 | 2009-05-28T12:49:33Z | [
"python",
"web-services",
"scripting",
"reporting",
"ms-office"
] |
Reporting charts and data for MS-Office users | 915,726 | <p>We have lots of data and some charts repesenting one logical item. Charts and data is stored in various files. As a result, most users can easily access and re-use the information in their applications.</p>
<p>However, this not exactly a good way of storing data. Amongst other reasons, charts belong to some data, the charts and data have some meta-information that is not reflected in the file system, there are a lot of files, etc.</p>
<p>Ideally, we want</p>
<ol>
<li><p>one big "file" that can store all
information (text, data and charts)</p></li>
<li><p>the "file" is human readable,
portable and accessible by
non-technical users</p></li>
<li><p>allows typical office applications
like MS Word or MS Excel to extract
text, data and charts easily.</p></li>
<li><p>light-weight, easy solution. Quick
and dirty is sufficient. Not many
users.</p></li>
</ol>
<p>I am happy to use some scripting language like Python to generate the "file", third-party tools (ideally free as in beer), and everything that you find on a typical Windows-centric office computer.</p>
<p>Some ideas that we currently ponder:</p>
<ul>
<li><p>using VB or pywin32 to script MS Word or Excel </p></li>
<li><p>creating html and publish it on a RESTful web server</p></li>
</ul>
<p>Could you expand on the ideas above? Do you have any other ideas? What should we consider?</p>
| 2 | 2009-05-27T13:34:06Z | 921,061 | <p>I can only agree with Reef on the general concepts he presented:</p>
<ul>
<li><p>You will almost certainly prefer the data in a database than in a single large file</p></li>
<li><p>You should not worry that the data is not directly manipulated by users because as Reef mentioned, it can only go wrong. And you would be suprised at how ugly it can get</p></li>
</ul>
<p>Concerning the usage of MS Office integration tools I disagree with Reef. You can quite easily create an ActiveX Server (in Python if you like) that is accessible from the MS Office suite. As long as you have a solid infrastructure that allows some sort of file share, you could use that shared area to keep your code. I guess the mess Reef was talking about mostly is about keeping users' versions of your extract/import code in sync. If you do not use some sort of shared repository (a simple shared folder) or if your infrastructure fails you often so that the shared folder becomes unavailable you will be in great pain. Note what is also somewhat painful if you do not have the appropriate tools but deal with many users: The ActiveX Server is best registered on each machine.</p>
<p>So.. I just said MS Office integration is very doable. But whether it is the best thing to do is a different matter. I strongly believe you will serve your users better if you build a web-site that handles their data for them. This sort of tool however almost certainly becomes an "ongoing project". Often, even as an "ongoing project", the time saved by your users could still make it worth it. But sometimes, strategically, you want to give your users a poorer experience to control project costs. In that case the ActiveX Server I mentioned could be what you want.</p>
| 2 | 2009-05-28T14:15:05Z | [
"python",
"web-services",
"scripting",
"reporting",
"ms-office"
] |
django auth User truncating email field | 915,910 | <p>I have an issue with the django.contrib.auth User model where the email max_length is 75.</p>
<p>I am receiving email addresses that are longer than 75 characters from the facebook api, and I need to (would really like to) store them in the user for continuity among users that are from facebook connect and others.</p>
<p>I am able to solve the problem of "<code>Data truncated for column 'email' at row 1</code>" by manually going editing the field in our mySql database, but <strong>is there a better way to solve this?</strong> preferably one that <strong>does not involve me manually editing the database</strong> every time I reset it for a schema change?</p>
<p>I am ok with editing the database as long as I can add it to the reset script, or the initial_data.json file.</p>
| 9 | 2009-05-27T14:06:33Z | 916,176 | <p>EmailField 75 chars length is hardcoded in django. You can fix this like that:</p>
<pre><code>from django.db.models.fields import EmailField
def email_field_init(self, *args, **kwargs):
kwargs['max_length'] = kwargs.get('max_length', 200)
CharField.__init__(self, *args, **kwargs)
EmailField.__init__ = email_field_init
</code></pre>
<p>but this will change ALL EmailField fields lengths, so you could also try:</p>
<pre><code>from django.contrib.auth.models import User
from django.utils.translation import ugettext as _
from django.db import models
User.email = models.EmailField(_('e-mail address'), blank=True, max_length=200)
</code></pre>
<p>both ways it'd be best to put this code in init of any module BEFORE django.contrib.auth in your INSTALLED_APPS</p>
| 12 | 2009-05-27T14:49:41Z | [
"python",
"mysql",
"django",
"authentication"
] |
django auth User truncating email field | 915,910 | <p>I have an issue with the django.contrib.auth User model where the email max_length is 75.</p>
<p>I am receiving email addresses that are longer than 75 characters from the facebook api, and I need to (would really like to) store them in the user for continuity among users that are from facebook connect and others.</p>
<p>I am able to solve the problem of "<code>Data truncated for column 'email' at row 1</code>" by manually going editing the field in our mySql database, but <strong>is there a better way to solve this?</strong> preferably one that <strong>does not involve me manually editing the database</strong> every time I reset it for a schema change?</p>
<p>I am ok with editing the database as long as I can add it to the reset script, or the initial_data.json file.</p>
| 9 | 2009-05-27T14:06:33Z | 1,196,117 | <p>There is now a ticket to increase the length of the email field in Django: <a href="http://code.djangoproject.com/ticket/11579" rel="nofollow">http://code.djangoproject.com/ticket/11579</a></p>
| 2 | 2009-07-28T19:04:45Z | [
"python",
"mysql",
"django",
"authentication"
] |
How can I handle a mouseMiddleDrag event in PythonCard? | 916,435 | <p>I would like to use the middle mouse button to drag an image in an application written in Python and using PythonCard/wxPython for the GUI.</p>
<p>The latest version of PythonCard only implements a "left mouse button drag" event and I am trying to modify PythonCard to handle a "middle mouse button drag" as well.</p>
<p>Here is the relevant code from Lib\site-packages\PythonCard\event.py :</p>
<pre><code>class MouseMoveEvent(MouseEvent, InsteadOfTypeEvent):
name = 'mouseMove'
binding = wx.EVT_MOTION
id = wx.wxEVT_MOTION
def translateEventType(self, aWxEvent):
if aWxEvent.Dragging():
return MouseDragEvent.id
else:
return self.id
class MouseDragEvent(MouseMoveEvent):
name = 'mouseDrag'
id = wx.NewEventType()
class MouseMiddleDragEvent(MouseMoveEvent): #My addition
name = 'mouseMiddleDrag'
id = wx.NewEventType()
</code></pre>
<p>My addition does not work. What can I do instead? Is there a specific wxPython method that I could use to bypass PythonCard?</p>
| 1 | 2009-05-27T15:33:55Z | 917,752 | <p>It turns out the the <em>mouseDrag</em> event is active regardless of which button on the mouse is pressed. To filter the middle mouse button, you need to call the <em>MiddleIsDown()</em> method from the <em>MouseEvent</em>.</p>
<pre><code>def on_mouseDrag( self, event ):
do_stuff()
if event.MiddleIsDown():
do_other_stuff()
</code></pre>
| 1 | 2009-05-27T20:01:59Z | [
"python",
"user-interface",
"wxpython",
"mouse",
"pythoncard"
] |
Would it be possible to write a 3D game as large as World of Warcraft in pure Python? | 916,663 | <p>Would it be possible to write a 3D game as large as World of Warcraft in pure Python?
Assuming the use of DirectX / D3D bindings or OpenGL bindings.</p>
<p>If not, what would be the largest hold-up to doing such a project in Python? I know games tend to fall into the realm of C and C++ but sometimes people do things out of habit!</p>
<p>Any information would help satisfy my curiosity.</p>
<h3>Edit:</h3>
<p>Would the GIL post a major issue on 3d client performance? And what is the general performance penalty for using say, OpenGL or DirectX bindings vs natively using the libraries?</p>
| 10 | 2009-05-27T16:16:05Z | 916,686 | <p>Yes. How it will perform is another question.</p>
<p>A good development pattern would be to develop it in pure python, and then profile it, and rewrite performance-critical bottlenecks, either in C/C++/Cython or even python itself but with more efficient code.</p>
| 14 | 2009-05-27T16:19:57Z | [
"python",
"3d",
"direct3d"
] |
Would it be possible to write a 3D game as large as World of Warcraft in pure Python? | 916,663 | <p>Would it be possible to write a 3D game as large as World of Warcraft in pure Python?
Assuming the use of DirectX / D3D bindings or OpenGL bindings.</p>
<p>If not, what would be the largest hold-up to doing such a project in Python? I know games tend to fall into the realm of C and C++ but sometimes people do things out of habit!</p>
<p>Any information would help satisfy my curiosity.</p>
<h3>Edit:</h3>
<p>Would the GIL post a major issue on 3d client performance? And what is the general performance penalty for using say, OpenGL or DirectX bindings vs natively using the libraries?</p>
| 10 | 2009-05-27T16:16:05Z | 916,693 | <p>Because Python is interpreted there would be a performance hit, as opposed to C/C++, but, you would want to use something like PyOpenGL instead of DirectX though, to run on more operating systems.</p>
<p>But, I don't see why you couldn't write such a game in Python.</p>
| 0 | 2009-05-27T16:20:34Z | [
"python",
"3d",
"direct3d"
] |
Would it be possible to write a 3D game as large as World of Warcraft in pure Python? | 916,663 | <p>Would it be possible to write a 3D game as large as World of Warcraft in pure Python?
Assuming the use of DirectX / D3D bindings or OpenGL bindings.</p>
<p>If not, what would be the largest hold-up to doing such a project in Python? I know games tend to fall into the realm of C and C++ but sometimes people do things out of habit!</p>
<p>Any information would help satisfy my curiosity.</p>
<h3>Edit:</h3>
<p>Would the GIL post a major issue on 3d client performance? And what is the general performance penalty for using say, OpenGL or DirectX bindings vs natively using the libraries?</p>
| 10 | 2009-05-27T16:16:05Z | 916,701 | <p>Technically, anything is possible in any Turing Complete programming language.</p>
<p>Practically though, you will run into trouble making the networking stack out of a high level language, because the server will have to be VERY fast to handle so many players. </p>
<p>The gaming side of things on the client, there should be no problem, because there is nothing too complicated about GUIs or quests or keyboard input and what have you. </p>
<p>The problems will be in whatever is computationally intensive up on the server. Anything that happens in human-time like logging on will probably be just fine, but if somemthing needs to be instantaneous over ten thousand users, you might want to go for an external library done up in C. </p>
<p>Now some Python guru is going to come out of the woodwork and rip my head off because, as I said at the top, technically, anything can be done with enough effort.</p>
| 7 | 2009-05-27T16:21:14Z | [
"python",
"3d",
"direct3d"
] |
Would it be possible to write a 3D game as large as World of Warcraft in pure Python? | 916,663 | <p>Would it be possible to write a 3D game as large as World of Warcraft in pure Python?
Assuming the use of DirectX / D3D bindings or OpenGL bindings.</p>
<p>If not, what would be the largest hold-up to doing such a project in Python? I know games tend to fall into the realm of C and C++ but sometimes people do things out of habit!</p>
<p>Any information would help satisfy my curiosity.</p>
<h3>Edit:</h3>
<p>Would the GIL post a major issue on 3d client performance? And what is the general performance penalty for using say, OpenGL or DirectX bindings vs natively using the libraries?</p>
| 10 | 2009-05-27T16:16:05Z | 916,704 | <p>Yes, you could write it in assembly, or Java, or Python, or brainfuck. It's just how much time you are willing to put into it. Language performance's aren't a major issue anymore, it's more about which algorithms you use, not what language you use.</p>
| 5 | 2009-05-27T16:22:05Z | [
"python",
"3d",
"direct3d"
] |
Would it be possible to write a 3D game as large as World of Warcraft in pure Python? | 916,663 | <p>Would it be possible to write a 3D game as large as World of Warcraft in pure Python?
Assuming the use of DirectX / D3D bindings or OpenGL bindings.</p>
<p>If not, what would be the largest hold-up to doing such a project in Python? I know games tend to fall into the realm of C and C++ but sometimes people do things out of habit!</p>
<p>Any information would help satisfy my curiosity.</p>
<h3>Edit:</h3>
<p>Would the GIL post a major issue on 3d client performance? And what is the general performance penalty for using say, OpenGL or DirectX bindings vs natively using the libraries?</p>
| 10 | 2009-05-27T16:16:05Z | 916,740 | <p>While I don't know all the technical details of World of Warcraft, I would say that an MMO of its size could be built in <a href="http://en.wikipedia.org/wiki/Stackless%5FPython">Stackless Python</a>.</p>
<p>EVE Online uses it and they have one server for 200,000 users.</p>
| 14 | 2009-05-27T16:30:00Z | [
"python",
"3d",
"direct3d"
] |
Would it be possible to write a 3D game as large as World of Warcraft in pure Python? | 916,663 | <p>Would it be possible to write a 3D game as large as World of Warcraft in pure Python?
Assuming the use of DirectX / D3D bindings or OpenGL bindings.</p>
<p>If not, what would be the largest hold-up to doing such a project in Python? I know games tend to fall into the realm of C and C++ but sometimes people do things out of habit!</p>
<p>Any information would help satisfy my curiosity.</p>
<h3>Edit:</h3>
<p>Would the GIL post a major issue on 3d client performance? And what is the general performance penalty for using say, OpenGL or DirectX bindings vs natively using the libraries?</p>
| 10 | 2009-05-27T16:16:05Z | 916,753 | <p>The game <a href="http://minionsofmirth.com/">Minions of Mirth</a> is a full MMO more or less on the scale of WoW, and was done <a href="http://www.garagegames.com/community/forums/viewthread/37703">mostly in Python</a>. The client side used the Torque Game Engine, which is written in C++, but the server code and behaviours were all Python.</p>
| 7 | 2009-05-27T16:32:33Z | [
"python",
"3d",
"direct3d"
] |
Would it be possible to write a 3D game as large as World of Warcraft in pure Python? | 916,663 | <p>Would it be possible to write a 3D game as large as World of Warcraft in pure Python?
Assuming the use of DirectX / D3D bindings or OpenGL bindings.</p>
<p>If not, what would be the largest hold-up to doing such a project in Python? I know games tend to fall into the realm of C and C++ but sometimes people do things out of habit!</p>
<p>Any information would help satisfy my curiosity.</p>
<h3>Edit:</h3>
<p>Would the GIL post a major issue on 3d client performance? And what is the general performance penalty for using say, OpenGL or DirectX bindings vs natively using the libraries?</p>
| 10 | 2009-05-27T16:16:05Z | 916,775 | <p>Since your main question has already been answered well, I'll answer your latter questions:</p>
<blockquote>
<p>Would the GIL post a major issue on 3d client performance?</p>
</blockquote>
<p>In Python 2.6, the <a href="http://docs.python.org/library/multiprocessing.html">multiprocessing</a> library was introduced, so you can take advantage of multiple processor cores without worrying about the GIL. <a href="http://www.stackless.com/">Stackless Python</a> also has some pretty cool related stuff.</p>
<blockquote>
<p>And what is the general performance penalty for using say, OpenGL or DirectX bindings vs natively using the libraries?</p>
</blockquote>
<p>I don't have any benchmarks to back it up, but the penalty for using the bindings vs. the native libraries is small enough that you don't need to worry about it.</p>
| 5 | 2009-05-27T16:38:35Z | [
"python",
"3d",
"direct3d"
] |
Would it be possible to write a 3D game as large as World of Warcraft in pure Python? | 916,663 | <p>Would it be possible to write a 3D game as large as World of Warcraft in pure Python?
Assuming the use of DirectX / D3D bindings or OpenGL bindings.</p>
<p>If not, what would be the largest hold-up to doing such a project in Python? I know games tend to fall into the realm of C and C++ but sometimes people do things out of habit!</p>
<p>Any information would help satisfy my curiosity.</p>
<h3>Edit:</h3>
<p>Would the GIL post a major issue on 3d client performance? And what is the general performance penalty for using say, OpenGL or DirectX bindings vs natively using the libraries?</p>
| 10 | 2009-05-27T16:16:05Z | 930,968 | <p>Just because it might give an interesting read, Civilization is partly written using Python.
A google on it returns interesting reading material.</p>
| 2 | 2009-05-31T00:46:38Z | [
"python",
"3d",
"direct3d"
] |
Would it be possible to write a 3D game as large as World of Warcraft in pure Python? | 916,663 | <p>Would it be possible to write a 3D game as large as World of Warcraft in pure Python?
Assuming the use of DirectX / D3D bindings or OpenGL bindings.</p>
<p>If not, what would be the largest hold-up to doing such a project in Python? I know games tend to fall into the realm of C and C++ but sometimes people do things out of habit!</p>
<p>Any information would help satisfy my curiosity.</p>
<h3>Edit:</h3>
<p>Would the GIL post a major issue on 3d client performance? And what is the general performance penalty for using say, OpenGL or DirectX bindings vs natively using the libraries?</p>
| 10 | 2009-05-27T16:16:05Z | 1,004,597 | <p>There are some additional real industry examples in addition to Eve Online. The server backend on the Ultima Online 2 project at Origin in the late 90's was mostly Python over a C++ server infrastructure, and the late Tablua Rasa game from NCSoft (with most of the same dev team) had the same architecture.</p>
<p>The <a href="http://twistedmatrix.com">Twisted Matrix</a> python server framework was created originally with this exact goals - actually from a developer on the UO2 project at the time, and there was a company called Ninjaneering that attempted to commercialize that code-base through MMO projects.</p>
<p>There has been a move towards lua as a scripting engine (eg EQ2) as is easier to embed and instance.</p>
<p>The problems with python in this environment tend to be in the interface between languages. When you do the inevitable optimization of moving some high performance system from python to C/C++, then pushing data back and forth across language boundaries and calling functions across language boundaries becomes an issue. The cost of serialization can be high if done poorly. For example, using early versions of SWIG would serialize pointers into their string representation and then parse the string back into a pointer on the other side!!</p>
<p>Check out <a href="http://www.asbahr.com/paper1html/paper1.html">this</a> paper from the mid-90's:</p>
<p>But, in the long term, i think it is possible.</p>
| 5 | 2009-06-17T00:51:39Z | [
"python",
"3d",
"direct3d"
] |
Would it be possible to write a 3D game as large as World of Warcraft in pure Python? | 916,663 | <p>Would it be possible to write a 3D game as large as World of Warcraft in pure Python?
Assuming the use of DirectX / D3D bindings or OpenGL bindings.</p>
<p>If not, what would be the largest hold-up to doing such a project in Python? I know games tend to fall into the realm of C and C++ but sometimes people do things out of habit!</p>
<p>Any information would help satisfy my curiosity.</p>
<h3>Edit:</h3>
<p>Would the GIL post a major issue on 3d client performance? And what is the general performance penalty for using say, OpenGL or DirectX bindings vs natively using the libraries?</p>
| 10 | 2009-05-27T16:16:05Z | 1,316,198 | <p>Python is not interpreted - it is tokenized/'just in time' bytecode 'interpreted' and it doesn't have a VM like Java does. This means, in english, it can be daaaaaamnfast. Not all the time though, it depends on the problem and the libraries, but python is <em>not</em> slow, this is a common misconception even among knowledgable people (and that includes deep java engine folks who have just not gone and tried python).</p>
| 0 | 2009-08-22T15:29:28Z | [
"python",
"3d",
"direct3d"
] |
Would it be possible to write a 3D game as large as World of Warcraft in pure Python? | 916,663 | <p>Would it be possible to write a 3D game as large as World of Warcraft in pure Python?
Assuming the use of DirectX / D3D bindings or OpenGL bindings.</p>
<p>If not, what would be the largest hold-up to doing such a project in Python? I know games tend to fall into the realm of C and C++ but sometimes people do things out of habit!</p>
<p>Any information would help satisfy my curiosity.</p>
<h3>Edit:</h3>
<p>Would the GIL post a major issue on 3d client performance? And what is the general performance penalty for using say, OpenGL or DirectX bindings vs natively using the libraries?</p>
| 10 | 2009-05-27T16:16:05Z | 1,360,670 | <p>The answer to what I think your specific question is, "... in pure Python ..." the answer is NO.</p>
<p>Python is not fast enough to call OpenGL or DirectX efficently enough to re-create World Of Warcraft at an exceptable frame rate.</p>
<p>Like many others have answered, given some high level frame work, it would be possible to use Python has the scripting language but at a minimum you'd need some kind of graphics system written in another language like C++ to handle the graphics. For networking, given that WoW is not an action game, you might be able to get away with pure python but most likely that part as well would need to be some non-python library.</p>
| 5 | 2009-09-01T05:27:02Z | [
"python",
"3d",
"direct3d"
] |
Would it be possible to write a 3D game as large as World of Warcraft in pure Python? | 916,663 | <p>Would it be possible to write a 3D game as large as World of Warcraft in pure Python?
Assuming the use of DirectX / D3D bindings or OpenGL bindings.</p>
<p>If not, what would be the largest hold-up to doing such a project in Python? I know games tend to fall into the realm of C and C++ but sometimes people do things out of habit!</p>
<p>Any information would help satisfy my curiosity.</p>
<h3>Edit:</h3>
<p>Would the GIL post a major issue on 3d client performance? And what is the general performance penalty for using say, OpenGL or DirectX bindings vs natively using the libraries?</p>
| 10 | 2009-05-27T16:16:05Z | 1,656,654 | <p>I have been trying my hand at writing 3D games in Python, and given a good rendering framework (my favourite is OGRE) and decent bindings, it is amazing what you can get away with. However, especially with games, you are always trying to squeeze as much as you can out of the hardware. The performance disadvantage of python eventually will make itself felt.</p>
<p>The main problem I ran into using python is its massive call overhead. Calling python functions, even from other python functions is very expensive. In a way, it's the price you pay for the dynamic nature of python. When you use the function call operator "()" on a symbol, it has to work out whether it's a function or a class, look over the method resolution order, handle the keyword arguments, etc etc. All these things are done ahead of time in less dynamic (compiled) languages.</p>
<p>I have seen people trying to overcome this problem by manually inlining function calls. I do not have to tell you that this medicine is worse than the ailment.</p>
| 4 | 2009-11-01T08:22:16Z | [
"python",
"3d",
"direct3d"
] |
Would it be possible to write a 3D game as large as World of Warcraft in pure Python? | 916,663 | <p>Would it be possible to write a 3D game as large as World of Warcraft in pure Python?
Assuming the use of DirectX / D3D bindings or OpenGL bindings.</p>
<p>If not, what would be the largest hold-up to doing such a project in Python? I know games tend to fall into the realm of C and C++ but sometimes people do things out of habit!</p>
<p>Any information would help satisfy my curiosity.</p>
<h3>Edit:</h3>
<p>Would the GIL post a major issue on 3d client performance? And what is the general performance penalty for using say, OpenGL or DirectX bindings vs natively using the libraries?</p>
| 10 | 2009-05-27T16:16:05Z | 1,656,715 | <p>As a technologist I know:</p>
<p>If it can be written in C\C++ it can be written in assembly (though it will take longer).
If it can be written in C\C++ and is not a low-level code - it can be written in any managed environment.
WoW is a high-level program that is written in C\C++
python is a managed environment</p>
<p>There for:
WoW can be written in python and so any other MMORPG in 3D...</p>
<hr>
<p>The hardest part will be the 3d engine for it is the "heaviest" part of code - you will need to use an outside engine (written in C\C++\Assebly) or to write one and optimize it (not recommended)</p>
| 2 | 2009-11-01T09:16:19Z | [
"python",
"3d",
"direct3d"
] |
How to debug PYGTK program | 916,674 | <p>When python raise an exception in the middle of a pygtk signal handling callback, the exception is catched by the gtk main loop, its value printed and the main loop just continue, ignoring it.</p>
<p>If you want to debug, with something like pdb (python -m pdb myscript.py), you want that when the exception occure PDB jump on it and you can start debuging. Because of that it's not possible.</p>
<p>How can i debug pygtk program then ?</p>
| 5 | 2009-05-27T16:17:48Z | 916,702 | <p>You can't make pdb jump to the exception, since the exception is caught and silenced by gtk's main loop.</p>
<p>One of the alternatives is using <code>pdb.set_trace()</code>:</p>
<pre><code>import pdb
pdb.set_trace()
</code></pre>
<p>See <a href="http://docs.python.org/library/pdb.html" rel="nofollow">pdb documentation</a>.</p>
<p>Alternatively you can just use <a href="http://winpdb.org/" rel="nofollow">Winpdb</a>:</p>
<p>It is a <strong>platform independent</strong> graphical GPL Python debugger with support for remote debugging over a network, multiple threads, namespace modification, embedded debugging, encrypted communication and is up to 20 times faster than pdb.</p>
<p>Features:</p>
<ul>
<li>GPL license. Winpdb is Free Software.</li>
<li>Compatible with CPython 2.3 through 2.6 and Python 3000</li>
<li>Compatible with wxPython 2.6 through 2.8</li>
<li>Platform independent, and tested on Ubuntu Gutsy and Windows XP.</li>
<li>User Interfaces: rpdb2 is console based, while winpdb requires wxPython 2.6 or later.</li>
</ul>
<p><img src="http://winpdb.org/images/screenshot%5Fwinpdb%5Fsmall.jpg" alt="Screenshot" /></p>
| 4 | 2009-05-27T16:21:23Z | [
"python",
"debugging",
"gtk",
"pygtk"
] |
Set up svnperms pre-commit hook | 916,758 | <p>I'm trying to implement svnperms into a repository, but am having difficulty with a few things:</p>
<p>pre-commit has the execute permissions:</p>
<pre><code>-rwxrwxr-x 1 svnadm svn 3018 May 27 10:11 pre-commit
</code></pre>
<p>This is my call to svnperms within pre-commit:</p>
<pre><code># Check that the author of this commit has the rights to perform
# the commit on the files and directories being modified.
SVNPERMS=/usr/local/svn/scripts/svnperms.py
$SVNPERMS -r $REPOS -t $TXN || exit 1
</code></pre>
<p>I've got svnperms.py installed in the location specified:</p>
<pre><code># ls -l /usr/local/svn/scripts
total 24
-rwxrwxr-x 1 svnadm svn 11840 May 25 07:48 svnperms.py
</code></pre>
<p>svnperms.py is in UNIX format - no ^M line endings.</p>
<p>TortoiseSVN comes back with:</p>
<pre><code>Command: Commit
Modified: C:\projects\Sandbox\Trunk\Test.txt
Sending content: C:\projects\Sandbox\Trunk\Test.txt
Error: Commit failed (details follow):
Error: 'pre-commit' hook failed with error output:
Error: No such file or directory: python
</code></pre>
<p>Calling svnperms with no paramters shows:</p>
<pre><code>/usr/local/svn/scripts/svnperms.py
missing required option(s): repository, either transaction or a revision
Usage: svnperms.py OPTIONS
Options:
-r PATH Use repository at PATH to check transactions
-t TXN Query transaction TXN for commit information
-f PATH Use PATH as configuration file (default is repository
path + /conf/svnperms.conf)
-s NAME Use section NAME as permission section (default is
repository name, extracted from repository path)
-R REV Query revision REV for commit information (for tests)
-A AUTHOR Check commit as if AUTHOR had commited it (for tests)
-h Show this message
</code></pre>
<p>The UNIX admin has recently installed python, but wasn't sure if all the dependencies are there. If that's the issue, I'm not sure how to determine that, since python seems to be working based on the output above.</p>
<p>What am I missing?</p>
| 0 | 2009-05-27T16:34:15Z | 917,021 | <p>My guess is that the location of the <code>python</code> binary is not in <code>$PATH</code> for the svn server. The shabang line of <code>svnperms.py</code> reads:</p>
<pre><code>#!/usr/bin/env python
</code></pre>
<p>But that assumes that the executable lies in the <code>$PATH</code> of the caller. If you don't have permissions to modify the runtime environment of your subversion server, try replacing <code>python</code> in the shabang line with the path given by <code>which python</code> when you run it interactively.</p>
| 6 | 2009-05-27T17:28:47Z | [
"python",
"svn",
"unix",
"pre-commit"
] |
Is something like ConfigParser appropriate for saving state (key, value) between runs? | 916,779 | <p>I want to save a set of key, value pairs (string, int) between runs of a Python program, reload them on subsequent runs and write the changes to be available on the next run.</p>
<p>I don't think of this data as a configuration file, but it would fit the ConfigParser capabilities quite well. I would only need two [sections]. It's only a few hundred pairs and very simple so I don't think it's necessary to do an actual database.</p>
<p>Is it appropriate to use ConfigParser in this way? I've also considered using Perl and XML::Simple. What about that? Is there a way to do this in bash without Python or Perl?</p>
| 1 | 2009-05-27T16:39:41Z | 916,833 | <p>Well, you have better options. You can for example use <a href="http://docs.python.org/library/pickle.html" rel="nofollow">pickle</a> or <a href="http://docs.python.org/library/json.html" rel="nofollow">json</a> format.
Pickle serializing module is very easy to use.</p>
<pre><code>import cPickle
cPickle.dump(obj, open('save.p', 'wb'))
obj = cPickle.load(open('save.p', 'rb'))
</code></pre>
<p>The format is not human readable and unpickling is not secure against erroneous or maliciously constructed data. You should not unpickle untrusted data.</p>
<p>If you are using python 2.6 there is a builtin module called <a href="http://docs.python.org/library/json.html" rel="nofollow">json</a>. It is as easy as pickle to use:</p>
<pre><code>import json
encoded = json.dumps(obj)
obj = json.loads(encoded)
</code></pre>
<p>Json format is human readable and is very similar to the dictionary string representation in python. And doesn't have any security issues like pickle.</p>
<p>If you are using an earlier version of python you can <a href="http://code.google.com/p/simplejson/" rel="nofollow">simplejson</a> instead.</p>
| 15 | 2009-05-27T16:49:26Z | [
"python",
"xml",
"perl",
"configparser"
] |
Is something like ConfigParser appropriate for saving state (key, value) between runs? | 916,779 | <p>I want to save a set of key, value pairs (string, int) between runs of a Python program, reload them on subsequent runs and write the changes to be available on the next run.</p>
<p>I don't think of this data as a configuration file, but it would fit the ConfigParser capabilities quite well. I would only need two [sections]. It's only a few hundred pairs and very simple so I don't think it's necessary to do an actual database.</p>
<p>Is it appropriate to use ConfigParser in this way? I've also considered using Perl and XML::Simple. What about that? Is there a way to do this in bash without Python or Perl?</p>
| 1 | 2009-05-27T16:39:41Z | 916,869 | <p>For me, <a href="http://pyyaml.org/wiki/PyYAML" rel="nofollow">PyYAML</a> works well for these kind of things. I used to use pickle or ConfigParser before.</p>
| 8 | 2009-05-27T16:55:39Z | [
"python",
"xml",
"perl",
"configparser"
] |
Is something like ConfigParser appropriate for saving state (key, value) between runs? | 916,779 | <p>I want to save a set of key, value pairs (string, int) between runs of a Python program, reload them on subsequent runs and write the changes to be available on the next run.</p>
<p>I don't think of this data as a configuration file, but it would fit the ConfigParser capabilities quite well. I would only need two [sections]. It's only a few hundred pairs and very simple so I don't think it's necessary to do an actual database.</p>
<p>Is it appropriate to use ConfigParser in this way? I've also considered using Perl and XML::Simple. What about that? Is there a way to do this in bash without Python or Perl?</p>
| 1 | 2009-05-27T16:39:41Z | 916,912 | <p>Re doing it in bash: If your strings are valid identifiers, you could use environment variables and <code>env</code>.</p>
| 0 | 2009-05-27T17:02:14Z | [
"python",
"xml",
"perl",
"configparser"
] |
Is something like ConfigParser appropriate for saving state (key, value) between runs? | 916,779 | <p>I want to save a set of key, value pairs (string, int) between runs of a Python program, reload them on subsequent runs and write the changes to be available on the next run.</p>
<p>I don't think of this data as a configuration file, but it would fit the ConfigParser capabilities quite well. I would only need two [sections]. It's only a few hundred pairs and very simple so I don't think it's necessary to do an actual database.</p>
<p>Is it appropriate to use ConfigParser in this way? I've also considered using Perl and XML::Simple. What about that? Is there a way to do this in bash without Python or Perl?</p>
| 1 | 2009-05-27T16:39:41Z | 916,939 | <p>ConfigParser is a fine way of doing it. There are other ways (the json and cPickle modules already mentioned may be useful) that are also good, depending on whether you want to have text files or binary files and if you want code to work simply in older versions of Python or not.</p>
<p>You may want to have a thin abstraction layer on top of your chosen way to make it easier to change your mind.</p>
| 2 | 2009-05-27T17:06:22Z | [
"python",
"xml",
"perl",
"configparser"
] |
Is something like ConfigParser appropriate for saving state (key, value) between runs? | 916,779 | <p>I want to save a set of key, value pairs (string, int) between runs of a Python program, reload them on subsequent runs and write the changes to be available on the next run.</p>
<p>I don't think of this data as a configuration file, but it would fit the ConfigParser capabilities quite well. I would only need two [sections]. It's only a few hundred pairs and very simple so I don't think it's necessary to do an actual database.</p>
<p>Is it appropriate to use ConfigParser in this way? I've also considered using Perl and XML::Simple. What about that? Is there a way to do this in bash without Python or Perl?</p>
| 1 | 2009-05-27T16:39:41Z | 917,375 | <p>Sounds like a job for a <a href="http://en.wikipedia.org/wiki/Dbm" rel="nofollow">dbm</a>. Basically it is a hash that lives external to your program. There are many implementations. In Perl it is trivial to <a href="http://perldoc.perl.org/AnyDBM%5FFile.html" rel="nofollow">tie a dbm to a hash</a> (i.e. make it look like a dbm is really a normal hash variable). I don't know if there is any equivalent in mechanism in Python, but I would be surprised if there weren't.</p>
| 2 | 2009-05-27T18:46:12Z | [
"python",
"xml",
"perl",
"configparser"
] |
Is something like ConfigParser appropriate for saving state (key, value) between runs? | 916,779 | <p>I want to save a set of key, value pairs (string, int) between runs of a Python program, reload them on subsequent runs and write the changes to be available on the next run.</p>
<p>I don't think of this data as a configuration file, but it would fit the ConfigParser capabilities quite well. I would only need two [sections]. It's only a few hundred pairs and very simple so I don't think it's necessary to do an actual database.</p>
<p>Is it appropriate to use ConfigParser in this way? I've also considered using Perl and XML::Simple. What about that? Is there a way to do this in bash without Python or Perl?</p>
| 1 | 2009-05-27T16:39:41Z | 919,084 | <p>If you can update the state key by key then any of the DBM databases will work. If you need really high performance and compact storage then Tokyo Cabinet - <a href="http://tokyocabinet.sourceforge.net/" rel="nofollow">http://tokyocabinet.sourceforge.net/</a> is the cool toy.</p>
<p>If you want to save and load the whole thing at once (to maybe keep old versions or some such) and don't have too much data then just use JSON. It's much nicer to work with than XML. I don't know how the JSON implementation is in Python, but in Perl the JSON::XS module is insanely fast.</p>
| 0 | 2009-05-28T03:45:52Z | [
"python",
"xml",
"perl",
"configparser"
] |
Is there a list of Python packages that are not 64 bit compatible somewhere? | 916,952 | <p>I am going to move to a 64 bit machine and a 64 bit OS (Windows) and am trying to figure out if any of the extensions/packages I am using are going to be lost when I make the move. I can't seem to find whether someone has built a list of known issues as flagged on the Python 2.5 <a href="http://www.python.org/download/releases/2.5/" rel="nofollow">release page</a>. I have been using 2.5 but will at this time move to 2.6. I see that the potential conflicts will arise because of the module relying on a C extension module that would not be compatible in a 64 bit environment. But I don't know how to anticipate them. I want to move to a 64 bit system to because my IT guys told me that is the only way to make a meaningful move up the memory ladder. </p>
| 3 | 2009-05-27T17:07:22Z | 916,964 | <p>Perhaps you should figure out what "make a meaningful move up the memory ladder" means. Do you currently need to address more than 4GB of RAM? If not then you don't need a 64-bit system.</p>
| 3 | 2009-05-27T17:09:48Z | [
"python",
"64bit",
"packages"
] |
Is there a list of Python packages that are not 64 bit compatible somewhere? | 916,952 | <p>I am going to move to a 64 bit machine and a 64 bit OS (Windows) and am trying to figure out if any of the extensions/packages I am using are going to be lost when I make the move. I can't seem to find whether someone has built a list of known issues as flagged on the Python 2.5 <a href="http://www.python.org/download/releases/2.5/" rel="nofollow">release page</a>. I have been using 2.5 but will at this time move to 2.6. I see that the potential conflicts will arise because of the module relying on a C extension module that would not be compatible in a 64 bit environment. But I don't know how to anticipate them. I want to move to a 64 bit system to because my IT guys told me that is the only way to make a meaningful move up the memory ladder. </p>
| 3 | 2009-05-27T17:07:22Z | 916,983 | <p>We're running 2.5 on a 64-bit Red Hat Enterprise Linux server.</p>
<p>Everything appears to be working.</p>
<p>I would suggest you do what we did. </p>
<ol>
<li><p>Get a VM.</p></li>
<li><p>Load up the app.</p></li>
<li><p>Test it.</p></li>
</ol>
<p>It was easier than trying to do research.</p>
| 4 | 2009-05-27T17:15:06Z | [
"python",
"64bit",
"packages"
] |
Is there a list of Python packages that are not 64 bit compatible somewhere? | 916,952 | <p>I am going to move to a 64 bit machine and a 64 bit OS (Windows) and am trying to figure out if any of the extensions/packages I am using are going to be lost when I make the move. I can't seem to find whether someone has built a list of known issues as flagged on the Python 2.5 <a href="http://www.python.org/download/releases/2.5/" rel="nofollow">release page</a>. I have been using 2.5 but will at this time move to 2.6. I see that the potential conflicts will arise because of the module relying on a C extension module that would not be compatible in a 64 bit environment. But I don't know how to anticipate them. I want to move to a 64 bit system to because my IT guys told me that is the only way to make a meaningful move up the memory ladder. </p>
| 3 | 2009-05-27T17:07:22Z | 917,007 | <p>It really depends on the specific modules you are using. I am running several 64-bit Linux systems and I have yet to come across problems with any of the C modules that I use.</p>
<p>Most C modules can be built from source, so you should read about the Python distribution utility <a href="http://docs.python.org/install/index.html#install-index" rel="nofollow">distutils</a> to see how you can build these modules if you cannot find 64-bit binaries. </p>
<p>Whether a specific module will work in a 64-bit environment depends on how the code was written. Many modules work correctly when compiled for 64-bits, however there is a chance that it won't. Many popular modules such those from <a href="http://www.scipy.org/" rel="nofollow">SciPy</a> work just fine.</p>
<p>In short you will either need to just try the module on a 64-bit system or you will have to find the developer/project page and determine if there is a 64-bit build or if there are known bugs. </p>
| 1 | 2009-05-27T17:23:28Z | [
"python",
"64bit",
"packages"
] |
Is there a list of Python packages that are not 64 bit compatible somewhere? | 916,952 | <p>I am going to move to a 64 bit machine and a 64 bit OS (Windows) and am trying to figure out if any of the extensions/packages I am using are going to be lost when I make the move. I can't seem to find whether someone has built a list of known issues as flagged on the Python 2.5 <a href="http://www.python.org/download/releases/2.5/" rel="nofollow">release page</a>. I have been using 2.5 but will at this time move to 2.6. I see that the potential conflicts will arise because of the module relying on a C extension module that would not be compatible in a 64 bit environment. But I don't know how to anticipate them. I want to move to a 64 bit system to because my IT guys told me that is the only way to make a meaningful move up the memory ladder. </p>
| 3 | 2009-05-27T17:07:22Z | 917,067 | <p>It seems like you already know this, but it's worth pointing out for the sake of completeness. With that said, remember that you shouldn't have any problems with pure Python packages. </p>
<p>Secondly, you also don't necessarily <em>have to</em> install the 64-bit version of Python unless you're planning on running a program that will take up greater than 4 GB of memory. The 32-bit version of Python should work perfectly fine on 64-bit windows.</p>
| 1 | 2009-05-27T17:39:22Z | [
"python",
"64bit",
"packages"
] |
How does Python OOP compare to PHP OOP? | 916,962 | <p>I'm basically wondering if Python has any OOP shortcomings like PHP does. PHP has been developing their OOP practices for the last few versions. It's getting better in PHP but it's still not perfect. I'm new to Python and I'm just wondering if Python's OOP support is better or just comparable. </p>
<p>If there are some issues in Python OOP which don't follow proper OOP practices I would definitely like to know those. PHP for instance, doesn't allow for multiple inheritance as far as I'm aware. </p>
<p>Thanks Everyone!</p>
<p>Edit:
How about support for Public and Private? or support of variable types. I think these are important regarding building OOP software.</p>
| 15 | 2009-05-27T17:09:28Z | 916,974 | <p>I would say that Python's OOP support is much better given the fact that it was introduced into the language in its infancy as opposed to PHP which bolted OOP onto an existing procedural model.</p>
| 21 | 2009-05-27T17:12:51Z | [
"php",
"python",
"oop",
"comparison"
] |
How does Python OOP compare to PHP OOP? | 916,962 | <p>I'm basically wondering if Python has any OOP shortcomings like PHP does. PHP has been developing their OOP practices for the last few versions. It's getting better in PHP but it's still not perfect. I'm new to Python and I'm just wondering if Python's OOP support is better or just comparable. </p>
<p>If there are some issues in Python OOP which don't follow proper OOP practices I would definitely like to know those. PHP for instance, doesn't allow for multiple inheritance as far as I'm aware. </p>
<p>Thanks Everyone!</p>
<p>Edit:
How about support for Public and Private? or support of variable types. I think these are important regarding building OOP software.</p>
| 15 | 2009-05-27T17:09:28Z | 916,988 | <p>I think they're comparable at this point. As a simple test, I doubt there's any pattern in <a href="http://rads.stackoverflow.com/amzn/click/0201633612" rel="nofollow">Design Patterns</a> or <a href="http://rads.stackoverflow.com/amzn/click/0321127420" rel="nofollow">Patterns of Enterprise Application Architecture</a>, arguably the two most influential books in OOP, that is impossible to implement in either language. </p>
<p>Both languages have come along by leaps and bounds since their infancies.</p>
<p>As far as multiple inheritance, it often <a href="http://en.wikipedia.org/wiki/Diamond%5Fproblem" rel="nofollow">creates more problems than it solves</a>, and is, these days, commonly left out of languages as an intentional design decision.</p>
| 3 | 2009-05-27T17:16:37Z | [
"php",
"python",
"oop",
"comparison"
] |
How does Python OOP compare to PHP OOP? | 916,962 | <p>I'm basically wondering if Python has any OOP shortcomings like PHP does. PHP has been developing their OOP practices for the last few versions. It's getting better in PHP but it's still not perfect. I'm new to Python and I'm just wondering if Python's OOP support is better or just comparable. </p>
<p>If there are some issues in Python OOP which don't follow proper OOP practices I would definitely like to know those. PHP for instance, doesn't allow for multiple inheritance as far as I'm aware. </p>
<p>Thanks Everyone!</p>
<p>Edit:
How about support for Public and Private? or support of variable types. I think these are important regarding building OOP software.</p>
| 15 | 2009-05-27T17:09:28Z | 917,005 | <p>Python's OOP support is very strong; it does allow multiple inheritance, and everything is manipulable as a first-class object (including classes, methods, etc). </p>
<p>Polymorphism is expressed through duck typing. For example, you can iterate over a list, a tuple, a dictionary, a file, a web resource, and more all in the same way.</p>
<p>There are a lot of little pedantic things that are debatably not OO, like getting the length of a sequence with len(list) rather than list.len(), but it's best not to worry about them.</p>
| 8 | 2009-05-27T17:21:57Z | [
"php",
"python",
"oop",
"comparison"
] |
How does Python OOP compare to PHP OOP? | 916,962 | <p>I'm basically wondering if Python has any OOP shortcomings like PHP does. PHP has been developing their OOP practices for the last few versions. It's getting better in PHP but it's still not perfect. I'm new to Python and I'm just wondering if Python's OOP support is better or just comparable. </p>
<p>If there are some issues in Python OOP which don't follow proper OOP practices I would definitely like to know those. PHP for instance, doesn't allow for multiple inheritance as far as I'm aware. </p>
<p>Thanks Everyone!</p>
<p>Edit:
How about support for Public and Private? or support of variable types. I think these are important regarding building OOP software.</p>
| 15 | 2009-05-27T17:09:28Z | 917,052 | <p>Also: Python has native operator overloading, unlike PHP (although it does exist an extension). Love it or hate it, it's there.</p>
| 3 | 2009-05-27T17:35:30Z | [
"php",
"python",
"oop",
"comparison"
] |
How does Python OOP compare to PHP OOP? | 916,962 | <p>I'm basically wondering if Python has any OOP shortcomings like PHP does. PHP has been developing their OOP practices for the last few versions. It's getting better in PHP but it's still not perfect. I'm new to Python and I'm just wondering if Python's OOP support is better or just comparable. </p>
<p>If there are some issues in Python OOP which don't follow proper OOP practices I would definitely like to know those. PHP for instance, doesn't allow for multiple inheritance as far as I'm aware. </p>
<p>Thanks Everyone!</p>
<p>Edit:
How about support for Public and Private? or support of variable types. I think these are important regarding building OOP software.</p>
| 15 | 2009-05-27T17:09:28Z | 917,054 | <p>If you are looking for "more pure" OOP, you should be looking at SmallTalk and/or Ruby.</p>
<p>PHP has grown considerably with it's support for OOP, but because of the way it works (reloads everything every time), things can get really slow if OOP best practices are followed. Which is one of the reasons you don't hear about PHP on Rails much.</p>
| 1 | 2009-05-27T17:35:45Z | [
"php",
"python",
"oop",
"comparison"
] |
How does Python OOP compare to PHP OOP? | 916,962 | <p>I'm basically wondering if Python has any OOP shortcomings like PHP does. PHP has been developing their OOP practices for the last few versions. It's getting better in PHP but it's still not perfect. I'm new to Python and I'm just wondering if Python's OOP support is better or just comparable. </p>
<p>If there are some issues in Python OOP which don't follow proper OOP practices I would definitely like to know those. PHP for instance, doesn't allow for multiple inheritance as far as I'm aware. </p>
<p>Thanks Everyone!</p>
<p>Edit:
How about support for Public and Private? or support of variable types. I think these are important regarding building OOP software.</p>
| 15 | 2009-05-27T17:09:28Z | 917,143 | <p>One aspect of Python's OOP model that is unusual is its encapsulation mechanism. Basically, Python assumes that programmers don't do bad things, and so it doesn't go out of its way to any extent to protect private member variables or methods. </p>
<p>It works by mangling names of members that begin with a two underscores and ending with fewer than two. Such identifiers are everywhere changed so that they have the class name prepended, with an additional underscore before that. thus: </p>
<pre><code>class foo:
def public(self):
return self.__private()
def __private(self):
return 5
print foo().public()
print foo()._foo__private()
</code></pre>
<p>names beginning and ending with two (or more) underscores are not mangled, so <code>__init__</code> the method python uses for constructing new instances, is left alone. </p>
<p>Here's a <a href="http://docs.python.org/tutorial/classes.html#private-variables">link</a> explaining it in more detail.</p>
| 7 | 2009-05-27T17:56:20Z | [
"php",
"python",
"oop",
"comparison"
] |
Python equivalent of maplist? | 916,978 | <p>What's the best Python equivalent of Common Lisp's <code>maplist</code> function? From the <a href="http://www.ai.mit.edu/projects/iiip/doc/CommonLISP/HyperSpec/Body/fun%5Fmapccm%5Fma%5Fistcm%5Fmapcon.html" rel="nofollow">maplist documentation</a>:</p>
<blockquote>
<p>maplist is like mapcar except that
function is applied to successive
sublists of the lists. function is
first applied to the lists themselves,
and then to the cdr of each list, and
then to the cdr of the cdr of each
list, and so on.</p>
</blockquote>
<p>Example (pseudoy-code, not tested):</p>
<pre><code>>>> def p(x): return x
>>> maplist(p, [1,2,3])
[[1, 2, 3], [2, 3], [3]]
</code></pre>
<p><strong>Note</strong>: the arguments passed to <code>p</code> in the example above would be the lists <code>[1, 2, 3]</code>, <code>[2, 3]</code>, <code>[3]</code>; i.e., <code>p</code> is not applied to the elements of those lists. E.g.:</p>
<pre><code>>>> maplist(lambda l: list(reversed(l)), [1,2,3])
[[3, 2, 1], [3, 2], [3]]
</code></pre>
| 11 | 2009-05-27T17:13:40Z | 917,028 | <p>You can write a little function for that</p>
<pre><code>def maplist(func, values):
return [map(func, values[i:]) for i in xrange(len(values))]
>>> maplist(lambda a: a* 2, [1,2,3])
[[2, 4, 6], [4, 6], [6]]
</code></pre>
<p><strong>[Edit]</strong></p>
<p>if you want to apply the function on the sublists you can change the function to this:</p>
<pre><code>def maplist(func, values):
return [func(values[i:]) for i in xrange(len(values))]
>>> maplist(lambda l: list(reversed(l)), [1,2,3])
[[3, 2, 1], [3, 2], [3]]
</code></pre>
| 11 | 2009-05-27T17:29:30Z | [
"python",
"functional-programming",
"lisp"
] |
Python equivalent of maplist? | 916,978 | <p>What's the best Python equivalent of Common Lisp's <code>maplist</code> function? From the <a href="http://www.ai.mit.edu/projects/iiip/doc/CommonLISP/HyperSpec/Body/fun%5Fmapccm%5Fma%5Fistcm%5Fmapcon.html" rel="nofollow">maplist documentation</a>:</p>
<blockquote>
<p>maplist is like mapcar except that
function is applied to successive
sublists of the lists. function is
first applied to the lists themselves,
and then to the cdr of each list, and
then to the cdr of the cdr of each
list, and so on.</p>
</blockquote>
<p>Example (pseudoy-code, not tested):</p>
<pre><code>>>> def p(x): return x
>>> maplist(p, [1,2,3])
[[1, 2, 3], [2, 3], [3]]
</code></pre>
<p><strong>Note</strong>: the arguments passed to <code>p</code> in the example above would be the lists <code>[1, 2, 3]</code>, <code>[2, 3]</code>, <code>[3]</code>; i.e., <code>p</code> is not applied to the elements of those lists. E.g.:</p>
<pre><code>>>> maplist(lambda l: list(reversed(l)), [1,2,3])
[[3, 2, 1], [3, 2], [3]]
</code></pre>
| 11 | 2009-05-27T17:13:40Z | 917,029 | <p>I think there isn't, but the following function can work:</p>
<pre><code>def maplist(func, l):
for i in range(len(l)):
func(l[i:])
</code></pre>
| -1 | 2009-05-27T17:30:23Z | [
"python",
"functional-programming",
"lisp"
] |
Python equivalent of maplist? | 916,978 | <p>What's the best Python equivalent of Common Lisp's <code>maplist</code> function? From the <a href="http://www.ai.mit.edu/projects/iiip/doc/CommonLISP/HyperSpec/Body/fun%5Fmapccm%5Fma%5Fistcm%5Fmapcon.html" rel="nofollow">maplist documentation</a>:</p>
<blockquote>
<p>maplist is like mapcar except that
function is applied to successive
sublists of the lists. function is
first applied to the lists themselves,
and then to the cdr of each list, and
then to the cdr of the cdr of each
list, and so on.</p>
</blockquote>
<p>Example (pseudoy-code, not tested):</p>
<pre><code>>>> def p(x): return x
>>> maplist(p, [1,2,3])
[[1, 2, 3], [2, 3], [3]]
</code></pre>
<p><strong>Note</strong>: the arguments passed to <code>p</code> in the example above would be the lists <code>[1, 2, 3]</code>, <code>[2, 3]</code>, <code>[3]</code>; i.e., <code>p</code> is not applied to the elements of those lists. E.g.:</p>
<pre><code>>>> maplist(lambda l: list(reversed(l)), [1,2,3])
[[3, 2, 1], [3, 2], [3]]
</code></pre>
| 11 | 2009-05-27T17:13:40Z | 917,044 | <p>this works like your example (I've modified reyjavikvi's code)</p>
<pre><code>def maplist(func, l):
result=[]
for i in range(len(l)):
result.append(func(l[i:]))
return result
</code></pre>
| 1 | 2009-05-27T17:34:11Z | [
"python",
"functional-programming",
"lisp"
] |
Python equivalent of maplist? | 916,978 | <p>What's the best Python equivalent of Common Lisp's <code>maplist</code> function? From the <a href="http://www.ai.mit.edu/projects/iiip/doc/CommonLISP/HyperSpec/Body/fun%5Fmapccm%5Fma%5Fistcm%5Fmapcon.html" rel="nofollow">maplist documentation</a>:</p>
<blockquote>
<p>maplist is like mapcar except that
function is applied to successive
sublists of the lists. function is
first applied to the lists themselves,
and then to the cdr of each list, and
then to the cdr of the cdr of each
list, and so on.</p>
</blockquote>
<p>Example (pseudoy-code, not tested):</p>
<pre><code>>>> def p(x): return x
>>> maplist(p, [1,2,3])
[[1, 2, 3], [2, 3], [3]]
</code></pre>
<p><strong>Note</strong>: the arguments passed to <code>p</code> in the example above would be the lists <code>[1, 2, 3]</code>, <code>[2, 3]</code>, <code>[3]</code>; i.e., <code>p</code> is not applied to the elements of those lists. E.g.:</p>
<pre><code>>>> maplist(lambda l: list(reversed(l)), [1,2,3])
[[3, 2, 1], [3, 2], [3]]
</code></pre>
| 11 | 2009-05-27T17:13:40Z | 917,051 | <p>You can use nested list comprehensions:</p>
<pre><code>>>> def p(x): return x
>>> l = range(4)[1:]
>>> [p([i:]) for i in range(len(l))]
[[1, 2, 3], [2, 3], [3]]
</code></pre>
<p>Which you can use to define maplist yourself:</p>
<pre><code>>>> def maplist(p, l): return [p([i:]) for i in range(len(l))]
>>> maplist(p, l)
[[1, 2, 3], [2, 3], [3]]
</code></pre>
| 1 | 2009-05-27T17:35:27Z | [
"python",
"functional-programming",
"lisp"
] |
Python equivalent of maplist? | 916,978 | <p>What's the best Python equivalent of Common Lisp's <code>maplist</code> function? From the <a href="http://www.ai.mit.edu/projects/iiip/doc/CommonLISP/HyperSpec/Body/fun%5Fmapccm%5Fma%5Fistcm%5Fmapcon.html" rel="nofollow">maplist documentation</a>:</p>
<blockquote>
<p>maplist is like mapcar except that
function is applied to successive
sublists of the lists. function is
first applied to the lists themselves,
and then to the cdr of each list, and
then to the cdr of the cdr of each
list, and so on.</p>
</blockquote>
<p>Example (pseudoy-code, not tested):</p>
<pre><code>>>> def p(x): return x
>>> maplist(p, [1,2,3])
[[1, 2, 3], [2, 3], [3]]
</code></pre>
<p><strong>Note</strong>: the arguments passed to <code>p</code> in the example above would be the lists <code>[1, 2, 3]</code>, <code>[2, 3]</code>, <code>[3]</code>; i.e., <code>p</code> is not applied to the elements of those lists. E.g.:</p>
<pre><code>>>> maplist(lambda l: list(reversed(l)), [1,2,3])
[[3, 2, 1], [3, 2], [3]]
</code></pre>
| 11 | 2009-05-27T17:13:40Z | 917,278 | <p>Modifying Aaron's answer:</p>
<pre><code>In [8]: def maplist(p, l): return [p([x for x in l[i:]]) for i in range(len(l))]
...:
In [9]: maplist(lambda x: x + x, [1,2,3])
Out[9]: [[1, 2, 3, 1, 2, 3], [2, 3, 2, 3], [3, 3]]
</code></pre>
| 0 | 2009-05-27T18:23:34Z | [
"python",
"functional-programming",
"lisp"
] |
Python equivalent of maplist? | 916,978 | <p>What's the best Python equivalent of Common Lisp's <code>maplist</code> function? From the <a href="http://www.ai.mit.edu/projects/iiip/doc/CommonLISP/HyperSpec/Body/fun%5Fmapccm%5Fma%5Fistcm%5Fmapcon.html" rel="nofollow">maplist documentation</a>:</p>
<blockquote>
<p>maplist is like mapcar except that
function is applied to successive
sublists of the lists. function is
first applied to the lists themselves,
and then to the cdr of each list, and
then to the cdr of the cdr of each
list, and so on.</p>
</blockquote>
<p>Example (pseudoy-code, not tested):</p>
<pre><code>>>> def p(x): return x
>>> maplist(p, [1,2,3])
[[1, 2, 3], [2, 3], [3]]
</code></pre>
<p><strong>Note</strong>: the arguments passed to <code>p</code> in the example above would be the lists <code>[1, 2, 3]</code>, <code>[2, 3]</code>, <code>[3]</code>; i.e., <code>p</code> is not applied to the elements of those lists. E.g.:</p>
<pre><code>>>> maplist(lambda l: list(reversed(l)), [1,2,3])
[[3, 2, 1], [3, 2], [3]]
</code></pre>
| 11 | 2009-05-27T17:13:40Z | 917,520 | <p>Eewww... Slicing a list is a linear-time operation. All of the solutions posted thus far have O(n^2) time complexity. Lisp's maplist, I believe, has O(n).</p>
<p>The problem is, Python's list type isn't a linked list. It's a dynamically resizable array (i.e., like C++ STL's "vector" type). </p>
<p>If maintaining linear time complexity is important to you, it isn't possible to create a "maplist" function over Python lists. It would be better to modify your code to work with indices into the list, or convert the list into an actual linked list (still a linear-time operation, but would have a lot of overhead).</p>
| 3 | 2009-05-27T19:13:39Z | [
"python",
"functional-programming",
"lisp"
] |
Python equivalent of maplist? | 916,978 | <p>What's the best Python equivalent of Common Lisp's <code>maplist</code> function? From the <a href="http://www.ai.mit.edu/projects/iiip/doc/CommonLISP/HyperSpec/Body/fun%5Fmapccm%5Fma%5Fistcm%5Fmapcon.html" rel="nofollow">maplist documentation</a>:</p>
<blockquote>
<p>maplist is like mapcar except that
function is applied to successive
sublists of the lists. function is
first applied to the lists themselves,
and then to the cdr of each list, and
then to the cdr of the cdr of each
list, and so on.</p>
</blockquote>
<p>Example (pseudoy-code, not tested):</p>
<pre><code>>>> def p(x): return x
>>> maplist(p, [1,2,3])
[[1, 2, 3], [2, 3], [3]]
</code></pre>
<p><strong>Note</strong>: the arguments passed to <code>p</code> in the example above would be the lists <code>[1, 2, 3]</code>, <code>[2, 3]</code>, <code>[3]</code>; i.e., <code>p</code> is not applied to the elements of those lists. E.g.:</p>
<pre><code>>>> maplist(lambda l: list(reversed(l)), [1,2,3])
[[3, 2, 1], [3, 2], [3]]
</code></pre>
| 11 | 2009-05-27T17:13:40Z | 917,911 | <p>As @Cybis and others mentioned, you can't keep the O(N) complexity with Python lists; you'll have to create a linked list. At the risk of proving <a href="http://en.wikipedia.org/wiki/Greenspun%27s%5FTenth%5FRule" rel="nofollow">Greenspun's 10th rule</a>, here is such a solution:</p>
<pre><code>class cons(tuple):
__slots__=()
def __new__(cls, car, cdr):
return tuple.__new__(cls, (car,cdr))
@classmethod
def from_seq(class_, l):
result = None
for el in reversed(l):
result = cons(el, result)
return result
@property
def car(self): return self._getitem(0)
@property
def cdr(self): return self._getitem(1)
def _getitem(self, i):
return tuple.__getitem__(self, i)
def __repr__(self):
return '(%s %r)' % (self.car, self.cdr)
def __iter__(self):
v = self
while v is not None:
yield v.car
v = v.cdr
def __len__(self):
return sum(1 for x in self)
def __getitem__(self, i):
v = self
while i > 0:
v = v.cdr
i -= 1
return v.car
def maplist(func, values):
result = [ ]
while values is not None:
result.append(func(values))
values = values.cdr
return result
</code></pre>
<p>Testing yields:</p>
<pre><code>>>> l = cons.from_seq([1,2,3,4])
>>> print l
(1 (2 (3 (4 None))))
>>> print list(l)
[1, 2, 3, 4]
>>> print maplistr(lambda l: list(reversed(l)), cons.from_seq([1,2,3]))
[[3, 2, 1], [3, 2], [3]]
</code></pre>
<p>EDIT: Here is a generator-based solution that basically solves the same problem without the use of linked lists:</p>
<pre><code>import itertools
def mapiter(func, iter_):
while True:
iter_, iter2 = itertools.tee(iter_)
iter_.next()
yield func(iter2)
</code></pre>
<p>Testing yields:</p>
<pre><code>>>> print list(mapiter(lambda l: list(reversed(list(l))), [1,2,3]))
[[3, 2, 1], [3, 2], [3]]
</code></pre>
| 6 | 2009-05-27T20:39:28Z | [
"python",
"functional-programming",
"lisp"
] |
Python equivalent of maplist? | 916,978 | <p>What's the best Python equivalent of Common Lisp's <code>maplist</code> function? From the <a href="http://www.ai.mit.edu/projects/iiip/doc/CommonLISP/HyperSpec/Body/fun%5Fmapccm%5Fma%5Fistcm%5Fmapcon.html" rel="nofollow">maplist documentation</a>:</p>
<blockquote>
<p>maplist is like mapcar except that
function is applied to successive
sublists of the lists. function is
first applied to the lists themselves,
and then to the cdr of each list, and
then to the cdr of the cdr of each
list, and so on.</p>
</blockquote>
<p>Example (pseudoy-code, not tested):</p>
<pre><code>>>> def p(x): return x
>>> maplist(p, [1,2,3])
[[1, 2, 3], [2, 3], [3]]
</code></pre>
<p><strong>Note</strong>: the arguments passed to <code>p</code> in the example above would be the lists <code>[1, 2, 3]</code>, <code>[2, 3]</code>, <code>[3]</code>; i.e., <code>p</code> is not applied to the elements of those lists. E.g.:</p>
<pre><code>>>> maplist(lambda l: list(reversed(l)), [1,2,3])
[[3, 2, 1], [3, 2], [3]]
</code></pre>
| 11 | 2009-05-27T17:13:40Z | 925,611 | <h3>O(N) implementation of <code>maplist()</code> for linked lists</h3>
<pre><code>maplist = lambda f, lst: cons(f(lst), maplist(f, cdr(lst))) if lst else lst
</code></pre>
<p>See <a href="http://stackoverflow.com/questions/280243/python-linked-list">Python Linked List</a> question.</p>
| 1 | 2009-05-29T11:40:27Z | [
"python",
"functional-programming",
"lisp"
] |
Python equivalent of maplist? | 916,978 | <p>What's the best Python equivalent of Common Lisp's <code>maplist</code> function? From the <a href="http://www.ai.mit.edu/projects/iiip/doc/CommonLISP/HyperSpec/Body/fun%5Fmapccm%5Fma%5Fistcm%5Fmapcon.html" rel="nofollow">maplist documentation</a>:</p>
<blockquote>
<p>maplist is like mapcar except that
function is applied to successive
sublists of the lists. function is
first applied to the lists themselves,
and then to the cdr of each list, and
then to the cdr of the cdr of each
list, and so on.</p>
</blockquote>
<p>Example (pseudoy-code, not tested):</p>
<pre><code>>>> def p(x): return x
>>> maplist(p, [1,2,3])
[[1, 2, 3], [2, 3], [3]]
</code></pre>
<p><strong>Note</strong>: the arguments passed to <code>p</code> in the example above would be the lists <code>[1, 2, 3]</code>, <code>[2, 3]</code>, <code>[3]</code>; i.e., <code>p</code> is not applied to the elements of those lists. E.g.:</p>
<pre><code>>>> maplist(lambda l: list(reversed(l)), [1,2,3])
[[3, 2, 1], [3, 2], [3]]
</code></pre>
| 11 | 2009-05-27T17:13:40Z | 9,757,474 | <p>Python has a linked list type, called <code>deque</code>:</p>
<pre><code>from collections import deque
def maplist(f, lst):
linked = deque(lst)
results = []
while linked:
results.append(f(linked))
linked.popleft() # assumes left is head, as in lisp
return results
In [134]: maplist(lambda l: list(reversed(l))*2, [1,2,3])
Out[134]: [[3, 2, 1, 3, 2, 1], [3, 2, 3, 2], [3, 3]]
</code></pre>
<p>Linear time, does the same thing, will have the same performance characteristics as operations on lisp lists (i.e. modifying interior elements will be linear in the length of the list being modified), and the same semantics (i.e. if <code>f</code> modifies the list, it modifies it for all subsequent executions of <code>f</code> within that <code>maplist</code> call; however, because this creates a copy of <code>lst</code>, <code>f</code> cannot modify <code>lst</code>, unlike in Common Lisp).</p>
| 1 | 2012-03-18T10:09:18Z | [
"python",
"functional-programming",
"lisp"
] |
WxPython differences between Windows and Linux | 916,987 | <p>The tutorials I've found on WxPython all use examples from Linux, but there seem to be differences in some details.</p>
<p>For example, in Windows a Panel behind the widgets is mandatory to show the background properly. Additionally, some examples that look fine in the tutorials don't work in my computer.</p>
<p>So, do you know what important differences are there, or maybe a good tutorial that is focused on Windows?</p>
<p><b>EDIT: </b> I just remembered this: Does anybody know why when subclassing wx.App an OnInit() method is required, rather than the more logical <code>__init__</code>()?</p>
| 1 | 2009-05-27T17:16:34Z | 917,040 | <blockquote>
<p><strong>EDIT:</strong> I just remembered this: Does anybody know why when subclassing wx.App an OnInit() method is required, rather than the more logical <code>__init__()</code>?</p>
</blockquote>
<p>I use <code>OnInit()</code> for symmetry: there's also an <code>OnExit()</code> method.</p>
<p>Edit: I may be wrong, but I don't think using <code>OnInit()</code> is required.</p>
| 0 | 2009-05-27T17:33:12Z | [
"python",
"windows",
"linux",
"user-interface",
"wxpython"
] |
WxPython differences between Windows and Linux | 916,987 | <p>The tutorials I've found on WxPython all use examples from Linux, but there seem to be differences in some details.</p>
<p>For example, in Windows a Panel behind the widgets is mandatory to show the background properly. Additionally, some examples that look fine in the tutorials don't work in my computer.</p>
<p>So, do you know what important differences are there, or maybe a good tutorial that is focused on Windows?</p>
<p><b>EDIT: </b> I just remembered this: Does anybody know why when subclassing wx.App an OnInit() method is required, rather than the more logical <code>__init__</code>()?</p>
| 1 | 2009-05-27T17:16:34Z | 917,063 | <p>I've noticed odd peculiarities in a small GUI I wrote a while back, but it's been a long time since I tried to the specifics are a rather distant memory. Do you have some specific examples which fail? Maybe we can improve them and fix the bugs?</p>
<p>Have you tried <a href="http://www.wxpython.org/tut-part1.php" rel="nofollow">the official wxPython tutorials</a>? ...or were you after something more specific?</p>
<p><strong>r.e. your edit</strong> - You should use <code>OnInit()</code> because you're subclassing <a href="http://docs.wxwidgets.org/stable/wx_wxapp.html#wxapponinit" rel="nofollow">wx.App</A> (i.e. it's a requirement for wxWidgets rather than Python) and the wxPython implementation is wherever possible, just a wrapper for wxWidgets.</p>
<p><strong>[Edit]</strong> Zetcode has <a href="http://zetcode.com/wxpython/" rel="nofollow">a fairly lengthy tutorial on wxPython</a>. I've not looked through it all myself, but it might be of some help?</p>
<p>The <a href="http://docs.wxwidgets.org/stable/wx_wxapp.html#wxapponinit" rel="nofollow"><code>wxWidgets::wxApp::OnInit()</code></a> documentation is fairly clear:</p>
<blockquote>
<p>This must be provided by the application, and will usually create the application's main window, optionally calling wxApp::SetTopWindow. You may use OnExit to clean up anything initialized here, provided that the function returns true.</p>
</blockquote>
<p>If wxWidgets didn't provide a common interface then you'd have to do different things in C++ (using a constructor) compared to Python's <code>__init__(self,...)</code>. Using a language-independent on-initialisation allows wxWidgets ports to other languages look more alike which should be a good thing right? :-)</p>
| 2 | 2009-05-27T17:38:02Z | [
"python",
"windows",
"linux",
"user-interface",
"wxpython"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.