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 |
|---|---|---|---|---|---|---|---|---|---|
How do I create an empty array/matrix in NumPy?
| 568,962
|
<p>I can't figure out how to use an array or matrix in the way that I would normally use a list. I want to create an empty array (or matrix) and then add one column (or row) to it at a time.</p>
<p>At the moment the only way I can find to do this is like:</p>
<pre><code>mat = None
for col in columns:
if mat is None:
mat = col
else:
mat = hstack((mat, col))
</code></pre>
<p>Whereas if it were a list, I'd do something like this:</p>
<pre><code>list = []
for item in data:
list.append(item)
</code></pre>
<p>Is there a way to use that kind of notation for <a href="http://en.wikipedia.org/wiki/NumPy">NumPy</a> arrays or matrices?</p>
| 103
|
2009-02-20T09:58:11Z
| 569,090
|
<p>A NumPy array is a very different data structure from a list and is designed to be used in different ways. Your use of <code>hstack</code> is potentially very inefficient... every time you call it, all the data in the existing array is copied into a new one. (The <code>append</code> function will have the same issue.) If you want to build up your matrix one column at a time, you might be best off to keep it in a list until it is finished, and only then convert it into an array.</p>
<p>e.g.</p>
<pre><code>
mylist = []
for item in data:
mylist.append(item)
mat = numpy.array(mylist)
</code></pre>
<p><code>item</code> can be a list, an array or any iterable, as long
as each <code>item</code> has the same number of elements.<br>
In this particular case (<code>data</code> is some iterable holding the matrix columns) you can simply use</p>
<pre><code>
mat = numpy.array(data)
</code></pre>
<p>(Also note that using <code>list</code> as a variable name is probably not good practice since it masks the built-in type by that name, which can lead to bugs.)</p>
<p>EDIT:</p>
<p>If for some reason you really do want to create an empty array, you can just use <code> numpy.array([])</code>, but this is rarely useful!</p>
| 42
|
2009-02-20T10:44:19Z
|
[
"python",
"arrays",
"numpy"
] |
How do I create an empty array/matrix in NumPy?
| 568,962
|
<p>I can't figure out how to use an array or matrix in the way that I would normally use a list. I want to create an empty array (or matrix) and then add one column (or row) to it at a time.</p>
<p>At the moment the only way I can find to do this is like:</p>
<pre><code>mat = None
for col in columns:
if mat is None:
mat = col
else:
mat = hstack((mat, col))
</code></pre>
<p>Whereas if it were a list, I'd do something like this:</p>
<pre><code>list = []
for item in data:
list.append(item)
</code></pre>
<p>Is there a way to use that kind of notation for <a href="http://en.wikipedia.org/wiki/NumPy">NumPy</a> arrays or matrices?</p>
| 103
|
2009-02-20T09:58:11Z
| 7,326,319
|
<p>If you absolutely don't know the final size of the array, you can increment the size of the array like this:</p>
<pre><code>my_arr = numpy.zeros((0,5))
for i in range(3):
my_arr=numpy.concatenate( ( my_arr, numpy.ones((1,5)) ) )
print(my_arr)
[[ 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1.]]
</code></pre>
<ul>
<li>Notice the <code>0</code> in the first line.</li>
<li><code>numpy.append</code> is another option. It calls <code>numpy.concatenate</code>.</li>
</ul>
| 2
|
2011-09-06T21:20:44Z
|
[
"python",
"arrays",
"numpy"
] |
How do I create an empty array/matrix in NumPy?
| 568,962
|
<p>I can't figure out how to use an array or matrix in the way that I would normally use a list. I want to create an empty array (or matrix) and then add one column (or row) to it at a time.</p>
<p>At the moment the only way I can find to do this is like:</p>
<pre><code>mat = None
for col in columns:
if mat is None:
mat = col
else:
mat = hstack((mat, col))
</code></pre>
<p>Whereas if it were a list, I'd do something like this:</p>
<pre><code>list = []
for item in data:
list.append(item)
</code></pre>
<p>Is there a way to use that kind of notation for <a href="http://en.wikipedia.org/wiki/NumPy">NumPy</a> arrays or matrices?</p>
| 103
|
2009-02-20T09:58:11Z
| 15,926,110
|
<p>I looked into this a lot because I needed to use a numpy.array as a set in one of my school projects and I needed to be initialized empty... I didn't found any relevant answer here on Stack Overflow, so I started doodling something. </p>
<pre><code># Initialize your variable as an empty list first
In [32]: x=[]
# and now cast it as a numpy ndarray
In [33]: x=np.array(x)
</code></pre>
<p>The result will be:</p>
<pre><code>In [34]: x
Out[34]: array([], dtype=float64)
</code></pre>
<p>Therefore you can directly initialize an np array as follows:</p>
<pre><code>In [36]: x= np.array([], dtype=np.float64)
</code></pre>
<p>I hope this helps.</p>
| 8
|
2013-04-10T12:39:58Z
|
[
"python",
"arrays",
"numpy"
] |
How do I create an empty array/matrix in NumPy?
| 568,962
|
<p>I can't figure out how to use an array or matrix in the way that I would normally use a list. I want to create an empty array (or matrix) and then add one column (or row) to it at a time.</p>
<p>At the moment the only way I can find to do this is like:</p>
<pre><code>mat = None
for col in columns:
if mat is None:
mat = col
else:
mat = hstack((mat, col))
</code></pre>
<p>Whereas if it were a list, I'd do something like this:</p>
<pre><code>list = []
for item in data:
list.append(item)
</code></pre>
<p>Is there a way to use that kind of notation for <a href="http://en.wikipedia.org/wiki/NumPy">NumPy</a> arrays or matrices?</p>
| 103
|
2009-02-20T09:58:11Z
| 22,978,734
|
<p>To create an empty multidimensional array in NumPy (e.g. a 2D array <code>m*n</code> to store your matrix), in case you don't know <code>m</code> how many rows you will append and don't care about the computational cost Stephen Simmons mentioned (namely re-buildinging the array at each append), you can squeeze to 0 the dimension to which you want to append to: <code>X = np.empty(shape=[0, n])</code>.</p>
<p>This way you can use for example (here <code>m = 5</code> which we assume we didn't know when creating the empty matrix, and <code>n = 2</code>):</p>
<pre><code>n = 2
X = np.empty(shape=[0, n])
for i in range(5):
for j in range(2):
X = np.append(X, [[i, j]], axis=0)
print X
</code></pre>
<p>which will give you:</p>
<pre><code>[[ 0. 0.]
[ 0. 1.]
[ 1. 0.]
[ 1. 1.]
[ 2. 0.]
[ 2. 1.]
[ 3. 0.]
[ 3. 1.]
[ 4. 0.]
[ 4. 1.]]
</code></pre>
| 13
|
2014-04-10T04:34:58Z
|
[
"python",
"arrays",
"numpy"
] |
How do I create an empty array/matrix in NumPy?
| 568,962
|
<p>I can't figure out how to use an array or matrix in the way that I would normally use a list. I want to create an empty array (or matrix) and then add one column (or row) to it at a time.</p>
<p>At the moment the only way I can find to do this is like:</p>
<pre><code>mat = None
for col in columns:
if mat is None:
mat = col
else:
mat = hstack((mat, col))
</code></pre>
<p>Whereas if it were a list, I'd do something like this:</p>
<pre><code>list = []
for item in data:
list.append(item)
</code></pre>
<p>Is there a way to use that kind of notation for <a href="http://en.wikipedia.org/wiki/NumPy">NumPy</a> arrays or matrices?</p>
| 103
|
2009-02-20T09:58:11Z
| 32,893,787
|
<p>You can apply it to build any kind of array, like zeros:</p>
<pre><code>a = range(5)
a = [i*0 for i in a]
print a
[0, 0, 0, 0, 0]
</code></pre>
| 1
|
2015-10-01T17:50:36Z
|
[
"python",
"arrays",
"numpy"
] |
How do I create an empty array/matrix in NumPy?
| 568,962
|
<p>I can't figure out how to use an array or matrix in the way that I would normally use a list. I want to create an empty array (or matrix) and then add one column (or row) to it at a time.</p>
<p>At the moment the only way I can find to do this is like:</p>
<pre><code>mat = None
for col in columns:
if mat is None:
mat = col
else:
mat = hstack((mat, col))
</code></pre>
<p>Whereas if it were a list, I'd do something like this:</p>
<pre><code>list = []
for item in data:
list.append(item)
</code></pre>
<p>Is there a way to use that kind of notation for <a href="http://en.wikipedia.org/wiki/NumPy">NumPy</a> arrays or matrices?</p>
| 103
|
2009-02-20T09:58:11Z
| 39,431,787
|
<p>Depending on what you are using this for, you may need to specify the data type (see <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.dtype.html" rel="nofollow">'dtype'</a>).</p>
<p>For example, to create a 2D array of 8-bit values (suitable for use as a monochrome image):</p>
<pre><code>myarray = numpy.empty(shape=(H,W),dtype='u1')
</code></pre>
<p>For an RGB image, include the number of color channels in the shape: <code>shape=(H,W,3)</code></p>
<p>You may also want to consider zero-initializing with <code>numpy.zeros</code> instead of using <code>numpy.empty</code>. See the note <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.empty.html" rel="nofollow">here</a>.</p>
| 0
|
2016-09-11T00:28:42Z
|
[
"python",
"arrays",
"numpy"
] |
How to programmatically insert comments into a Microsoft Word document?
| 568,972
|
<p>Looking for a way to programmatically insert comments (using the comments feature in Word) into a specific location in a MS Word document. I would prefer an approach that is usable across recent versions of MS Word standard formats and implementable in a non-Windows environment (ideally using Python and/or Common Lisp). I have been looking at the OpenXML SDK but can't seem to find a solution there.</p>
| 9
|
2009-02-20T10:02:47Z
| 569,040
|
<p>If this is server side (non-interactive) use of the Word application itself is unsupported (but I see this is not applicable). So either take that route or use the <a href="http://msdn.microsoft.com/en-us/library/bb448854.aspx" rel="nofollow">OpenXML SDK</a> to learn the markup needed to create a comment. With that knowledge it is all about manipulating data.</p>
<p>The .docx format is a ZIP of XML files with a defines structure, so mostly once you get into the ZIP and get the right XML file it becomes a matter of modifying an XML DOM.</p>
<p>The best route might be to take a docx, copy it, add a comment (using Word) to one, and compare. A diff will show you the kind of elements/structures you need to be looking up in the SDK (or ISO/Ecma standard).</p>
| 2
|
2009-02-20T10:27:54Z
|
[
"python",
"ms-word",
"common-lisp",
"openxml"
] |
How to programmatically insert comments into a Microsoft Word document?
| 568,972
|
<p>Looking for a way to programmatically insert comments (using the comments feature in Word) into a specific location in a MS Word document. I would prefer an approach that is usable across recent versions of MS Word standard formats and implementable in a non-Windows environment (ideally using Python and/or Common Lisp). I have been looking at the OpenXML SDK but can't seem to find a solution there.</p>
| 9
|
2009-02-20T10:02:47Z
| 569,092
|
<p>Here is what I did:</p>
<ol>
<li>Create a simple document with word (i.e. a very small one)</li>
<li>Add a comment in Word</li>
<li>Save as docx.</li>
<li>Use the zip module of python to access the archive (docx files are ZIP archives).</li>
<li>Dump the content of the entry "word/document.xml" in the archive. This is the XML of the document itself.</li>
</ol>
<p>This should give you an idea what you need to do. After that, you can use one of the XML libraries in Python to parse the document, change it and add it back to a new ZIP archive with the extension ".docx". Simply copy every other entry from the original ZIP and you have a new, valid Word document.</p>
<p>There is also a library which might help: <a href="http://code.google.com/p/openxmllib/">openxmllib</a></p>
| 7
|
2009-02-20T10:44:49Z
|
[
"python",
"ms-word",
"common-lisp",
"openxml"
] |
Django: multiple models in one template using forms
| 569,468
|
<p>I'm building a support ticket tracking app and have a few models I'd like to create from one page. Tickets belong to a Customer via a ForeignKey. Notes belong to Tickets via a ForeignKey as well. I'd like to have the option of selecting a Customer (that's a whole separate project) OR creating a new Customer, then creating a Ticket and finally creating a Note assigned to the new ticket.</p>
<p>Since I'm fairly new to Django, I tend to work iteratively, trying out new features each time. I've played with ModelForms but I want to hide some of the fields and do some complex validation. It seems like the level of control I'm looking for either requires formsets or doing everything by hand, complete with a tedious, hand-coded template page, which I'm trying to avoid.</p>
<p>Is there some lovely feature I'm missing? Does someone have a good reference or example for using formsets? I spent a whole weekend on the API docs for them and I'm still clueless. Is it a design issue if I break down and hand-code everything?</p>
| 85
|
2009-02-20T12:50:26Z
| 569,763
|
<p>"I want to hide some of the fields and do some complex validation."</p>
<p>I start with the built-in admin interface.</p>
<ol>
<li><p>Build the ModelForm to show the desired fields.</p></li>
<li><p>Extend the Form with the validation rules within the form. Usually this is a <code>clean</code> method.</p>
<p>Be sure this part works reasonably well.</p></li>
</ol>
<p>Once this is done, you can move away from the built-in admin interface.</p>
<p>Then you can fool around with multiple, partially related forms on a single web page. This is a bunch of template stuff to present all the forms on a single page.</p>
<p>Then you have to write the view function to read and validated the various form things and do the various object saves().</p>
<p>"Is it a design issue if I break down and hand-code everything?" No, it's just a lot of time for not much benefit.</p>
| 2
|
2009-02-20T14:38:37Z
|
[
"python",
"django",
"design",
"django-forms"
] |
Django: multiple models in one template using forms
| 569,468
|
<p>I'm building a support ticket tracking app and have a few models I'd like to create from one page. Tickets belong to a Customer via a ForeignKey. Notes belong to Tickets via a ForeignKey as well. I'd like to have the option of selecting a Customer (that's a whole separate project) OR creating a new Customer, then creating a Ticket and finally creating a Note assigned to the new ticket.</p>
<p>Since I'm fairly new to Django, I tend to work iteratively, trying out new features each time. I've played with ModelForms but I want to hide some of the fields and do some complex validation. It seems like the level of control I'm looking for either requires formsets or doing everything by hand, complete with a tedious, hand-coded template page, which I'm trying to avoid.</p>
<p>Is there some lovely feature I'm missing? Does someone have a good reference or example for using formsets? I spent a whole weekend on the API docs for them and I'm still clueless. Is it a design issue if I break down and hand-code everything?</p>
| 85
|
2009-02-20T12:50:26Z
| 575,133
|
<p>This really isn't too hard to implement with <a href="http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#topics-forms-modelforms">ModelForms</a>. So lets say you have Forms A, B, and C. You print out each of the forms and the page and now you need to handle the POST.</p>
<pre><code>if request.POST():
a_valid = formA.is_valid()
b_valid = formB.is_valid()
c_valid = formC.is_valid()
# we do this since 'and' short circuits and we want to check to whole page for form errors
if a_valid and b_valid and c_valid:
a = formA.save()
b = formB.save(commit=False)
c = formC.save(commit=False)
b.foreignkeytoA = a
b.save()
c.foreignkeytoB = b
c.save()
</code></pre>
<p><a href="http://docs.djangoproject.com/en/dev/ref/forms/validation/#ref-forms-validation">Here</a> are the docs for custom validation.</p>
| 56
|
2009-02-22T16:09:05Z
|
[
"python",
"django",
"design",
"django-forms"
] |
Django: multiple models in one template using forms
| 569,468
|
<p>I'm building a support ticket tracking app and have a few models I'd like to create from one page. Tickets belong to a Customer via a ForeignKey. Notes belong to Tickets via a ForeignKey as well. I'd like to have the option of selecting a Customer (that's a whole separate project) OR creating a new Customer, then creating a Ticket and finally creating a Note assigned to the new ticket.</p>
<p>Since I'm fairly new to Django, I tend to work iteratively, trying out new features each time. I've played with ModelForms but I want to hide some of the fields and do some complex validation. It seems like the level of control I'm looking for either requires formsets or doing everything by hand, complete with a tedious, hand-coded template page, which I'm trying to avoid.</p>
<p>Is there some lovely feature I'm missing? Does someone have a good reference or example for using formsets? I spent a whole weekend on the API docs for them and I'm still clueless. Is it a design issue if I break down and hand-code everything?</p>
| 85
|
2009-02-20T12:50:26Z
| 606,318
|
<p>I very recently had the some problem and just figured out how to do this.
Assuming you have three classes, Primary, B, C and that B,C have a foreign key to primary</p>
<pre><code> class PrimaryForm(ModelForm):
class Meta:
model = Primary
class BForm(ModelForm):
class Meta:
model = B
exclude = ('primary',)
class CForm(ModelForm):
class Meta:
model = C
exclude = ('primary',)
def generateView(request):
if request.method == 'POST': # If the form has been submitted...
primary_form = PrimaryForm(request.POST, prefix = "primary")
b_form = BForm(request.POST, prefix = "b")
c_form = CForm(request.POST, prefix = "c")
if primary_form.is_valid() and b_form.is_valid() and c_form.is_valid(): # All validation rules pass
print "all validation passed"
primary = primary_form.save()
b_form.cleaned_data["primary"] = primary
b = b_form.save()
c_form.cleaned_data["primary"] = primary
c = c_form.save()
return HttpResponseRedirect("/viewer/%s/" % (primary.name))
else:
print "failed"
else:
primary_form = PrimaryForm(prefix = "primary")
b_form = BForm(prefix = "b")
c_form = Form(prefix = "c")
return render_to_response('multi_model.html', {
'primary_form': primary_form,
'b_form': b_form,
'c_form': c_form,
})
</code></pre>
<p>This method should allow you to do whatever validation you require, as well as generating all three objects on the same page. I have also used javascript and hidden fields to allow the generation of multiple B,C objects on the same page.</p>
| 19
|
2009-03-03T13:05:53Z
|
[
"python",
"django",
"design",
"django-forms"
] |
Django: multiple models in one template using forms
| 569,468
|
<p>I'm building a support ticket tracking app and have a few models I'd like to create from one page. Tickets belong to a Customer via a ForeignKey. Notes belong to Tickets via a ForeignKey as well. I'd like to have the option of selecting a Customer (that's a whole separate project) OR creating a new Customer, then creating a Ticket and finally creating a Note assigned to the new ticket.</p>
<p>Since I'm fairly new to Django, I tend to work iteratively, trying out new features each time. I've played with ModelForms but I want to hide some of the fields and do some complex validation. It seems like the level of control I'm looking for either requires formsets or doing everything by hand, complete with a tedious, hand-coded template page, which I'm trying to avoid.</p>
<p>Is there some lovely feature I'm missing? Does someone have a good reference or example for using formsets? I spent a whole weekend on the API docs for them and I'm still clueless. Is it a design issue if I break down and hand-code everything?</p>
| 85
|
2009-02-20T12:50:26Z
| 985,901
|
<p>I just was in about the same situation a day ago, and here are my 2 cents:</p>
<p>1) I found arguably the shortest and most concise demonstration of multiple model entry in single form here: <a href="http://collingrady.wordpress.com/2008/02/18/editing-multiple-objects-in-django-with-newforms/">http://collingrady.wordpress.com/2008/02/18/editing-multiple-objects-in-django-with-newforms/</a> . </p>
<p>In a nutshell: Make a form for each model, submit them both to template in a single <code><form></code>, using <code>prefix</code> keyarg and have the view handle validation. If there is dependency, just make sure you save the "parent"
model before dependant, and use parent's ID for foreign key before commiting save of "child" model. The link has the demo.</p>
<p>2) Maybe formsets can be beaten into doing this, but as far as I delved in, formsets are primarily for entering multiples of the same model, which <em>may</em> be optionally tied to another model/models by foreign keys. However, there seem to be no default option for entering more than one model's data and that's not what formset seems to be meant for.</p>
| 60
|
2009-06-12T09:50:28Z
|
[
"python",
"django",
"design",
"django-forms"
] |
Django: multiple models in one template using forms
| 569,468
|
<p>I'm building a support ticket tracking app and have a few models I'd like to create from one page. Tickets belong to a Customer via a ForeignKey. Notes belong to Tickets via a ForeignKey as well. I'd like to have the option of selecting a Customer (that's a whole separate project) OR creating a new Customer, then creating a Ticket and finally creating a Note assigned to the new ticket.</p>
<p>Since I'm fairly new to Django, I tend to work iteratively, trying out new features each time. I've played with ModelForms but I want to hide some of the fields and do some complex validation. It seems like the level of control I'm looking for either requires formsets or doing everything by hand, complete with a tedious, hand-coded template page, which I'm trying to avoid.</p>
<p>Is there some lovely feature I'm missing? Does someone have a good reference or example for using formsets? I spent a whole weekend on the API docs for them and I'm still clueless. Is it a design issue if I break down and hand-code everything?</p>
| 85
|
2009-02-20T12:50:26Z
| 10,217,798
|
<p>I currently have a workaround functional (it passes my unit tests). It is a good solution to my opinion when you only want to add a limited number of fields from other models.</p>
<p>Am I missing something here ?</p>
<pre><code>class UserProfileForm(ModelForm):
def __init__(self, instance=None, *args, **kwargs):
# Add these fields from the user object
_fields = ('first_name', 'last_name', 'email',)
# Retrieve initial (current) data from the user object
_initial = model_to_dict(instance.user, _fields) if instance is not None else {}
# Pass the initial data to the base
super(UserProfileForm, self).__init__(initial=_initial, instance=instance, *args, **kwargs)
# Retrieve the fields from the user model and update the fields with it
self.fields.update(fields_for_model(User, _fields))
class Meta:
model = UserProfile
exclude = ('user',)
def save(self, *args, **kwargs):
u = self.instance.user
u.first_name = self.cleaned_data['first_name']
u.last_name = self.cleaned_data['last_name']
u.email = self.cleaned_data['email']
u.save()
profile = super(UserProfileForm, self).save(*args,**kwargs)
return profile
</code></pre>
| 3
|
2012-04-18T20:53:18Z
|
[
"python",
"django",
"design",
"django-forms"
] |
Django: multiple models in one template using forms
| 569,468
|
<p>I'm building a support ticket tracking app and have a few models I'd like to create from one page. Tickets belong to a Customer via a ForeignKey. Notes belong to Tickets via a ForeignKey as well. I'd like to have the option of selecting a Customer (that's a whole separate project) OR creating a new Customer, then creating a Ticket and finally creating a Note assigned to the new ticket.</p>
<p>Since I'm fairly new to Django, I tend to work iteratively, trying out new features each time. I've played with ModelForms but I want to hide some of the fields and do some complex validation. It seems like the level of control I'm looking for either requires formsets or doing everything by hand, complete with a tedious, hand-coded template page, which I'm trying to avoid.</p>
<p>Is there some lovely feature I'm missing? Does someone have a good reference or example for using formsets? I spent a whole weekend on the API docs for them and I'm still clueless. Is it a design issue if I break down and hand-code everything?</p>
| 85
|
2009-02-20T12:50:26Z
| 10,762,684
|
<p>According to Django documentation, inline formsets are for this purpose:
"Inline formsets is a small abstraction layer on top of model formsets. These simplify the case of working with related objects via a foreign key".</p>
<p>See <a href="https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#inline-formsets" rel="nofollow">https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#inline-formsets</a></p>
| 0
|
2012-05-26T00:16:10Z
|
[
"python",
"django",
"design",
"django-forms"
] |
Django: multiple models in one template using forms
| 569,468
|
<p>I'm building a support ticket tracking app and have a few models I'd like to create from one page. Tickets belong to a Customer via a ForeignKey. Notes belong to Tickets via a ForeignKey as well. I'd like to have the option of selecting a Customer (that's a whole separate project) OR creating a new Customer, then creating a Ticket and finally creating a Note assigned to the new ticket.</p>
<p>Since I'm fairly new to Django, I tend to work iteratively, trying out new features each time. I've played with ModelForms but I want to hide some of the fields and do some complex validation. It seems like the level of control I'm looking for either requires formsets or doing everything by hand, complete with a tedious, hand-coded template page, which I'm trying to avoid.</p>
<p>Is there some lovely feature I'm missing? Does someone have a good reference or example for using formsets? I spent a whole weekend on the API docs for them and I'm still clueless. Is it a design issue if I break down and hand-code everything?</p>
| 85
|
2009-02-20T12:50:26Z
| 33,213,960
|
<p>The <a href="https://django-betterforms.readthedocs.org/en/latest/multiform.html#working-with-modelforms">MultiModelForm</a> from <a href="https://github.com/fusionbox/django-betterforms"><code>django-betterforms</code></a> is a convenient wrapper to do what is described in <a href="http://stackoverflow.com/a/985901/1888983">Gnudiff's answer</a>. It wraps regular <code>ModelForm</code>s in a single class which is transparently (at least for basic usage) used as a single form. I've copied an example from their docs below.</p>
<pre><code># forms.py
from django import forms
from django.contrib.auth import get_user_model
from betterforms.multiform import MultiModelForm
from .models import UserProfile
User = get_user_model()
class UserEditForm(forms.ModelForm):
class Meta:
fields = ('email',)
class UserProfileForm(forms.ModelForm):
class Meta:
fields = ('favorite_color',)
class UserEditMultiForm(MultiModelForm):
form_classes = {
'user': UserEditForm,
'profile': UserProfileForm,
}
# views.py
from django.views.generic import UpdateView
from django.core.urlresolvers import reverse_lazy
from django.shortcuts import redirect
from django.contrib.auth import get_user_model
from .forms import UserEditMultiForm
User = get_user_model()
class UserSignupView(UpdateView):
model = User
form_class = UserEditMultiForm
success_url = reverse_lazy('home')
def get_form_kwargs(self):
kwargs = super(UserSignupView, self).get_form_kwargs()
kwargs.update(instance={
'user': self.object,
'profile': self.object.profile,
})
return kwargs
</code></pre>
| 6
|
2015-10-19T12:05:43Z
|
[
"python",
"django",
"design",
"django-forms"
] |
Getting Forms on Page in Python
| 569,477
|
<p>I'm working on a web vulnerability scanner. I have completed 30% of the program, in that it can scan only HTTP GET methods. But I've hit a snag now: I have no idea how I shall make the program pentest the POST method.</p>
<p>I had the idea to make it extract the form data/names from all the pages on the website, but I have no idea how I should do that. Any ideas?</p>
| 0
|
2009-02-20T12:54:57Z
| 569,483
|
<p>Are you asking how to use <a href="http://www.python.org/doc/2.5.2/lib/module-urllib2.html" rel="nofollow">urllib2</a> to execute a POST method?</p>
<p>You might want to look at the <a href="http://www.python.org/doc/2.5.2/lib/urllib2-examples.html" rel="nofollow">examples</a>.</p>
<p>After trying some of that, you might want to post code with a more specific question.</p>
| 1
|
2009-02-20T12:57:53Z
|
[
"python"
] |
Getting Forms on Page in Python
| 569,477
|
<p>I'm working on a web vulnerability scanner. I have completed 30% of the program, in that it can scan only HTTP GET methods. But I've hit a snag now: I have no idea how I shall make the program pentest the POST method.</p>
<p>I had the idea to make it extract the form data/names from all the pages on the website, but I have no idea how I should do that. Any ideas?</p>
| 0
|
2009-02-20T12:54:57Z
| 569,487
|
<p>Use <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a> for screen scraping.</p>
<p>For heavier scripting, use <a href="http://twill.idyll.org/" rel="nofollow">twill</a> :</p>
<blockquote>
<p>twill is a simple language that allows users to browse the Web from a command-line interface. With twill, you can navigate through Web sites that use forms, cookies, and most standard Web features.</p>
</blockquote>
<p>With twill, you can easily fill forms and <code>POST</code> them back to a server. Twill has a <a href="http://twill.idyll.org/python-api.html" rel="nofollow">Python API</a>. A from-filling example:</p>
<pre><code>from twill.commands import go, showforms, formclear, fv, submit
go('http://issola.caltech.edu/~t/qwsgi/qwsgi-demo.cgi/')
go('./widgets')
showforms()
formclear('1')
fv("1", "name", "test")
fv("1", "password", "testpass")
fv("1", "confirm", "yes")
showforms()
submit('0')
</code></pre>
| 3
|
2009-02-20T12:58:39Z
|
[
"python"
] |
Getting Forms on Page in Python
| 569,477
|
<p>I'm working on a web vulnerability scanner. I have completed 30% of the program, in that it can scan only HTTP GET methods. But I've hit a snag now: I have no idea how I shall make the program pentest the POST method.</p>
<p>I had the idea to make it extract the form data/names from all the pages on the website, but I have no idea how I should do that. Any ideas?</p>
| 0
|
2009-02-20T12:54:57Z
| 569,728
|
<p>If you know how to collect the data/names from the form, you just need a way to deal with http POST method. I guess you will need a solution for sending multipart form-data.</p>
<p>You should look at the MultipartPostHandler:</p>
<p><a href="http://odin.himinbi.org/MultipartPostHandler.py" rel="nofollow">http://odin.himinbi.org/MultipartPostHandler.py</a></p>
<p>And if you need to support unicode file names , see a fix at:
<a href="http://peerit.blogspot.com/2007/07/multipartposthandler-doesnt-work-for.html" rel="nofollow">http://peerit.blogspot.com/2007/07/multipartposthandler-doesnt-work-for.html</a></p>
| 0
|
2009-02-20T14:28:49Z
|
[
"python"
] |
What's a good embedded browser for a pygtk application?
| 569,547
|
<p>I'm planning on using an embedded browser in my pygtk application and I'm debating between gtkmozembed and pywebkitgtk. Is there any compelling difference between the two? Are there any third options that I don't know about?</p>
<p>It should be noted that I won't be using this to access content on the web. I'm mainly using it for UI purposes.</p>
<p>My priorities are:</p>
<ol>
<li>It needs to be stable.</li>
<li>It needs to be cross-platform.</li>
<li>It should be easy to use.</li>
<li>It should be actively maintained.</li>
<li>It should be extensible.</li>
<li>It should be fast.</li>
</ol>
| 3
|
2009-02-20T13:19:32Z
| 569,784
|
<p>if you judge by the web pages then definitely pywebkitgtk </p>
<p><a href="http://sourceforge.net/projects/pygtkmoz" rel="nofollow">pygtkmoz</a> from this page</p>
<p>"Note: this project is no longer maintained. Please use gnome-python-extras (<a href="http://www.pygtk.org" rel="nofollow">http://www.pygtk.org</a>) instead. I apologize for any trouble this might cause, but this is better in the long run. Python bindings for GtkEmbedMozilla."</p>
<p>and <a href="http://code.google.com/p/pywebkitgtk/" rel="nofollow">pywebkitgtk</a> looks like active project <a href="http://code.google.com/p/pywebkitgtk/source/list" rel="nofollow">changes</a></p>
| 2
|
2009-02-20T14:44:31Z
|
[
"python",
"user-interface",
"gtk",
"webkit",
"mozilla"
] |
What's a good embedded browser for a pygtk application?
| 569,547
|
<p>I'm planning on using an embedded browser in my pygtk application and I'm debating between gtkmozembed and pywebkitgtk. Is there any compelling difference between the two? Are there any third options that I don't know about?</p>
<p>It should be noted that I won't be using this to access content on the web. I'm mainly using it for UI purposes.</p>
<p>My priorities are:</p>
<ol>
<li>It needs to be stable.</li>
<li>It needs to be cross-platform.</li>
<li>It should be easy to use.</li>
<li>It should be actively maintained.</li>
<li>It should be extensible.</li>
<li>It should be fast.</li>
</ol>
| 3
|
2009-02-20T13:19:32Z
| 636,369
|
<p>gtkmozembed is not available on Windows, although you can use the gecko embedding interface directly. This would require you to write some C++ code.</p>
<p>As far as I know, the gtk webkit port is not available on Windows yet, and still appears to be undergoing a lot of change.</p>
<p>For an example of a cross-platform gecko embedding solution, check out <a href="http://www.getmiro.com/" rel="nofollow" title="miro">Miro</a>.
Miro is python, and they've written just a couple of C++ classes to embed gecko on Windows, while using gtkmozembed on linux.</p>
| 6
|
2009-03-11T21:06:20Z
|
[
"python",
"user-interface",
"gtk",
"webkit",
"mozilla"
] |
How to keep track of thread progress in Python without freezing the PyQt GUI?
| 569,650
|
<h2><strong>Questions:</strong></h2>
<ol>
<li>What is the best practice for
keeping track of a tread's
progress without locking the GUI
("Not Responding")?</li>
<li>Generally, what are the best practices for
threading as it applies to GUI
development?</li>
</ol>
<h2><strong>Question Background:</strong></h2>
<ul>
<li>I have a PyQt GUI for Windows.</li>
<li>It is used to process sets of HTML
documents.</li>
<li>It takes anywhere from three seconds
to three hours to process a set of
documents.</li>
<li>I want to be able to process
multiple sets at the same time.</li>
<li>I don't want the GUI to lock.</li>
<li>I'm looking at the threading module
to achieve this.</li>
<li>I am relatively new to threading.</li>
<li>The GUI has one progress bar.</li>
<li>I want it to display the progress of
the selected thread.</li>
<li>Display results of the selected
thread if it's finished.</li>
<li>I'm using Python 2.5.</li>
</ul>
<p><strong>My Idea:</strong> Have the threads emit a QtSignal when the progress is updated that triggers some function that updates the progress bar. Also signal when finished processing so results can be displayed.</p>
<pre><code>#NOTE: this is example code for my idea, you do not have
# to read this to answer the question(s).
import threading
from PyQt4 import QtCore, QtGui
import re
import copy
class ProcessingThread(threading.Thread, QtCore.QObject):
__pyqtSignals__ = ( "progressUpdated(str)",
"resultsReady(str)")
def __init__(self, docs):
self.docs = docs
self.progress = 0 #int between 0 and 100
self.results = []
threading.Thread.__init__(self)
def getResults(self):
return copy.deepcopy(self.results)
def run(self):
num_docs = len(self.docs) - 1
for i, doc in enumerate(self.docs):
processed_doc = self.processDoc(doc)
self.results.append(processed_doc)
new_progress = int((float(i)/num_docs)*100)
#emit signal only if progress has changed
if self.progress != new_progress:
self.emit(QtCore.SIGNAL("progressUpdated(str)"), self.getName())
self.progress = new_progress
if self.progress == 100:
self.emit(QtCore.SIGNAL("resultsReady(str)"), self.getName())
def processDoc(self, doc):
''' this is tivial for shortness sake '''
return re.findall('<a [^>]*>.*?</a>', doc)
class GuiApp(QtGui.QMainWindow):
def __init__(self):
self.processing_threads = {} #{'thread_name': Thread(processing_thread)}
self.progress_object = {} #{'thread_name': int(thread_progress)}
self.results_object = {} #{'thread_name': []}
self.selected_thread = '' #'thread_name'
def processDocs(self, docs):
#create new thread
p_thread = ProcessingThread(docs)
thread_name = "example_thread_name"
p_thread.setName(thread_name)
p_thread.start()
#add thread to dict of threads
self.processing_threads[thread_name] = p_thread
#init progress_object for this thread
self.progress_object[thread_name] = p_thread.progress
#connect thread signals to GuiApp functions
QtCore.QObject.connect(p_thread, QtCore.SIGNAL('progressUpdated(str)'), self.updateProgressObject(thread_name))
QtCore.QObject.connect(p_thread, QtCore.SIGNAL('resultsReady(str)'), self.updateResultsObject(thread_name))
def updateProgressObject(self, thread_name):
#update progress_object for all threads
self.progress_object[thread_name] = self.processing_threads[thread_name].progress
#update progress bar for selected thread
if self.selected_thread == thread_name:
self.setProgressBar(self.progress_object[self.selected_thread])
def updateResultsObject(self, thread_name):
#update results_object for thread with results
self.results_object[thread_name] = self.processing_threads[thread_name].getResults()
#update results widget for selected thread
try:
self.setResultsWidget(self.results_object[thread_name])
except KeyError:
self.setResultsWidget(None)
</code></pre>
<p>Any commentary on this approach (e.g. drawbacks, pitfalls, praises, etc.) will be appreciated.</p>
<h2><strong>Resolution:</strong></h2>
<p>I ended up using the QThread class and associated signals and slots to communicate between threads. This is primarily because my program already uses Qt/PyQt4 for the GUI objects/widgets. This solution also required fewer changes to my existing code to implement.</p>
<p>Here is a link to an applicable Qt article that explains how Qt handles threads and signals, <a href="http://www.linuxjournal.com/article/9602">http://www.linuxjournal.com/article/9602</a>. Excerpt below:</p>
<blockquote>
<p>Fortunately, Qt permits
signals and slots to be connected
across threadsâas long as the threads
are running their own event loops.
This is a much cleaner method of
communication compared to sending and
receiving events, because it avoids
all the bookkeeping and intermediate
QEvent-derived classes that become
necessary in any nontrivial
application. Communicating between
threads now becomes a matter of
connecting signals from one thread to
the slots in another, and the mutexing
and thread-safety issues of exchanging
data between threads are handled by
Qt.</p>
<p>Why is it necessary to run an event
loop within each thread to which you
want to connect signals? The reason
has to do with the inter-thread
communication mechanism used by Qt
when connecting signals from one
thread to the slot of another thread.
When such a connection is made, it is
referred to as a queued connection.
When signals are emitted through a
queued connection, the slot is invoked
the next time the destination object's
event loop is executed. If the slot
had instead been invoked directly by a
signal from another thread, that slot
would execute in the same context as
the calling thread. Normally, this is
not what you want (and especially not
what you want if you are using a
database connection, as the database
connection can be used only by the
thread that created it). The queued
connection properly dispatches the
signal to the thread object and
invokes its slot in its own context by
piggy-backing on the event system.
This is precisely what we want for
inter-thread communication in which
some of the threads are handling
database connections. The Qt
signal/slot mechanism is at root an
implementation of the inter-thread
event-passing scheme outlined above,
but with a much cleaner and
easier-to-use interface.</p>
</blockquote>
<p><strong>NOTE:</strong> <em>eliben</em> also has a good answer, and if I weren't using PyQt4, which handles thread-safety and mutexing, his solution would have been my choice.</p>
| 18
|
2009-02-20T14:00:06Z
| 570,770
|
<p>You are always going to have this problem in Python. Google GIL "global interpretor lock" for more background. There are two generally recommended ways to get around the problem that you are experiencing: use <a href="http://twistedmatrix.com/trac/" rel="nofollow">Twisted</a>, or use a module similar to the <a href="http://docs.python.org/library/multiprocessing.html" rel="nofollow">multiprocessing</a> module introduced in 2.5.</p>
<p>Twisted will require that you learn asynchronous programming techniques which may be confusing in the beginning but will be helpful if you ever need to write high throughput network apps and will be more beneficial to you in the long run.</p>
<p>The multiprocessing module will fork a new process and uses IPC to make it behave as if you had true threading. Only downside is that you would need python 2.5 installed which is fairly new and inst' included in most Linux distros or OSX by default.</p>
| 0
|
2009-02-20T18:43:44Z
|
[
"python",
"multithreading",
"user-interface",
"pyqt"
] |
How to keep track of thread progress in Python without freezing the PyQt GUI?
| 569,650
|
<h2><strong>Questions:</strong></h2>
<ol>
<li>What is the best practice for
keeping track of a tread's
progress without locking the GUI
("Not Responding")?</li>
<li>Generally, what are the best practices for
threading as it applies to GUI
development?</li>
</ol>
<h2><strong>Question Background:</strong></h2>
<ul>
<li>I have a PyQt GUI for Windows.</li>
<li>It is used to process sets of HTML
documents.</li>
<li>It takes anywhere from three seconds
to three hours to process a set of
documents.</li>
<li>I want to be able to process
multiple sets at the same time.</li>
<li>I don't want the GUI to lock.</li>
<li>I'm looking at the threading module
to achieve this.</li>
<li>I am relatively new to threading.</li>
<li>The GUI has one progress bar.</li>
<li>I want it to display the progress of
the selected thread.</li>
<li>Display results of the selected
thread if it's finished.</li>
<li>I'm using Python 2.5.</li>
</ul>
<p><strong>My Idea:</strong> Have the threads emit a QtSignal when the progress is updated that triggers some function that updates the progress bar. Also signal when finished processing so results can be displayed.</p>
<pre><code>#NOTE: this is example code for my idea, you do not have
# to read this to answer the question(s).
import threading
from PyQt4 import QtCore, QtGui
import re
import copy
class ProcessingThread(threading.Thread, QtCore.QObject):
__pyqtSignals__ = ( "progressUpdated(str)",
"resultsReady(str)")
def __init__(self, docs):
self.docs = docs
self.progress = 0 #int between 0 and 100
self.results = []
threading.Thread.__init__(self)
def getResults(self):
return copy.deepcopy(self.results)
def run(self):
num_docs = len(self.docs) - 1
for i, doc in enumerate(self.docs):
processed_doc = self.processDoc(doc)
self.results.append(processed_doc)
new_progress = int((float(i)/num_docs)*100)
#emit signal only if progress has changed
if self.progress != new_progress:
self.emit(QtCore.SIGNAL("progressUpdated(str)"), self.getName())
self.progress = new_progress
if self.progress == 100:
self.emit(QtCore.SIGNAL("resultsReady(str)"), self.getName())
def processDoc(self, doc):
''' this is tivial for shortness sake '''
return re.findall('<a [^>]*>.*?</a>', doc)
class GuiApp(QtGui.QMainWindow):
def __init__(self):
self.processing_threads = {} #{'thread_name': Thread(processing_thread)}
self.progress_object = {} #{'thread_name': int(thread_progress)}
self.results_object = {} #{'thread_name': []}
self.selected_thread = '' #'thread_name'
def processDocs(self, docs):
#create new thread
p_thread = ProcessingThread(docs)
thread_name = "example_thread_name"
p_thread.setName(thread_name)
p_thread.start()
#add thread to dict of threads
self.processing_threads[thread_name] = p_thread
#init progress_object for this thread
self.progress_object[thread_name] = p_thread.progress
#connect thread signals to GuiApp functions
QtCore.QObject.connect(p_thread, QtCore.SIGNAL('progressUpdated(str)'), self.updateProgressObject(thread_name))
QtCore.QObject.connect(p_thread, QtCore.SIGNAL('resultsReady(str)'), self.updateResultsObject(thread_name))
def updateProgressObject(self, thread_name):
#update progress_object for all threads
self.progress_object[thread_name] = self.processing_threads[thread_name].progress
#update progress bar for selected thread
if self.selected_thread == thread_name:
self.setProgressBar(self.progress_object[self.selected_thread])
def updateResultsObject(self, thread_name):
#update results_object for thread with results
self.results_object[thread_name] = self.processing_threads[thread_name].getResults()
#update results widget for selected thread
try:
self.setResultsWidget(self.results_object[thread_name])
except KeyError:
self.setResultsWidget(None)
</code></pre>
<p>Any commentary on this approach (e.g. drawbacks, pitfalls, praises, etc.) will be appreciated.</p>
<h2><strong>Resolution:</strong></h2>
<p>I ended up using the QThread class and associated signals and slots to communicate between threads. This is primarily because my program already uses Qt/PyQt4 for the GUI objects/widgets. This solution also required fewer changes to my existing code to implement.</p>
<p>Here is a link to an applicable Qt article that explains how Qt handles threads and signals, <a href="http://www.linuxjournal.com/article/9602">http://www.linuxjournal.com/article/9602</a>. Excerpt below:</p>
<blockquote>
<p>Fortunately, Qt permits
signals and slots to be connected
across threadsâas long as the threads
are running their own event loops.
This is a much cleaner method of
communication compared to sending and
receiving events, because it avoids
all the bookkeeping and intermediate
QEvent-derived classes that become
necessary in any nontrivial
application. Communicating between
threads now becomes a matter of
connecting signals from one thread to
the slots in another, and the mutexing
and thread-safety issues of exchanging
data between threads are handled by
Qt.</p>
<p>Why is it necessary to run an event
loop within each thread to which you
want to connect signals? The reason
has to do with the inter-thread
communication mechanism used by Qt
when connecting signals from one
thread to the slot of another thread.
When such a connection is made, it is
referred to as a queued connection.
When signals are emitted through a
queued connection, the slot is invoked
the next time the destination object's
event loop is executed. If the slot
had instead been invoked directly by a
signal from another thread, that slot
would execute in the same context as
the calling thread. Normally, this is
not what you want (and especially not
what you want if you are using a
database connection, as the database
connection can be used only by the
thread that created it). The queued
connection properly dispatches the
signal to the thread object and
invokes its slot in its own context by
piggy-backing on the event system.
This is precisely what we want for
inter-thread communication in which
some of the threads are handling
database connections. The Qt
signal/slot mechanism is at root an
implementation of the inter-thread
event-passing scheme outlined above,
but with a much cleaner and
easier-to-use interface.</p>
</blockquote>
<p><strong>NOTE:</strong> <em>eliben</em> also has a good answer, and if I weren't using PyQt4, which handles thread-safety and mutexing, his solution would have been my choice.</p>
| 18
|
2009-02-20T14:00:06Z
| 572,456
|
<p>If your method "processDoc" doesn't change any other data (just looks for some data and return it and don't change variables or properties of parent class) you may use Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS macroses ( <a href="http://www.python.org/doc/2.4/api/threads.html" rel="nofollow">see here for details</a> ) in it. So the document will be processed in thread which will not lock the interpreter and UI will be updated.</p>
| 1
|
2009-02-21T05:44:14Z
|
[
"python",
"multithreading",
"user-interface",
"pyqt"
] |
How to keep track of thread progress in Python without freezing the PyQt GUI?
| 569,650
|
<h2><strong>Questions:</strong></h2>
<ol>
<li>What is the best practice for
keeping track of a tread's
progress without locking the GUI
("Not Responding")?</li>
<li>Generally, what are the best practices for
threading as it applies to GUI
development?</li>
</ol>
<h2><strong>Question Background:</strong></h2>
<ul>
<li>I have a PyQt GUI for Windows.</li>
<li>It is used to process sets of HTML
documents.</li>
<li>It takes anywhere from three seconds
to three hours to process a set of
documents.</li>
<li>I want to be able to process
multiple sets at the same time.</li>
<li>I don't want the GUI to lock.</li>
<li>I'm looking at the threading module
to achieve this.</li>
<li>I am relatively new to threading.</li>
<li>The GUI has one progress bar.</li>
<li>I want it to display the progress of
the selected thread.</li>
<li>Display results of the selected
thread if it's finished.</li>
<li>I'm using Python 2.5.</li>
</ul>
<p><strong>My Idea:</strong> Have the threads emit a QtSignal when the progress is updated that triggers some function that updates the progress bar. Also signal when finished processing so results can be displayed.</p>
<pre><code>#NOTE: this is example code for my idea, you do not have
# to read this to answer the question(s).
import threading
from PyQt4 import QtCore, QtGui
import re
import copy
class ProcessingThread(threading.Thread, QtCore.QObject):
__pyqtSignals__ = ( "progressUpdated(str)",
"resultsReady(str)")
def __init__(self, docs):
self.docs = docs
self.progress = 0 #int between 0 and 100
self.results = []
threading.Thread.__init__(self)
def getResults(self):
return copy.deepcopy(self.results)
def run(self):
num_docs = len(self.docs) - 1
for i, doc in enumerate(self.docs):
processed_doc = self.processDoc(doc)
self.results.append(processed_doc)
new_progress = int((float(i)/num_docs)*100)
#emit signal only if progress has changed
if self.progress != new_progress:
self.emit(QtCore.SIGNAL("progressUpdated(str)"), self.getName())
self.progress = new_progress
if self.progress == 100:
self.emit(QtCore.SIGNAL("resultsReady(str)"), self.getName())
def processDoc(self, doc):
''' this is tivial for shortness sake '''
return re.findall('<a [^>]*>.*?</a>', doc)
class GuiApp(QtGui.QMainWindow):
def __init__(self):
self.processing_threads = {} #{'thread_name': Thread(processing_thread)}
self.progress_object = {} #{'thread_name': int(thread_progress)}
self.results_object = {} #{'thread_name': []}
self.selected_thread = '' #'thread_name'
def processDocs(self, docs):
#create new thread
p_thread = ProcessingThread(docs)
thread_name = "example_thread_name"
p_thread.setName(thread_name)
p_thread.start()
#add thread to dict of threads
self.processing_threads[thread_name] = p_thread
#init progress_object for this thread
self.progress_object[thread_name] = p_thread.progress
#connect thread signals to GuiApp functions
QtCore.QObject.connect(p_thread, QtCore.SIGNAL('progressUpdated(str)'), self.updateProgressObject(thread_name))
QtCore.QObject.connect(p_thread, QtCore.SIGNAL('resultsReady(str)'), self.updateResultsObject(thread_name))
def updateProgressObject(self, thread_name):
#update progress_object for all threads
self.progress_object[thread_name] = self.processing_threads[thread_name].progress
#update progress bar for selected thread
if self.selected_thread == thread_name:
self.setProgressBar(self.progress_object[self.selected_thread])
def updateResultsObject(self, thread_name):
#update results_object for thread with results
self.results_object[thread_name] = self.processing_threads[thread_name].getResults()
#update results widget for selected thread
try:
self.setResultsWidget(self.results_object[thread_name])
except KeyError:
self.setResultsWidget(None)
</code></pre>
<p>Any commentary on this approach (e.g. drawbacks, pitfalls, praises, etc.) will be appreciated.</p>
<h2><strong>Resolution:</strong></h2>
<p>I ended up using the QThread class and associated signals and slots to communicate between threads. This is primarily because my program already uses Qt/PyQt4 for the GUI objects/widgets. This solution also required fewer changes to my existing code to implement.</p>
<p>Here is a link to an applicable Qt article that explains how Qt handles threads and signals, <a href="http://www.linuxjournal.com/article/9602">http://www.linuxjournal.com/article/9602</a>. Excerpt below:</p>
<blockquote>
<p>Fortunately, Qt permits
signals and slots to be connected
across threadsâas long as the threads
are running their own event loops.
This is a much cleaner method of
communication compared to sending and
receiving events, because it avoids
all the bookkeeping and intermediate
QEvent-derived classes that become
necessary in any nontrivial
application. Communicating between
threads now becomes a matter of
connecting signals from one thread to
the slots in another, and the mutexing
and thread-safety issues of exchanging
data between threads are handled by
Qt.</p>
<p>Why is it necessary to run an event
loop within each thread to which you
want to connect signals? The reason
has to do with the inter-thread
communication mechanism used by Qt
when connecting signals from one
thread to the slot of another thread.
When such a connection is made, it is
referred to as a queued connection.
When signals are emitted through a
queued connection, the slot is invoked
the next time the destination object's
event loop is executed. If the slot
had instead been invoked directly by a
signal from another thread, that slot
would execute in the same context as
the calling thread. Normally, this is
not what you want (and especially not
what you want if you are using a
database connection, as the database
connection can be used only by the
thread that created it). The queued
connection properly dispatches the
signal to the thread object and
invokes its slot in its own context by
piggy-backing on the event system.
This is precisely what we want for
inter-thread communication in which
some of the threads are handling
database connections. The Qt
signal/slot mechanism is at root an
implementation of the inter-thread
event-passing scheme outlined above,
but with a much cleaner and
easier-to-use interface.</p>
</blockquote>
<p><strong>NOTE:</strong> <em>eliben</em> also has a good answer, and if I weren't using PyQt4, which handles thread-safety and mutexing, his solution would have been my choice.</p>
| 18
|
2009-02-20T14:00:06Z
| 572,577
|
<p>I recommend you to use Queue instead of signaling. Personally I find it a much more robust and understandable way of programming, because it's more synchronous.</p>
<p>Threads should get "jobs" from a Queue, and put back results on another Queue. Yet a third Queue can be used by the threads for notifications and messages, like errors and "progress reports". Once you structure your code this way, it becomes much simpler to manage.</p>
<p>This way, a single "job Queue" and "result Queue" can also be used by a group of worker threads, it routes all the information from the threads into the main GUI thread.</p>
| 4
|
2009-02-21T07:18:06Z
|
[
"python",
"multithreading",
"user-interface",
"pyqt"
] |
How to keep track of thread progress in Python without freezing the PyQt GUI?
| 569,650
|
<h2><strong>Questions:</strong></h2>
<ol>
<li>What is the best practice for
keeping track of a tread's
progress without locking the GUI
("Not Responding")?</li>
<li>Generally, what are the best practices for
threading as it applies to GUI
development?</li>
</ol>
<h2><strong>Question Background:</strong></h2>
<ul>
<li>I have a PyQt GUI for Windows.</li>
<li>It is used to process sets of HTML
documents.</li>
<li>It takes anywhere from three seconds
to three hours to process a set of
documents.</li>
<li>I want to be able to process
multiple sets at the same time.</li>
<li>I don't want the GUI to lock.</li>
<li>I'm looking at the threading module
to achieve this.</li>
<li>I am relatively new to threading.</li>
<li>The GUI has one progress bar.</li>
<li>I want it to display the progress of
the selected thread.</li>
<li>Display results of the selected
thread if it's finished.</li>
<li>I'm using Python 2.5.</li>
</ul>
<p><strong>My Idea:</strong> Have the threads emit a QtSignal when the progress is updated that triggers some function that updates the progress bar. Also signal when finished processing so results can be displayed.</p>
<pre><code>#NOTE: this is example code for my idea, you do not have
# to read this to answer the question(s).
import threading
from PyQt4 import QtCore, QtGui
import re
import copy
class ProcessingThread(threading.Thread, QtCore.QObject):
__pyqtSignals__ = ( "progressUpdated(str)",
"resultsReady(str)")
def __init__(self, docs):
self.docs = docs
self.progress = 0 #int between 0 and 100
self.results = []
threading.Thread.__init__(self)
def getResults(self):
return copy.deepcopy(self.results)
def run(self):
num_docs = len(self.docs) - 1
for i, doc in enumerate(self.docs):
processed_doc = self.processDoc(doc)
self.results.append(processed_doc)
new_progress = int((float(i)/num_docs)*100)
#emit signal only if progress has changed
if self.progress != new_progress:
self.emit(QtCore.SIGNAL("progressUpdated(str)"), self.getName())
self.progress = new_progress
if self.progress == 100:
self.emit(QtCore.SIGNAL("resultsReady(str)"), self.getName())
def processDoc(self, doc):
''' this is tivial for shortness sake '''
return re.findall('<a [^>]*>.*?</a>', doc)
class GuiApp(QtGui.QMainWindow):
def __init__(self):
self.processing_threads = {} #{'thread_name': Thread(processing_thread)}
self.progress_object = {} #{'thread_name': int(thread_progress)}
self.results_object = {} #{'thread_name': []}
self.selected_thread = '' #'thread_name'
def processDocs(self, docs):
#create new thread
p_thread = ProcessingThread(docs)
thread_name = "example_thread_name"
p_thread.setName(thread_name)
p_thread.start()
#add thread to dict of threads
self.processing_threads[thread_name] = p_thread
#init progress_object for this thread
self.progress_object[thread_name] = p_thread.progress
#connect thread signals to GuiApp functions
QtCore.QObject.connect(p_thread, QtCore.SIGNAL('progressUpdated(str)'), self.updateProgressObject(thread_name))
QtCore.QObject.connect(p_thread, QtCore.SIGNAL('resultsReady(str)'), self.updateResultsObject(thread_name))
def updateProgressObject(self, thread_name):
#update progress_object for all threads
self.progress_object[thread_name] = self.processing_threads[thread_name].progress
#update progress bar for selected thread
if self.selected_thread == thread_name:
self.setProgressBar(self.progress_object[self.selected_thread])
def updateResultsObject(self, thread_name):
#update results_object for thread with results
self.results_object[thread_name] = self.processing_threads[thread_name].getResults()
#update results widget for selected thread
try:
self.setResultsWidget(self.results_object[thread_name])
except KeyError:
self.setResultsWidget(None)
</code></pre>
<p>Any commentary on this approach (e.g. drawbacks, pitfalls, praises, etc.) will be appreciated.</p>
<h2><strong>Resolution:</strong></h2>
<p>I ended up using the QThread class and associated signals and slots to communicate between threads. This is primarily because my program already uses Qt/PyQt4 for the GUI objects/widgets. This solution also required fewer changes to my existing code to implement.</p>
<p>Here is a link to an applicable Qt article that explains how Qt handles threads and signals, <a href="http://www.linuxjournal.com/article/9602">http://www.linuxjournal.com/article/9602</a>. Excerpt below:</p>
<blockquote>
<p>Fortunately, Qt permits
signals and slots to be connected
across threadsâas long as the threads
are running their own event loops.
This is a much cleaner method of
communication compared to sending and
receiving events, because it avoids
all the bookkeeping and intermediate
QEvent-derived classes that become
necessary in any nontrivial
application. Communicating between
threads now becomes a matter of
connecting signals from one thread to
the slots in another, and the mutexing
and thread-safety issues of exchanging
data between threads are handled by
Qt.</p>
<p>Why is it necessary to run an event
loop within each thread to which you
want to connect signals? The reason
has to do with the inter-thread
communication mechanism used by Qt
when connecting signals from one
thread to the slot of another thread.
When such a connection is made, it is
referred to as a queued connection.
When signals are emitted through a
queued connection, the slot is invoked
the next time the destination object's
event loop is executed. If the slot
had instead been invoked directly by a
signal from another thread, that slot
would execute in the same context as
the calling thread. Normally, this is
not what you want (and especially not
what you want if you are using a
database connection, as the database
connection can be used only by the
thread that created it). The queued
connection properly dispatches the
signal to the thread object and
invokes its slot in its own context by
piggy-backing on the event system.
This is precisely what we want for
inter-thread communication in which
some of the threads are handling
database connections. The Qt
signal/slot mechanism is at root an
implementation of the inter-thread
event-passing scheme outlined above,
but with a much cleaner and
easier-to-use interface.</p>
</blockquote>
<p><strong>NOTE:</strong> <em>eliben</em> also has a good answer, and if I weren't using PyQt4, which handles thread-safety and mutexing, his solution would have been my choice.</p>
| 18
|
2009-02-20T14:00:06Z
| 574,130
|
<p>If you want to use signals to indicate progress to the main thread then you should really be using PyQt's QThread class instead of the Thread class from Python's threading module.</p>
<p>A simple example which uses QThread, signals and slots can be found on the PyQt Wiki:</p>
<p><a href="https://wiki.python.org/moin/PyQt/Threading,_Signals_and_Slots" rel="nofollow">https://wiki.python.org/moin/PyQt/Threading,_Signals_and_Slots</a></p>
| 10
|
2009-02-22T01:33:00Z
|
[
"python",
"multithreading",
"user-interface",
"pyqt"
] |
How to keep track of thread progress in Python without freezing the PyQt GUI?
| 569,650
|
<h2><strong>Questions:</strong></h2>
<ol>
<li>What is the best practice for
keeping track of a tread's
progress without locking the GUI
("Not Responding")?</li>
<li>Generally, what are the best practices for
threading as it applies to GUI
development?</li>
</ol>
<h2><strong>Question Background:</strong></h2>
<ul>
<li>I have a PyQt GUI for Windows.</li>
<li>It is used to process sets of HTML
documents.</li>
<li>It takes anywhere from three seconds
to three hours to process a set of
documents.</li>
<li>I want to be able to process
multiple sets at the same time.</li>
<li>I don't want the GUI to lock.</li>
<li>I'm looking at the threading module
to achieve this.</li>
<li>I am relatively new to threading.</li>
<li>The GUI has one progress bar.</li>
<li>I want it to display the progress of
the selected thread.</li>
<li>Display results of the selected
thread if it's finished.</li>
<li>I'm using Python 2.5.</li>
</ul>
<p><strong>My Idea:</strong> Have the threads emit a QtSignal when the progress is updated that triggers some function that updates the progress bar. Also signal when finished processing so results can be displayed.</p>
<pre><code>#NOTE: this is example code for my idea, you do not have
# to read this to answer the question(s).
import threading
from PyQt4 import QtCore, QtGui
import re
import copy
class ProcessingThread(threading.Thread, QtCore.QObject):
__pyqtSignals__ = ( "progressUpdated(str)",
"resultsReady(str)")
def __init__(self, docs):
self.docs = docs
self.progress = 0 #int between 0 and 100
self.results = []
threading.Thread.__init__(self)
def getResults(self):
return copy.deepcopy(self.results)
def run(self):
num_docs = len(self.docs) - 1
for i, doc in enumerate(self.docs):
processed_doc = self.processDoc(doc)
self.results.append(processed_doc)
new_progress = int((float(i)/num_docs)*100)
#emit signal only if progress has changed
if self.progress != new_progress:
self.emit(QtCore.SIGNAL("progressUpdated(str)"), self.getName())
self.progress = new_progress
if self.progress == 100:
self.emit(QtCore.SIGNAL("resultsReady(str)"), self.getName())
def processDoc(self, doc):
''' this is tivial for shortness sake '''
return re.findall('<a [^>]*>.*?</a>', doc)
class GuiApp(QtGui.QMainWindow):
def __init__(self):
self.processing_threads = {} #{'thread_name': Thread(processing_thread)}
self.progress_object = {} #{'thread_name': int(thread_progress)}
self.results_object = {} #{'thread_name': []}
self.selected_thread = '' #'thread_name'
def processDocs(self, docs):
#create new thread
p_thread = ProcessingThread(docs)
thread_name = "example_thread_name"
p_thread.setName(thread_name)
p_thread.start()
#add thread to dict of threads
self.processing_threads[thread_name] = p_thread
#init progress_object for this thread
self.progress_object[thread_name] = p_thread.progress
#connect thread signals to GuiApp functions
QtCore.QObject.connect(p_thread, QtCore.SIGNAL('progressUpdated(str)'), self.updateProgressObject(thread_name))
QtCore.QObject.connect(p_thread, QtCore.SIGNAL('resultsReady(str)'), self.updateResultsObject(thread_name))
def updateProgressObject(self, thread_name):
#update progress_object for all threads
self.progress_object[thread_name] = self.processing_threads[thread_name].progress
#update progress bar for selected thread
if self.selected_thread == thread_name:
self.setProgressBar(self.progress_object[self.selected_thread])
def updateResultsObject(self, thread_name):
#update results_object for thread with results
self.results_object[thread_name] = self.processing_threads[thread_name].getResults()
#update results widget for selected thread
try:
self.setResultsWidget(self.results_object[thread_name])
except KeyError:
self.setResultsWidget(None)
</code></pre>
<p>Any commentary on this approach (e.g. drawbacks, pitfalls, praises, etc.) will be appreciated.</p>
<h2><strong>Resolution:</strong></h2>
<p>I ended up using the QThread class and associated signals and slots to communicate between threads. This is primarily because my program already uses Qt/PyQt4 for the GUI objects/widgets. This solution also required fewer changes to my existing code to implement.</p>
<p>Here is a link to an applicable Qt article that explains how Qt handles threads and signals, <a href="http://www.linuxjournal.com/article/9602">http://www.linuxjournal.com/article/9602</a>. Excerpt below:</p>
<blockquote>
<p>Fortunately, Qt permits
signals and slots to be connected
across threadsâas long as the threads
are running their own event loops.
This is a much cleaner method of
communication compared to sending and
receiving events, because it avoids
all the bookkeeping and intermediate
QEvent-derived classes that become
necessary in any nontrivial
application. Communicating between
threads now becomes a matter of
connecting signals from one thread to
the slots in another, and the mutexing
and thread-safety issues of exchanging
data between threads are handled by
Qt.</p>
<p>Why is it necessary to run an event
loop within each thread to which you
want to connect signals? The reason
has to do with the inter-thread
communication mechanism used by Qt
when connecting signals from one
thread to the slot of another thread.
When such a connection is made, it is
referred to as a queued connection.
When signals are emitted through a
queued connection, the slot is invoked
the next time the destination object's
event loop is executed. If the slot
had instead been invoked directly by a
signal from another thread, that slot
would execute in the same context as
the calling thread. Normally, this is
not what you want (and especially not
what you want if you are using a
database connection, as the database
connection can be used only by the
thread that created it). The queued
connection properly dispatches the
signal to the thread object and
invokes its slot in its own context by
piggy-backing on the event system.
This is precisely what we want for
inter-thread communication in which
some of the threads are handling
database connections. The Qt
signal/slot mechanism is at root an
implementation of the inter-thread
event-passing scheme outlined above,
but with a much cleaner and
easier-to-use interface.</p>
</blockquote>
<p><strong>NOTE:</strong> <em>eliben</em> also has a good answer, and if I weren't using PyQt4, which handles thread-safety and mutexing, his solution would have been my choice.</p>
| 18
|
2009-02-20T14:00:06Z
| 1,020,072
|
<p>Native python queues won't work because you have to block on queue get(), which bungs up your UI. </p>
<p>Qt essentially implements a queuing system on the inside for cross thread communication. Try this call from any thread to post a call to a slot.</p>
<p>QtCore.QMetaObject.invokeMethod()</p>
<p>It's clunky and is poorly documented, but it should do what you want even from from a non-Qt thread.</p>
<p>You can also use event machinery for this. See QApplication (or QCoreApplication) for a method named something like "post".</p>
<p>Edit: Here's a more complete example...</p>
<p>I created my own class based on QWidget. It has a slot that accepts a string; I define it like this:</p>
<pre><code>@QtCore.pyqtSlot(str)
def add_text(self, text):
...
</code></pre>
<p>Later, I create an instance of this widget in the main GUI thread. From the main GUI thread or any other thread (knock on wood) I can call:</p>
<pre><code>QtCore.QMetaObject.invokeMethod(mywidget, "add_text", QtCore.Q_ARG(str,"hello world"))
</code></pre>
<p>Clunky, but it gets you there.</p>
<p>Dan.</p>
| 5
|
2009-06-19T21:21:59Z
|
[
"python",
"multithreading",
"user-interface",
"pyqt"
] |
Lazy choices in Django form
| 569,696
|
<p>I have a Django my_forms.py like this:</p>
<pre><code>class CarSearchForm(forms.Form):
# lots of fields like this
bodystyle = forms.ChoiceField(choices=bodystyle_choices())
</code></pre>
<p>Each choice is e.g. ("Saloon", "Saloon (15 cars)"). So the choices are computed by this function.</p>
<pre><code>def bodystyle_choices():
return [(bodystyle.bodystyle_name, '%s (%s cars)' %
(bodystyle.bodystyle_name, bodystyle.car_set.count()))
for bodystyle in Bodystyle.objects.all()]
</code></pre>
<p>My problem is the choices functions are getting executed every time I merely import my_forms.py. I think this is due to the way Django declares its fields: in the class but not in a class method. Which is fine but my views.py imports my_forms.py so the choices lookups are done on every request no matter which view is used.</p>
<p>I thought that maybe putting choices=bodystyle_choices with no bracket would work, but I get: <pre>'function' object is not iterable</pre></p>
<p>Obviously I can use caching and put the "import my_forms" just in the view functions required but that doesn't change the main point: my choices need to be lazy!</p>
| 16
|
2009-02-20T14:18:37Z
| 569,748
|
<p>Try using a ModelChoiceField instead of a simple ChoiceField. I think you will be able to achieve what you want by tweaking your models a bit. Take a look at the <a href="http://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield">docs</a> for more.</p>
<p>I would also add that ModelChoiceFields are <code>lazy</code> by default :)</p>
| 16
|
2009-02-20T14:33:58Z
|
[
"python",
"django",
"forms",
"lazy-evaluation"
] |
Lazy choices in Django form
| 569,696
|
<p>I have a Django my_forms.py like this:</p>
<pre><code>class CarSearchForm(forms.Form):
# lots of fields like this
bodystyle = forms.ChoiceField(choices=bodystyle_choices())
</code></pre>
<p>Each choice is e.g. ("Saloon", "Saloon (15 cars)"). So the choices are computed by this function.</p>
<pre><code>def bodystyle_choices():
return [(bodystyle.bodystyle_name, '%s (%s cars)' %
(bodystyle.bodystyle_name, bodystyle.car_set.count()))
for bodystyle in Bodystyle.objects.all()]
</code></pre>
<p>My problem is the choices functions are getting executed every time I merely import my_forms.py. I think this is due to the way Django declares its fields: in the class but not in a class method. Which is fine but my views.py imports my_forms.py so the choices lookups are done on every request no matter which view is used.</p>
<p>I thought that maybe putting choices=bodystyle_choices with no bracket would work, but I get: <pre>'function' object is not iterable</pre></p>
<p>Obviously I can use caching and put the "import my_forms" just in the view functions required but that doesn't change the main point: my choices need to be lazy!</p>
| 16
|
2009-02-20T14:18:37Z
| 845,140
|
<p>You can use the "lazy" function :)</p>
<pre><code>from django.utils.functional import lazy
class CarSearchForm(forms.Form):
# lots of fields like this
bodystyle = forms.ChoiceField(choices=lazy(bodystyle_choices, tuple)())
</code></pre>
<p>very nice util function !</p>
| 39
|
2009-05-10T11:21:16Z
|
[
"python",
"django",
"forms",
"lazy-evaluation"
] |
Lazy choices in Django form
| 569,696
|
<p>I have a Django my_forms.py like this:</p>
<pre><code>class CarSearchForm(forms.Form):
# lots of fields like this
bodystyle = forms.ChoiceField(choices=bodystyle_choices())
</code></pre>
<p>Each choice is e.g. ("Saloon", "Saloon (15 cars)"). So the choices are computed by this function.</p>
<pre><code>def bodystyle_choices():
return [(bodystyle.bodystyle_name, '%s (%s cars)' %
(bodystyle.bodystyle_name, bodystyle.car_set.count()))
for bodystyle in Bodystyle.objects.all()]
</code></pre>
<p>My problem is the choices functions are getting executed every time I merely import my_forms.py. I think this is due to the way Django declares its fields: in the class but not in a class method. Which is fine but my views.py imports my_forms.py so the choices lookups are done on every request no matter which view is used.</p>
<p>I thought that maybe putting choices=bodystyle_choices with no bracket would work, but I get: <pre>'function' object is not iterable</pre></p>
<p>Obviously I can use caching and put the "import my_forms" just in the view functions required but that doesn't change the main point: my choices need to be lazy!</p>
| 16
|
2009-02-20T14:18:37Z
| 29,517,662
|
<p>Expanding on what Baishampayan Ghose said, this should probably be considered the most direct approach:</p>
<pre><code>from django.forms import ModelChoiceField
class BodystyleChoiceField(ModelChoiceField):
def label_from_instance(self, obj):
return '%s (%s cars)' % (obj.bodystyle_name, obj.car_set.count()))
class CarSearchForm(forms.Form):
bodystyle = BodystyleChoiceField(queryset=Bodystyle.objects.all())
</code></pre>
<p>Docs are here: <a href="https://docs.djangoproject.com/en/1.8/ref/forms/fields/#modelchoicefield" rel="nofollow">https://docs.djangoproject.com/en/1.8/ref/forms/fields/#modelchoicefield</a></p>
<p>This has the benefit that <code>form.cleaned_data['bodystyle']</code> is a <code>Bodystyle</code> instance instead of a string.</p>
| 0
|
2015-04-08T14:32:53Z
|
[
"python",
"django",
"forms",
"lazy-evaluation"
] |
How to tell for which object attribute pickle fails?
| 569,754
|
<p>When you pickle an object that has some attributes which cannot be pickled it will fail with a generic error message like:</p>
<pre><code>PicklingError: Can't pickle <type 'instancemethod'>: attribute lookup __builtin__.instancemethod failed
</code></pre>
<p>Is there any way to tell which attribute caused the exception? I am using Python 2.5.2.</p>
<p>Even though I understand in principle the root cause of the problem (e.g. in the above example having an instance method) it can still be very hard to <em>exactly pinpoint it</em>. In my case I already defined a custom <code>__getstate__</code> method, but forgot about a critical attribute. This happened in a complicated structure of nested objects, so it took me a while to identify the bad attribute.</p>
<p>As requested, here is one simple example were pickle intentionally fails:</p>
<pre><code>import cPickle as pickle
import new
class Test(object):
pass
def test_func(self):
pass
test = Test()
pickle.dumps(test)
print "now with instancemethod..."
test.test_meth = new.instancemethod(test_func, test)
pickle.dumps(test)
</code></pre>
<p>This is the output:</p>
<pre><code>now with instancemethod...
Traceback (most recent call last):
File "/home/wilbert/develop/workspace/Playground/src/misc/picklefail.py", line 15, in <module>
pickle.dumps(test)
File "/home/wilbert/lib/python2.5/copy_reg.py", line 69, in _reduce_ex
raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle instancemethod objects
</code></pre>
<p>Unfortunately there is no hint that the attribute <code>test_meth</code> causes the problem.</p>
| 28
|
2009-02-20T14:36:09Z
| 570,910
|
<p>You could file a bug against Python for not including more helpful error messages. In the meantime, modify the <code>_reduce_ex()</code> function in <code>copy_reg.py</code>.</p>
<pre><code>if base is self.__class__:
print self # new
raise TypeError, "can't pickle %s objects" % base.__name__
</code></pre>
<p>Output:</p>
<pre><code><bound method ?.test_func of <__main__.Test object at 0xb7f4230c>>
Traceback (most recent call last):
File "nopickle.py", line 14, in ?
pickle.dumps(test)
File "/usr/lib/python2.4/copy_reg.py", line 69, in _reduce_ex
raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle instancemethod objects
</code></pre>
| 14
|
2009-02-20T19:30:46Z
|
[
"python",
"serialization"
] |
How to tell for which object attribute pickle fails?
| 569,754
|
<p>When you pickle an object that has some attributes which cannot be pickled it will fail with a generic error message like:</p>
<pre><code>PicklingError: Can't pickle <type 'instancemethod'>: attribute lookup __builtin__.instancemethod failed
</code></pre>
<p>Is there any way to tell which attribute caused the exception? I am using Python 2.5.2.</p>
<p>Even though I understand in principle the root cause of the problem (e.g. in the above example having an instance method) it can still be very hard to <em>exactly pinpoint it</em>. In my case I already defined a custom <code>__getstate__</code> method, but forgot about a critical attribute. This happened in a complicated structure of nested objects, so it took me a while to identify the bad attribute.</p>
<p>As requested, here is one simple example were pickle intentionally fails:</p>
<pre><code>import cPickle as pickle
import new
class Test(object):
pass
def test_func(self):
pass
test = Test()
pickle.dumps(test)
print "now with instancemethod..."
test.test_meth = new.instancemethod(test_func, test)
pickle.dumps(test)
</code></pre>
<p>This is the output:</p>
<pre><code>now with instancemethod...
Traceback (most recent call last):
File "/home/wilbert/develop/workspace/Playground/src/misc/picklefail.py", line 15, in <module>
pickle.dumps(test)
File "/home/wilbert/lib/python2.5/copy_reg.py", line 69, in _reduce_ex
raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle instancemethod objects
</code></pre>
<p>Unfortunately there is no hint that the attribute <code>test_meth</code> causes the problem.</p>
| 28
|
2009-02-20T14:36:09Z
| 7,218,986
|
<p>I had the same problem as you, but my classes were a bit more complicated (i.e. a large tree of similar objects) so the printing didn't help much so I hacked together a helper function. It is not complete and is only intended for use with pickling protocol 2:
It was enough so I could locate my problems. If you want to extend it to cover everything, the protocol is described at <a href="http://www.python.org/dev/peps/pep-0307/">http://www.python.org/dev/peps/pep-0307/</a> i've made this post editable so everybody can update the code.</p>
<pre><code>import pickle
def get_pickling_errors(obj,seen=None):
if seen == None:
seen = []
try:
state = obj.__getstate__()
except AttributeError:
return
if state == None:
return
if isinstance(state,tuple):
if not isinstance(state[0],dict):
state=state[1]
else:
state=state[0].update(state[1])
result = {}
for i in state:
try:
pickle.dumps(state[i],protocol=2)
except pickle.PicklingError:
if not state[i] in seen:
seen.append(state[i])
result[i]=get_pickling_errors(state[i],seen)
return result
</code></pre>
<p>An example of the usage where K is the object that doesn't pickle</p>
<pre><code>>>> get_pickling_errors(K)
{'_gen': {}, '_base': {'_gens': None}}
</code></pre>
<p>This means that the attibute K._gen is not picklable and the same goes for K._base._gens.</p>
| 7
|
2011-08-28T04:04:50Z
|
[
"python",
"serialization"
] |
How to tell for which object attribute pickle fails?
| 569,754
|
<p>When you pickle an object that has some attributes which cannot be pickled it will fail with a generic error message like:</p>
<pre><code>PicklingError: Can't pickle <type 'instancemethod'>: attribute lookup __builtin__.instancemethod failed
</code></pre>
<p>Is there any way to tell which attribute caused the exception? I am using Python 2.5.2.</p>
<p>Even though I understand in principle the root cause of the problem (e.g. in the above example having an instance method) it can still be very hard to <em>exactly pinpoint it</em>. In my case I already defined a custom <code>__getstate__</code> method, but forgot about a critical attribute. This happened in a complicated structure of nested objects, so it took me a while to identify the bad attribute.</p>
<p>As requested, here is one simple example were pickle intentionally fails:</p>
<pre><code>import cPickle as pickle
import new
class Test(object):
pass
def test_func(self):
pass
test = Test()
pickle.dumps(test)
print "now with instancemethod..."
test.test_meth = new.instancemethod(test_func, test)
pickle.dumps(test)
</code></pre>
<p>This is the output:</p>
<pre><code>now with instancemethod...
Traceback (most recent call last):
File "/home/wilbert/develop/workspace/Playground/src/misc/picklefail.py", line 15, in <module>
pickle.dumps(test)
File "/home/wilbert/lib/python2.5/copy_reg.py", line 69, in _reduce_ex
raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle instancemethod objects
</code></pre>
<p>Unfortunately there is no hint that the attribute <code>test_meth</code> causes the problem.</p>
| 28
|
2009-02-20T14:36:09Z
| 7,843,281
|
<p>I have found that if you subclass Pickler and wrap the Pickler.save() method in a try, except block</p>
<pre><code>import pickle
class MyPickler (pickle.Pickler):
def save(self, obj):
try:
pickle.Pickler.save(self, obj)
except Exception, e:
import pdb;pdb.set_trace()
</code></pre>
<p>Then call it like so</p>
<pre><code>import StringIO
output = StringIO.StringIO()
MyPickler(output).dump(thingee)
</code></pre>
| 3
|
2011-10-20T23:01:38Z
|
[
"python",
"serialization"
] |
How to tell for which object attribute pickle fails?
| 569,754
|
<p>When you pickle an object that has some attributes which cannot be pickled it will fail with a generic error message like:</p>
<pre><code>PicklingError: Can't pickle <type 'instancemethod'>: attribute lookup __builtin__.instancemethod failed
</code></pre>
<p>Is there any way to tell which attribute caused the exception? I am using Python 2.5.2.</p>
<p>Even though I understand in principle the root cause of the problem (e.g. in the above example having an instance method) it can still be very hard to <em>exactly pinpoint it</em>. In my case I already defined a custom <code>__getstate__</code> method, but forgot about a critical attribute. This happened in a complicated structure of nested objects, so it took me a while to identify the bad attribute.</p>
<p>As requested, here is one simple example were pickle intentionally fails:</p>
<pre><code>import cPickle as pickle
import new
class Test(object):
pass
def test_func(self):
pass
test = Test()
pickle.dumps(test)
print "now with instancemethod..."
test.test_meth = new.instancemethod(test_func, test)
pickle.dumps(test)
</code></pre>
<p>This is the output:</p>
<pre><code>now with instancemethod...
Traceback (most recent call last):
File "/home/wilbert/develop/workspace/Playground/src/misc/picklefail.py", line 15, in <module>
pickle.dumps(test)
File "/home/wilbert/lib/python2.5/copy_reg.py", line 69, in _reduce_ex
raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle instancemethod objects
</code></pre>
<p>Unfortunately there is no hint that the attribute <code>test_meth</code> causes the problem.</p>
| 28
|
2009-02-20T14:36:09Z
| 25,171,609
|
<p>If you use <code>dill</code>, your example doesn't fail to pickle...</p>
<pre><code>>>> import dill
>>> import new
>>>
>>> class Test(object):
... pass
...
>>> def test_func(self):
... pass
...
>>> test = Test()
>>> dill.dumps(test)
'\x80\x02cdill.dill\n_create_type\nq\x00(cdill.dill\n_load_type\nq\x01U\x08TypeTypeq\x02\x85q\x03Rq\x04U\x04Testq\x05h\x01U\nObjectTypeq\x06\x85q\x07Rq\x08\x85q\t}q\n(U\r__slotnames__q\x0b]q\x0cU\n__module__q\rU\x08__main__q\x0eU\x07__doc__q\x0fNutq\x10Rq\x11)\x81q\x12}q\x13b.'
>>> test.test_meth = new.instancemethod(test_func, test)
>>> dill.dumps(test)
'\x80\x02cdill.dill\n_create_type\nq\x00(cdill.dill\n_load_type\nq\x01U\x08TypeTypeq\x02\x85q\x03Rq\x04U\x04Testq\x05h\x01U\nObjectTypeq\x06\x85q\x07Rq\x08\x85q\t}q\n(U\r__slotnames__q\x0b]q\x0cU\n__module__q\rU\x08__main__q\x0eU\x07__doc__q\x0fNutq\x10Rq\x11)\x81q\x12}q\x13U\ttest_methq\x14h\x01U\nMethodTypeq\x15\x85q\x16Rq\x17cdill.dill\n_create_function\nq\x18(cdill.dill\n_unmarshal\nq\x19Ubc\x01\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00C\x00\x00\x00s\x04\x00\x00\x00d\x00\x00S(\x01\x00\x00\x00N(\x00\x00\x00\x00(\x01\x00\x00\x00t\x04\x00\x00\x00self(\x00\x00\x00\x00(\x00\x00\x00\x00s\x07\x00\x00\x00<stdin>t\t\x00\x00\x00test_func\x01\x00\x00\x00s\x02\x00\x00\x00\x00\x01q\x1a\x85q\x1bRq\x1cc__builtin__\n__main__\nU\ttest_funcq\x1dNN}q\x1etq\x1fRq h\x12N\x87q!Rq"sb.'
</code></pre>
<p>So we have to find something that <code>dill</code> can't pickle...</p>
<pre><code>>>> class Unpicklable(object):
... def breakme(self):
... self.x = iter(set())
...
>>> u = Unpicklable()
>>> dill.dumps(u)
'\x80\x02cdill.dill\n_create_type\nq\x00(cdill.dill\n_load_type\nq\x01U\x08TypeTypeq\x02\x85q\x03Rq\x04U\x0bUnpicklableq\x05h\x01U\nObjectTypeq\x06\x85q\x07Rq\x08\x85q\t}q\n(U\r__slotnames__q\x0b]q\x0cU\n__module__q\rU\x08__main__q\x0eU\x07breakmeq\x0fcdill.dill\n_create_function\nq\x10(cdill.dill\n_unmarshal\nq\x11U\xafc\x01\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00C\x00\x00\x00s"\x00\x00\x00d\x01\x00d\x00\x00l\x00\x00}\x01\x00t\x01\x00t\x02\x00\x83\x00\x00\x83\x01\x00|\x00\x00_\x03\x00d\x00\x00S(\x02\x00\x00\x00Ni\xff\xff\xff\xff(\x04\x00\x00\x00t\t\x00\x00\x00itertoolst\x04\x00\x00\x00itert\x03\x00\x00\x00sett\x01\x00\x00\x00x(\x02\x00\x00\x00t\x04\x00\x00\x00selfR\x00\x00\x00\x00(\x00\x00\x00\x00(\x00\x00\x00\x00s\x07\x00\x00\x00<stdin>t\x07\x00\x00\x00breakme\x02\x00\x00\x00s\x04\x00\x00\x00\x00\x01\x0c\x01q\x12\x85q\x13Rq\x14c__builtin__\n__main__\nh\x0fNN}q\x15tq\x16Rq\x17U\x07__doc__q\x18Nutq\x19Rq\x1a)\x81q\x1b}q\x1cb.'
>>> u.breakme()
>>> dill.dumps(u)
Traceback (most recent call last):
â¦(snip)â¦
pickle.PicklingError: Can't pickle <type 'setiterator'>: it's not found as __builtin__.setiterator
>>>
</code></pre>
<p>If the error message wasn't good, I could use <code>dill.detect</code> to see which what unpicklable objects the top-level object contains.</p>
<pre><code>>>> dill.detect.badobjects(u, depth=1)
{'__hash__': <method-wrapper '__hash__' of Unpicklable object at 0x10a37b350>, '__setattr__': <method-wrapper '__setattr__' of Unpicklable object at 0x10a37b350>, '__reduce_ex__': <built-in method __reduce_ex__ of Unpicklable object at 0x10a37b350>, '__reduce__': <built-in method __reduce__ of Unpicklable object at 0x10a37b350>, '__str__': <method-wrapper '__str__' of Unpicklable object at 0x10a37b350>, '__format__': <built-in method __format__ of Unpicklable object at 0x10a37b350>, '__getattribute__': <method-wrapper '__getattribute__' of Unpicklable object at 0x10a37b350>, '__delattr__': <method-wrapper '__delattr__' of Unpicklable object at 0x10a37b350>, 'breakme': <bound method Unpicklable.breakme of <__main__.Unpicklable object at 0x10a37b350>>, '__repr__': <method-wrapper '__repr__' of Unpicklable object at 0x10a37b350>, '__dict__': {'x': <setiterator object at 0x10a370820>}, 'x': <setiterator object at 0x10a370820>, '__sizeof__': <built-in method __sizeof__ of Unpicklable object at 0x10a37b350>, '__init__': <method-wrapper '__init__' of Unpicklable object at 0x10a37b350>}
>>> dill.detect.badtypes(u, depth=1)
{'__hash__': <type 'method-wrapper'>, '__setattr__': <type 'method-wrapper'>, '__reduce_ex__': <type 'builtin_function_or_method'>, '__reduce__': <type 'builtin_function_or_method'>, '__str__': <type 'method-wrapper'>, '__format__': <type 'builtin_function_or_method'>, '__getattribute__': <type 'method-wrapper'>, '__delattr__': <type 'method-wrapper'>, 'breakme': <type 'instancemethod'>, '__repr__': <type 'method-wrapper'>, '__dict__': <type 'dict'>, 'x': <type 'setiterator'>, '__sizeof__': <type 'builtin_function_or_method'>, '__init__': <type 'method-wrapper'>}
>>> set(dill.detect.badtypes(u, depth=1).values())
set([<type 'dict'>, <type 'method-wrapper'>, <type 'instancemethod'>, <type 'setiterator'>, <type 'builtin_function_or_method'>])
</code></pre>
<p><code>dill</code> doesn't rely on the <code>__getstate__</code> method being present, although maybe it should utilize it if it exists. You can also use <code>objgraph</code> to get a picture of all the object dependencies that are used to build the thing that doesn't pickle. It can help you sort out what the root of the problem is, based on the above information.</p>
<p>See <code>dill.detect</code> use in tracking down unpicklable items in this issue: <a href="https://github.com/uqfoundation/dill/issues/58" rel="nofollow">https://github.com/uqfoundation/dill/issues/58</a></p>
| 2
|
2014-08-06T22:55:07Z
|
[
"python",
"serialization"
] |
Statistics with numpy
| 570,137
|
<p>I am working at some plots and statistics for work and I am not sure how I can do some statistics using numpy: I have a list of prices and another one of basePrices. And I want to know how many prices are with X percent above basePrice, how many are with Y percent above basePrice.</p>
<p>Is there a simple way to do that using numpy?</p>
| 1
|
2009-02-20T16:04:25Z
| 570,169
|
<p>Say you have</p>
<pre><code>>>> prices = array([100, 200, 150, 145, 300])
>>> base_prices = array([90, 220, 100, 350, 350])
</code></pre>
<p>Then the number of prices that are more than 10% above the base price are</p>
<pre><code>>>> sum(prices > 1.10 * base_prices)
2
</code></pre>
| 7
|
2009-02-20T16:12:39Z
|
[
"python",
"numpy"
] |
Statistics with numpy
| 570,137
|
<p>I am working at some plots and statistics for work and I am not sure how I can do some statistics using numpy: I have a list of prices and another one of basePrices. And I want to know how many prices are with X percent above basePrice, how many are with Y percent above basePrice.</p>
<p>Is there a simple way to do that using numpy?</p>
| 1
|
2009-02-20T16:04:25Z
| 570,197
|
<p>In addition to df's answer, if you want to know the specific prices that are above the base prices, you can do:</p>
<p>prices[prices > (1.10 * base_prices)]</p>
| 1
|
2009-02-20T16:19:14Z
|
[
"python",
"numpy"
] |
Statistics with numpy
| 570,137
|
<p>I am working at some plots and statistics for work and I am not sure how I can do some statistics using numpy: I have a list of prices and another one of basePrices. And I want to know how many prices are with X percent above basePrice, how many are with Y percent above basePrice.</p>
<p>Is there a simple way to do that using numpy?</p>
| 1
|
2009-02-20T16:04:25Z
| 570,204
|
<p>I don't think you need numpy ...</p>
<pre><code>prices = [40.0, 150.0, 35.0, 65.0, 90.0]
baseprices = [45.0, 130.0, 40.0, 80.0, 100.0]
x = .1
y = .5
# how many are within 10%
len([p for p,bp in zip(prices,baseprices) if p <= (1+x)*bp]) # 1
# how many are within 50%
len([p for p,bp in zip(prices,baseprices) if p <= (1+y)*bp]) # 5
</code></pre>
| 0
|
2009-02-20T16:21:24Z
|
[
"python",
"numpy"
] |
Statistics with numpy
| 570,137
|
<p>I am working at some plots and statistics for work and I am not sure how I can do some statistics using numpy: I have a list of prices and another one of basePrices. And I want to know how many prices are with X percent above basePrice, how many are with Y percent above basePrice.</p>
<p>Is there a simple way to do that using numpy?</p>
| 1
|
2009-02-20T16:04:25Z
| 570,372
|
<p>Just for amusement, here's a slightly different take on dF's answer:</p>
<pre><code>>>> prices = array([100, 200, 150, 145, 300])
>>> base_prices = array([90, 220, 100, 350, 350])
>>> ratio = prices / base_prices
</code></pre>
<p>Then you can extract the number that are 5% above, 10% above, etc. with</p>
<pre><code>>>> sum(ratio > 1.05)
2
>>> sum(ratio > 1.10)
2
>>> sum(ratio > 1.15)
1
</code></pre>
| 2
|
2009-02-20T16:58:35Z
|
[
"python",
"numpy"
] |
admin template for manytomany
| 570,138
|
<p>I have a manytomany relationship between publication and pathology. Each publication can have many pathologies. When a publication appears in the admin template, I need to be able to see the many pathologies associated with that publication. Here is the model statement:</p>
<pre><code>class Pathology(models.Model):
pathology = models.CharField(max_length=100)
def __unicode__(self):
return self.pathology
class Meta:
ordering = ["pathology"]
class Publication(models.Model):
pubtitle = models.TextField()
pathology = models.ManyToManyField(Pathology)
def __unicode__(self):
return self.pubtitle
class Meta:
ordering = ["pubtitle"]
</code></pre>
<p>Here is the admin.py. I have tried variations of the following, but always
get an error saying either publication or pathology doesn't have a foreign key
associated.</p>
<pre><code>from myprograms.cpssite.models import Pathology
class PathologyAdmin(admin.ModelAdmin):
# ...
list_display = ('pathology', 'id')
admin.site.register(Pathology, PathologyAdmin)
class PathologyInline(admin.TabularInline):
#...
model = Pathology
extra = 3
class PublicationAdmin(admin.ModelAdmin):
# ...
ordering = ('pubtitle', 'year')
inlines = [PathologyInline]
admin.site.register(Publication,PublicationAdmin)
</code></pre>
<p>Thanks for any help.</p>
| 1
|
2009-02-20T16:05:00Z
| 570,198
|
<p>Unless you are using a intermediate table as documented here <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#working-with-many-to-many-intermediary-models" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/contrib/admin/#working-with-many-to-many-intermediary-models</a>, I don't think you need to create an Inline class. Try removing the line <code>includes=[PathologyInline]</code> and see what happens.</p>
| 1
|
2009-02-20T16:19:30Z
|
[
"python",
"django",
"django-admin",
"many-to-many"
] |
admin template for manytomany
| 570,138
|
<p>I have a manytomany relationship between publication and pathology. Each publication can have many pathologies. When a publication appears in the admin template, I need to be able to see the many pathologies associated with that publication. Here is the model statement:</p>
<pre><code>class Pathology(models.Model):
pathology = models.CharField(max_length=100)
def __unicode__(self):
return self.pathology
class Meta:
ordering = ["pathology"]
class Publication(models.Model):
pubtitle = models.TextField()
pathology = models.ManyToManyField(Pathology)
def __unicode__(self):
return self.pubtitle
class Meta:
ordering = ["pubtitle"]
</code></pre>
<p>Here is the admin.py. I have tried variations of the following, but always
get an error saying either publication or pathology doesn't have a foreign key
associated.</p>
<pre><code>from myprograms.cpssite.models import Pathology
class PathologyAdmin(admin.ModelAdmin):
# ...
list_display = ('pathology', 'id')
admin.site.register(Pathology, PathologyAdmin)
class PathologyInline(admin.TabularInline):
#...
model = Pathology
extra = 3
class PublicationAdmin(admin.ModelAdmin):
# ...
ordering = ('pubtitle', 'year')
inlines = [PathologyInline]
admin.site.register(Publication,PublicationAdmin)
</code></pre>
<p>Thanks for any help.</p>
| 1
|
2009-02-20T16:05:00Z
| 582,818
|
<p>I realize now that Django is great for the administration (data entry) of a website, simple searching and template inheritance, but Django and Python are not very good for complex web applications, where data is moved back and forth between a database and an html template. I have decided to combine Django and PHP, hopefully, applying the strengths of both. Thanks for you help!</p>
| 0
|
2009-02-24T17:57:57Z
|
[
"python",
"django",
"django-admin",
"many-to-many"
] |
admin template for manytomany
| 570,138
|
<p>I have a manytomany relationship between publication and pathology. Each publication can have many pathologies. When a publication appears in the admin template, I need to be able to see the many pathologies associated with that publication. Here is the model statement:</p>
<pre><code>class Pathology(models.Model):
pathology = models.CharField(max_length=100)
def __unicode__(self):
return self.pathology
class Meta:
ordering = ["pathology"]
class Publication(models.Model):
pubtitle = models.TextField()
pathology = models.ManyToManyField(Pathology)
def __unicode__(self):
return self.pubtitle
class Meta:
ordering = ["pubtitle"]
</code></pre>
<p>Here is the admin.py. I have tried variations of the following, but always
get an error saying either publication or pathology doesn't have a foreign key
associated.</p>
<pre><code>from myprograms.cpssite.models import Pathology
class PathologyAdmin(admin.ModelAdmin):
# ...
list_display = ('pathology', 'id')
admin.site.register(Pathology, PathologyAdmin)
class PathologyInline(admin.TabularInline):
#...
model = Pathology
extra = 3
class PublicationAdmin(admin.ModelAdmin):
# ...
ordering = ('pubtitle', 'year')
inlines = [PathologyInline]
admin.site.register(Publication,PublicationAdmin)
</code></pre>
<p>Thanks for any help.</p>
| 1
|
2009-02-20T16:05:00Z
| 596,600
|
<p>That looks more like a one-to-many relationship to me, tho I'm somewhat unclear on what exactly Pathologies are. Also, so far as I understand, Inlines don't work on manytomany. That should work if you flip the order of the models, remove the manytomany and add a ForeignKey field to Publication in Pathology.</p>
<pre><code>class Publication(models.Model):
pubtitle = models.TextField()
def __unicode__(self):
return self.pubtitle
class Meta:
ordering = ["pubtitle"]
class Pathology(models.Model):
pathology = models.CharField(max_length=100)
publication = models.ForeignKey(Publication)
def __unicode__(self):
return self.pathology
class Meta:
ordering = ["pathology"]
</code></pre>
| 0
|
2009-02-27T20:41:15Z
|
[
"python",
"django",
"django-admin",
"many-to-many"
] |
With Twisted, how can 'connectionMade' fire a specific Deferred?
| 570,397
|
<p>This is part of a larger program; I'll explain only the relevant parts. Basically, my code wants to create a new connection to a remote host. This should return a Deferred, which fires once the connection is established, so I can send something on it.</p>
<p>I'm creating the connection with <code>twisted.internet.interfaces.IReactorSSL.connectSSL</code>. That calls <code>buildProtocol</code> on my <code>ClientFactory</code> instance to get a new connection (<code>twisted.internet.protocol.Protocol</code>) object, and returns a <code>twisted.internet.interfaces.IConnector</code>. When the connection is started, Twisted calls <code>startedConnecting</code> on the factory, giving it the <code>IConnector</code>. When the connection is actually made, the protocol's <code>connectionMade</code> callback is called, with no arguments.</p>
<p>Now, if I only needed one connection per host/port, the rest would be easy. Before calling <code>connectSSL</code>, I would create a Deferred and put it in a dictionary keyed on (host, port). Then, in the protocol's connectionMade, I could use <code>self.transport.getPeer()</code> to retrieve the host/port, use it to look up the Deferred, and fire its callbacks. But this obviously breaks down if I want to create more than one connection.</p>
<p>The problem is that I can't see any other way to associate a Deferred I created before calling <code>connectSSL</code> with the <code>connectionMade</code> later on.</p>
| 2
|
2009-02-20T17:03:48Z
| 570,561
|
<p>Looking at this some more, I think I've come up with a solution, although hopefully there is a better way; this seems kind of weird.</p>
<p>Twisted has a class, <code>ClientCreator</code> that is used for producing simple single-use connections. It in theory does what I want; connects and returns a <code>Deferred</code> that fires when the connection is established. I didn't think I could use this, though, since I'd lose the ability to pass arguments to the protocol constructor, and therefore have no way to share state between connections.</p>
<p>However, I just realized that the <code>ClientFactory</code> constructor does accept <code>*args</code> to pass to the protocol constructor. Or at least it looks like it; there is virtually no documentation for this. In that case, I can give it a reference to my factory (or whatever else, if the factory is no longer necessary). And I get back the <code>Deferred</code> that fires when the connection is established.</p>
| 0
|
2009-02-20T17:39:22Z
|
[
"python",
"connection",
"twisted",
"reactor"
] |
How can I get the newest file from an FTP server?
| 570,433
|
<p>I am using Python to connect to an FTP server that contains a new list of data once every hour. I am only connecting once a day, and I only want to download the newest file in the directory. Is there a way to do this?</p>
| 3
|
2009-02-20T17:10:20Z
| 571,363
|
<p>Look at ftplib in your current version of python. You can see a function to handle the result of the LIST command that you would issue to do a dir, if you know a last time that you run a successful script then you can parse the result from the LIST and act on the new files on the directory. See the <a href="http://www.python.org/doc/2.5.2/lib/module-ftplib.html" rel="nofollow">ftplib</a> for more info on how to do it. The retrlines function is what I would expect to use.</p>
| 0
|
2009-02-20T21:49:10Z
|
[
"python",
"ftp"
] |
How can I get the newest file from an FTP server?
| 570,433
|
<p>I am using Python to connect to an FTP server that contains a new list of data once every hour. I am only connecting once a day, and I only want to download the newest file in the directory. Is there a way to do this?</p>
| 3
|
2009-02-20T17:10:20Z
| 571,410
|
<p>Seems like any system that is automatically generating a file once an hour is likely to be using an automated naming scheme. Are you over thinking the problem by asking the server for the newest file instead of more easily parsing the file names? </p>
<p>This wouldn't work in all cases, and if the directory got large it might become time consuming to get the file listing. But it seems likely to work in most cases.</p>
| 1
|
2009-02-20T22:02:56Z
|
[
"python",
"ftp"
] |
How do I add plain text info to forms in a formset in Django?
| 570,522
|
<p>I want to show a title and description from a db query in each form, but I don't want it to be in a charfield, I want it to be html-formatted text.</p>
<p>sample template code:</p>
<pre><code>{% for form, data in zipped_data %}
<div class="row">
<div class="first_col">
<span class="title">{{ data.0 }}</span>
<div class="desc">
{{ data.1|default:"None" }}
</div>
</div>
{% for field in form %}
<div class="fieldWrapper" style="float: left; ">
{{ field.errors }}
{{ field }}
</div>
{% endfor %}
{% endfor %}
</code></pre>
<p>Is this the most idiomatic way of doing this? Or, is there a way to add text that will not be displayed inside of a textarea or text input to my model:</p>
<pre><code>class ReportForm(forms.Form):
comment = forms.CharField()
</code></pre>
<p>?</p>
| 3
|
2009-02-20T17:30:00Z
| 571,334
|
<p>Instead of zipping your forms with the additional data, you can override the constructor on your form and hold your title/description as <em>instance-level</em> member variables. This is a bit more object-oriented and learning how to do this will help you solve other problems down the road such as dynamic choice fields.</p>
<pre><code>class MyForm (forms.Form):
def __init__ (self, title, desc, *args, **kwargs):
self.title = title
self.desc = desc
super (MyForm, self).__init__ (*args, **kwargs) # call base class
</code></pre>
<p>Then in your view code:</p>
<pre><code>form = MyForm ('Title A', 'Description A')
</code></pre>
<p>Adjust accordingly if you need these values to come from the database. Then in your template, you access the instance variables just like you do anything else, e.g.:</p>
<pre><code> <h1>{{ form.title }}</h1>
<p>{{ form.desc }}</p>
</code></pre>
<p>From the way you phrased your question, I think you probably have some confusion around the way Django uses Python <em>class attributes</em> to provide a declarative form API versus <em>instance-level</em> attributes that you apply to individual instances of a class, in this case your form objects.</p>
<ul>
<li><a href="http://stackoverflow.com/questions/207000/python-difference-between-class-and-instance-attributes">Check out this link for a good discussion on the distinction</a></li>
<li><a href="http://stackoverflow.com/questions/206734/why-do-attribute-references-act-like-this-with-python-inheritance">And this one</a></li>
</ul>
| 8
|
2009-02-20T21:39:03Z
|
[
"python",
"django",
"django-forms"
] |
How do I add plain text info to forms in a formset in Django?
| 570,522
|
<p>I want to show a title and description from a db query in each form, but I don't want it to be in a charfield, I want it to be html-formatted text.</p>
<p>sample template code:</p>
<pre><code>{% for form, data in zipped_data %}
<div class="row">
<div class="first_col">
<span class="title">{{ data.0 }}</span>
<div class="desc">
{{ data.1|default:"None" }}
</div>
</div>
{% for field in form %}
<div class="fieldWrapper" style="float: left; ">
{{ field.errors }}
{{ field }}
</div>
{% endfor %}
{% endfor %}
</code></pre>
<p>Is this the most idiomatic way of doing this? Or, is there a way to add text that will not be displayed inside of a textarea or text input to my model:</p>
<pre><code>class ReportForm(forms.Form):
comment = forms.CharField()
</code></pre>
<p>?</p>
| 3
|
2009-02-20T17:30:00Z
| 574,345
|
<p>I just created a read-only widget by subclassing the text input field one:</p>
<pre><code>class ReadOnlyText(forms.TextInput):
input_type = 'text'
def render(self, name, value, attrs=None):
if value is None:
value = ''
return value
</code></pre>
<p>And: </p>
<pre><code>class ReportForm(forms.Form):
comment = forms.CharField(widget=ReadOnlyText, label='comment')
</code></pre>
| 3
|
2009-02-22T04:35:57Z
|
[
"python",
"django",
"django-forms"
] |
How do I add plain text info to forms in a formset in Django?
| 570,522
|
<p>I want to show a title and description from a db query in each form, but I don't want it to be in a charfield, I want it to be html-formatted text.</p>
<p>sample template code:</p>
<pre><code>{% for form, data in zipped_data %}
<div class="row">
<div class="first_col">
<span class="title">{{ data.0 }}</span>
<div class="desc">
{{ data.1|default:"None" }}
</div>
</div>
{% for field in form %}
<div class="fieldWrapper" style="float: left; ">
{{ field.errors }}
{{ field }}
</div>
{% endfor %}
{% endfor %}
</code></pre>
<p>Is this the most idiomatic way of doing this? Or, is there a way to add text that will not be displayed inside of a textarea or text input to my model:</p>
<pre><code>class ReportForm(forms.Form):
comment = forms.CharField()
</code></pre>
<p>?</p>
| 3
|
2009-02-20T17:30:00Z
| 866,227
|
<p>I had to solve a similar problem and like your idea Andrei. I had some issues using it though, as, if there were validation errors, the value of the read-only field would get lost. To solve this, I did something similar but overrode HiddenInput instead and kept the value in a hidden form field. ie:</p>
<pre><code>class ReadOnlyText(forms.HiddenInput):
input_type = 'hidden'
def render(self, name, value, attrs=None):
if value is None:
value = ''
return mark_safe(value + super(ReadOnlyTextWidget, self).render(name, value, attrs))
class ReportForm(forms.Form):
comment = forms.CharField(widget=ReadOnlyText, label='comment')
</code></pre>
| 1
|
2009-05-14T22:37:37Z
|
[
"python",
"django",
"django-forms"
] |
How do I add plain text info to forms in a formset in Django?
| 570,522
|
<p>I want to show a title and description from a db query in each form, but I don't want it to be in a charfield, I want it to be html-formatted text.</p>
<p>sample template code:</p>
<pre><code>{% for form, data in zipped_data %}
<div class="row">
<div class="first_col">
<span class="title">{{ data.0 }}</span>
<div class="desc">
{{ data.1|default:"None" }}
</div>
</div>
{% for field in form %}
<div class="fieldWrapper" style="float: left; ">
{{ field.errors }}
{{ field }}
</div>
{% endfor %}
{% endfor %}
</code></pre>
<p>Is this the most idiomatic way of doing this? Or, is there a way to add text that will not be displayed inside of a textarea or text input to my model:</p>
<pre><code>class ReportForm(forms.Form):
comment = forms.CharField()
</code></pre>
<p>?</p>
| 3
|
2009-02-20T17:30:00Z
| 20,201,594
|
<p>I think you can get it with "{{ field.value }}". Maybe it's the easier way.</p>
<pre><code>{% for form in formset %}
{% for field in form %}
{% if forloop.counter = 1 %}
<td><img src="{{ MEDIA_URL }}{{ field.value }}"/></td>
{% endif %}
{% if forloop.counter = 2 %}
<td>{{ field.value }}</td>
{% endif %}
{% if forloop.counter > 2 %}
<td>{{ field }}{{ field.errors }}</td>
{% endif %}
{% endfor %}
{% endfor %}
</code></pre>
| 0
|
2013-11-25T19:30:00Z
|
[
"python",
"django",
"django-forms"
] |
Detect when a Python module unloads
| 570,636
|
<p>I have a module that uses ctypes to wrap some functionality from a static library into a class. When the module loads, it calls an initialize function in the static library. When the module is unloaded (presumably when the interpreter exits), there's an unload function in the library that I'd like to be called. How can I create this hook?</p>
| 7
|
2009-02-20T18:00:23Z
| 570,704
|
<p>Use the <a href="http://docs.python.org/library/atexit.html">atexit</a> module:</p>
<pre><code>import mymodule
import atexit
# call mymodule.unload('param1', 'param2') when the interpreter exits:
atexit.register(mymodule.unload, 'param1', 'param2')
</code></pre>
<p>Another simple example from the docs, using <a href="http://docs.python.org/library/atexit.html#atexit.register"><code>register</code></a> as a decorator:</p>
<pre><code>import atexit
@atexit.register
def goodbye():
print "You are now leaving the Python sector."
</code></pre>
| 12
|
2009-02-20T18:19:37Z
|
[
"python"
] |
Python c-api and unicode strings
| 570,781
|
<p>I need to convert between python objects and c strings of various encodings. Going from a c string to a unicode object was fairly simple using PyUnicode_Decode, however Im not sure how to go the other way</p>
<pre><code>//char* can be a wchar_t or any other element size, just make sure it is correctly terminated for its encoding
Unicode(const char *str, size_t bytes, const char *encoding="utf-16", const char *errors="strict")
:Object(PyUnicode_Decode(str, bytes, encoding, errors))
{
//check for any python exceptions
ExceptionCheck();
}
</code></pre>
<p>I want to create another function that takes the python Unicode string and puts it in a buffer using a given encodeing, eg:</p>
<pre><code>//fills buffer with a null terminated string in encoding
void AsCString(char *buffer, size_t bufferBytes,
const char *encoding="utf-16", const char *errors="strict")
{
...
}
</code></pre>
<p>I suspect it has somthing to do with PyUnicode_AsEncodedString however that returns a PyObject so I'm not sure how to put that into my buffer...</p>
<p>Note: both methods above are members of a c++ Unicode class that wraps the python api
I'm using Python 3.0</p>
| 4
|
2009-02-20T18:47:34Z
| 570,896
|
<blockquote>
<p>I suspect it has somthing to do with PyUnicode_AsEncodedString however that returns a PyObject so I'm not sure how to put that into my buffer...</p>
</blockquote>
<p>The PyObject returned is a PyStringObject, so you just need to use <code>PyString_Size</code> and <code>PyString_AsString</code> to get a pointer to the string's buffer and memcpy it to your own buffer.</p>
<p>If you're looking for a way to go <em>directly</em> from a PyUnicode object into your own char buffer, I don't think that you can do that.</p>
| 3
|
2009-02-20T19:26:50Z
|
[
"python",
"c",
"python-c-api"
] |
Django "SuspiciousOperation" Error While Deleting Uploaded File
| 570,952
|
<p>I'm developing in Django on Windows XP using the <code>manage.py runserver</code> command to serve files. Apache isn't involved. When I login to the administration and try to delete a file I get a "SuspiciousOperation" error.</p>
<p>Here's the traceback:<br />
<a href="http://dpaste.com/123112/" rel="nofollow">http://dpaste.com/123112/</a> </p>
<p>Here's my full model:<br />
<a href="http://dpaste.com/hold/123110/" rel="nofollow">http://dpaste.com/hold/123110/</a></p>
<p>How can I get rid of this "SuspiciousOperation" error?</p>
<p><strong>EDIT:</strong> Here are my media settings:</p>
<pre><code>MEDIA_ROOT = 'C:/Server/Projects/postnzb/static/'
MEDIA_URL = '/static/'
</code></pre>
| 2
|
2009-02-20T19:41:08Z
| 571,047
|
<p>What is your <code>MEDIA_ROOT</code> in <code>settings.py</code>? From the back-trace, it seems you have set your <code>MEDIA_ROOT</code> to <code>/static/</code>.</p>
<p>This error is coming since Django is trying to access <code>/static/</code> to which it has no access. Put an absolute pathname for <code>MEDIA_ROOT</code> like <code>C:/Documents/static/</code> and give full permissions to Django to access that directory.</p>
<p>That should solve your problem.</p>
<p><strong>Addendum</strong>: Since your <code>MEDIA_ROOT</code> seems to be OK, I am guessing that you are using <code>MEDIA_URL</code> for deleting the file instead of <code>MEDIA_ROOT</code>. Indeed, from the error it seems that Django was trying to access the <code>/static/files/8.nzb</code> and was denied access. Clearly, <code>/static/</code> is your <code>MEDIA_URL</code> and not your <code>MEDIA_ROOT</code>. The model methods should never try accessing the files using the <code>MEDIA_URL</code>. I am sure a review of your code will spot the error.</p>
<p><strong>Update</strong>: I skimmed your code and it seems you are setting <code>File.nzb</code> to <code>%(1)sfiles/%(2)s.nzb' % {'1': settings.MEDIA_URL, '2': self.pk}</code> which uses its <code>MEDIA_URL</code> and then in the <code>delete()</code> method you are calling the <code>delete()</code> method of the super-class of <code>File</code> as <code>super(File, self).delete()</code> which is obviously wrong as it will try deleting <code>File.nzb</code> and will try accessing the file through the <code>MEDIA_URL</code>. Fixing that will get rid of the error. I will leave the exact solution as an exercise to you :)</p>
| 5
|
2009-02-20T20:08:44Z
|
[
"python",
"windows",
"django"
] |
In Python, how might one log in, answer a web form via HTTP POST (not url-encoded), and fetch a returned XML file?
| 571,083
|
<p>I am basically trying to export a configuration file, once a week. While the product in question allows you to log in manually via a web client, enter some information, and get an XML file back when you submit, there's no facility for automating this. I can get away with using Python 2.5 (have used for a while) or 2.6 (unfamiliar) to do this.</p>
<ol>
<li><p>I think I need to have some way to authenticate against the product. Although I can view the cookie in Firefox, when I looked through the actual <code>cookie.txt</code> file, it was not present. Didn't show up after clearing my private data and re-authenticating. Odd. Should I be shooting for the <code>Cookie</code> module, or could this be some arcane method of authentication that only <em>looks</em> like cookies? How would I know?</p></li>
<li><p>I think I need the <code>httplib</code> module to do the HTTP POST, but I don't know how to do the <code>multipart/form-data</code> encoding. Have I overlooked a handy option, or is this something where I must roll my own?</p></li>
<li><p>I assume I can get the XML file back in the <code>HTTPesponse</code> from <code>httplib</code>.</p></li>
</ol>
<p>I've fetched web things via Python before, but not with POST, multipart encoding, and authentication in the mix.</p>
| 3
|
2009-02-20T20:20:18Z
| 571,093
|
<p><a href="http://docs.python.org/library/urllib2.html" rel="nofollow">urllib2</a> should cover all of this.</p>
<p>Here's a <a href="http://www.voidspace.org.uk/python/articles/urllib2.shtml#id6" rel="nofollow">Basic Authentication example</a>.</p>
<p>Here's a <a href="http://code.activestate.com/recipes/146306/" rel="nofollow">Post with multipart/form-data</a>.</p>
| 3
|
2009-02-20T20:23:05Z
|
[
"python",
"authentication",
"cookies",
"post"
] |
In Python, how might one log in, answer a web form via HTTP POST (not url-encoded), and fetch a returned XML file?
| 571,083
|
<p>I am basically trying to export a configuration file, once a week. While the product in question allows you to log in manually via a web client, enter some information, and get an XML file back when you submit, there's no facility for automating this. I can get away with using Python 2.5 (have used for a while) or 2.6 (unfamiliar) to do this.</p>
<ol>
<li><p>I think I need to have some way to authenticate against the product. Although I can view the cookie in Firefox, when I looked through the actual <code>cookie.txt</code> file, it was not present. Didn't show up after clearing my private data and re-authenticating. Odd. Should I be shooting for the <code>Cookie</code> module, or could this be some arcane method of authentication that only <em>looks</em> like cookies? How would I know?</p></li>
<li><p>I think I need the <code>httplib</code> module to do the HTTP POST, but I don't know how to do the <code>multipart/form-data</code> encoding. Have I overlooked a handy option, or is this something where I must roll my own?</p></li>
<li><p>I assume I can get the XML file back in the <code>HTTPesponse</code> from <code>httplib</code>.</p></li>
</ol>
<p>I've fetched web things via Python before, but not with POST, multipart encoding, and authentication in the mix.</p>
| 3
|
2009-02-20T20:20:18Z
| 571,106
|
<p>Try <a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow">mechanize</a> module.</p>
| 2
|
2009-02-20T20:25:44Z
|
[
"python",
"authentication",
"cookies",
"post"
] |
In Python, how might one log in, answer a web form via HTTP POST (not url-encoded), and fetch a returned XML file?
| 571,083
|
<p>I am basically trying to export a configuration file, once a week. While the product in question allows you to log in manually via a web client, enter some information, and get an XML file back when you submit, there's no facility for automating this. I can get away with using Python 2.5 (have used for a while) or 2.6 (unfamiliar) to do this.</p>
<ol>
<li><p>I think I need to have some way to authenticate against the product. Although I can view the cookie in Firefox, when I looked through the actual <code>cookie.txt</code> file, it was not present. Didn't show up after clearing my private data and re-authenticating. Odd. Should I be shooting for the <code>Cookie</code> module, or could this be some arcane method of authentication that only <em>looks</em> like cookies? How would I know?</p></li>
<li><p>I think I need the <code>httplib</code> module to do the HTTP POST, but I don't know how to do the <code>multipart/form-data</code> encoding. Have I overlooked a handy option, or is this something where I must roll my own?</p></li>
<li><p>I assume I can get the XML file back in the <code>HTTPesponse</code> from <code>httplib</code>.</p></li>
</ol>
<p>I've fetched web things via Python before, but not with POST, multipart encoding, and authentication in the mix.</p>
| 3
|
2009-02-20T20:20:18Z
| 571,182
|
<p>You should look at the MultipartPostHandler:</p>
<p><a href="http://odin.himinbi.org/MultipartPostHandler.py" rel="nofollow">http://odin.himinbi.org/MultipartPostHandler.py</a></p>
<p>And if you need to support unicode file names , see a fix at:
<a href="http://peerit.blogspot.com/2007/07/multipartposthandler-doesnt-work-for.html" rel="nofollow">http://peerit.blogspot.com/2007/07/multipartposthandler-doesnt-work-for.html</a></p>
| 0
|
2009-02-20T20:47:51Z
|
[
"python",
"authentication",
"cookies",
"post"
] |
Split tags in python
| 571,186
|
<p>I have a file that contains this:</p>
<pre class="lang-none prettyprint-override"><code><html>
<head>
<title> Hello! - {{ today }}</title>
</head>
<body>
{{ runner_up }}
avasd
{{ blabla }}
sdvas
{{ oooo }}
</body>
</html>
</code></pre>
<p>What is the best or most Pythonic way to extract the <code>{{today}}</code>, <code>{{runner_up}}</code>, etc.?</p>
<p>I know it can be done with splits/regular expressions, but I wondered if there were another way.</p>
<p>PS: consider the data loaded in a variable called <code>thedata</code>.</p>
<p>Edit: I think that the HTML example was bad, because it directed some commenters to BeautifulSoup. So, here is a new input data:</p>
<pre class="lang-none prettyprint-override"><code>Fix grammatical or {{spelling}} errors.
Clarify meaning without changing it.
Correct minor {{mistakes}}.
Add related resources or links.
Always respect the original {{author}}.
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>spelling
mistakes
author
</code></pre>
| 3
|
2009-02-20T20:50:04Z
| 571,231
|
<p>try <a href="http://code.google.com/p/templatemaker/" rel="nofollow">templatemaker</a>, a reverse-template maker. it can actually learn them automatically from examples!</p>
| 3
|
2009-02-20T21:08:00Z
|
[
"python",
"split",
"template-engine"
] |
Split tags in python
| 571,186
|
<p>I have a file that contains this:</p>
<pre class="lang-none prettyprint-override"><code><html>
<head>
<title> Hello! - {{ today }}</title>
</head>
<body>
{{ runner_up }}
avasd
{{ blabla }}
sdvas
{{ oooo }}
</body>
</html>
</code></pre>
<p>What is the best or most Pythonic way to extract the <code>{{today}}</code>, <code>{{runner_up}}</code>, etc.?</p>
<p>I know it can be done with splits/regular expressions, but I wondered if there were another way.</p>
<p>PS: consider the data loaded in a variable called <code>thedata</code>.</p>
<p>Edit: I think that the HTML example was bad, because it directed some commenters to BeautifulSoup. So, here is a new input data:</p>
<pre class="lang-none prettyprint-override"><code>Fix grammatical or {{spelling}} errors.
Clarify meaning without changing it.
Correct minor {{mistakes}}.
Add related resources or links.
Always respect the original {{author}}.
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>spelling
mistakes
author
</code></pre>
| 3
|
2009-02-20T20:50:04Z
| 571,238
|
<p>Mmkay, well here's a generator solution that seems to work well for me. You can also provide different open and close tags if you like.</p>
<pre><code>def get_tags(s, open_delim ='{{',
close_delim ='}}' ):
while True:
# Search for the next two delimiters in the source text
start = s.find(open_delim)
end = s.find(close_delim)
# We found a non-empty match
if -1 < start < end:
# Skip the length of the open delimiter
start += len(open_delim)
# Spit out the tag
yield s[start:end].strip()
# Truncate string to start from last match
s = s[end+len(close_delim):]
else:
return
</code></pre>
<p>Run against your target input like so:</p>
<pre><code># prints: today, runner_up, blabla, oooo
for tag in get_tags(html):
print tag
</code></pre>
<p>Edit: it also works against your new example :). In my obviously quick testing, it also seemed to handle malformed tags in a reasonable way, though I make no guarantees of its robustness!</p>
| 7
|
2009-02-20T21:09:48Z
|
[
"python",
"split",
"template-engine"
] |
Split tags in python
| 571,186
|
<p>I have a file that contains this:</p>
<pre class="lang-none prettyprint-override"><code><html>
<head>
<title> Hello! - {{ today }}</title>
</head>
<body>
{{ runner_up }}
avasd
{{ blabla }}
sdvas
{{ oooo }}
</body>
</html>
</code></pre>
<p>What is the best or most Pythonic way to extract the <code>{{today}}</code>, <code>{{runner_up}}</code>, etc.?</p>
<p>I know it can be done with splits/regular expressions, but I wondered if there were another way.</p>
<p>PS: consider the data loaded in a variable called <code>thedata</code>.</p>
<p>Edit: I think that the HTML example was bad, because it directed some commenters to BeautifulSoup. So, here is a new input data:</p>
<pre class="lang-none prettyprint-override"><code>Fix grammatical or {{spelling}} errors.
Clarify meaning without changing it.
Correct minor {{mistakes}}.
Add related resources or links.
Always respect the original {{author}}.
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>spelling
mistakes
author
</code></pre>
| 3
|
2009-02-20T20:50:04Z
| 571,240
|
<p>If the data is that straightforward, a simple regex would do the trick.</p>
| 0
|
2009-02-20T21:10:17Z
|
[
"python",
"split",
"template-engine"
] |
Split tags in python
| 571,186
|
<p>I have a file that contains this:</p>
<pre class="lang-none prettyprint-override"><code><html>
<head>
<title> Hello! - {{ today }}</title>
</head>
<body>
{{ runner_up }}
avasd
{{ blabla }}
sdvas
{{ oooo }}
</body>
</html>
</code></pre>
<p>What is the best or most Pythonic way to extract the <code>{{today}}</code>, <code>{{runner_up}}</code>, etc.?</p>
<p>I know it can be done with splits/regular expressions, but I wondered if there were another way.</p>
<p>PS: consider the data loaded in a variable called <code>thedata</code>.</p>
<p>Edit: I think that the HTML example was bad, because it directed some commenters to BeautifulSoup. So, here is a new input data:</p>
<pre class="lang-none prettyprint-override"><code>Fix grammatical or {{spelling}} errors.
Clarify meaning without changing it.
Correct minor {{mistakes}}.
Add related resources or links.
Always respect the original {{author}}.
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>spelling
mistakes
author
</code></pre>
| 3
|
2009-02-20T20:50:04Z
| 571,257
|
<p>I know you said no regex/split, but I couldn't help but try for a one-liner solution:</p>
<pre><code>import re
for s in re.findall("\{\{.*\}\}",thedata):
print s.replace("{","").replace("}","")
</code></pre>
<p>EDIT: JFS</p>
<p>Compare:</p>
<pre><code>>>> re.findall('\{\{.*\}\}', '{{a}}b{{c}}')
['{{a}}b{{c}}']
>>> re.findall('{{(.+?)}}', '{{a}}b{{c}}')
['a', 'c']
</code></pre>
| 2
|
2009-02-20T21:14:03Z
|
[
"python",
"split",
"template-engine"
] |
Split tags in python
| 571,186
|
<p>I have a file that contains this:</p>
<pre class="lang-none prettyprint-override"><code><html>
<head>
<title> Hello! - {{ today }}</title>
</head>
<body>
{{ runner_up }}
avasd
{{ blabla }}
sdvas
{{ oooo }}
</body>
</html>
</code></pre>
<p>What is the best or most Pythonic way to extract the <code>{{today}}</code>, <code>{{runner_up}}</code>, etc.?</p>
<p>I know it can be done with splits/regular expressions, but I wondered if there were another way.</p>
<p>PS: consider the data loaded in a variable called <code>thedata</code>.</p>
<p>Edit: I think that the HTML example was bad, because it directed some commenters to BeautifulSoup. So, here is a new input data:</p>
<pre class="lang-none prettyprint-override"><code>Fix grammatical or {{spelling}} errors.
Clarify meaning without changing it.
Correct minor {{mistakes}}.
Add related resources or links.
Always respect the original {{author}}.
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>spelling
mistakes
author
</code></pre>
| 3
|
2009-02-20T20:50:04Z
| 571,314
|
<p>J.F. Sebastian wrote this in a comment but I thought it was good enough to deserve its own answer:</p>
<pre><code>re.findall(r'{{(.+?)}}', thestring)
</code></pre>
<p>I know the OP was asking for a way that didn't involve splits or regexes - so maybe this doesn't <em>quite</em> answer the question as stated. But this one line of code definitely gets my vote as the most Pythonic way to accomplish the task.</p>
| 1
|
2009-02-20T21:34:59Z
|
[
"python",
"split",
"template-engine"
] |
triangle numbers in python
| 571,488
|
<p>I'm trying to solve the problem:</p>
<blockquote>
<p>What is the value of the first triangle number to have over five hundred divisors?</p>
</blockquote>
<p><em>A triangle number is a number in the sequence of the sum of numbers i.e. 1+2+3+4+5...</em></p>
<p>I'm pretty sure that this is working code but I don't know because my computer is taking too long to calculate it. Does anybody have any idea of how to make the program a little faster.<br>
Thanks.</p>
<pre><code>import math
def main():
l = []
one = 0
a = 1
b = 2
while one == 0:
a = a + b
b += 1
for x in range(1, int(a/2 + 1)):
if a % x == 0:
l.append(x)
if len(l) > 499:
print a
if __name__ == '__main__':
main()
</code></pre>
| 10
|
2009-02-20T22:27:36Z
| 571,518
|
<p>You're not updating the value of <code>one</code>, so your program will never end.</p>
| 5
|
2009-02-20T22:36:25Z
|
[
"python"
] |
triangle numbers in python
| 571,488
|
<p>I'm trying to solve the problem:</p>
<blockquote>
<p>What is the value of the first triangle number to have over five hundred divisors?</p>
</blockquote>
<p><em>A triangle number is a number in the sequence of the sum of numbers i.e. 1+2+3+4+5...</em></p>
<p>I'm pretty sure that this is working code but I don't know because my computer is taking too long to calculate it. Does anybody have any idea of how to make the program a little faster.<br>
Thanks.</p>
<pre><code>import math
def main():
l = []
one = 0
a = 1
b = 2
while one == 0:
a = a + b
b += 1
for x in range(1, int(a/2 + 1)):
if a % x == 0:
l.append(x)
if len(l) > 499:
print a
if __name__ == '__main__':
main()
</code></pre>
| 10
|
2009-02-20T22:27:36Z
| 571,526
|
<p>Hints:</p>
<ul>
<li>what is the formula for <code>n</code>-th triangular number?</li>
<li><code>n</code> and <code>n+1</code> have no common factors (except <code>1</code>). Question: given number of factors in <code>n</code> and <code>n+1</code> how to calculate number of factors in <code>n*(n+1)</code>? What about <code>n/2</code> and <code>(n+1)</code> (or <code>n</code> and <code>(n+1)/2</code>)?</li>
<li>if you know all prime factors of <code>n</code> how to calculate number of divisors of <code>n</code>?</li>
</ul>
<p>If you don't want to change your algorithm then you can make it faster by:</p>
<ul>
<li>replace <code>l.append</code> by <code>factor_count += 1</code></li>
<li>enumerate to <code>int(a**.5)</code> instead of <code>a/2</code> (use <code>factor_count += 2</code> in this case). </li>
</ul>
| 27
|
2009-02-20T22:39:49Z
|
[
"python"
] |
triangle numbers in python
| 571,488
|
<p>I'm trying to solve the problem:</p>
<blockquote>
<p>What is the value of the first triangle number to have over five hundred divisors?</p>
</blockquote>
<p><em>A triangle number is a number in the sequence of the sum of numbers i.e. 1+2+3+4+5...</em></p>
<p>I'm pretty sure that this is working code but I don't know because my computer is taking too long to calculate it. Does anybody have any idea of how to make the program a little faster.<br>
Thanks.</p>
<pre><code>import math
def main():
l = []
one = 0
a = 1
b = 2
while one == 0:
a = a + b
b += 1
for x in range(1, int(a/2 + 1)):
if a % x == 0:
l.append(x)
if len(l) > 499:
print a
if __name__ == '__main__':
main()
</code></pre>
| 10
|
2009-02-20T22:27:36Z
| 572,562
|
<p>You'll have to think more and use less brute force to solve Project Euler questions.</p>
<p>In this case you should investigate which and how many divisors triangle numbers have. Start at the beginning, look for patterns, try to understand the problem.</p>
| 6
|
2009-02-21T06:59:57Z
|
[
"python"
] |
triangle numbers in python
| 571,488
|
<p>I'm trying to solve the problem:</p>
<blockquote>
<p>What is the value of the first triangle number to have over five hundred divisors?</p>
</blockquote>
<p><em>A triangle number is a number in the sequence of the sum of numbers i.e. 1+2+3+4+5...</em></p>
<p>I'm pretty sure that this is working code but I don't know because my computer is taking too long to calculate it. Does anybody have any idea of how to make the program a little faster.<br>
Thanks.</p>
<pre><code>import math
def main():
l = []
one = 0
a = 1
b = 2
while one == 0:
a = a + b
b += 1
for x in range(1, int(a/2 + 1)):
if a % x == 0:
l.append(x)
if len(l) > 499:
print a
if __name__ == '__main__':
main()
</code></pre>
| 10
|
2009-02-20T22:27:36Z
| 573,935
|
<p>Just for sanity's sake, you should use</p>
<pre><code>while True:
</code></pre>
<p>and get rid of <code>one</code>.</p>
| 5
|
2009-02-21T23:42:47Z
|
[
"python"
] |
triangle numbers in python
| 571,488
|
<p>I'm trying to solve the problem:</p>
<blockquote>
<p>What is the value of the first triangle number to have over five hundred divisors?</p>
</blockquote>
<p><em>A triangle number is a number in the sequence of the sum of numbers i.e. 1+2+3+4+5...</em></p>
<p>I'm pretty sure that this is working code but I don't know because my computer is taking too long to calculate it. Does anybody have any idea of how to make the program a little faster.<br>
Thanks.</p>
<pre><code>import math
def main():
l = []
one = 0
a = 1
b = 2
while one == 0:
a = a + b
b += 1
for x in range(1, int(a/2 + 1)):
if a % x == 0:
l.append(x)
if len(l) > 499:
print a
if __name__ == '__main__':
main()
</code></pre>
| 10
|
2009-02-20T22:27:36Z
| 3,821,619
|
<p>Your current brute force algorithm is too inefficient to solve this problem in the Project Euler time limit of 1 minute. Instead, I suggest looking at the Divisor Function:</p>
<p><a href="http://www.artofproblemsolving.com/Wiki/index.php/Divisor_function" rel="nofollow">http://www.artofproblemsolving.com/Wiki/index.php/Divisor_function</a></p>
| 3
|
2010-09-29T12:38:12Z
|
[
"python"
] |
triangle numbers in python
| 571,488
|
<p>I'm trying to solve the problem:</p>
<blockquote>
<p>What is the value of the first triangle number to have over five hundred divisors?</p>
</blockquote>
<p><em>A triangle number is a number in the sequence of the sum of numbers i.e. 1+2+3+4+5...</em></p>
<p>I'm pretty sure that this is working code but I don't know because my computer is taking too long to calculate it. Does anybody have any idea of how to make the program a little faster.<br>
Thanks.</p>
<pre><code>import math
def main():
l = []
one = 0
a = 1
b = 2
while one == 0:
a = a + b
b += 1
for x in range(1, int(a/2 + 1)):
if a % x == 0:
l.append(x)
if len(l) > 499:
print a
if __name__ == '__main__':
main()
</code></pre>
| 10
|
2009-02-20T22:27:36Z
| 11,820,553
|
<p>First of all, the people telling you that you can't solve this problem with brute force in under a minute are wrong. A brute force algorithm for a problem this size will run in a few seconds.</p>
<p>Second, the code that you posted has several problems, some of them already mentioned.</p>
<ul>
<li>You should terminate the loop by setting <code>one</code> to some value other than <code>0</code> once you reach your goal condition (where you currently <code>print a</code>).</li>
<li>You never reinitialize the list (<code>l = []</code>). This should be done each time you recalculate <code>a</code> and <code>b</code>, right before you enter the for loop.</li>
<li>The question asks for the first triangle number to have <strong>over</strong> five hundred divisors. Your condition for termination should be <code>if len(l) > 500:</code>.</li>
<li>Your probably don't want to <code>print a</code> inside the for loop, but wait until the while loop is done.</li>
</ul>
<p>The thing that's really slowing you down is that for each triangle number <code>a</code> you're checking every value up to <code>a / 2</code> to see if it's a divisor. Your only need to check values up to the square root of <code>a</code>. This way for each value of <code>x</code>, if <code>x</code> is a divisor you can just add <code>x</code> and <code>a / x</code> to the list.</p>
<p>Here's your code with the modifications I outlined above:</p>
<pre><code>import math
def main():
l = []
one = 0
a = 1
b = 2
while one == 0:
a = a + b
b += 1
l = []
sqrt_a = int(math.sqrt(a))
for x in range(1, sqrt_a + 1):
if a % x == 0:
l.append(x)
if x < math.sqrt(a):
l.append(a // x)
if len(l) > 500:
# print(a)
one = 1
print(a, b, len(l))
if __name__ == '__main__':
main()
</code></pre>
<p>You'll see that it runs in about 5 or 6 seconds, so well under a minute with these modifications.</p>
| 5
|
2012-08-05T22:21:32Z
|
[
"python"
] |
Are there any declaration keywords in Python?
| 571,514
|
<p>Are there any declaration keywords in python, like local, global, private, public etc. I know it's type free but how do you know if this statement:</p>
<pre><code>x = 5;
</code></pre>
<ul>
<li>Creates a new variable.</li>
</ul>
<p>or</p>
<ul>
<li>Sets an existing one.</li>
</ul>
| 9
|
2009-02-20T22:34:34Z
| 571,546
|
<p>An important thing to understand about Python is there are no variables, only "names".</p>
<p>In your example, you have an object "5" and you are creating a name "x" that references the object "5".</p>
<p>If later you do:</p>
<pre><code>x = "Some string"
</code></pre>
<p>that is still perfectly valid. Name "x" is now pointing to object "Some string".</p>
<p>It's not a conflict of types because the name itself doesn't have a type, only the object.</p>
<p>If you try x = 5 + "Some string" you will get a type error because you can't add two incompatible types.</p>
<p>In other words, it's not type free. Python objects are strongly typed.</p>
<p>Here are some very good discussions about Python typing:</p>
<ul>
<li><a href="http://mindview.net/WebLog/log-0025">Strong Typing vs. Strong Testing</a></li>
<li><a href="http://www.artima.com/weblogs/viewpost.jsp?thread=7590">Typing: Strong vs. Weak, Static vs. Dynamic</a></li>
</ul>
<p><strong>Edit</strong>: to finish tying this in with your question, a name can reference an existing object or a new one.</p>
<pre><code># Create a new int object
>>> x = 500
# Another name to same object
>>> y = x
# Create another new int object
>>> x = 600
# y still references original object
>>> print y
500
# This doesn't update x, it creates a new object and x becomes
# a reference to the new int object (which is int because that
# is the defined result of adding to int objects).
>>> x = x + y
>>> print x
1100
# Make original int object 500 go away
>>> del y
</code></pre>
<p><strong>Edit 2</strong>: The most complete discussion of the difference between mutable objects (that can be changed) and immutable objects (that cannot be changed) in the the official documentation of the <a href="http://docs.python.org/reference/datamodel.html">Python Data Model</a>.</p>
| 14
|
2009-02-20T22:46:25Z
|
[
"python",
"variables"
] |
Are there any declaration keywords in Python?
| 571,514
|
<p>Are there any declaration keywords in python, like local, global, private, public etc. I know it's type free but how do you know if this statement:</p>
<pre><code>x = 5;
</code></pre>
<ul>
<li>Creates a new variable.</li>
</ul>
<p>or</p>
<ul>
<li>Sets an existing one.</li>
</ul>
| 9
|
2009-02-20T22:34:34Z
| 571,559
|
<p>It doesn't look like the asker is trying to assign a type, just to specify that this a declaration, not an assignment.</p>
<p>Looks like you are looking for something like javascript has:</p>
<pre><code>var x = 5;
</code></pre>
<p>The concept of the declaration keyword in javascript is to ensure that you are making a new object in the current scope and are not simply changing some other variable of the same name.</p>
<p>Python does <strong>not</strong> have this feature. The programmer has to make sure that he or she is not reassigning preexisting names.</p>
| 4
|
2009-02-20T22:53:07Z
|
[
"python",
"variables"
] |
Are there any declaration keywords in Python?
| 571,514
|
<p>Are there any declaration keywords in python, like local, global, private, public etc. I know it's type free but how do you know if this statement:</p>
<pre><code>x = 5;
</code></pre>
<ul>
<li>Creates a new variable.</li>
</ul>
<p>or</p>
<ul>
<li>Sets an existing one.</li>
</ul>
| 9
|
2009-02-20T22:34:34Z
| 571,610
|
<p>It's worth mentioning that there is a global keyword, so if you want to refer to the global x:</p>
<pre><code>x = 4
def foo():
x = 7 # x is local to your function
</code></pre>
<p>You need to do this:</p>
<pre><code>x = 4
def foo():
global x # let python know you want to use the top-level x
x = 7
</code></pre>
| 11
|
2009-02-20T23:09:54Z
|
[
"python",
"variables"
] |
Are there any declaration keywords in Python?
| 571,514
|
<p>Are there any declaration keywords in python, like local, global, private, public etc. I know it's type free but how do you know if this statement:</p>
<pre><code>x = 5;
</code></pre>
<ul>
<li>Creates a new variable.</li>
</ul>
<p>or</p>
<ul>
<li>Sets an existing one.</li>
</ul>
| 9
|
2009-02-20T22:34:34Z
| 571,757
|
<p>I really like the understanding that Van Gale is providing, but it doesn't really answer the question of, "how do you know if this statement: creates a new variable or sets an existing variable?"</p>
<p>If you want to know how to recognize it when looking at code, you simply look for a previous assignment. Avoid global variables, which is good practice anyway, and you'll be all set.</p>
<p>Programmatically, you could try to reference the variable, and see if you get a "Name Error" exception</p>
<pre><code>try:
x
except NameError:
# x doesn't exist, do something
else:
# x exists, do something else
</code></pre>
<p>I've never needed to do this... and I doubt you will really need to either. </p>
<h2>soapbox alert !!!</h2>
<p>Even though Python looks kinda loosey-goosey to someone who is used to having to type the class name (or type) over and over and over... it's actually exactly as strict as you want to make it.</p>
<p>If you want strict types, you would do it explictly:</p>
<pre><code>assert(isinstance(variable, type))
</code></pre>
<p>Decorators exist to do this in a very convenient way for function calls...</p>
<p>Before long, you might just come to the conclusion that static type checking (at compile time) doesn't actually make your code that much better. There's only a small benefit for the cost of having to have redundant type information all over the place.</p>
<p>I'm currently working in actionscript, and typing things like:</p>
<pre><code>var win:ThingPicker = PopUpManager.createPopUp(fEmotionsButton,
ThingPicker, false) as ThingPicker;
</code></pre>
<p>which in python would look like:</p>
<pre><code>win = createPopup(parent, ThingPicker)
</code></pre>
<p>And I can see, looking at the actionscript code, that there's simply no benefit to the static type-checking. The variable's lifetime is so short that I would have to be completely drunk to do the wrong thing with it... and have the compiler save me by pointing out a type error. </p>
| 11
|
2009-02-21T00:21:28Z
|
[
"python",
"variables"
] |
Are there any declaration keywords in Python?
| 571,514
|
<p>Are there any declaration keywords in python, like local, global, private, public etc. I know it's type free but how do you know if this statement:</p>
<pre><code>x = 5;
</code></pre>
<ul>
<li>Creates a new variable.</li>
</ul>
<p>or</p>
<ul>
<li>Sets an existing one.</li>
</ul>
| 9
|
2009-02-20T22:34:34Z
| 2,112,033
|
<p>I just realized there's a more direct answer too:</p>
<pre><code>x = 5
def test():
print 'x' in globals()
if __name__ == "__main__":
test()
</code></pre>
<p>So if 'variablename' in globals():
the statement is an assignment
otherwise
the statement is a declaration</p>
| -1
|
2010-01-21T19:04:35Z
|
[
"python",
"variables"
] |
What's the reason of providing some of the default methods in the global scope in Python?
| 571,522
|
<p>What's the reason of providing some of the default methods in the global scope, like the len function, instead of providing them on an instance level, like:</p>
<pre><code>list.len()
</code></pre>
<p>instead of:</p>
<pre><code>len (list)
</code></pre>
<p>I find methods like len to be harder to discover than instance methods.</p>
<p>Is there any reason behind this?</p>
| 1
|
2009-02-20T22:37:44Z
| 571,550
|
<p>You can write</p>
<pre><code>re.match(r"\w+", "dog")
</code></pre>
<p>instead of</p>
<pre><code>pattern = re.compile(r"\w+")
pattern.match("dog")
</code></pre>
<p>Like You noticed, sometimes it doesn't make sense.</p>
| -1
|
2009-02-20T22:47:28Z
|
[
"python",
"function"
] |
What's the reason of providing some of the default methods in the global scope in Python?
| 571,522
|
<p>What's the reason of providing some of the default methods in the global scope, like the len function, instead of providing them on an instance level, like:</p>
<pre><code>list.len()
</code></pre>
<p>instead of:</p>
<pre><code>len (list)
</code></pre>
<p>I find methods like len to be harder to discover than instance methods.</p>
<p>Is there any reason behind this?</p>
| 1
|
2009-02-20T22:37:44Z
| 571,552
|
<p>Once you learn the "len" method, you know you can apply it to any sequence. You don't have to read the doc for each sequence you encounter to find out whether or not it has a len method. There's an expectation that it does.</p>
<p>Built-in functions are not harder to discover because there's a list of built-in methods in the <a href="http://docs.python.org/library/functions.html" rel="nofollow">python documentation</a>. You can learn them all in one sitting from <a href="http://docs.python.org/library/functions.html" rel="nofollow">this page</a> instead of having to hunt for them all over the class library Java style.</p>
| 2
|
2009-02-20T22:48:28Z
|
[
"python",
"function"
] |
What's the reason of providing some of the default methods in the global scope in Python?
| 571,522
|
<p>What's the reason of providing some of the default methods in the global scope, like the len function, instead of providing them on an instance level, like:</p>
<pre><code>list.len()
</code></pre>
<p>instead of:</p>
<pre><code>len (list)
</code></pre>
<p>I find methods like len to be harder to discover than instance methods.</p>
<p>Is there any reason behind this?</p>
| 1
|
2009-02-20T22:37:44Z
| 571,626
|
<p><a href="http://www.python.org/doc/faq/general/#why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list" rel="nofollow">This FAQ entry</a> might answer your question:</p>
<blockquote>
<p>4.7 Why does Python use methods for some functionality (e.g. list.index())
but functions for other (e.g.
len(list))?</p>
<p>The major reason is history. Functions
were used for those operations that
were generic for a group of types and
which were intended to work even for
objects that didn't have methods at
all (e.g. tuples). It is also
convenient to have a function that can
readily be applied to an amorphous
collection of objects when you use the
functional features of Python (map(),
apply() et al).</p>
<p>In fact, implementing len(), max(),
min() as a built-in function is
actually less code than implementing
them as methods for each type. One can
quibble about individual cases but
it's a part of Python, and it's too
late to make such fundamental changes
now. The functions have to remain to
avoid massive code breakage.</p>
<p>Note that for string operations Python
has moved from external functions (the
string module) to methods. However,
len() is still a function.</p>
</blockquote>
<p>There is a list of all those functions (not too many) <a href="http://docs.python.org/library/functions.html" rel="nofollow">here in the docs</a>.</p>
| 4
|
2009-02-20T23:17:55Z
|
[
"python",
"function"
] |
What's the reason of providing some of the default methods in the global scope in Python?
| 571,522
|
<p>What's the reason of providing some of the default methods in the global scope, like the len function, instead of providing them on an instance level, like:</p>
<pre><code>list.len()
</code></pre>
<p>instead of:</p>
<pre><code>len (list)
</code></pre>
<p>I find methods like len to be harder to discover than instance methods.</p>
<p>Is there any reason behind this?</p>
| 1
|
2009-02-20T22:37:44Z
| 571,632
|
<p>This question is very similar to <a href="http://stackoverflow.com/questions/83983/why-isnt-the-len-function-inherited-by-dictionaries-and-lists-in-python">this one</a>. And the answers is the same:</p>
<p>Because Guido van Rossum, the creator of Python, thinks that prefix notation is more readable in some cases. <a href="http://mail.python.org/pipermail/python-3000/2006-November/004643.html" rel="nofollow">Here</a> is the complete answer. I'm going to quote some parts:</p>
<blockquote>
<p>(a) For some operations, prefix notation just reads better than
postfix -- prefix (and infix!) operations have a long tradition in
mathematics which likes notations where the visuals help the
mathematician thinking about a problem. Compare the easy with which we
rewrite a formula like x*(a+b) into x*a + x*b to the clumsiness of
doing the same thing using a raw OO notation.</p>
<p>(b) When I read code that says len(x) I <em>know</em> that it is asking for
the length of something. This tells me two things: the result is an
integer, and the argument is some kind of container. To the contrary,
when I read x.len(), I have to already know that x is some kind of
container implementing an interface or inheriting from a class that
has a standard len(). Witness the confusion we occasionally have when
a class that is not implementing a mapping has a get() or keys()
method, or something that isn't a file has a write() method.</p>
<p>Saying the same thing in another way, I see 'len' as a built-in
<em>operation</em>. I'd hate to lose that. I can't say for sure whether you
meant that or not, but 'def len(self): ...' certainly sounds like you
want to demote it to an ordinary method. I'm strongly -1 on that.</p>
</blockquote>
| 6
|
2009-02-20T23:21:22Z
|
[
"python",
"function"
] |
What's the reason of providing some of the default methods in the global scope in Python?
| 571,522
|
<p>What's the reason of providing some of the default methods in the global scope, like the len function, instead of providing them on an instance level, like:</p>
<pre><code>list.len()
</code></pre>
<p>instead of:</p>
<pre><code>len (list)
</code></pre>
<p>I find methods like len to be harder to discover than instance methods.</p>
<p>Is there any reason behind this?</p>
| 1
|
2009-02-20T22:37:44Z
| 571,636
|
<p>Besides the FAQ answer provided by MrTopf, lists (and other objects) do have a length method <strong>__len__()</strong></p>
<p>The len() function is just a shorthand for calling that method.</p>
| 2
|
2009-02-20T23:23:03Z
|
[
"python",
"function"
] |
What's the reason of providing some of the default methods in the global scope in Python?
| 571,522
|
<p>What's the reason of providing some of the default methods in the global scope, like the len function, instead of providing them on an instance level, like:</p>
<pre><code>list.len()
</code></pre>
<p>instead of:</p>
<pre><code>len (list)
</code></pre>
<p>I find methods like len to be harder to discover than instance methods.</p>
<p>Is there any reason behind this?</p>
| 1
|
2009-02-20T22:37:44Z
| 571,926
|
<p>They are fairly discoverable:</p>
<pre><code>>>> import __builtin__
>>> dir(__builtin__)
['ArithmeticError', 'AssertionError', ...
...
</code></pre>
<p>or better</p>
<pre><code>>>> help(__builtin__)
Help on built-in module __builtin__:
NAME
__builtin__ - Built-in functions, exceptions, and other objects.
...
</code></pre>
| 0
|
2009-02-21T01:53:36Z
|
[
"python",
"function"
] |
The `%` operator
| 571,538
|
<p>I want to find all the numbers divisble by all the numbers between 1 and 5. how do I write the program so that if the remainder of 'start' divided by all the numbers that x goes through is equal to 0 that it will print start. Is there any syntax that will calculate what I'm looking for. thanks.</p>
<p>import math</p>
<pre><code>def main():
one = 1
start = 1
while one == 1:
for x in range(1, 5):
if start % x == 0:
print start
start += 1
</code></pre>
| 0
|
2009-02-20T22:43:06Z
| 571,618
|
<p>if I understood correctly you want something like this:</p>
<pre><code>start = 1
while (True):
flgEvenlyDiv = True
for x in range(1, 5):
if (start % x != 0):
flgEvenlyDiv = False
break
if (flgEvenlyDiv == True):
print start
start += 1
</code></pre>
| 0
|
2009-02-20T23:13:19Z
|
[
"python",
"math"
] |
The `%` operator
| 571,538
|
<p>I want to find all the numbers divisble by all the numbers between 1 and 5. how do I write the program so that if the remainder of 'start' divided by all the numbers that x goes through is equal to 0 that it will print start. Is there any syntax that will calculate what I'm looking for. thanks.</p>
<p>import math</p>
<pre><code>def main():
one = 1
start = 1
while one == 1:
for x in range(1, 5):
if start % x == 0:
print start
start += 1
</code></pre>
| 0
|
2009-02-20T22:43:06Z
| 571,647
|
<p>First of all, you seem to ask for all multiples of 60. Those can be rendered easily like this (beware, this is an infinite loop):</p>
<pre><code>from itertools import count
for i in count():
print i*60
</code></pre>
<p>If you just oversimplified your example, this is a more pythonic (and correct) solution of what you wrote (again an infinite loop):</p>
<pre><code>from itertools import count
# put any test you like in this function
def test(number):
return all((number % i) == 0 for i in range(1,6))
my_numbers = (number for number in count() if test(number))
for number in my_numbers:
print number
</code></pre>
<p>You had a grave bug in your original code: <code>range(1,5)</code> equals <code>[1, 2, 3, 4]</code>, so it would not test whether a number is divisble by 5!</p>
<p>PS: You have used that insane <code>one = 1</code> construct before, and we showd you how to code that in a better way. Please learn from our answers!</p>
| 3
|
2009-02-20T23:27:58Z
|
[
"python",
"math"
] |
Adding elements to python generators
| 571,850
|
<p>Is it possible to append elements to a python generator?</p>
<p>I'm currently trying to get all images from a set of disorganized folders and write them to a new directory. To get the files, I'm using os.walk() which returns a list of image files in a single directory. While I can make a generator out of this single list, I don't know how to combine all these lists into one single generator. Any help would be much appreciated.</p>
<p>Related:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python">Flattening a shallow list in python</a></li>
</ul>
| 15
|
2009-02-21T01:11:36Z
| 571,875
|
<pre><code>def files_gen(topdir='.'):
for root, dirs, files in os.walk(topdir):
# ... do some stuff with files
for f in files:
yield os.path.join(root, f)
# ... do other stuff
for f in files_gen():
print f
</code></pre>
| 4
|
2009-02-21T01:25:53Z
|
[
"python",
"append",
"generator"
] |
Adding elements to python generators
| 571,850
|
<p>Is it possible to append elements to a python generator?</p>
<p>I'm currently trying to get all images from a set of disorganized folders and write them to a new directory. To get the files, I'm using os.walk() which returns a list of image files in a single directory. While I can make a generator out of this single list, I don't know how to combine all these lists into one single generator. Any help would be much appreciated.</p>
<p>Related:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python">Flattening a shallow list in python</a></li>
</ul>
| 15
|
2009-02-21T01:11:36Z
| 571,881
|
<p>Like this.</p>
<pre><code>def threeGens( i, j, k ):
for x in range(i):
yield x
for x in range(j):
yield x
for x in range(k):
yield x
</code></pre>
<p>Works well. </p>
| -1
|
2009-02-21T01:28:36Z
|
[
"python",
"append",
"generator"
] |
Adding elements to python generators
| 571,850
|
<p>Is it possible to append elements to a python generator?</p>
<p>I'm currently trying to get all images from a set of disorganized folders and write them to a new directory. To get the files, I'm using os.walk() which returns a list of image files in a single directory. While I can make a generator out of this single list, I don't know how to combine all these lists into one single generator. Any help would be much appreciated.</p>
<p>Related:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python">Flattening a shallow list in python</a></li>
</ul>
| 15
|
2009-02-21T01:11:36Z
| 571,888
|
<p>You are looking for <a href="http://docs.python.org/library/itertools.html"><code>itertools.chain</code></a>. It will combine multiple iterables into a single one, like this:</p>
<pre><code>>>> for i in itertools.chain([1,2,3], [4,5,6]):
... print i
...
1
2
3
4
5
6
</code></pre>
| 13
|
2009-02-21T01:31:45Z
|
[
"python",
"append",
"generator"
] |
Adding elements to python generators
| 571,850
|
<p>Is it possible to append elements to a python generator?</p>
<p>I'm currently trying to get all images from a set of disorganized folders and write them to a new directory. To get the files, I'm using os.walk() which returns a list of image files in a single directory. While I can make a generator out of this single list, I don't know how to combine all these lists into one single generator. Any help would be much appreciated.</p>
<p>Related:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/406121/flattening-a-shallow-list-in-python">Flattening a shallow list in python</a></li>
</ul>
| 15
|
2009-02-21T01:11:36Z
| 571,928
|
<p>This should do it, where <code>directories</code> is your list of directories:</p>
<pre><code>import os
import itertools
generators = [os.walk(d) for d in directories]
for root, dirs, files in itertools.chain(*generators):
print root, dirs, files
</code></pre>
| 13
|
2009-02-21T01:54:52Z
|
[
"python",
"append",
"generator"
] |
Django and Sqlite Concurrency issue
| 572,009
|
<p>I've done a bit of reading related to the concurrency issues with sqlite, but I don't see how they'd apply to Django since it's inherently single threaded. I'm not using any multiprocess modules either. I have absolutely no experience with concurrent programming either, so if someone can identify WHY the following code is causing an OperationalError: 'database is locked' I'd be grateful.</p>
<p>views.py </p>
<pre><code>def screening(request, ovramt=None):
errors = []
if request.method == "POST":
form = ScreeningForm(request.POST)
if form.is_valid():
print "Woo valid!!"
return HttpResponse()
else: # GET
if ovramt is None:
o = Ovramt.objects.select_related(depth=1).latest("date_completed")
print "found?"
print o.id
else:
try:
o = Ovramt.objects.select_related(depth=1).get(id=ovramt)
except:
errors.append("OVRAMT NOT FOUND")
if o.residents.count() <= 0:
o.add_active_residents()
residents = list(o.residents)
</code></pre>
<p>models.py</p>
<pre><code>def add_active_residents(self):
ssa_res = SSA_Resident.objects.select_related(depth=1).filter(ssa=self.ssa, active=True)
for r in ssa_res:
self.residents.add(r.resident) # Fails Here
self.save()
</code></pre>
<p>The add_active_residents method works fine, until it is called from the views module. Is there an open connection to the database open in the view which prevents writing from the model? Does someone have an explanation why this code will error?</p>
| 4
|
2009-02-21T02:48:27Z
| 572,052
|
<p>In the following method function</p>
<pre><code>def add_active_residents(self):
ssa_res = SSA_Resident.objects.select_related(depth=1).filter(ssa=self.ssa, active=True)
for r in ssa_res:
self.residents.add(r.resident) # Fails Here
self.save()
</code></pre>
<p>Why is there a select_related? You only really need the FK's of <code>ssa_res</code> items. Why do additional queries for related items?</p>
| 4
|
2009-02-21T03:16:22Z
|
[
"python",
"django",
"sqlite",
"concurrency"
] |
Django and Sqlite Concurrency issue
| 572,009
|
<p>I've done a bit of reading related to the concurrency issues with sqlite, but I don't see how they'd apply to Django since it's inherently single threaded. I'm not using any multiprocess modules either. I have absolutely no experience with concurrent programming either, so if someone can identify WHY the following code is causing an OperationalError: 'database is locked' I'd be grateful.</p>
<p>views.py </p>
<pre><code>def screening(request, ovramt=None):
errors = []
if request.method == "POST":
form = ScreeningForm(request.POST)
if form.is_valid():
print "Woo valid!!"
return HttpResponse()
else: # GET
if ovramt is None:
o = Ovramt.objects.select_related(depth=1).latest("date_completed")
print "found?"
print o.id
else:
try:
o = Ovramt.objects.select_related(depth=1).get(id=ovramt)
except:
errors.append("OVRAMT NOT FOUND")
if o.residents.count() <= 0:
o.add_active_residents()
residents = list(o.residents)
</code></pre>
<p>models.py</p>
<pre><code>def add_active_residents(self):
ssa_res = SSA_Resident.objects.select_related(depth=1).filter(ssa=self.ssa, active=True)
for r in ssa_res:
self.residents.add(r.resident) # Fails Here
self.save()
</code></pre>
<p>The add_active_residents method works fine, until it is called from the views module. Is there an open connection to the database open in the view which prevents writing from the model? Does someone have an explanation why this code will error?</p>
| 4
|
2009-02-21T02:48:27Z
| 572,181
|
<p>Sounds like you are actually running a multithreaded application, despite what you say. I am a bit clueless about Django, but I would assume that even though it might be single-threaded, whatever debugging server, or production server you run your application in won't be "inherently single threaded".</p>
| 1
|
2009-02-21T03:48:31Z
|
[
"python",
"django",
"sqlite",
"concurrency"
] |
Django and Sqlite Concurrency issue
| 572,009
|
<p>I've done a bit of reading related to the concurrency issues with sqlite, but I don't see how they'd apply to Django since it's inherently single threaded. I'm not using any multiprocess modules either. I have absolutely no experience with concurrent programming either, so if someone can identify WHY the following code is causing an OperationalError: 'database is locked' I'd be grateful.</p>
<p>views.py </p>
<pre><code>def screening(request, ovramt=None):
errors = []
if request.method == "POST":
form = ScreeningForm(request.POST)
if form.is_valid():
print "Woo valid!!"
return HttpResponse()
else: # GET
if ovramt is None:
o = Ovramt.objects.select_related(depth=1).latest("date_completed")
print "found?"
print o.id
else:
try:
o = Ovramt.objects.select_related(depth=1).get(id=ovramt)
except:
errors.append("OVRAMT NOT FOUND")
if o.residents.count() <= 0:
o.add_active_residents()
residents = list(o.residents)
</code></pre>
<p>models.py</p>
<pre><code>def add_active_residents(self):
ssa_res = SSA_Resident.objects.select_related(depth=1).filter(ssa=self.ssa, active=True)
for r in ssa_res:
self.residents.add(r.resident) # Fails Here
self.save()
</code></pre>
<p>The add_active_residents method works fine, until it is called from the views module. Is there an open connection to the database open in the view which prevents writing from the model? Does someone have an explanation why this code will error?</p>
| 4
|
2009-02-21T02:48:27Z
| 572,280
|
<p>Are you using Python 2.6?</p>
<p>If so, this is (apparently) a known issue that can be mitigated by adding:</p>
<pre><code>DATABASE_OPTIONS = {'timeout': 30}
</code></pre>
<p>to your settings.py</p>
<p>See <a href="http://code.djangoproject.com/ticket/9409" rel="nofollow">http://code.djangoproject.com/ticket/9409</a></p>
| 2
|
2009-02-21T04:33:57Z
|
[
"python",
"django",
"sqlite",
"concurrency"
] |
Django and Sqlite Concurrency issue
| 572,009
|
<p>I've done a bit of reading related to the concurrency issues with sqlite, but I don't see how they'd apply to Django since it's inherently single threaded. I'm not using any multiprocess modules either. I have absolutely no experience with concurrent programming either, so if someone can identify WHY the following code is causing an OperationalError: 'database is locked' I'd be grateful.</p>
<p>views.py </p>
<pre><code>def screening(request, ovramt=None):
errors = []
if request.method == "POST":
form = ScreeningForm(request.POST)
if form.is_valid():
print "Woo valid!!"
return HttpResponse()
else: # GET
if ovramt is None:
o = Ovramt.objects.select_related(depth=1).latest("date_completed")
print "found?"
print o.id
else:
try:
o = Ovramt.objects.select_related(depth=1).get(id=ovramt)
except:
errors.append("OVRAMT NOT FOUND")
if o.residents.count() <= 0:
o.add_active_residents()
residents = list(o.residents)
</code></pre>
<p>models.py</p>
<pre><code>def add_active_residents(self):
ssa_res = SSA_Resident.objects.select_related(depth=1).filter(ssa=self.ssa, active=True)
for r in ssa_res:
self.residents.add(r.resident) # Fails Here
self.save()
</code></pre>
<p>The add_active_residents method works fine, until it is called from the views module. Is there an open connection to the database open in the view which prevents writing from the model? Does someone have an explanation why this code will error?</p>
| 4
|
2009-02-21T02:48:27Z
| 575,107
|
<p>My understanding is that only write operations will result in a db-locked condition.
<a href="http://www.sqlite.org/lockingv3.html" rel="nofollow">http://www.sqlite.org/lockingv3.html</a></p>
<p>It's hard to say what the problem is without knowing how django is handling sqlite internally.</p>
<p>Speaking from using sqlite with standard cgi, I've noticed that in some cases it can take a 'long' time to release the lock. You may want to increase the timeout value mentioned by Matthew Christensen.</p>
| 2
|
2009-02-22T15:53:42Z
|
[
"python",
"django",
"sqlite",
"concurrency"
] |
How do I create a Django form that displays a checkbox label to the right of the checkbox?
| 572,263
|
<p>When I define a Django form class similar to this:</p>
<pre><code>def class MyForm(forms.Form):
check = forms.BooleanField(required=True, label="Check this")
</code></pre>
<p>It expands to HTML that looks like this:</p>
<pre><code><form action="." id="form" method=POST>
<p><label for="check">Check this:</label> <input type="checkbox" name="check" id="check" /></p>
<p><input type=submit value="Submit"></p>
</form>
</code></pre>
<p>I would like the checkbox input element to have a label that follows the checkbox, not the other way around. Is there a way to convince Django to do that?</p>
<p><strong>[Edit]</strong></p>
<p>Thanks for the answer from Jonas - still, while it fixes the issue I asked about (checkbox labels are rendered to the right of the checkbox) it introduces a new problem (all widget labels are rendered to the right of their widgets...)</p>
<p>I'd like to avoid overriding _html_output() since it's obviously not designed for it. The design I would come up with would be to implement a field html output method in the Field classes, override the one for the Boolean field and use that method in _html_output(). Sadly, the Django developers chose to go a different way, and I would like to work within the existing framework as much as possible. </p>
<p>CSS sounds like a decent approach, except that I don't know enough CSS to pull this off or even to decide whether I like this approach or not. Besides, I prefer markup that still resembles the final output, at least in rendering order.</p>
<p>Furthermore, since it can be reasonable to have more than one style sheet for any particular markup, doing this in CSS could mean having to do it multiple times for multiple styles, which pretty much makes CSS the wrong answer. </p>
<p><strong>[Edit]</strong></p>
<p>Seems like I'm answering my own question below. If anyone has a better idea how to do this, don't be shy.</p>
| 28
|
2009-02-21T04:18:17Z
| 572,554
|
<p>Order of inputs and labels is provided via normal_row parameter of the form and there are no different row patterns for checkboxes. So there are two ways to do this (in 0.96 version exactly):<br />
1. override _html_output of the form<br />
2. use CSS to change position of the label and checkbox</p>
| 1
|
2009-02-21T06:52:58Z
|
[
"python",
"django",
"checkbox"
] |
How do I create a Django form that displays a checkbox label to the right of the checkbox?
| 572,263
|
<p>When I define a Django form class similar to this:</p>
<pre><code>def class MyForm(forms.Form):
check = forms.BooleanField(required=True, label="Check this")
</code></pre>
<p>It expands to HTML that looks like this:</p>
<pre><code><form action="." id="form" method=POST>
<p><label for="check">Check this:</label> <input type="checkbox" name="check" id="check" /></p>
<p><input type=submit value="Submit"></p>
</form>
</code></pre>
<p>I would like the checkbox input element to have a label that follows the checkbox, not the other way around. Is there a way to convince Django to do that?</p>
<p><strong>[Edit]</strong></p>
<p>Thanks for the answer from Jonas - still, while it fixes the issue I asked about (checkbox labels are rendered to the right of the checkbox) it introduces a new problem (all widget labels are rendered to the right of their widgets...)</p>
<p>I'd like to avoid overriding _html_output() since it's obviously not designed for it. The design I would come up with would be to implement a field html output method in the Field classes, override the one for the Boolean field and use that method in _html_output(). Sadly, the Django developers chose to go a different way, and I would like to work within the existing framework as much as possible. </p>
<p>CSS sounds like a decent approach, except that I don't know enough CSS to pull this off or even to decide whether I like this approach or not. Besides, I prefer markup that still resembles the final output, at least in rendering order.</p>
<p>Furthermore, since it can be reasonable to have more than one style sheet for any particular markup, doing this in CSS could mean having to do it multiple times for multiple styles, which pretty much makes CSS the wrong answer. </p>
<p><strong>[Edit]</strong></p>
<p>Seems like I'm answering my own question below. If anyone has a better idea how to do this, don't be shy.</p>
| 28
|
2009-02-21T04:18:17Z
| 574,460
|
<p>Here's what I ended up doing. I wrote a custom template stringfilter to switch the tags around. Now, my template code looks like this:</p>
<pre><code>{% load pretty_forms %}
<form action="." method="POST">
{{ form.as_p|pretty_checkbox }}
<p><input type="submit" value="Submit"></p>
</form>
</code></pre>
<p>The only difference from a plain Django template is the addition of the {% load %} template tag and the <strong>pretty_checkbox</strong> filter.</p>
<p>Here's a functional but ugly implementation of <strong>pretty_checkbox</strong> - this code doesn't have any error handling, it assumes that the Django generated attributes are formatted in a very specific way, and it would be a bad idea to use anything like this in your code:</p>
<pre><code>from django import template
from django.template.defaultfilters import stringfilter
import logging
register=template.Library()
@register.filter(name='pretty_checkbox')
@stringfilter
def pretty_checkbox(value):
# Iterate over the HTML fragment, extract <label> and <input> tags, and
# switch the order of the pairs where the input type is "checkbox".
scratch = value
output = ''
try:
while True:
ls = scratch.find('<label')
if ls > -1:
le = scratch.find('</label>')
ins = scratch.find('<input')
ine = scratch.find('/>', ins)
# Check whether we're dealing with a checkbox:
if scratch[ins:ine+2].find(' type="checkbox" ')>-1:
# Switch the tags
output += scratch[:ls]
output += scratch[ins:ine+2]
output += scratch[ls:le-1]+scratch[le:le+8]
else:
output += scratch[:ine+2]
scratch = scratch[ine+2:]
else:
output += scratch
break
except:
logging.error("pretty_checkbox caught an exception")
return output
</code></pre>
<p><strong>pretty_checkbox</strong> scans its string argument, finds pairs of <label> and <input> tags, and switches them around if the <input> tag's type is "checkbox". It also strips the last character of the label, which happens to be the ':' character.</p>
<p>Advantages: </p>
<ol>
<li>No futzing with CSS.</li>
<li>The markup ends up looking the way it's supposed to.</li>
<li>I didn't hack Django internals.</li>
<li>The template is nice, compact and idiomatic.</li>
</ol>
<p>Disadvantages: </p>
<ol>
<li>The filter code needs to be tested for exciting values of the labels and input field names. </li>
<li>There's probably something somewhere out there that does it better and faster. </li>
<li>More work than I planned on doing on a Saturday.</li>
</ol>
| 1
|
2009-02-22T06:25:08Z
|
[
"python",
"django",
"checkbox"
] |
How do I create a Django form that displays a checkbox label to the right of the checkbox?
| 572,263
|
<p>When I define a Django form class similar to this:</p>
<pre><code>def class MyForm(forms.Form):
check = forms.BooleanField(required=True, label="Check this")
</code></pre>
<p>It expands to HTML that looks like this:</p>
<pre><code><form action="." id="form" method=POST>
<p><label for="check">Check this:</label> <input type="checkbox" name="check" id="check" /></p>
<p><input type=submit value="Submit"></p>
</form>
</code></pre>
<p>I would like the checkbox input element to have a label that follows the checkbox, not the other way around. Is there a way to convince Django to do that?</p>
<p><strong>[Edit]</strong></p>
<p>Thanks for the answer from Jonas - still, while it fixes the issue I asked about (checkbox labels are rendered to the right of the checkbox) it introduces a new problem (all widget labels are rendered to the right of their widgets...)</p>
<p>I'd like to avoid overriding _html_output() since it's obviously not designed for it. The design I would come up with would be to implement a field html output method in the Field classes, override the one for the Boolean field and use that method in _html_output(). Sadly, the Django developers chose to go a different way, and I would like to work within the existing framework as much as possible. </p>
<p>CSS sounds like a decent approach, except that I don't know enough CSS to pull this off or even to decide whether I like this approach or not. Besides, I prefer markup that still resembles the final output, at least in rendering order.</p>
<p>Furthermore, since it can be reasonable to have more than one style sheet for any particular markup, doing this in CSS could mean having to do it multiple times for multiple styles, which pretty much makes CSS the wrong answer. </p>
<p><strong>[Edit]</strong></p>
<p>Seems like I'm answering my own question below. If anyone has a better idea how to do this, don't be shy.</p>
| 28
|
2009-02-21T04:18:17Z
| 2,045,308
|
<p>Here's a solution I've come up with (Django v1.1):</p>
<pre><code>{% load myfilters %}
[...]
{% for field in form %}
[...]
{% if field.field.widget|is_checkbox %}
{{ field }}{{ field.label_tag }}
{% else %}
{{ field.label_tag }}{{ field }}
{% endif %}
[...]
{% endfor %}
</code></pre>
<p>You'll need to create a custom template tag (in this example in a "myfilters.py" file) containing something like this:</p>
<pre><code>from django import template
from django.forms.fields import CheckboxInput
register = template.Library()
@register.filter(name='is_checkbox')
def is_checkbox(value):
return isinstance(value, CheckboxInput)
</code></pre>
<p>More info on custom template tags available <a href="http://docs.djangoproject.com/en/dev/howto/custom-template-tags/">here</a>.</p>
<p><strong>Edit</strong>: in the spirit of asker's own answer:</p>
<p>Advantages:</p>
<ol>
<li>No futzing with CSS.</li>
<li>The markup ends up looking the way it's supposed to.</li>
<li>I didn't hack Django internals. (but had to look at quite a bunch)</li>
<li>The template is nice, compact and idiomatic.</li>
<li>The filter code plays nice regardless of the exact values of the labels and input field names.</li>
</ol>
<p>Disadvantages:</p>
<ol>
<li>There's probably something somewhere out there that does it better and faster.</li>
<li>Unlikely that the client will be willing to pay for all the time spent on this just to move the label to the right...</li>
</ol>
| 30
|
2010-01-11T22:06:27Z
|
[
"python",
"django",
"checkbox"
] |
How do I create a Django form that displays a checkbox label to the right of the checkbox?
| 572,263
|
<p>When I define a Django form class similar to this:</p>
<pre><code>def class MyForm(forms.Form):
check = forms.BooleanField(required=True, label="Check this")
</code></pre>
<p>It expands to HTML that looks like this:</p>
<pre><code><form action="." id="form" method=POST>
<p><label for="check">Check this:</label> <input type="checkbox" name="check" id="check" /></p>
<p><input type=submit value="Submit"></p>
</form>
</code></pre>
<p>I would like the checkbox input element to have a label that follows the checkbox, not the other way around. Is there a way to convince Django to do that?</p>
<p><strong>[Edit]</strong></p>
<p>Thanks for the answer from Jonas - still, while it fixes the issue I asked about (checkbox labels are rendered to the right of the checkbox) it introduces a new problem (all widget labels are rendered to the right of their widgets...)</p>
<p>I'd like to avoid overriding _html_output() since it's obviously not designed for it. The design I would come up with would be to implement a field html output method in the Field classes, override the one for the Boolean field and use that method in _html_output(). Sadly, the Django developers chose to go a different way, and I would like to work within the existing framework as much as possible. </p>
<p>CSS sounds like a decent approach, except that I don't know enough CSS to pull this off or even to decide whether I like this approach or not. Besides, I prefer markup that still resembles the final output, at least in rendering order.</p>
<p>Furthermore, since it can be reasonable to have more than one style sheet for any particular markup, doing this in CSS could mean having to do it multiple times for multiple styles, which pretty much makes CSS the wrong answer. </p>
<p><strong>[Edit]</strong></p>
<p>Seems like I'm answering my own question below. If anyone has a better idea how to do this, don't be shy.</p>
| 28
|
2009-02-21T04:18:17Z
| 2,308,693
|
<p>I took the answer from romkyns and made it a little more general</p>
<pre><code>def field_type(field, ftype):
try:
t = field.field.widget.__class__.__name__
return t.lower() == ftype
except:
pass
return False
</code></pre>
<p>This way you can check the widget type directly with a string</p>
<pre><code>{% if field|field_type:'checkboxinput' %}
<label>{{ field }} {{ field.label }}</label>
{% else %}
<label> {{ field.label }} </label> {{ field }}
{% endif %}
</code></pre>
| 13
|
2010-02-22T03:52:58Z
|
[
"python",
"django",
"checkbox"
] |
How do I create a Django form that displays a checkbox label to the right of the checkbox?
| 572,263
|
<p>When I define a Django form class similar to this:</p>
<pre><code>def class MyForm(forms.Form):
check = forms.BooleanField(required=True, label="Check this")
</code></pre>
<p>It expands to HTML that looks like this:</p>
<pre><code><form action="." id="form" method=POST>
<p><label for="check">Check this:</label> <input type="checkbox" name="check" id="check" /></p>
<p><input type=submit value="Submit"></p>
</form>
</code></pre>
<p>I would like the checkbox input element to have a label that follows the checkbox, not the other way around. Is there a way to convince Django to do that?</p>
<p><strong>[Edit]</strong></p>
<p>Thanks for the answer from Jonas - still, while it fixes the issue I asked about (checkbox labels are rendered to the right of the checkbox) it introduces a new problem (all widget labels are rendered to the right of their widgets...)</p>
<p>I'd like to avoid overriding _html_output() since it's obviously not designed for it. The design I would come up with would be to implement a field html output method in the Field classes, override the one for the Boolean field and use that method in _html_output(). Sadly, the Django developers chose to go a different way, and I would like to work within the existing framework as much as possible. </p>
<p>CSS sounds like a decent approach, except that I don't know enough CSS to pull this off or even to decide whether I like this approach or not. Besides, I prefer markup that still resembles the final output, at least in rendering order.</p>
<p>Furthermore, since it can be reasonable to have more than one style sheet for any particular markup, doing this in CSS could mean having to do it multiple times for multiple styles, which pretty much makes CSS the wrong answer. </p>
<p><strong>[Edit]</strong></p>
<p>Seems like I'm answering my own question below. If anyone has a better idea how to do this, don't be shy.</p>
| 28
|
2009-02-21T04:18:17Z
| 15,308,315
|
<p>All presented solutions involve template modifications, which are in general rather inefficient concerning performance. Here's a custom widget that does the job:</p>
<pre><code>from django import forms
from django.forms.fields import BooleanField
from django.forms.util import flatatt
from django.utils.encoding import force_text
from django.utils.html import format_html
from django.utils.translation import ugettext as _
class PrettyCheckboxWidget(forms.widgets.CheckboxInput):
def render(self, name, value, attrs=None):
final_attrs = self.build_attrs(attrs, type='checkbox', name=name)
if self.check_test(value):
final_attrs['checked'] = 'checked'
if not (value is True or value is False or value is None or value == ''):
final_attrs['value'] = force_text(value)
if 'prettycheckbox-label' in final_attrs:
label = _(final_attrs.pop('prettycheckbox-label'))
else:
label = ''
return format_html('<label for="{0}"><input{1} /> {2}</label>', attrs['id'], flatatt(final_attrs), label)
class PrettyCheckboxField(BooleanField):
widget = PrettyCheckboxWidget
def __init__(self, *args, **kwargs):
if kwargs['label']:
kwargs['widget'].attrs['prettycheckbox-label'] = kwargs['label']
kwargs['label'] = ''
super(PrettyCheckboxField, self).__init__(*args, **kwargs)
# usage in form
class MyForm(forms.Form):
my_boolean = PrettyCheckboxField(label=_('Some label'), widget=PrettyCheckboxWidget())
</code></pre>
<p>I have <em>PrettyCheckboxWidget</em> and <em>PrettyCheckboxField</em> in an extra file, so they may be imported where needed. If you don't need translations, you can remove the ugettext parts. This code works on <strong>Django 1.5</strong> and is untested for lower versions.</p>
<p><strong>Advantages:</strong></p>
<ul>
<li>Highly performant, needs no template modifications</li>
<li>Easy to use as a custom widget</li>
</ul>
<p><strong>Disadvantages:</strong></p>
<ul>
<li>"as_table" renders the checkbox + label inside the second column</li>
<li>{{ field.label }} inside the template is empty. The label is instead bound to {{ field }}</li>
<li>More work than I planned on doing on a Saturday ;-)</li>
</ul>
| 10
|
2013-03-09T07:18:55Z
|
[
"python",
"django",
"checkbox"
] |
How do I create a Django form that displays a checkbox label to the right of the checkbox?
| 572,263
|
<p>When I define a Django form class similar to this:</p>
<pre><code>def class MyForm(forms.Form):
check = forms.BooleanField(required=True, label="Check this")
</code></pre>
<p>It expands to HTML that looks like this:</p>
<pre><code><form action="." id="form" method=POST>
<p><label for="check">Check this:</label> <input type="checkbox" name="check" id="check" /></p>
<p><input type=submit value="Submit"></p>
</form>
</code></pre>
<p>I would like the checkbox input element to have a label that follows the checkbox, not the other way around. Is there a way to convince Django to do that?</p>
<p><strong>[Edit]</strong></p>
<p>Thanks for the answer from Jonas - still, while it fixes the issue I asked about (checkbox labels are rendered to the right of the checkbox) it introduces a new problem (all widget labels are rendered to the right of their widgets...)</p>
<p>I'd like to avoid overriding _html_output() since it's obviously not designed for it. The design I would come up with would be to implement a field html output method in the Field classes, override the one for the Boolean field and use that method in _html_output(). Sadly, the Django developers chose to go a different way, and I would like to work within the existing framework as much as possible. </p>
<p>CSS sounds like a decent approach, except that I don't know enough CSS to pull this off or even to decide whether I like this approach or not. Besides, I prefer markup that still resembles the final output, at least in rendering order.</p>
<p>Furthermore, since it can be reasonable to have more than one style sheet for any particular markup, doing this in CSS could mean having to do it multiple times for multiple styles, which pretty much makes CSS the wrong answer. </p>
<p><strong>[Edit]</strong></p>
<p>Seems like I'm answering my own question below. If anyone has a better idea how to do this, don't be shy.</p>
| 28
|
2009-02-21T04:18:17Z
| 17,808,895
|
<p>I know that the user excluded CSS, but considered the top answers take half an hour of work to so such a small thing, but knowing that details like these are important on a website, I'd settle for the CSS solution.</p>
<p>checkbox.css</p>
<pre><code>input[type="checkbox"] {
float: left;
margin-right: 10px;
margin-top: 4px;
}
</code></pre>
<p>forms.py</p>
<pre><code>class MyForm(forms.ModelForm):
# ...
class Media:
css = {
'all': 'checkbox.css',
}
</code></pre>
<p>template.html</p>
<pre><code>{{ form.media }}
{{ form.as_p }}
</code></pre>
<p>Advantages:</p>
<ul>
<li>fast!</li>
<li>no futzing with template tags (just <code>form.as_p</code>)</li>
<li>no new damned widgets</li>
<li>the CSS file is automatically included in every form</li>
</ul>
<p>Disadvantages:</p>
<ul>
<li>the HTML doesn't reflect the presentation (but is good enough!)</li>
<li>your frontendist could complain</li>
</ul>
| 1
|
2013-07-23T11:27:15Z
|
[
"python",
"django",
"checkbox"
] |
How do I create a Django form that displays a checkbox label to the right of the checkbox?
| 572,263
|
<p>When I define a Django form class similar to this:</p>
<pre><code>def class MyForm(forms.Form):
check = forms.BooleanField(required=True, label="Check this")
</code></pre>
<p>It expands to HTML that looks like this:</p>
<pre><code><form action="." id="form" method=POST>
<p><label for="check">Check this:</label> <input type="checkbox" name="check" id="check" /></p>
<p><input type=submit value="Submit"></p>
</form>
</code></pre>
<p>I would like the checkbox input element to have a label that follows the checkbox, not the other way around. Is there a way to convince Django to do that?</p>
<p><strong>[Edit]</strong></p>
<p>Thanks for the answer from Jonas - still, while it fixes the issue I asked about (checkbox labels are rendered to the right of the checkbox) it introduces a new problem (all widget labels are rendered to the right of their widgets...)</p>
<p>I'd like to avoid overriding _html_output() since it's obviously not designed for it. The design I would come up with would be to implement a field html output method in the Field classes, override the one for the Boolean field and use that method in _html_output(). Sadly, the Django developers chose to go a different way, and I would like to work within the existing framework as much as possible. </p>
<p>CSS sounds like a decent approach, except that I don't know enough CSS to pull this off or even to decide whether I like this approach or not. Besides, I prefer markup that still resembles the final output, at least in rendering order.</p>
<p>Furthermore, since it can be reasonable to have more than one style sheet for any particular markup, doing this in CSS could mean having to do it multiple times for multiple styles, which pretty much makes CSS the wrong answer. </p>
<p><strong>[Edit]</strong></p>
<p>Seems like I'm answering my own question below. If anyone has a better idea how to do this, don't be shy.</p>
| 28
|
2009-02-21T04:18:17Z
| 28,530,013
|
<p>Changing checkbox position in Django admin can be quite tricky, but luckily there is a simple solution using custom widget:</p>
<pre><code>from django.forms.widgets import Widget, CheckboxInput, boolean_check
class RightCheckbox(Widget):
render = CheckboxInput().render
def __init__(self, attrs=None, check_test=None):
super(RightCheckbox, self).__init__(attrs)
self.check_test = boolean_check if check_test is None else check_test
</code></pre>
<p>Django uses left position only when widget is subclass of <code>CheckboxInput</code></p>
| 0
|
2015-02-15T19:11:24Z
|
[
"python",
"django",
"checkbox"
] |
Solr search with escaping solr reserved keywords
| 572,599
|
<p>How do i query fields that contain solr reserved keywords as ":" in solr?</p>
<p>For instance,</p>
<pre><code>q = 'uri:http://www.example.com'
</code></pre>
<p>throws up an error for "http://www.example.com" containing reserved word ":"</p>
| 4
|
2009-02-21T07:46:45Z
| 572,725
|
<p>Escape/replace Lucene reserved characters during indexing and store original value in separate field (<code>stored="true" indexed="false"</code> in schema). If you replace reserved characters with space, you'll get <code>http www.example.com</code> in indexed field and <code>http://www.example.com</code> in stored. Depending on the type of indexed field, you'd be able to query for exact value (if it is plain string) or for tokens (if it has analyzer).</p>
| 1
|
2009-02-21T10:07:15Z
|
[
"python",
"solr",
"pysolr"
] |
Solr search with escaping solr reserved keywords
| 572,599
|
<p>How do i query fields that contain solr reserved keywords as ":" in solr?</p>
<p>For instance,</p>
<pre><code>q = 'uri:http://www.example.com'
</code></pre>
<p>throws up an error for "http://www.example.com" containing reserved word ":"</p>
| 4
|
2009-02-21T07:46:45Z
| 573,082
|
<p>I just tested this and it seem that simply escaping ":" like "\:" does the trick:</p>
<pre><code>q = 'uri:http\://www.example.com'
</code></pre>
<p>For my the index of my own site I tend to simply store the path of the URL though as I know the domain myself so that wasn't an issue for me before. But if you index external URLs then of course you need the full URL.</p>
| 5
|
2009-02-21T14:10:54Z
|
[
"python",
"solr",
"pysolr"
] |
CPython internal structures
| 572,780
|
<p>GAE has various limitations, one of which is size of biggest allocatable block of memory amounting to 1Mb (now 10 times more, but that doesn't change the question). The limitation means that one cannot put more then some number of items in list() as CPython would try to allocate contiguous memory block for element pointers. Having huge list()s can be considered bad programming practice, but even if no huge structure is created in program itself, CPython maintains some behind the scenes.</p>
<p>It appears that CPython is maintaining single global list of objects or something. I.e. application that has many small objects tend to allocate bigger and bigger single blocks of memory.</p>
<p>First idea was gc, and disabling it changes application behavior a bit but still some structures are maintained.</p>
<p>A simplest short application that experience the issue is:</p>
<pre><code>a = b = []
number_of_lists = 8000000
for i in xrange(number_of_lists):
b.append([])
b = b[0]
</code></pre>
<p>Can anyone enlighten me how to prevent CPython from allocating huge internal structures when having many objects in application?</p>
| 3
|
2009-02-21T10:41:40Z
| 572,789
|
<p>I'm a bit confused as to what you're asking. In that code example, nothing should be garbage collected, as you're never actually killing off any references. You're holding a reference to the top level list in a and you're adding nested lists (held in b at each iteration) inside of that. If you remove the 'a =', <em>then</em> you've got unreferenced objects.</p>
<p>Edit: In response to the first part, yes, Python holds a list of objects so it can know what to cull. Is that the whole question? If not, comment/edit your question and I'll do my best to help fill in the gaps.</p>
| 0
|
2009-02-21T10:47:02Z
|
[
"python",
"google-app-engine",
"data-structures",
"internals",
"cpython"
] |
CPython internal structures
| 572,780
|
<p>GAE has various limitations, one of which is size of biggest allocatable block of memory amounting to 1Mb (now 10 times more, but that doesn't change the question). The limitation means that one cannot put more then some number of items in list() as CPython would try to allocate contiguous memory block for element pointers. Having huge list()s can be considered bad programming practice, but even if no huge structure is created in program itself, CPython maintains some behind the scenes.</p>
<p>It appears that CPython is maintaining single global list of objects or something. I.e. application that has many small objects tend to allocate bigger and bigger single blocks of memory.</p>
<p>First idea was gc, and disabling it changes application behavior a bit but still some structures are maintained.</p>
<p>A simplest short application that experience the issue is:</p>
<pre><code>a = b = []
number_of_lists = 8000000
for i in xrange(number_of_lists):
b.append([])
b = b[0]
</code></pre>
<p>Can anyone enlighten me how to prevent CPython from allocating huge internal structures when having many objects in application?</p>
| 3
|
2009-02-21T10:41:40Z
| 572,821
|
<p>What are you trying to accomplish with the</p>
<pre><code>a = b = []
</code></pre>
<p>and</p>
<pre><code>b = b[0]
</code></pre>
<p>statements? It's certainly odd to see statements like that in Python, because they don't do what you might naively expect: in that example, <code>a</code> and <code>b</code> are two names for the <em>same</em> list (think pointers in C). If you're doing a lot of manipulation like that, it's easy to confuse the garbage collector (and yourself!) because you've got a lot of strange references floating around that haven't been properly cleared.</p>
<p>It's hard to diagnose what's wrong with that code without knowing why you want to do what it appears to be doing. Sure, it exposes a bit of interpreter weirdness... but I'm guessing you're approaching your problem in an odd way, and a more Pythonic approach might yield better results.</p>
| 0
|
2009-02-21T11:20:33Z
|
[
"python",
"google-app-engine",
"data-structures",
"internals",
"cpython"
] |
CPython internal structures
| 572,780
|
<p>GAE has various limitations, one of which is size of biggest allocatable block of memory amounting to 1Mb (now 10 times more, but that doesn't change the question). The limitation means that one cannot put more then some number of items in list() as CPython would try to allocate contiguous memory block for element pointers. Having huge list()s can be considered bad programming practice, but even if no huge structure is created in program itself, CPython maintains some behind the scenes.</p>
<p>It appears that CPython is maintaining single global list of objects or something. I.e. application that has many small objects tend to allocate bigger and bigger single blocks of memory.</p>
<p>First idea was gc, and disabling it changes application behavior a bit but still some structures are maintained.</p>
<p>A simplest short application that experience the issue is:</p>
<pre><code>a = b = []
number_of_lists = 8000000
for i in xrange(number_of_lists):
b.append([])
b = b[0]
</code></pre>
<p>Can anyone enlighten me how to prevent CPython from allocating huge internal structures when having many objects in application?</p>
| 3
|
2009-02-21T10:41:40Z
| 573,021
|
<p>On a 32-bit system, each of the 8000000 lists you create will allocate 20 bytes for the list object itself, plus 16 bytes for a vector of list elements. So you are trying to allocate at least (20+16) * 8000000 = 20168000000 bytes, about 20 GB. And that's in the best case, if the system malloc only allocates exactly as much memory as requested.</p>
<p>I calculated the size of the list object as follows:</p>
<ul>
<li>2 Pointers in the <code>PyListObject</code> structure itself (see <a href="http://svn.python.org/view/python/branches/release26-maint/Include/listobject.h?view=markup">listobject.h</a>)</li>
<li>1 Pointer and one <code>Py_ssize_t</code> for the <code>PyObject_HEAD</code> part of the list object (see <a href="http://svn.python.org/view/python/branches/release26-maint/Include/object.h?view=markup">object.h</a>)</li>
<li>one <code>Py_ssize_t</code> for the <code>PyObject_VAR_HEAD</code> (also in object.h)</li>
</ul>
<p>The vector of list elements is slightly overallocated to avoid having to resize it at each append - see list_resize in <a href="http://svn.python.org/view/python/branches/release26-maint/Objects/listobject.c?view=markup">listobject.c</a>. The sizes are 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ... Thus, your one-element lists will allocate room for 4 elements.</p>
<p>Your data structure is a somewhat pathological example, paying the price of a variable-sized list object without utilizing it - all your lists have only a single element. You could avoid the 12 bytes overallocation by using tuples instead of lists, but to further reduce the memory consumption, you will have to use a different data structure that uses fewer objects. It's hard to be more specific, as I don't know what you are trying to accomplish.</p>
| 8
|
2009-02-21T13:43:26Z
|
[
"python",
"google-app-engine",
"data-structures",
"internals",
"cpython"
] |
CPython internal structures
| 572,780
|
<p>GAE has various limitations, one of which is size of biggest allocatable block of memory amounting to 1Mb (now 10 times more, but that doesn't change the question). The limitation means that one cannot put more then some number of items in list() as CPython would try to allocate contiguous memory block for element pointers. Having huge list()s can be considered bad programming practice, but even if no huge structure is created in program itself, CPython maintains some behind the scenes.</p>
<p>It appears that CPython is maintaining single global list of objects or something. I.e. application that has many small objects tend to allocate bigger and bigger single blocks of memory.</p>
<p>First idea was gc, and disabling it changes application behavior a bit but still some structures are maintained.</p>
<p>A simplest short application that experience the issue is:</p>
<pre><code>a = b = []
number_of_lists = 8000000
for i in xrange(number_of_lists):
b.append([])
b = b[0]
</code></pre>
<p>Can anyone enlighten me how to prevent CPython from allocating huge internal structures when having many objects in application?</p>
| 3
|
2009-02-21T10:41:40Z
| 573,452
|
<p>So that you're aware of it, Python has its own allocator. You can disable it using --without-pyalloc during the configure step.</p>
<p>However, the largest arena is 256KB so that shouldn't be the problem. You can also compile Python with debugging enabled, using --with-pydebug. This would give you more information about memory use.</p>
<p>I suspect your hunch and am sure that oefe's diagnosis are correct. A list uses contiguous memory, so if your list gets too large for a system arena then you're out of luck. If you're really adventurous you can reimplement PyList to use multiple blocks, but that's going to be a lot of work since various bits of Python expect contiguous data.</p>
| 0
|
2009-02-21T17:43:43Z
|
[
"python",
"google-app-engine",
"data-structures",
"internals",
"cpython"
] |
Drawing a chart with proportional X axis in Python
| 572,808
|
<p><br />
Is there an easy way to draw a date/value chart in Python, if the "dates" axis had non-equidistant values?<br />
For example, given these: </p>
<p>2009-02-01: 10<br />
2009-02-02: 13<br />
2009-02-07: 25<br />
2009-03-01: 80</p>
<p>I'd like the chart to show that between the 2nd and 3nd value there's a longer gap than between the 1st and the 2nd.<br />
I tried a few chart libraries but they all seem to assume that the X axis has non-scalar values..<br />
(Side note: the chart should be exportable to PNG/GIF/whatever)<br />
Thanks for your time!</p>
| 2
|
2009-02-21T11:06:21Z
| 572,811
|
<p>If it is enough for you to get a PNG with the chart, you can use <a href="http://code.google.com/intl/de-DE/apis/chart/" rel="nofollow">Google Chart API</a> which will give you a PNG image you can save. You could also use your data to parse the URL using Python.</p>
<p>EDIT: <a href="http://chart.apis.google.com/chart?chs=200x200&cht=s&chd=t:1,2,7|10,13,25&chds=0,10,0,30" rel="nofollow">Image URL</a> for your example (very basic).</p>
| 1
|
2009-02-21T11:11:21Z
|
[
"python",
"charts"
] |
Drawing a chart with proportional X axis in Python
| 572,808
|
<p><br />
Is there an easy way to draw a date/value chart in Python, if the "dates" axis had non-equidistant values?<br />
For example, given these: </p>
<p>2009-02-01: 10<br />
2009-02-02: 13<br />
2009-02-07: 25<br />
2009-03-01: 80</p>
<p>I'd like the chart to show that between the 2nd and 3nd value there's a longer gap than between the 1st and the 2nd.<br />
I tried a few chart libraries but they all seem to assume that the X axis has non-scalar values..<br />
(Side note: the chart should be exportable to PNG/GIF/whatever)<br />
Thanks for your time!</p>
| 2
|
2009-02-21T11:06:21Z
| 573,380
|
<p>you should be able to do this with <a href="http://matplotlib.sourceforge.net/" rel="nofollow">matplotlib</a> barchart. you can use xticks to give the x-axis date values, and the 'left' sizes don't have to be homogeneous. see the <a href="http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.bar" rel="nofollow">documentation</a> for barchart for a full list of parameters.</p>
| 2
|
2009-02-21T17:04:36Z
|
[
"python",
"charts"
] |
Python C-API Object Allocationâ
| 573,275
|
<p>I want to use the new and delete operators for creating and destroying my objects.</p>
<p>The problem is python seems to break it into several stages. tp_new, tp_init and tp_alloc for creation and tp_del, tp_free and tp_dealloc for destruction. However c++ just has new which allocates and fully constructs the object and delete which destructs and deallocates the object.</p>
<p>Which of the python tp_* methods do I need to provide and what must they do?</p>
<p>Also I want to be able to create the object directly in c++ eg "PyObject *obj = new MyExtensionObject(args);" Will I also need to overload the new operator in some way to support this?</p>
<p>I also would like to be able to subclass my extension types in python, is there anything special I need to do to support this?</p>
<p>I'm using python 3.0.1.</p>
<p>EDIT:
ok, tp_init seems to make objects a bit too mutable for what I'm doing (eg take a Texture object, changing the contents after creation is fine, but change fundamental aspects of it such as, size, bitdept, etc will break lots of existing c++ stuff that assumes those sort of things are fixed). If I dont implement it will it simply stop people calling __init__ AFTER its constructed (or at least ignore the call, like tuple does). Or should I have some flag that throws an exception or somthing if tp_init is called more than once on the same object?</p>
<p>Apart from that I think ive got most of the rest sorted.</p>
<pre><code>extern "C"
{
//creation + destruction
PyObject* global_alloc(PyTypeObject *type, Py_ssize_t items)
{
return (PyObject*)new char[type->tp_basicsize + items*type->tp_itemsize];
}
void global_free(void *mem)
{
delete[] (char*)mem;
}
}
template<class T> class ExtensionType
{
PyTypeObject *t;
ExtensionType()
{
t = new PyTypeObject();//not sure on this one, what is the "correct" way to create an empty type object
memset((void*)t, 0, sizeof(PyTypeObject));
static PyVarObject init = {PyObject_HEAD_INIT, 0};
*((PyObject*)t) = init;
t->tp_basicsize = sizeof(T);
t->tp_itemsize = 0;
t->tp_name = "unknown";
t->tp_alloc = (allocfunc) global_alloc;
t->tp_free = (freefunc) global_free;
t->tp_new = (newfunc) T::obj_new;
t->tp_dealloc = (destructor)T::obj_dealloc;
...
}
...bunch of methods for changing stuff...
PyObject *Finalise()
{
...
}
};
template <class T> PyObjectExtension : public PyObject
{
...
extern "C" static PyObject* obj_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds)
{
void *mem = (void*)subtype->tp_alloc(subtype, 0);
return (PyObject*)new(mem) T(args, kwds)
}
extern "C" static void obj_dealloc(PyObject *obj)
{
~T();
obj->ob_type->tp_free(obj);//most of the time this is global_free(obj)
}
...
};
class MyObject : PyObjectExtension<MyObject>
{
public:
static PyObject* InitType()
{
ExtensionType<MyObject> extType();
...sets other stuff...
return extType.Finalise();
}
...
};
</code></pre>
| 5
|
2009-02-21T16:01:45Z
| 573,300
|
<p>I don't know the python APIs at all, but if python splits up allocation and initialization, you should be able to use placement new.</p>
<p>e.g.:</p>
<pre><code> // tp_alloc
void *buffer = new char[sizeof(MyExtensionObject)];
// tp_init or tp_new (not sure what the distinction is there)
new (buffer) MyExtensionObject(args);
return static_cast<MyExtensionObject*>(buffer);
...
// tp_del
myExtensionObject->~MyExtensionObject(); // call dtor
// tp_dealloc (or tp_free? again I don't know the python apis)
delete [] (static_cast<char*>(static_cast<void*>(myExtensionObject)));
</code></pre>
| 0
|
2009-02-21T16:16:58Z
|
[
"c++",
"python",
"c",
"python-3.x",
"python-c-api"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.