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
sequence |
---|---|---|---|---|---|---|---|---|---|
Reading and running a mathematical expression in Python | 400,050 | <p>Using Python, how would I go about reading in (be from a string, file or url) a mathematical expression (1 + 1 is a good start) and executing it? </p>
<p>Aside from grabbing a string, file or url I have no idea of where to start with this.</p>
| 5 | 2008-12-30T11:22:43Z | 403,252 | <p>Don't writing your own parser unless you want to learn how to write a parser. As already mentioned in the comments by @J.F. Sebastian, I would suggest a full-on <a href="http://en.wikipedia.org/wiki/Computer_algebra_system" rel="nofollow">computer algebra system (CAS)</a> like <a href="http://www.sagemath.org/" rel="nofollow">SAGE</a>. It will handle mathematical statements <strong>much</strong> more complicated than 1+1 :)</p>
| 2 | 2008-12-31T15:45:28Z | [
"python"
] |
Reading and running a mathematical expression in Python | 400,050 | <p>Using Python, how would I go about reading in (be from a string, file or url) a mathematical expression (1 + 1 is a good start) and executing it? </p>
<p>Aside from grabbing a string, file or url I have no idea of where to start with this.</p>
| 5 | 2008-12-30T11:22:43Z | 5,115,775 | <p>You can take advantage of Python's own evaluation capabilities. However, blind use of eval() is a very dangerous, since somebody can trick your program into:</p>
<pre><code>eval( (__import__("os").system("rm important_file") or 1) + 1)
</code></pre>
<p>The correct way to use eval is with the following receipe, which will make sure nothing dangerous is contained in the expression that you are evaluating:</p>
<p><a href="http://code.activestate.com/recipes/496746-restricted-safe-eval/" rel="nofollow">http://code.activestate.com/recipes/496746-restricted-safe-eval/</a></p>
| 0 | 2011-02-25T09:51:54Z | [
"python"
] |
Resize image in Python without losing EXIF data | 400,788 | <p>I need to resize jpg images with Python without losing the original image's EXIF data (metadata about date taken, camera model etc.). All google searches about python and images point to the PIL library which I'm currently using, but doesn't seem to be able to retain the metadata. The code I have so far (using PIL) is this:</p>
<pre><code>img = Image.open('foo.jpg')
width,height = 800,600
if img.size[0] < img.size[1]:
width,height = height,width
resized_img = img.resize((width, height), Image.ANTIALIAS) # best down-sizing filter
resized_img.save('foo-resized.jpg')
</code></pre>
<p>Any ideas? Or other libraries that I could be using?</p>
| 23 | 2008-12-30T16:42:02Z | 400,838 | <pre><code>import jpeg
jpeg.setExif(jpeg.getExif('foo.jpg'), 'foo-resized.jpg')
</code></pre>
<p><a href="http://www.emilas.com/jpeg/">http://www.emilas.com/jpeg/</a></p>
| 12 | 2008-12-30T17:00:10Z | [
"python",
"image-processing",
"python-imaging-library",
"exif"
] |
Resize image in Python without losing EXIF data | 400,788 | <p>I need to resize jpg images with Python without losing the original image's EXIF data (metadata about date taken, camera model etc.). All google searches about python and images point to the PIL library which I'm currently using, but doesn't seem to be able to retain the metadata. The code I have so far (using PIL) is this:</p>
<pre><code>img = Image.open('foo.jpg')
width,height = 800,600
if img.size[0] < img.size[1]:
width,height = height,width
resized_img = img.resize((width, height), Image.ANTIALIAS) # best down-sizing filter
resized_img.save('foo-resized.jpg')
</code></pre>
<p>Any ideas? Or other libraries that I could be using?</p>
| 23 | 2008-12-30T16:42:02Z | 400,840 | <p>PIL handles EXIF data, doesn't it? Look in PIL.ExifTags.</p>
| 0 | 2008-12-30T17:01:28Z | [
"python",
"image-processing",
"python-imaging-library",
"exif"
] |
Resize image in Python without losing EXIF data | 400,788 | <p>I need to resize jpg images with Python without losing the original image's EXIF data (metadata about date taken, camera model etc.). All google searches about python and images point to the PIL library which I'm currently using, but doesn't seem to be able to retain the metadata. The code I have so far (using PIL) is this:</p>
<pre><code>img = Image.open('foo.jpg')
width,height = 800,600
if img.size[0] < img.size[1]:
width,height = height,width
resized_img = img.resize((width, height), Image.ANTIALIAS) # best down-sizing filter
resized_img.save('foo-resized.jpg')
</code></pre>
<p>Any ideas? Or other libraries that I could be using?</p>
| 23 | 2008-12-30T16:42:02Z | 401,208 | <p>Why not using <a href="http://www.imagemagick.org/script/index.php" rel="nofollow">ImageMagick</a>?<br>
It is quite a standard tool (for instance, it is the standard tool used by Gallery 2); I have never used it, however it has a <a href="http://www.imagemagick.org/download/python/" rel="nofollow">python interface</a> as well (or, you can also simply spawn the command) and most of all, should maintain EXIF information between all transformation.</p>
| 4 | 2008-12-30T19:27:17Z | [
"python",
"image-processing",
"python-imaging-library",
"exif"
] |
Resize image in Python without losing EXIF data | 400,788 | <p>I need to resize jpg images with Python without losing the original image's EXIF data (metadata about date taken, camera model etc.). All google searches about python and images point to the PIL library which I'm currently using, but doesn't seem to be able to retain the metadata. The code I have so far (using PIL) is this:</p>
<pre><code>img = Image.open('foo.jpg')
width,height = 800,600
if img.size[0] < img.size[1]:
width,height = height,width
resized_img = img.resize((width, height), Image.ANTIALIAS) # best down-sizing filter
resized_img.save('foo-resized.jpg')
</code></pre>
<p>Any ideas? Or other libraries that I could be using?</p>
| 23 | 2008-12-30T16:42:02Z | 403,293 | <p>You can use pyexiv2 to modify the file after saving it.</p>
| 1 | 2008-12-31T15:59:57Z | [
"python",
"image-processing",
"python-imaging-library",
"exif"
] |
Resize image in Python without losing EXIF data | 400,788 | <p>I need to resize jpg images with Python without losing the original image's EXIF data (metadata about date taken, camera model etc.). All google searches about python and images point to the PIL library which I'm currently using, but doesn't seem to be able to retain the metadata. The code I have so far (using PIL) is this:</p>
<pre><code>img = Image.open('foo.jpg')
width,height = 800,600
if img.size[0] < img.size[1]:
width,height = height,width
resized_img = img.resize((width, height), Image.ANTIALIAS) # best down-sizing filter
resized_img.save('foo-resized.jpg')
</code></pre>
<p>Any ideas? Or other libraries that I could be using?</p>
| 23 | 2008-12-30T16:42:02Z | 4,270,949 | <p>You can use pyexiv2 to copy EXIF data from source image. In the following example image is resized using PIL library, EXIF data copied with pyexiv2 and image size EXIF fields are set with new size.</p>
<pre><code>def resize_image(source_path, dest_path, size):
# resize image
image = Image.open(source_path)
image.thumbnail(size, Image.ANTIALIAS)
image.save(dest_path, "JPEG")
# copy EXIF data
source_image = pyexiv2.Image(source_path)
source_image.readMetadata()
dest_image = pyexiv2.Image(dest_path)
dest_image.readMetadata()
source_image.copyMetadataTo(dest_image)
# set EXIF image size info to resized size
dest_image["Exif.Photo.PixelXDimension"] = image.size[0]
dest_image["Exif.Photo.PixelYDimension"] = image.size[1]
dest_image.writeMetadata()
# resizing local file
resize_image("41965749.jpg", "resized.jpg", (600,400))
</code></pre>
| 10 | 2010-11-24T19:57:13Z | [
"python",
"image-processing",
"python-imaging-library",
"exif"
] |
Resize image in Python without losing EXIF data | 400,788 | <p>I need to resize jpg images with Python without losing the original image's EXIF data (metadata about date taken, camera model etc.). All google searches about python and images point to the PIL library which I'm currently using, but doesn't seem to be able to retain the metadata. The code I have so far (using PIL) is this:</p>
<pre><code>img = Image.open('foo.jpg')
width,height = 800,600
if img.size[0] < img.size[1]:
width,height = height,width
resized_img = img.resize((width, height), Image.ANTIALIAS) # best down-sizing filter
resized_img.save('foo-resized.jpg')
</code></pre>
<p>Any ideas? Or other libraries that I could be using?</p>
| 23 | 2008-12-30T16:42:02Z | 17,549,368 | <p>For pyexiv2 v0.3.2, the <a href="http://tilloy.net/dev/pyexiv2/api.html#pyexiv2.metadata.ImageMetadata.copy" rel="nofollow">API documentation</a> refers to the copy method to carry over EXIF data from one image to another. In this case it would be the EXIF data of the original image over to the resized image.</p>
<p>Going off @Maksym Kozlenko, the updated code for copying EXIF data is:</p>
<pre><code> source_image = pyexiv2.ImageMetadata(source_path)
source_image.read()
dest_image = pyexiv2.ImageMetadata(dest_path)
dest_image.read()
source_image.copy(dest_image,exif=True)
dest_image.write()
</code></pre>
| 1 | 2013-07-09T13:24:08Z | [
"python",
"image-processing",
"python-imaging-library",
"exif"
] |
Resize image in Python without losing EXIF data | 400,788 | <p>I need to resize jpg images with Python without losing the original image's EXIF data (metadata about date taken, camera model etc.). All google searches about python and images point to the PIL library which I'm currently using, but doesn't seem to be able to retain the metadata. The code I have so far (using PIL) is this:</p>
<pre><code>img = Image.open('foo.jpg')
width,height = 800,600
if img.size[0] < img.size[1]:
width,height = height,width
resized_img = img.resize((width, height), Image.ANTIALIAS) # best down-sizing filter
resized_img.save('foo-resized.jpg')
</code></pre>
<p>Any ideas? Or other libraries that I could be using?</p>
| 23 | 2008-12-30T16:42:02Z | 22,063,878 | <p>There is actually a really simple way of copying EXIF data from a picture to another with only PIL. Though it doesn't permit to modify the exif tags.</p>
<pre class="lang-py prettyprint-override"><code>image = Image.open('test.jpg')
exif = image.info['exif']
# Your picture process here
image = image.rotate(90)
image.save('test_rotated.jpg', 'JPEG', exif=exif)
</code></pre>
<p>As you can see, the save function can take the exif argument which permits to copy the raw exif data in the new image when saving. You don't actually need any other lib if that's all you want to do. I can't seem to find any documentation on the save options and I don't even know if that's specific to Pillow or working with PIL too. (If someone has some kind of link, I would enjoy if they posted it in the comments)</p>
| 7 | 2014-02-27T09:13:16Z | [
"python",
"image-processing",
"python-imaging-library",
"exif"
] |
Resize image in Python without losing EXIF data | 400,788 | <p>I need to resize jpg images with Python without losing the original image's EXIF data (metadata about date taken, camera model etc.). All google searches about python and images point to the PIL library which I'm currently using, but doesn't seem to be able to retain the metadata. The code I have so far (using PIL) is this:</p>
<pre><code>img = Image.open('foo.jpg')
width,height = 800,600
if img.size[0] < img.size[1]:
width,height = height,width
resized_img = img.resize((width, height), Image.ANTIALIAS) # best down-sizing filter
resized_img.save('foo-resized.jpg')
</code></pre>
<p>Any ideas? Or other libraries that I could be using?</p>
| 23 | 2008-12-30T16:42:02Z | 25,659,450 | <pre><code>from PIL import Image
img_path = "/tmp/img.jpg"
img = Image.open(img_path)
exif = img.info['exif']
img.save("output_"+img_path, exif=exif)
</code></pre>
<p>Tested in Pillow 2.5.3</p>
| 0 | 2014-09-04T07:18:15Z | [
"python",
"image-processing",
"python-imaging-library",
"exif"
] |
Resize image in Python without losing EXIF data | 400,788 | <p>I need to resize jpg images with Python without losing the original image's EXIF data (metadata about date taken, camera model etc.). All google searches about python and images point to the PIL library which I'm currently using, but doesn't seem to be able to retain the metadata. The code I have so far (using PIL) is this:</p>
<pre><code>img = Image.open('foo.jpg')
width,height = 800,600
if img.size[0] < img.size[1]:
width,height = height,width
resized_img = img.resize((width, height), Image.ANTIALIAS) # best down-sizing filter
resized_img.save('foo-resized.jpg')
</code></pre>
<p>Any ideas? Or other libraries that I could be using?</p>
| 23 | 2008-12-30T16:42:02Z | 30,236,764 | <p>It seems @Depado's solution does not work for me, in my scenario the image does not even contain an exif segment.</p>
<p>pyexiv2 is hard to install on my Mac, instead I use the module pexif <a href="https://github.com/bennoleslie/pexif/blob/master/pexif.py" rel="nofollow">https://github.com/bennoleslie/pexif/blob/master/pexif.py</a>. To "add exif segment" to an image does not contain exif info, I added the exif info contained in an image which owns a exif segment</p>
<pre><code>from pexif import JpegFile
#get exif segment from an image
jpeg = JpegFile.fromFile(path_with_exif)
jpeg_exif = jpeg.get_exif()
#import the exif segment above to the image file which does not contain exif segment
jpeg = JpegFile.fromFile(path_without_exif)
exif = jpeg.import_exif(jpeg_exif)
jpeg.writeFile(path_without_exif)
</code></pre>
| 0 | 2015-05-14T11:55:44Z | [
"python",
"image-processing",
"python-imaging-library",
"exif"
] |
Define css class in django Forms | 401,025 | <p>Assume I have a form</p>
<pre><code>class SampleClass(forms.Form):
name = forms.CharField(max_length=30)
age = forms.IntegerField()
django_hacker = forms.BooleanField(required=False)
</code></pre>
<p>Is there a way for me to define css classes on each field such that I can then use jQuery based on class in my rendered page?</p>
<p>I was hoping not to have to manually build the form.</p>
| 125 | 2008-12-30T18:18:41Z | 401,030 | <p>Answered my own question. <em>Sigh</em></p>
<p><a href="http://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.Widget.attrs">http://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.Widget.attrs</a></p>
<p>I didn't realize it was passed into the widget constructor.</p>
| 66 | 2008-12-30T18:20:28Z | [
"python",
"django",
"forms",
"newforms"
] |
Define css class in django Forms | 401,025 | <p>Assume I have a form</p>
<pre><code>class SampleClass(forms.Form):
name = forms.CharField(max_length=30)
age = forms.IntegerField()
django_hacker = forms.BooleanField(required=False)
</code></pre>
<p>Is there a way for me to define css classes on each field such that I can then use jQuery based on class in my rendered page?</p>
<p>I was hoping not to have to manually build the form.</p>
| 125 | 2008-12-30T18:18:41Z | 401,057 | <p>Here is another solution for adding class definitions to the widgets after declaring the fields in the class.</p>
<pre><code>def __init__(self, *args, **kwargs):
super(SampleClass, self).__init__(*args, **kwargs)
self.fields['name'].widget.attrs['class'] = 'my_class'
</code></pre>
| 59 | 2008-12-30T18:32:11Z | [
"python",
"django",
"forms",
"newforms"
] |
Define css class in django Forms | 401,025 | <p>Assume I have a form</p>
<pre><code>class SampleClass(forms.Form):
name = forms.CharField(max_length=30)
age = forms.IntegerField()
django_hacker = forms.BooleanField(required=False)
</code></pre>
<p>Is there a way for me to define css classes on each field such that I can then use jQuery based on class in my rendered page?</p>
<p>I was hoping not to have to manually build the form.</p>
| 125 | 2008-12-30T18:18:41Z | 2,377,554 | <p>Here is a variation on the above which will give all fields the same class (e.g. jquery nice rounded corners).</p>
<pre><code> # Simple way to assign css class to every field
def __init__(self, *args, **kwargs):
super(TranslatedPageForm, self).__init__(*args, **kwargs)
for myField in self.fields:
self.fields[myField].widget.attrs['class'] = 'ui-state-default ui-corner-all'
</code></pre>
| 3 | 2010-03-04T07:38:15Z | [
"python",
"django",
"forms",
"newforms"
] |
Define css class in django Forms | 401,025 | <p>Assume I have a form</p>
<pre><code>class SampleClass(forms.Form):
name = forms.CharField(max_length=30)
age = forms.IntegerField()
django_hacker = forms.BooleanField(required=False)
</code></pre>
<p>Is there a way for me to define css classes on each field such that I can then use jQuery based on class in my rendered page?</p>
<p>I was hoping not to have to manually build the form.</p>
| 125 | 2008-12-30T18:18:41Z | 4,272,671 | <p>Expanding on the method pointed to at docs.djangoproject.com:</p>
<pre><code>class MyForm(forms.Form):
comment = forms.CharField(
widget=forms.TextInput(attrs={'size':'40'}))
</code></pre>
<p>I thought it was troublesome to have to know the native widget type for every field, and thought it funny to override the default just to put a class name on a form field. This seems to work for me:</p>
<pre><code>class MyForm(forms.Form):
#This instantiates the field w/ the default widget
comment = forms.CharField()
#We only override the part we care about
comment.widget.attrs['size'] = '40'
</code></pre>
<p>This seems a little cleaner to me.</p>
| 23 | 2010-11-25T00:06:15Z | [
"python",
"django",
"forms",
"newforms"
] |
Define css class in django Forms | 401,025 | <p>Assume I have a form</p>
<pre><code>class SampleClass(forms.Form):
name = forms.CharField(max_length=30)
age = forms.IntegerField()
django_hacker = forms.BooleanField(required=False)
</code></pre>
<p>Is there a way for me to define css classes on each field such that I can then use jQuery based on class in my rendered page?</p>
<p>I was hoping not to have to manually build the form.</p>
| 125 | 2008-12-30T18:18:41Z | 4,667,831 | <p>Here is Simple way to alter in view. add below in view just before passing it into template.</p>
<pre><code>form = MyForm(instance = instance.obj)
form.fields['email'].widget.attrs = {'class':'here_class_name'}
</code></pre>
| 13 | 2011-01-12T10:42:45Z | [
"python",
"django",
"forms",
"newforms"
] |
Define css class in django Forms | 401,025 | <p>Assume I have a form</p>
<pre><code>class SampleClass(forms.Form):
name = forms.CharField(max_length=30)
age = forms.IntegerField()
django_hacker = forms.BooleanField(required=False)
</code></pre>
<p>Is there a way for me to define css classes on each field such that I can then use jQuery based on class in my rendered page?</p>
<p>I was hoping not to have to manually build the form.</p>
| 125 | 2008-12-30T18:18:41Z | 4,676,071 | <p>Yet another solution that doesn't require changes in python code and so is better for designers and one-off presentational changes: <a href="https://github.com/kmike/django-widget-tweaks">django-widget-tweaks</a>. Hope somebody will find it useful.</p>
| 128 | 2011-01-13T01:56:34Z | [
"python",
"django",
"forms",
"newforms"
] |
Define css class in django Forms | 401,025 | <p>Assume I have a form</p>
<pre><code>class SampleClass(forms.Form):
name = forms.CharField(max_length=30)
age = forms.IntegerField()
django_hacker = forms.BooleanField(required=False)
</code></pre>
<p>Is there a way for me to define css classes on each field such that I can then use jQuery based on class in my rendered page?</p>
<p>I was hoping not to have to manually build the form.</p>
| 125 | 2008-12-30T18:18:41Z | 18,962,481 | <p>This can be done using a custom template filter.
considering you render your form this way :</p>
<pre><code><form action="/contact/" method="post">
{{ form.non_field_errors }}
<div class="fieldWrapper">
{{ form.subject.errors }}
<label for="id_subject">Email subject:</label>
{{ form.subject }}
</div>
</form>
</code></pre>
<p>form.subject is an instance of <a href="https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.BoundField">BoundField</a> which has the <strong>as_widget</strong> method.</p>
<p>you can create a custom filter "addcss" in "my_app/templatetags/myfilters.py"</p>
<pre><code>from django import template
register = template.Library()
@register.filter(name='addcss')
def addcss(value, arg):
return value.as_widget(attrs={'class': arg})
</code></pre>
<p>And then apply your filter:</p>
<pre><code>{% load myfilters %}
<form action="/contact/" method="post">
{{ form.non_field_errors }}
<div class="fieldWrapper">
{{ form.subject.errors }}
<label for="id_subject">Email subject:</label>
{{ form.subject|addcss:'MyClass' }}
</div>
</form>
</code></pre>
<p>form.subjects will then be rendered with the "MyClass" css class.</p>
<p>Hope this help.</p>
| 26 | 2013-09-23T14:55:01Z | [
"python",
"django",
"forms",
"newforms"
] |
Define css class in django Forms | 401,025 | <p>Assume I have a form</p>
<pre><code>class SampleClass(forms.Form):
name = forms.CharField(max_length=30)
age = forms.IntegerField()
django_hacker = forms.BooleanField(required=False)
</code></pre>
<p>Is there a way for me to define css classes on each field such that I can then use jQuery based on class in my rendered page?</p>
<p>I was hoping not to have to manually build the form.</p>
| 125 | 2008-12-30T18:18:41Z | 20,573,612 | <p>If you want all the fields in the form to inherit a certain class, you just define a parent class, that inherits from <code>forms.ModelForm</code>, and then inherit from it</p>
<pre><code>class BaseForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(BaseForm, self).__init__(*args, **kwargs)
for field_name, field in self.fields.items():
field.widget.attrs['class'] = 'someClass'
class WhateverForm(BaseForm):
class Meta:
model = SomeModel
</code></pre>
<p>This helped me to add the <code>'form-control'</code> class to all of the fields on all of the forms of my application automatically, without adding replication of code. </p>
| 12 | 2013-12-13T18:35:43Z | [
"python",
"django",
"forms",
"newforms"
] |
Define css class in django Forms | 401,025 | <p>Assume I have a form</p>
<pre><code>class SampleClass(forms.Form):
name = forms.CharField(max_length=30)
age = forms.IntegerField()
django_hacker = forms.BooleanField(required=False)
</code></pre>
<p>Is there a way for me to define css classes on each field such that I can then use jQuery based on class in my rendered page?</p>
<p>I was hoping not to have to manually build the form.</p>
| 125 | 2008-12-30T18:18:41Z | 28,874,624 | <p>As it turns out you can do this in form constructor (<strong>init</strong> function) or after form class was initiated. This is sometimes required if you are not writing your own form and that form is coming from somewhere else -</p>
<pre><code>def some_view(request):
add_css_to_fields = ['list','of','fields']
if request.method == 'POST':
form = SomeForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('/thanks/')
else:
form = SomeForm()
for key in form.fields.keys():
if key in add_css_to_fields:
field = form.fields[key]
css_addition = 'css_addition '
css = field.widget.attrs.get('class', '')
field.widget.attrs['class'] = css_addition + css_classes
return render(request, 'template_name.html', {'form': form})
</code></pre>
| 1 | 2015-03-05T09:44:53Z | [
"python",
"django",
"forms",
"newforms"
] |
ForeignKey form restrictions in Django | 401,118 | <p>I'm using Django to write a blog app, and I'm trying to implement a hierarchical category structure. Each category has a "parent" ForeignKey pointing back to the same Category model. I want to allow admins to add categories, and I want the interface to allow them to select a category's parent category. However, I want to avoid I'm-my-own-grandpa situations, so I want to limit the available choices of categories to those which do not have category in question as an ancestor.</p>
<p>Right now, I'm controlling this from the view:</p>
<pre><code>parent_candidates = list(Category.objects.all())
pruned_parent_list = [cat for cat in parent_candidates if instance.id not in cat.getHierarchy()]
</code></pre>
<p>where instance is the category being edited and getHierarchy() is a method to get a list of ancestor ids.</p>
<p>There are a number of problems with this approach. In particular, it uses an extra database hit to get the list of all categories and it makes me write the selection mechanism into my template by looping through pruned_parent_list to get the options, when I'd really rather just specify a widget.</p>
<p>Is there any better way to do this? I know I can add custom validation on the back-end to prevent this, but why give users the option?</p>
| 4 | 2008-12-30T19:04:16Z | 401,186 | <p>"Is there any better way to do this?" Not really. Hierarchies are hard in the relational model. Nothing makes the easier except giving up on SQL entirely.</p>
<p>"write the selection mechanism into my template by looping through pruned_parent_list to get the options" -- probably not optimal. This should happen in your view.</p>
| 0 | 2008-12-30T19:20:22Z | [
"python",
"django",
"django-forms"
] |
ForeignKey form restrictions in Django | 401,118 | <p>I'm using Django to write a blog app, and I'm trying to implement a hierarchical category structure. Each category has a "parent" ForeignKey pointing back to the same Category model. I want to allow admins to add categories, and I want the interface to allow them to select a category's parent category. However, I want to avoid I'm-my-own-grandpa situations, so I want to limit the available choices of categories to those which do not have category in question as an ancestor.</p>
<p>Right now, I'm controlling this from the view:</p>
<pre><code>parent_candidates = list(Category.objects.all())
pruned_parent_list = [cat for cat in parent_candidates if instance.id not in cat.getHierarchy()]
</code></pre>
<p>where instance is the category being edited and getHierarchy() is a method to get a list of ancestor ids.</p>
<p>There are a number of problems with this approach. In particular, it uses an extra database hit to get the list of all categories and it makes me write the selection mechanism into my template by looping through pruned_parent_list to get the options, when I'd really rather just specify a widget.</p>
<p>Is there any better way to do this? I know I can add custom validation on the back-end to prevent this, but why give users the option?</p>
| 4 | 2008-12-30T19:04:16Z | 401,256 | <p>If I understand your predicament correctly, the problem itself lies with the way you're dealing with which categories can be parents and which ones can't. One option to avoid these problems is to actually limit the level of categories which can become parents. For example, let's say you have the following categories:</p>
<ul>
<li>Internet
<ul>
<li>Google</li>
<li>Yahoo</li>
</ul></li>
<li>Offline
<ul>
<li>MS Office</li>
<li>OpenOffice</li>
</ul></li>
</ul>
<p>The way I usually handle this is I obviously have a parent_id FK on the categories table. For the root elements (Internet, Offline), the parent_id would be 0. So, when in your view you're trying to retrieve the "parent categories" for the dropdown, you need to decide how far down can they keep nesting. I mostly limit this to the first level, so to choose which categories to show in your dropdown, you'd do something like:</p>
<pre><code>parents = Category.objects.filter(parent_id=0)
</code></pre>
<p>Now obviously, this limits the approach somewhat, but you can increase the level you'd like to include and work out some kind of visual identification system in your template for the dropdown (including extra spaces or dashes for each level in the hierarchy or something).</p>
<p>Anyway, sorry about the long response, and hopefully this addressed your issue somewhat.</p>
| 0 | 2008-12-30T19:42:19Z | [
"python",
"django",
"django-forms"
] |
ForeignKey form restrictions in Django | 401,118 | <p>I'm using Django to write a blog app, and I'm trying to implement a hierarchical category structure. Each category has a "parent" ForeignKey pointing back to the same Category model. I want to allow admins to add categories, and I want the interface to allow them to select a category's parent category. However, I want to avoid I'm-my-own-grandpa situations, so I want to limit the available choices of categories to those which do not have category in question as an ancestor.</p>
<p>Right now, I'm controlling this from the view:</p>
<pre><code>parent_candidates = list(Category.objects.all())
pruned_parent_list = [cat for cat in parent_candidates if instance.id not in cat.getHierarchy()]
</code></pre>
<p>where instance is the category being edited and getHierarchy() is a method to get a list of ancestor ids.</p>
<p>There are a number of problems with this approach. In particular, it uses an extra database hit to get the list of all categories and it makes me write the selection mechanism into my template by looping through pruned_parent_list to get the options, when I'd really rather just specify a widget.</p>
<p>Is there any better way to do this? I know I can add custom validation on the back-end to prevent this, but why give users the option?</p>
| 4 | 2008-12-30T19:04:16Z | 401,428 | <p>I am not sure if this is better (interaction-wise or otherwise) but...</p>
<p>You can check hierarchical integrity on save and raise an error if necessary.</p>
<p>Ideally for such a data type I would like to see a tree of instances on the side. Or at least the full ancestory on the object detail view. In both cases you'd already have done the extra trip mentioned to the database.</p>
| 0 | 2008-12-30T20:36:29Z | [
"python",
"django",
"django-forms"
] |
ForeignKey form restrictions in Django | 401,118 | <p>I'm using Django to write a blog app, and I'm trying to implement a hierarchical category structure. Each category has a "parent" ForeignKey pointing back to the same Category model. I want to allow admins to add categories, and I want the interface to allow them to select a category's parent category. However, I want to avoid I'm-my-own-grandpa situations, so I want to limit the available choices of categories to those which do not have category in question as an ancestor.</p>
<p>Right now, I'm controlling this from the view:</p>
<pre><code>parent_candidates = list(Category.objects.all())
pruned_parent_list = [cat for cat in parent_candidates if instance.id not in cat.getHierarchy()]
</code></pre>
<p>where instance is the category being edited and getHierarchy() is a method to get a list of ancestor ids.</p>
<p>There are a number of problems with this approach. In particular, it uses an extra database hit to get the list of all categories and it makes me write the selection mechanism into my template by looping through pruned_parent_list to get the options, when I'd really rather just specify a widget.</p>
<p>Is there any better way to do this? I know I can add custom validation on the back-end to prevent this, but why give users the option?</p>
| 4 | 2008-12-30T19:04:16Z | 402,530 | <p>I have had to deal with arbitrary-depth categories on SQL and it seems not well suited for storing data of this type in a normal form, as nested queries and/or multiple JOINs tend to get ugly <em>extremely</em> quickly.</p>
<p>This is almost the only case where I would go with a sort of improper solution, namely to store categories in string form, subcategories separated by a delimiter. It makes both database queries and other operations much more trivial.</p>
<p>Categories table would look something like this:</p>
<pre><code>id name
1 Internet
2 Internet/Google
3 Internet/Yahoo
4 Offline
5 Offline/MS Office/MS Excel
6 Offline/Openoffice
</code></pre>
<p>Another solution is, that depending on your expected usage, you can maybe implement binary tree in the category list. That allows to select category trees and parent/child relationships elegantly. It has the limitation, however, that upon inserting new categories the whole tree may have to be recalculated, and that knowing the approximate size of tree in advance is useful.</p>
<p>At any rate, hierarchical data in SQL is not trivial by itself, so, whatever you do, you will probably have to do quite some custom coding.</p>
| 1 | 2008-12-31T08:20:45Z | [
"python",
"django",
"django-forms"
] |
ForeignKey form restrictions in Django | 401,118 | <p>I'm using Django to write a blog app, and I'm trying to implement a hierarchical category structure. Each category has a "parent" ForeignKey pointing back to the same Category model. I want to allow admins to add categories, and I want the interface to allow them to select a category's parent category. However, I want to avoid I'm-my-own-grandpa situations, so I want to limit the available choices of categories to those which do not have category in question as an ancestor.</p>
<p>Right now, I'm controlling this from the view:</p>
<pre><code>parent_candidates = list(Category.objects.all())
pruned_parent_list = [cat for cat in parent_candidates if instance.id not in cat.getHierarchy()]
</code></pre>
<p>where instance is the category being edited and getHierarchy() is a method to get a list of ancestor ids.</p>
<p>There are a number of problems with this approach. In particular, it uses an extra database hit to get the list of all categories and it makes me write the selection mechanism into my template by looping through pruned_parent_list to get the options, when I'd really rather just specify a widget.</p>
<p>Is there any better way to do this? I know I can add custom validation on the back-end to prevent this, but why give users the option?</p>
| 4 | 2008-12-30T19:04:16Z | 406,752 | <p>Take a look at the <a href="http://code.google.com/p/django-treebeard/" rel="nofollow">django-treebeard</a> app.</p>
| 1 | 2009-01-02T13:09:01Z | [
"python",
"django",
"django-forms"
] |
How to limit rate of requests to web services in Python? | 401,215 | <p>I'm working on a Python library that interfaces with a web service API. Like many web services I've encountered, this one requests limiting the rate of requests. I would like to provide an optional parameter, <code>limit</code>, to the class instantiation that, if provided, will hold outgoing requests until the number of seconds specified passes.</p>
<p>I understand that the general scenario is the following: an instance of the class makes a request via a method. When it does, the method emits some signal that sets a lock variable somewhere, and begins a countdown timer for the number of seconds in <code>limit</code>. (In all likelihood, the lock is the countdown timer itself.) If another request is made within this time frame, it must be queued until the countdown timer reaches zero and the lock is disengaged; at this point, the oldest request on the queue is sent, and the countdown timer is reset and the lock is re-engaged.</p>
<p>Is this a case for threading? Is there another approach I'm not seeing?</p>
<p>Should the countdown timer and lock be instance variables, or should they belong to the class, such that all instances of the class hold requests?</p>
<p>Also, is this generally a bad idea to provide rate-limiting functionality within a library? I reason since, by default, the countdown is zero seconds, the library still allows developers to use the library and provide their own rate-limiting schemes. Given any developers using the service will need to rate-limit requests anyway, however, I figure that it would be a convenience for the library to provide a means of rate-limiting.</p>
<p>Regardless of placing a rate-limiting scheme in the library or not, I'll want to write an application using the library, so suggested techniques will come in handy.</p>
<p>Many thanks for your suggestions!</p>
<p>Chris</p>
| 9 | 2008-12-30T19:30:11Z | 401,316 | <p>This works out better with a queue and a dispatcher.</p>
<p>You split your processing into two sides: <strong>source</strong> and <strong>dispatch</strong>. These can be separate threads (or separate processes if that's easier).</p>
<p>The <strong>Source</strong> side creates and enqueues requests at whatever rate makes them happy.</p>
<p>The <strong>Dispatch</strong> side does this.</p>
<ol>
<li><p>Get the request start time, <em>s</em>.</p></li>
<li><p>Dequeues a request, process the request through the remote service.</p></li>
<li><p>Get the current time, <em>t</em>. Sleep for <em>rate</em> - (<em>t</em> - <em>s</em>) seconds.</p></li>
</ol>
<p>If you want to run the <strong>Source</strong> side connected directly to the remote service, you can do that, and bypass rate limiting. This is good for internal testing with a mock version of the remote service.</p>
<p>The hard part about this is creating some representation for each request that you can enqueue. Since the Python <a href="https://docs.python.org/2/library/queue.html" rel="nofollow">Queue</a> will handle almost anything, you don't have to do much. </p>
<p>If you're using multi-processing, you'll have to <a href="https://docs.python.org/2/library/pickle.html" rel="nofollow">pickle</a> your objects to put them into a pipe.</p>
| 5 | 2008-12-30T20:00:33Z | [
"python",
"web-services",
"rate-limiting"
] |
How to limit rate of requests to web services in Python? | 401,215 | <p>I'm working on a Python library that interfaces with a web service API. Like many web services I've encountered, this one requests limiting the rate of requests. I would like to provide an optional parameter, <code>limit</code>, to the class instantiation that, if provided, will hold outgoing requests until the number of seconds specified passes.</p>
<p>I understand that the general scenario is the following: an instance of the class makes a request via a method. When it does, the method emits some signal that sets a lock variable somewhere, and begins a countdown timer for the number of seconds in <code>limit</code>. (In all likelihood, the lock is the countdown timer itself.) If another request is made within this time frame, it must be queued until the countdown timer reaches zero and the lock is disengaged; at this point, the oldest request on the queue is sent, and the countdown timer is reset and the lock is re-engaged.</p>
<p>Is this a case for threading? Is there another approach I'm not seeing?</p>
<p>Should the countdown timer and lock be instance variables, or should they belong to the class, such that all instances of the class hold requests?</p>
<p>Also, is this generally a bad idea to provide rate-limiting functionality within a library? I reason since, by default, the countdown is zero seconds, the library still allows developers to use the library and provide their own rate-limiting schemes. Given any developers using the service will need to rate-limit requests anyway, however, I figure that it would be a convenience for the library to provide a means of rate-limiting.</p>
<p>Regardless of placing a rate-limiting scheme in the library or not, I'll want to write an application using the library, so suggested techniques will come in handy.</p>
<p>Many thanks for your suggestions!</p>
<p>Chris</p>
| 9 | 2008-12-30T19:30:11Z | 401,332 | <p>Your rate limiting scheme should be heavily influenced by the calling conventions of the underlying code (syncronous or async), as well as what scope (thread, process, machine, cluster?) this rate-limiting will operate at.</p>
<p>I would suggest keeping all the variables within the instance, so you can easily implement multiple periods/rates of control.</p>
<p>Lastly, it sounds like you want to be a middleware component. Don't try to be an application and introduce threads on your own. Just block/sleep if you are synchronous and use the async dispatching framework if you are being called by one of them.</p>
| 1 | 2008-12-30T20:05:47Z | [
"python",
"web-services",
"rate-limiting"
] |
How to limit rate of requests to web services in Python? | 401,215 | <p>I'm working on a Python library that interfaces with a web service API. Like many web services I've encountered, this one requests limiting the rate of requests. I would like to provide an optional parameter, <code>limit</code>, to the class instantiation that, if provided, will hold outgoing requests until the number of seconds specified passes.</p>
<p>I understand that the general scenario is the following: an instance of the class makes a request via a method. When it does, the method emits some signal that sets a lock variable somewhere, and begins a countdown timer for the number of seconds in <code>limit</code>. (In all likelihood, the lock is the countdown timer itself.) If another request is made within this time frame, it must be queued until the countdown timer reaches zero and the lock is disengaged; at this point, the oldest request on the queue is sent, and the countdown timer is reset and the lock is re-engaged.</p>
<p>Is this a case for threading? Is there another approach I'm not seeing?</p>
<p>Should the countdown timer and lock be instance variables, or should they belong to the class, such that all instances of the class hold requests?</p>
<p>Also, is this generally a bad idea to provide rate-limiting functionality within a library? I reason since, by default, the countdown is zero seconds, the library still allows developers to use the library and provide their own rate-limiting schemes. Given any developers using the service will need to rate-limit requests anyway, however, I figure that it would be a convenience for the library to provide a means of rate-limiting.</p>
<p>Regardless of placing a rate-limiting scheme in the library or not, I'll want to write an application using the library, so suggested techniques will come in handy.</p>
<p>Many thanks for your suggestions!</p>
<p>Chris</p>
| 9 | 2008-12-30T19:30:11Z | 401,390 | <p>Queuing may be overly complicated. A simpler solution is to give your class a variable for the time the service was last called. Whenever the service is called (!1), set waitTime to <code>delay - Now + lastcalltime</code>. <code>delay</code> should be equal to the minimum allowable time between requests. If this number is positive, sleep for that long before making the call (!2). The disadvantage/advantage of this approach is that it treats the web service requests as being synchronous. The advantage is that it is absurdly simple and easy to implement. </p>
<ul>
<li>(!1): Should happen right after receiving a response from the service, inside the wrapper (probably at the bottom of the wrapper).</li>
<li>(!2): Should happen when the python wrapper around the web service is called, at the top of the wrapper.</li>
</ul>
<p>S.Lott's solution is more elegant, of course.</p>
| 2 | 2008-12-30T20:23:16Z | [
"python",
"web-services",
"rate-limiting"
] |
How to limit rate of requests to web services in Python? | 401,215 | <p>I'm working on a Python library that interfaces with a web service API. Like many web services I've encountered, this one requests limiting the rate of requests. I would like to provide an optional parameter, <code>limit</code>, to the class instantiation that, if provided, will hold outgoing requests until the number of seconds specified passes.</p>
<p>I understand that the general scenario is the following: an instance of the class makes a request via a method. When it does, the method emits some signal that sets a lock variable somewhere, and begins a countdown timer for the number of seconds in <code>limit</code>. (In all likelihood, the lock is the countdown timer itself.) If another request is made within this time frame, it must be queued until the countdown timer reaches zero and the lock is disengaged; at this point, the oldest request on the queue is sent, and the countdown timer is reset and the lock is re-engaged.</p>
<p>Is this a case for threading? Is there another approach I'm not seeing?</p>
<p>Should the countdown timer and lock be instance variables, or should they belong to the class, such that all instances of the class hold requests?</p>
<p>Also, is this generally a bad idea to provide rate-limiting functionality within a library? I reason since, by default, the countdown is zero seconds, the library still allows developers to use the library and provide their own rate-limiting schemes. Given any developers using the service will need to rate-limit requests anyway, however, I figure that it would be a convenience for the library to provide a means of rate-limiting.</p>
<p>Regardless of placing a rate-limiting scheme in the library or not, I'll want to write an application using the library, so suggested techniques will come in handy.</p>
<p>Many thanks for your suggestions!</p>
<p>Chris</p>
| 9 | 2008-12-30T19:30:11Z | 401,445 | <p>If your library is designed to be synchronous, then I'd recommend leaving out the limit enforcement (although you could track rates and at least help the caller decide how to honor limits).</p>
<p>I use <a href="http://twistedmatrix.com/" rel="nofollow">twisted</a> to interface with pretty much everything nowadays. It makes it easy to do that type of thing by having a model that separates request submission from response handling. If you don't want your API users to have to use twisted, you'd at least be better off understanding their API for deferred execution.</p>
<p>For example, I have a twitter interface that pushes a rather absurd number of requests through on behalf of <a href="http://dustin.github.com/twitterspy/" rel="nofollow">xmpp users</a>. I don't rate limit, but I did have to do a bit of work to prevent all of the requests from happening at the same time.</p>
| 1 | 2008-12-30T20:43:37Z | [
"python",
"web-services",
"rate-limiting"
] |
How to limit rate of requests to web services in Python? | 401,215 | <p>I'm working on a Python library that interfaces with a web service API. Like many web services I've encountered, this one requests limiting the rate of requests. I would like to provide an optional parameter, <code>limit</code>, to the class instantiation that, if provided, will hold outgoing requests until the number of seconds specified passes.</p>
<p>I understand that the general scenario is the following: an instance of the class makes a request via a method. When it does, the method emits some signal that sets a lock variable somewhere, and begins a countdown timer for the number of seconds in <code>limit</code>. (In all likelihood, the lock is the countdown timer itself.) If another request is made within this time frame, it must be queued until the countdown timer reaches zero and the lock is disengaged; at this point, the oldest request on the queue is sent, and the countdown timer is reset and the lock is re-engaged.</p>
<p>Is this a case for threading? Is there another approach I'm not seeing?</p>
<p>Should the countdown timer and lock be instance variables, or should they belong to the class, such that all instances of the class hold requests?</p>
<p>Also, is this generally a bad idea to provide rate-limiting functionality within a library? I reason since, by default, the countdown is zero seconds, the library still allows developers to use the library and provide their own rate-limiting schemes. Given any developers using the service will need to rate-limit requests anyway, however, I figure that it would be a convenience for the library to provide a means of rate-limiting.</p>
<p>Regardless of placing a rate-limiting scheme in the library or not, I'll want to write an application using the library, so suggested techniques will come in handy.</p>
<p>Many thanks for your suggestions!</p>
<p>Chris</p>
| 9 | 2008-12-30T19:30:11Z | 401,826 | <p>SO I am assuming something simple like
import time
time.sleep(2)
will not work for waiting 2 seconds between requests</p>
| 0 | 2008-12-30T23:25:39Z | [
"python",
"web-services",
"rate-limiting"
] |
Naming Python loggers | 401,277 | <p>In Django, I've got loggers all over the place, currently with hard-coded names.</p>
<p>For module-level logging (i.e., in a module of view functions) I have the urge to do this.</p>
<pre><code>log = logging.getLogger(__name__)
</code></pre>
<p>For class-level logging (i.e., in a class <code>__init__</code> method) I have the urge to do this.</p>
<pre><code>self.log = logging.getLogger("%s.%s" % (
self.__module__, self.__class__.__name__))
</code></pre>
<p>I'm looking for second opinions before I tackle several dozen occurrences of <code>getLogger("hard.coded.name")</code>.</p>
<p>Will this work? Anyone else naming their loggers with the same unimaginative ways? </p>
<p>Further, should I break down and write a class decorator for this log definition?</p>
| 44 | 2008-12-30T19:47:53Z | 401,352 | <p>That looks like it will work, except that <code>self</code> won't have a <code>__module__</code> attribute; its class will. The class-level logger call should look like:</p>
<pre><code>self.log = logging.getLogger( "%s.%s" % ( self.__class__.__module__, self.__class__.__name__ ) )
</code></pre>
| 2 | 2008-12-30T20:12:00Z | [
"python",
"django",
"logging"
] |
Naming Python loggers | 401,277 | <p>In Django, I've got loggers all over the place, currently with hard-coded names.</p>
<p>For module-level logging (i.e., in a module of view functions) I have the urge to do this.</p>
<pre><code>log = logging.getLogger(__name__)
</code></pre>
<p>For class-level logging (i.e., in a class <code>__init__</code> method) I have the urge to do this.</p>
<pre><code>self.log = logging.getLogger("%s.%s" % (
self.__module__, self.__class__.__name__))
</code></pre>
<p>I'm looking for second opinions before I tackle several dozen occurrences of <code>getLogger("hard.coded.name")</code>.</p>
<p>Will this work? Anyone else naming their loggers with the same unimaginative ways? </p>
<p>Further, should I break down and write a class decorator for this log definition?</p>
| 44 | 2008-12-30T19:47:53Z | 402,471 | <p>I typically don't use or find a need for class-level loggers, but I keep my modules at a few classes at most. A simple:</p>
<pre><code>import logging
LOG = logging.getLogger(__name__)
</code></pre>
<p>At the top of the module and subsequent:</p>
<pre><code>LOG.info('Spam and eggs are tasty!')
</code></pre>
<p>from anywhere in the file typically gets me to where I want to be. This avoids the need for <code>self.log</code> all over the place, which tends to bother me from both a put-it-in-every-class perspective and makes me 5 characters closer to 79 character lines that fit.</p>
<p>You could always use a pseudo-class-decorator:</p>
<pre><code>>>> import logging
>>> class Foo(object):
... def __init__(self):
... self.log.info('Meh')
...
>>> def logged_class(cls):
... cls.log = logging.getLogger('{0}.{1}'.format(__name__, cls.__name__))
...
>>> logged_class(Foo)
>>> logging.basicConfig(level=logging.DEBUG)
>>> f = Foo()
INFO:__main__.Foo:Meh
</code></pre>
| 63 | 2008-12-31T07:31:40Z | [
"python",
"django",
"logging"
] |
Naming Python loggers | 401,277 | <p>In Django, I've got loggers all over the place, currently with hard-coded names.</p>
<p>For module-level logging (i.e., in a module of view functions) I have the urge to do this.</p>
<pre><code>log = logging.getLogger(__name__)
</code></pre>
<p>For class-level logging (i.e., in a class <code>__init__</code> method) I have the urge to do this.</p>
<pre><code>self.log = logging.getLogger("%s.%s" % (
self.__module__, self.__class__.__name__))
</code></pre>
<p>I'm looking for second opinions before I tackle several dozen occurrences of <code>getLogger("hard.coded.name")</code>.</p>
<p>Will this work? Anyone else naming their loggers with the same unimaginative ways? </p>
<p>Further, should I break down and write a class decorator for this log definition?</p>
| 44 | 2008-12-30T19:47:53Z | 1,628,641 | <p>For class level logging, as an alternative to a pseudo-class decorator, you could use a metaclass to make the logger for you at class creation time...</p>
<pre><code>import logging
class Foo(object):
class __metaclass__(type):
def __init__(cls, name, bases, attrs):
type.__init__(name, bases, attrs)
cls.log = logging.getLogger('%s.%s' % (attrs['__module__'], name))
def __init__(self):
self.log.info('here I am, a %s!' % type(self).__name__)
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
foo = Foo()
</code></pre>
| 3 | 2009-10-27T03:36:18Z | [
"python",
"django",
"logging"
] |
Regex that only matches text that's not part of HTML markup? (python) | 401,726 | <p>How can I make a pattern match so long as it's not inside of an HTML tag?</p>
<p>Here's my attempt below. Anyone have a better/different approach?</p>
<pre><code>import re
inputstr = 'mary had a <b class="foo"> little loomb</b>'
rx = re.compile('[aob]')
repl = 'x'
outputstr = ''
i = 0
for astr in re.compile(r'(<[^>]*>)').split(inputstr):
i = 1 - i
if i:
astr = re.sub(rx, repl, astr)
outputstr += astr
print outputstr
</code></pre>
<p>output:</p>
<pre><code>mxry hxd x <b class="foo"> little lxxmx</b>
</code></pre>
<p>Notes:</p>
<ul>
<li>The <[^>]*> pattern to match HTML tags is obviously flawed -- I wrote this quickly and didn't account for the possibility of angle brackets within quoted attributes (e.g. '<img alt="next >" />'). It doesn't account for <script> or <style> tags or comments, either.</li>
</ul>
| 1 | 2008-12-30T22:33:22Z | 401,774 | <p>Since you are using Python anyway, if I were you, I would have a look at <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a>, which is a <strong>Python HTML/XML parser</strong>. Really, there are so many special cases and headaches with writing your own parser, it just doesn't worth the effort. Your regular expression will get unmanageably large and will still not yield the correct results in all of the cases.</p>
<p>Just use <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a>.</p>
| 12 | 2008-12-30T22:56:26Z | [
"python",
"regex"
] |
Scaling the y-axis with Matplotlib in Python | 401,787 | <p>How to scale the y-axis with <a href="http://matplotlib.sourceforge.net/" rel="nofollow">Matplotlib</a>? I don't want to change the y-limit, I just want to extend the physical space.</p>
<pre><code>^ ^
| |
| |
+----> |
Before +---->
After
</code></pre>
| 4 | 2008-12-30T23:02:08Z | 401,823 | <p>Just use a larger height value when you instantiate the figure:</p>
<pre><code>from pylab import *
x = linspace(0, 10*pi, 2**10)
y = sin(x)
figure(figsize=(5, 10))
plot(x, y)
show()
</code></pre>
<p>Where <code>figsize=(width, height)</code> and defaults to <code>(8, 6)</code>. Values are in inches (the <code>dpi</code> keyword arg can be used to define the <a href="http://en.wikipedia.org/wiki/Dots_per_inch" rel="nofollow">DPI</a> for the figure, and there's a default value in your <code>matplotlibrc</code> file)</p>
<p>For a figure already created, I believe there is a <code>set_size_inches(width, height)</code> method.</p>
| 7 | 2008-12-30T23:21:52Z | [
"python",
"matplotlib"
] |
Scaling the y-axis with Matplotlib in Python | 401,787 | <p>How to scale the y-axis with <a href="http://matplotlib.sourceforge.net/" rel="nofollow">Matplotlib</a>? I don't want to change the y-limit, I just want to extend the physical space.</p>
<pre><code>^ ^
| |
| |
+----> |
Before +---->
After
</code></pre>
| 4 | 2008-12-30T23:02:08Z | 404,971 | <p>Use the subplots_adjust function to control the abount of whitespace:</p>
<p>fig.subplots_adust(bottom=0.05, top=0.95)</p>
<p>There is an icon on the toolbar to do this interactively with a widget </p>
| 2 | 2009-01-01T14:00:22Z | [
"python",
"matplotlib"
] |
How to store a dictionary on a Django Model? | 402,217 | <p>I need to store some data in a Django model. These data are not equal to all instances of the model.</p>
<p>At first I thought about subclassing the model, but Iâm trying to keep the application flexible. If I use subclasses, Iâll need to create a whole class each time I need a new kind of object, and thatâs no good. Iâll also end up with a lot of subclasses only to store a pair of extra fields.</p>
<p>I really feel that a dictionary would be the best approach, but thereâs nothing in the Django documentation about storing a dictionary in a Django model (or I canât find it).</p>
<p>Any clues?</p>
| 32 | 2008-12-31T03:18:15Z | 402,248 | <p>If you don't need to query by any of this extra data, then you can store it as a serialized dictionary. Use <code>repr</code> to turn the dictionary into a string, and <code>eval</code> to turn the string back into a dictionary. Take care with eval that there's no user data in the dictionary, or use a safe_eval implementation.</p>
| 13 | 2008-12-31T03:39:18Z | [
"python",
"django",
"orm",
"persistence"
] |
How to store a dictionary on a Django Model? | 402,217 | <p>I need to store some data in a Django model. These data are not equal to all instances of the model.</p>
<p>At first I thought about subclassing the model, but Iâm trying to keep the application flexible. If I use subclasses, Iâll need to create a whole class each time I need a new kind of object, and thatâs no good. Iâll also end up with a lot of subclasses only to store a pair of extra fields.</p>
<p>I really feel that a dictionary would be the best approach, but thereâs nothing in the Django documentation about storing a dictionary in a Django model (or I canât find it).</p>
<p>Any clues?</p>
| 32 | 2008-12-31T03:18:15Z | 402,387 | <p>Think it over, and find the commonalities of each data set... then define your model. It may require the use of subclasses or not. Foreign keys representing commonalities aren't to be avoided, but encouraged when they make sense.</p>
<p>Stuffing random data into a SQL table is not smart, unless it's truly non-relational data. If that's the case, define your problem and we may be able to help.</p>
| 2 | 2008-12-31T05:54:12Z | [
"python",
"django",
"orm",
"persistence"
] |
How to store a dictionary on a Django Model? | 402,217 | <p>I need to store some data in a Django model. These data are not equal to all instances of the model.</p>
<p>At first I thought about subclassing the model, but Iâm trying to keep the application flexible. If I use subclasses, Iâll need to create a whole class each time I need a new kind of object, and thatâs no good. Iâll also end up with a lot of subclasses only to store a pair of extra fields.</p>
<p>I really feel that a dictionary would be the best approach, but thereâs nothing in the Django documentation about storing a dictionary in a Django model (or I canât find it).</p>
<p>Any clues?</p>
| 32 | 2008-12-31T03:18:15Z | 402,452 | <p>I'm not sure exactly sure of the nature of the problem you're trying to solve, but it sounds curiously similar to <a href="http://code.google.com/appengine/docs/datastore/expandoclass.html" rel="nofollow">Google App Engine's BigTable Expando</a>.</p>
<p>Expandos allow you to specify and store additional fields on an database-backed object instance at runtime. To quote from the docs:</p>
<pre><code>import datetime
from google.appengine.ext import db
class Song(db.Expando):
title = db.StringProperty()
crazy = Song(title='Crazy like a diamond',
author='Lucy Sky',
publish_date='yesterday',
rating=5.0)
crazy.last_minute_note=db.Text('Get a train to the station.')
</code></pre>
<p>Google App Engine currently supports both Python and the Django framework. Might be worth looking into if this is the best way to express your models.</p>
<p>Traditional relational database models don't have this kind of column-addition flexibility. If your datatypes are simple enough you could break from traditional RDBMS philosophy and hack values into a single column via serialization as <a href="http://stackoverflow.com/questions/402217/how-to-store-a-dictionary-on-a-django-model#402248">@Ned Batchelder</a> proposes; however, if you <em>have</em> to use an RDBMS, Django model inheritance is probably the way to go. Notably, it will create <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.OneToOneField" rel="nofollow">a one-to-one foreign key</a> relation for each level of derivation.</p>
| 3 | 2008-12-31T07:09:29Z | [
"python",
"django",
"orm",
"persistence"
] |
How to store a dictionary on a Django Model? | 402,217 | <p>I need to store some data in a Django model. These data are not equal to all instances of the model.</p>
<p>At first I thought about subclassing the model, but Iâm trying to keep the application flexible. If I use subclasses, Iâll need to create a whole class each time I need a new kind of object, and thatâs no good. Iâll also end up with a lot of subclasses only to store a pair of extra fields.</p>
<p>I really feel that a dictionary would be the best approach, but thereâs nothing in the Django documentation about storing a dictionary in a Django model (or I canât find it).</p>
<p>Any clues?</p>
| 32 | 2008-12-31T03:18:15Z | 402,487 | <p>As Ned answered, you won't be able to query "some data" if you use the dictionary approach.</p>
<p>If you still need to store dictionaries then the best approach, by far, is the PickleField class documented in Marty Alchin's new book <strong>Pro Django</strong>. This method uses Python class properties to pickle/unpickle a python object, only on demand, that is stored in a model field.</p>
<p>The basics of this approach is to use django's <a href="http://code.djangoproject.com/browser/django/trunk/django/db/models/fields/__init__.py"><code>contibute_to_class</code></a> method to dynamically add a new field to your model and uses getattr/setattr to do the serializing on demand.</p>
<p>One of the few online examples I could find that is similar is this definition of a <a href="http://svn.navi.cx/misc/trunk/djblets/djblets/util/fields.py">JSONField</a>.</p>
| 6 | 2008-12-31T07:44:46Z | [
"python",
"django",
"orm",
"persistence"
] |
How to store a dictionary on a Django Model? | 402,217 | <p>I need to store some data in a Django model. These data are not equal to all instances of the model.</p>
<p>At first I thought about subclassing the model, but Iâm trying to keep the application flexible. If I use subclasses, Iâll need to create a whole class each time I need a new kind of object, and thatâs no good. Iâll also end up with a lot of subclasses only to store a pair of extra fields.</p>
<p>I really feel that a dictionary would be the best approach, but thereâs nothing in the Django documentation about storing a dictionary in a Django model (or I canât find it).</p>
<p>Any clues?</p>
| 32 | 2008-12-31T03:18:15Z | 402,526 | <p>If it's really dictionary like arbitrary data you're looking for you can probably use a two-level setup with one model that's a container and another model that's key-value pairs. You'd create an instance of the container, create each of the key-value instances, and associate the set of key-value instances with the container instance. Something like:</p>
<pre><code>class Dicty(models.Model):
name = models.CharField(max_length=50)
class KeyVal(models.Model):
container = models.ForeignKey(Dicty, db_index=True)
key = models.CharField(max_length=240, db_index=True)
value = models.CharField(max_length=240, db_index=True)
</code></pre>
<p>It's not pretty, but it'll let you access/search the innards of the dictionary using the DB whereas a pickle/serialize solution will not.</p>
| 22 | 2008-12-31T08:19:28Z | [
"python",
"django",
"orm",
"persistence"
] |
How to store a dictionary on a Django Model? | 402,217 | <p>I need to store some data in a Django model. These data are not equal to all instances of the model.</p>
<p>At first I thought about subclassing the model, but Iâm trying to keep the application flexible. If I use subclasses, Iâll need to create a whole class each time I need a new kind of object, and thatâs no good. Iâll also end up with a lot of subclasses only to store a pair of extra fields.</p>
<p>I really feel that a dictionary would be the best approach, but thereâs nothing in the Django documentation about storing a dictionary in a Django model (or I canât find it).</p>
<p>Any clues?</p>
| 32 | 2008-12-31T03:18:15Z | 410,919 | <p>Being "not equal to all instances of the model" sounds to me like a good match for a "Schema-free database". <a href="http://couchdb.apache.org/" rel="nofollow">CouchDB</a> is the poster child for that approach and you might consider that. </p>
<p>In a project I moved several tables which never played very nice with the Django ORM over to CouchDB and I'm quite happy with that. I use <a href="http://code.google.com/p/couchdb-python/" rel="nofollow">couchdb-python</a> without any of the Django-specific CouchDB modules. A description of the data model can be found <a href="http://blogs.23.nu/c0re/2008/12/building-a-track-and-trace-application-with-couchdb/" rel="nofollow">here</a>. The movement from five "models" in Django to 3 "models" in Django and one CouchDB "database" actually slightly reduced the total lines of code in my application.</p>
| 3 | 2009-01-04T12:28:20Z | [
"python",
"django",
"orm",
"persistence"
] |
How to store a dictionary on a Django Model? | 402,217 | <p>I need to store some data in a Django model. These data are not equal to all instances of the model.</p>
<p>At first I thought about subclassing the model, but Iâm trying to keep the application flexible. If I use subclasses, Iâll need to create a whole class each time I need a new kind of object, and thatâs no good. Iâll also end up with a lot of subclasses only to store a pair of extra fields.</p>
<p>I really feel that a dictionary would be the best approach, but thereâs nothing in the Django documentation about storing a dictionary in a Django model (or I canât find it).</p>
<p>Any clues?</p>
| 32 | 2008-12-31T03:18:15Z | 859,088 | <p>Django-Geo includes a "DictionaryField" you might find helpful:</p>
<p><a href="http://code.google.com/p/django-geo/source/browse/trunk/fields.py?r=13#49" rel="nofollow">http://code.google.com/p/django-geo/source/browse/trunk/fields.py?r=13#49</a></p>
<p>In general, if you don't need to query across the data use a denormalized approach to avoid extra queries. User settings are a pretty good example!</p>
| 2 | 2009-05-13T16:50:37Z | [
"python",
"django",
"orm",
"persistence"
] |
How to store a dictionary on a Django Model? | 402,217 | <p>I need to store some data in a Django model. These data are not equal to all instances of the model.</p>
<p>At first I thought about subclassing the model, but Iâm trying to keep the application flexible. If I use subclasses, Iâll need to create a whole class each time I need a new kind of object, and thatâs no good. Iâll also end up with a lot of subclasses only to store a pair of extra fields.</p>
<p>I really feel that a dictionary would be the best approach, but thereâs nothing in the Django documentation about storing a dictionary in a Django model (or I canât find it).</p>
<p>Any clues?</p>
| 32 | 2008-12-31T03:18:15Z | 859,470 | <p>I agree that you need to refrain stuffing otherwise structured data into a single column. But if you must do that, Django has an <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#xmlfield" rel="nofollow">XMLField</a> build-in.</p>
<p>There's also <a href="http://www.djangosnippets.org/snippets/377/" rel="nofollow">JSONField</a> at Django snipplets.</p>
| 2 | 2009-05-13T18:05:44Z | [
"python",
"django",
"orm",
"persistence"
] |
How to store a dictionary on a Django Model? | 402,217 | <p>I need to store some data in a Django model. These data are not equal to all instances of the model.</p>
<p>At first I thought about subclassing the model, but Iâm trying to keep the application flexible. If I use subclasses, Iâll need to create a whole class each time I need a new kind of object, and thatâs no good. Iâll also end up with a lot of subclasses only to store a pair of extra fields.</p>
<p>I really feel that a dictionary would be the best approach, but thereâs nothing in the Django documentation about storing a dictionary in a Django model (or I canât find it).</p>
<p>Any clues?</p>
| 32 | 2008-12-31T03:18:15Z | 7,469,287 | <p>I came to this post by google's 4rth result to "django store object"</p>
<p>A little bit late, but <a href="http://pypi.python.org/pypi/django-picklefield">django-picklefield</a> looks like good solution to me.</p>
<p>Example from doc:</p>
<p>To use, just define a field in your model:</p>
<pre><code>>>> from picklefield.fields import PickledObjectField
>>> class SomeObject(models.Model):
>>> args = PickledObjectField()
</code></pre>
<p>and assign whatever you like (as long as it's picklable) to the field:</p>
<pre><code>>>> obj = SomeObject()
>>> obj.args = ['fancy', {'objects': 'inside'}]
>>> obj.save()
</code></pre>
| 5 | 2011-09-19T10:10:04Z | [
"python",
"django",
"orm",
"persistence"
] |
How to store a dictionary on a Django Model? | 402,217 | <p>I need to store some data in a Django model. These data are not equal to all instances of the model.</p>
<p>At first I thought about subclassing the model, but Iâm trying to keep the application flexible. If I use subclasses, Iâll need to create a whole class each time I need a new kind of object, and thatâs no good. Iâll also end up with a lot of subclasses only to store a pair of extra fields.</p>
<p>I really feel that a dictionary would be the best approach, but thereâs nothing in the Django documentation about storing a dictionary in a Django model (or I canât find it).</p>
<p>Any clues?</p>
| 32 | 2008-12-31T03:18:15Z | 17,970,922 | <p>Another clean and fast solution can be found here: <a href="https://github.com/bradjasper/django-jsonfield" rel="nofollow">https://github.com/bradjasper/django-jsonfield</a></p>
<p>For convenience I copied the simple instructions.</p>
<p><strong>Install</strong></p>
<pre><code>pip install jsonfield
</code></pre>
<p><strong>Usage</strong></p>
<pre><code>from django.db import models
from jsonfield import JSONField
class MyModel(models.Model):
json = JSONField()
</code></pre>
| 3 | 2013-07-31T12:50:28Z | [
"python",
"django",
"orm",
"persistence"
] |
How to store a dictionary on a Django Model? | 402,217 | <p>I need to store some data in a Django model. These data are not equal to all instances of the model.</p>
<p>At first I thought about subclassing the model, but Iâm trying to keep the application flexible. If I use subclasses, Iâll need to create a whole class each time I need a new kind of object, and thatâs no good. Iâll also end up with a lot of subclasses only to store a pair of extra fields.</p>
<p>I really feel that a dictionary would be the best approach, but thereâs nothing in the Django documentation about storing a dictionary in a Django model (or I canât find it).</p>
<p>Any clues?</p>
| 32 | 2008-12-31T03:18:15Z | 39,235,784 | <p>If you are using Postgres, you can use an hstore field: <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/postgres/fields/#hstorefield" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/contrib/postgres/fields/#hstorefield</a>.</p>
| 0 | 2016-08-30T19:36:59Z | [
"python",
"django",
"orm",
"persistence"
] |
How do you uninstall a python package that was installed using distutils? | 402,359 | <p>Can you simply delete the directory from your python installation, or are there any lingering files that you must delete?</p>
| 72 | 2008-12-31T05:26:14Z | 402,444 | <p>It varies based on the options that you pass to <code>install</code> and the contents of the <a href="http://docs.python.org/install/index.html#inst-config-files">distutils configuration files</a> on the system/in the package. I don't believe that any files are modified outside of directories specified in these ways.</p>
<p>Notably, <a href="http://bugs.python.org/issue4673">distutils does not have an uninstall command</a> at this time. </p>
<p>It's also noteworthy that deleting a package/egg can cause dependency issues -- utilities like <a href="http://peak.telecommunity.com/DevCenter/EasyInstall"><code>easy_install</code></a> attempt to alleviate such problems.</p>
| 34 | 2008-12-31T07:00:04Z | [
"python"
] |
How do you uninstall a python package that was installed using distutils? | 402,359 | <p>Can you simply delete the directory from your python installation, or are there any lingering files that you must delete?</p>
| 72 | 2008-12-31T05:26:14Z | 403,540 | <p>If this is for testing and/or development purposes, <a href="http://peak.telecommunity.com/DevCenter/setuptools" rel="nofollow">setuptools</a> has a <a href="http://peak.telecommunity.com/DevCenter/setuptools#develop-deploy-the-project-source-in-development-mode" rel="nofollow">develop</a> command that updates every time you make a change (so you don't have to uninstall and reinstall every time you make a change). And you can uninstall the package using this command as well.</p>
<p>If you do use this, anything that you declare as a <em>script</em> will be left behind as a lingering file.</p>
| 4 | 2008-12-31T17:24:59Z | [
"python"
] |
How do you uninstall a python package that was installed using distutils? | 402,359 | <p>Can you simply delete the directory from your python installation, or are there any lingering files that you must delete?</p>
| 72 | 2008-12-31T05:26:14Z | 403,563 | <p>The three things that get installed that you will need to delete are:</p>
<ol>
<li>Packages/modules</li>
<li>Scripts</li>
<li>Data files</li>
</ol>
<p>Now on my linux system these live in:</p>
<ol>
<li>/usr/lib/python2.5/site-packages</li>
<li>/usr/bin</li>
<li>/usr/share</li>
</ol>
<p>But on a windows system they are more likely to be entirely within the Python distribution directory. I have no idea about OSX except it is more likey to follow the linux pattern.</p>
| 12 | 2008-12-31T17:31:17Z | [
"python"
] |
How do you uninstall a python package that was installed using distutils? | 402,359 | <p>Can you simply delete the directory from your python installation, or are there any lingering files that you must delete?</p>
| 72 | 2008-12-31T05:26:14Z | 405,406 | <p>Yes, it is safe to simply delete anything that distutils installed. That goes for installed folders or .egg files. Naturally anything that depends on that code will no longer work. </p>
<p>If you want to make it work again, simply re-install. </p>
<p>By the way, if you are using distutils also consider using the multi-version feature. It allows you to have multiple versions of any single package installed. That means you do not need to delete an old version of a package if you simply want to install a newer version.</p>
| 7 | 2009-01-01T20:06:35Z | [
"python"
] |
How do you uninstall a python package that was installed using distutils? | 402,359 | <p>Can you simply delete the directory from your python installation, or are there any lingering files that you must delete?</p>
| 72 | 2008-12-31T05:26:14Z | 928,621 | <p>I just uninstalled a python package, and even though I'm not <em>certain</em> I did so perfectly, I'm reasonably confident. </p>
<p>I started by getting a list of <em>all</em> python-related files, ordered by date, on the assumption that all of the files in my package will have more or less the same timestamp, and no other files will.</p>
<p>Luckily, I've got python installed under <code>/opt/Python-2.6.1</code>; if I had been using the Python that comes with my Linux distro, I'd have had to scour all of <code>/usr</code>, which would have taken a long time.</p>
<p>Then I just examined that list, and noted with relief that all the stuff that I wanted to nuke consisted of one directory, <code>/opt/Python-2.6.1/lib/python2.6/site-packages/module-name/</code>, and one file, <code>/opt/Python-2.6.1/lib/python2.6/site-packages/module-x.x.x_blah-py2.6.egg-info</code>.</p>
<p>So I just deleted those.</p>
<p>Here's how I got the date-sorted list of files:</p>
<p><code>find "$@" -printf '%T@ ' -ls | sort -n | cut -d\ -f 2-</code></p>
<p>(I think that's got to be GNU "find", by the way; the flavor you get on OS X doesn't know about "-printf '%T@'")</p>
<p>I use that <em>all</em> the time.</p>
| 2 | 2009-05-30T00:12:08Z | [
"python"
] |
How do you uninstall a python package that was installed using distutils? | 402,359 | <p>Can you simply delete the directory from your python installation, or are there any lingering files that you must delete?</p>
| 72 | 2008-12-31T05:26:14Z | 4,524,074 | <p>For Windows 7,</p>
<p><strong>Control Panel --> Programs --> Uninstall</strong></p>
<p>, then </p>
<p>choose the python package to remove.</p>
| 2 | 2010-12-24T03:50:18Z | [
"python"
] |
How do you uninstall a python package that was installed using distutils? | 402,359 | <p>Can you simply delete the directory from your python installation, or are there any lingering files that you must delete?</p>
| 72 | 2008-12-31T05:26:14Z | 8,471,143 | <p>Another time stamp based hack:</p>
<ol>
<li>Create an anchor: <code>touch /tmp/ts</code></li>
<li>Reinstall the package to be removed: <code>python setup.py install --prefix=<PREFIX></code></li>
<li>Remove files what are more recent than the anchor file: <code>find <PREFIX> -cnewer /tmp/ts | xargs rm -r</code></li>
</ol>
| 11 | 2011-12-12T07:27:00Z | [
"python"
] |
How do you uninstall a python package that was installed using distutils? | 402,359 | <p>Can you simply delete the directory from your python installation, or are there any lingering files that you must delete?</p>
| 72 | 2008-12-31T05:26:14Z | 11,749,229 | <p>In ubuntu 12.04, I have found that the only place you need to look by default is under</p>
<pre><code>/usr/local/lib/python2.7/
</code></pre>
<p>And simply remove the associated folder and file, if there is one!</p>
| 4 | 2012-07-31T21:24:50Z | [
"python"
] |
Help--Function Pointers in Python | 402,364 | <p>My idea of program:</p>
<p>I have a dictionary:</p>
<pre><code>options = { 'string' : select_fun(function pointer),
'float' : select_fun(function pointer),
'double' : select_fun(function pointer)
}
</code></pre>
<p>whatever type comes single function <code>select_fun(function pointer)</code> gets called.
Inside <code>select_fun(function pointer)</code>,I will have diff functions for float, double and so on.</p>
<p>Depending on function pointers, specified function will get called.</p>
<p>I don't know whether my programming knowledge is good or bad, still I need help.</p>
| 3 | 2008-12-31T05:34:38Z | 402,369 | <p>Could you be more specific on what you're trying to do? You don't have to do anything special to get function pointers in Python -- you can pass around functions like regular objects:</p>
<pre><code>def plus_1(x):
return x + 1
def minus_1(x):
return x - 1
func_map = {'+' : plus_1, '-' : minus_1}
func_map['+'](3) # returns plus_1(3) ==> 4
func_map['-'](3) # returns minus_1(3) ==> 2
</code></pre>
| 20 | 2008-12-31T05:41:07Z | [
"python",
"function",
"pointers"
] |
Help--Function Pointers in Python | 402,364 | <p>My idea of program:</p>
<p>I have a dictionary:</p>
<pre><code>options = { 'string' : select_fun(function pointer),
'float' : select_fun(function pointer),
'double' : select_fun(function pointer)
}
</code></pre>
<p>whatever type comes single function <code>select_fun(function pointer)</code> gets called.
Inside <code>select_fun(function pointer)</code>,I will have diff functions for float, double and so on.</p>
<p>Depending on function pointers, specified function will get called.</p>
<p>I don't know whether my programming knowledge is good or bad, still I need help.</p>
| 3 | 2008-12-31T05:34:38Z | 402,382 | <p>You can use the <a href="http://diveintopython.net/power_of_introspection/built_in_functions.html#d0e8510" rel="nofollow"><code>type()</code> built-in function</a> to detect the type of the function.</p>
<p>Say, if you want to check if a certain name hold a string data, you could do this:</p>
<pre><code>if type(this_is_string) == type('some random string'):
# this_is_string is indeed a string
</code></pre>
<p>So in your case, you could do it like this:</p>
<pre><code>options = { 'some string' : string_function,
(float)(123.456) : float_function,
(int)(123) : int_function
}
def call_option(arg):
# loop through the dictionary
for (k, v) in options.iteritems():
# if found matching type...
if type(k) == type(arg):
# call the matching function
func = option[k]
func(arg)
</code></pre>
<p>Then you can use it like this:</p>
<pre><code>call_option('123') # string_function gets called
call_option(123.456) # float_function gets called
call_option(123) # int_function gets called
</code></pre>
<p>I don't have a python interpreter nearby and I don't program in Python much so there may be some errors, but you should get the idea.</p>
<hr>
<p><strong>EDIT:</strong> As per @Adam's suggestion, there are built-in type constants that you can check against directly, so a better approach would be:</p>
<pre><code>from types import *
options = { types.StringType : string_function,
types.FloatType : float_function,
types.IntType : int_function,
types.LongType : long_function
}
def call_option(arg):
for (k, v) in options.iteritems():
# check if arg is of type k
if type(arg) == k:
# call the matching function
func = options[k]
func(arg)
</code></pre>
<p>And since the key itself is comparable to the value of the type() function, you can just do this:</p>
<pre><code>def call_option(arg):
func = options[type(arg)]
func(arg)
</code></pre>
<p>Which is more elegant :-) save for some error-checking.</p>
<hr>
<p><strong>EDIT:</strong> And for ctypes support, after some fiddling around, I've found that ctypes.[type_name_here] is actually implented as classes. So this method still works, you just need to use the ctypes.c_xxx type classes.</p>
<pre><code>options = { ctypes.c_long : c_long_processor,
ctypes.c_ulong : c_unsigned_long_processor,
types.StringType : python_string_procssor
}
call_option = lambda x: options[type(x)](x)
</code></pre>
| 6 | 2008-12-31T05:51:29Z | [
"python",
"function",
"pointers"
] |
Help--Function Pointers in Python | 402,364 | <p>My idea of program:</p>
<p>I have a dictionary:</p>
<pre><code>options = { 'string' : select_fun(function pointer),
'float' : select_fun(function pointer),
'double' : select_fun(function pointer)
}
</code></pre>
<p>whatever type comes single function <code>select_fun(function pointer)</code> gets called.
Inside <code>select_fun(function pointer)</code>,I will have diff functions for float, double and so on.</p>
<p>Depending on function pointers, specified function will get called.</p>
<p>I don't know whether my programming knowledge is good or bad, still I need help.</p>
| 3 | 2008-12-31T05:34:38Z | 402,393 | <p>Maybe you want to call the same <code>select_fun()</code> every time, with a different argument. If that is what you mean, you need a different dictionary:</p>
<pre><code>>>> options = {'string' : str, 'float' : float, 'double' : float }
>>> options
{'double': <type 'float'>, 'float': <type 'float'>, 'string': <type 'str'>}
>>> def call_option(val, func):
... return func(val)
...
>>> call_option('555',options['float'])
555.0
>>>
</code></pre>
| 3 | 2008-12-31T06:03:51Z | [
"python",
"function",
"pointers"
] |
Help--Function Pointers in Python | 402,364 | <p>My idea of program:</p>
<p>I have a dictionary:</p>
<pre><code>options = { 'string' : select_fun(function pointer),
'float' : select_fun(function pointer),
'double' : select_fun(function pointer)
}
</code></pre>
<p>whatever type comes single function <code>select_fun(function pointer)</code> gets called.
Inside <code>select_fun(function pointer)</code>,I will have diff functions for float, double and so on.</p>
<p>Depending on function pointers, specified function will get called.</p>
<p>I don't know whether my programming knowledge is good or bad, still I need help.</p>
| 3 | 2008-12-31T05:34:38Z | 402,397 | <p>Functions are the first-class objects in Python therefore you can pass them as arguments to other functions as you would with any other object such as string or an integer.</p>
<p>There is no single-precision floating point type in Python. Python's <code>float</code> corresponds to C's <code>double</code>.</p>
<pre><code>def process(anobject):
if isinstance(anobject, basestring):
# anobject is a string
fun = process_string
elif isinstance(anobject, (float, int, long, complex)):
# anobject is a number
fun = process_number
else:
raise TypeError("expected string or number but received: '%s'" % (
type(anobject),))
return fun(anobject)
</code></pre>
<p>There is <a href="https://docs.python.org/3/library/functools.html#functools.singledispatch" rel="nofollow"><code>functools.singledispatch</code></a> that allows to create a generic function:</p>
<pre><code>from functools import singledispatch
from numbers import Number
@singledispatch
def process(anobject): # default implementation
raise TypeError("'%s' type is not supported" % type(anobject))
@process.register(str)
def _(anobject):
# handle strings here
return process_string(anobject)
process.register(Number)(process_number) # use existing function for numbers
</code></pre>
<p>On Python 2, similar functionality is available as <code>pkgutil.simplegeneric()</code>.</p>
<p>Here's a couple of code example of using generic functions:</p>
<ul>
<li><a href="http://stackoverflow.com/q/17098553/4279">Remove whitespaces and newlines from JSON file</a></li>
<li><a href="http://stackoverflow.com/q/23550870/4279">Make my_average(a, b) work with any a and b for which f_add and d_div are defined. As well as builtins</a></li>
</ul>
| 4 | 2008-12-31T06:08:04Z | [
"python",
"function",
"pointers"
] |
Help--Function Pointers in Python | 402,364 | <p>My idea of program:</p>
<p>I have a dictionary:</p>
<pre><code>options = { 'string' : select_fun(function pointer),
'float' : select_fun(function pointer),
'double' : select_fun(function pointer)
}
</code></pre>
<p>whatever type comes single function <code>select_fun(function pointer)</code> gets called.
Inside <code>select_fun(function pointer)</code>,I will have diff functions for float, double and so on.</p>
<p>Depending on function pointers, specified function will get called.</p>
<p>I don't know whether my programming knowledge is good or bad, still I need help.</p>
| 3 | 2008-12-31T05:34:38Z | 402,489 | <p>Looking at your example, it seems to me some C procedure, directly translated to Python.</p>
<p>For this reason, I think there could be some design issue, because usually, in Python, you do not care about type of an object, but only about the messages you can send to it.</p>
<p>Of course, there are plenty of exceptions to this approach, but still in this case I would try encapsulating in some polymorphism; eg.</p>
<pre><code>class StringSomething(object):
data = None
def data_function(self):
string_function_pointer(self.data)
class FloatSomething(object):
data = None
def data_function(self):
float_function_pointer(self.data)
</code></pre>
<p>etc.</p>
<p>Again, all of this under the assumption you are translating from a procedural language to python; if it is not the case, then discard my answer :-)</p>
| 4 | 2008-12-31T07:46:22Z | [
"python",
"function",
"pointers"
] |
Caching result of setUp() using Python unittest | 402,483 | <p>I currently have a unittest.TestCase that looks like..</p>
<pre><code>class test_appletrailer(unittest.TestCase):
def setup(self):
self.all_trailers = Trailers(res = "720", verbose = True)
def test_has_trailers(self):
self.failUnless(len(self.all_trailers) > 1)
# ..more tests..
</code></pre>
<p>This works fine, but the <code>Trailers()</code> call takes about 2 seconds to run.. Given that <code>setUp()</code> is called before each test is run, the tests now take almost 10 seconds to run (with only 3 test functions)</p>
<p>What is the correct way of caching the <code>self.all_trailers</code> variable between tests?</p>
<p>Removing the setUp function, and doing..</p>
<pre><code>class test_appletrailer(unittest.TestCase):
all_trailers = Trailers(res = "720", verbose = True)
</code></pre>
<p>..works, but then it claims "Ran 3 tests in 0.000s" which is incorrect.. The only other way I could think of is to have a cache_trailers global variable (which works correctly, but is rather horrible):</p>
<pre><code>cache_trailers = None
class test_appletrailer(unittest.TestCase):
def setUp(self):
global cache_trailers
if cache_trailers is None:
cache_trailers = self.all_trailers = all_trailers = Trailers(res = "720", verbose = True)
else:
self.all_trailers = cache_trailers
</code></pre>
| 7 | 2008-12-31T07:43:31Z | 402,492 | <p>How about using a class member that only gets initialized once?</p>
<pre><code>class test_appletrailer(unittest.TestCase):
all_trailers = None
def setup(self):
# Only initialize all_trailers once.
if self.all_trailers is None:
self.__class__.all_trailers = Trailers(res = "720", verbose = True)
</code></pre>
<p>Lookups that refer to <code>self.all_trailers</code> will go to the next step in the <a href="http://www.python.org/download/releases/2.3/mro/">MRO</a> -- <code>self.__class__.all_trailers</code>, which will be initialized.</p>
| 14 | 2008-12-31T07:48:46Z | [
"python",
"unit-testing"
] |
Caching result of setUp() using Python unittest | 402,483 | <p>I currently have a unittest.TestCase that looks like..</p>
<pre><code>class test_appletrailer(unittest.TestCase):
def setup(self):
self.all_trailers = Trailers(res = "720", verbose = True)
def test_has_trailers(self):
self.failUnless(len(self.all_trailers) > 1)
# ..more tests..
</code></pre>
<p>This works fine, but the <code>Trailers()</code> call takes about 2 seconds to run.. Given that <code>setUp()</code> is called before each test is run, the tests now take almost 10 seconds to run (with only 3 test functions)</p>
<p>What is the correct way of caching the <code>self.all_trailers</code> variable between tests?</p>
<p>Removing the setUp function, and doing..</p>
<pre><code>class test_appletrailer(unittest.TestCase):
all_trailers = Trailers(res = "720", verbose = True)
</code></pre>
<p>..works, but then it claims "Ran 3 tests in 0.000s" which is incorrect.. The only other way I could think of is to have a cache_trailers global variable (which works correctly, but is rather horrible):</p>
<pre><code>cache_trailers = None
class test_appletrailer(unittest.TestCase):
def setUp(self):
global cache_trailers
if cache_trailers is None:
cache_trailers = self.all_trailers = all_trailers = Trailers(res = "720", verbose = True)
else:
self.all_trailers = cache_trailers
</code></pre>
| 7 | 2008-12-31T07:43:31Z | 402,495 | <p>What is Trailers class doing?<br>
If it holds some state, then you <strong>have</strong> to reset it each time unit test is being executed.</p>
<p>To solve your problem, I would use a mock object - just emulating the interface of Trailers, providing a faked set of data.</p>
<p><hr /></p>
<p><strong>Update</strong>: as Trailers is only reading XML data, I would go for a solution like the one proposed by cdleary.</p>
| 1 | 2008-12-31T07:49:55Z | [
"python",
"unit-testing"
] |
Caching result of setUp() using Python unittest | 402,483 | <p>I currently have a unittest.TestCase that looks like..</p>
<pre><code>class test_appletrailer(unittest.TestCase):
def setup(self):
self.all_trailers = Trailers(res = "720", verbose = True)
def test_has_trailers(self):
self.failUnless(len(self.all_trailers) > 1)
# ..more tests..
</code></pre>
<p>This works fine, but the <code>Trailers()</code> call takes about 2 seconds to run.. Given that <code>setUp()</code> is called before each test is run, the tests now take almost 10 seconds to run (with only 3 test functions)</p>
<p>What is the correct way of caching the <code>self.all_trailers</code> variable between tests?</p>
<p>Removing the setUp function, and doing..</p>
<pre><code>class test_appletrailer(unittest.TestCase):
all_trailers = Trailers(res = "720", verbose = True)
</code></pre>
<p>..works, but then it claims "Ran 3 tests in 0.000s" which is incorrect.. The only other way I could think of is to have a cache_trailers global variable (which works correctly, but is rather horrible):</p>
<pre><code>cache_trailers = None
class test_appletrailer(unittest.TestCase):
def setUp(self):
global cache_trailers
if cache_trailers is None:
cache_trailers = self.all_trailers = all_trailers = Trailers(res = "720", verbose = True)
else:
self.all_trailers = cache_trailers
</code></pre>
| 7 | 2008-12-31T07:43:31Z | 403,541 | <p>An alternative to the proposed solution would be to use a more featured test runner like <a href="http://somethingaboutorange.com/mrl/projects/nose/">Nose</a>. With Nose, you can have module-level setup functions which will be run once for a test module. Since it is entirely compatible with unittest, you wouldn't have to change any code.</p>
<p>From the Nose manual:</p>
<blockquote>
<p>nose supports fixtures at the package,
module, class, and test case level, <strong>so</strong>
<strong>expensive initialization can be done</strong>
<strong>as infrequently as possible</strong>.</p>
</blockquote>
<p>Fixtures are <a href="http://somethingaboutorange.com/mrl/projects/nose/#fixtures">described in detail here</a>. Of course, apart from fulfilling your use-case, I can also strongly recommend it as a general testing tool. None of my projects will leave home without it.</p>
| 8 | 2008-12-31T17:25:38Z | [
"python",
"unit-testing"
] |
Caching result of setUp() using Python unittest | 402,483 | <p>I currently have a unittest.TestCase that looks like..</p>
<pre><code>class test_appletrailer(unittest.TestCase):
def setup(self):
self.all_trailers = Trailers(res = "720", verbose = True)
def test_has_trailers(self):
self.failUnless(len(self.all_trailers) > 1)
# ..more tests..
</code></pre>
<p>This works fine, but the <code>Trailers()</code> call takes about 2 seconds to run.. Given that <code>setUp()</code> is called before each test is run, the tests now take almost 10 seconds to run (with only 3 test functions)</p>
<p>What is the correct way of caching the <code>self.all_trailers</code> variable between tests?</p>
<p>Removing the setUp function, and doing..</p>
<pre><code>class test_appletrailer(unittest.TestCase):
all_trailers = Trailers(res = "720", verbose = True)
</code></pre>
<p>..works, but then it claims "Ran 3 tests in 0.000s" which is incorrect.. The only other way I could think of is to have a cache_trailers global variable (which works correctly, but is rather horrible):</p>
<pre><code>cache_trailers = None
class test_appletrailer(unittest.TestCase):
def setUp(self):
global cache_trailers
if cache_trailers is None:
cache_trailers = self.all_trailers = all_trailers = Trailers(res = "720", verbose = True)
else:
self.all_trailers = cache_trailers
</code></pre>
| 7 | 2008-12-31T07:43:31Z | 4,578,221 | <p>It's worth mentioning that during 2010 the testrunner used in the Zope/Plone world was released as a separate module, unsurprisingly called <a href="http://pypi.python.org/pypi/zope.testrunner" rel="nofollow">zope.testrunner</a>. It supports caching setUps in the form of "Layers". Check it out.</p>
| 0 | 2011-01-02T11:47:56Z | [
"python",
"unit-testing"
] |
Caching result of setUp() using Python unittest | 402,483 | <p>I currently have a unittest.TestCase that looks like..</p>
<pre><code>class test_appletrailer(unittest.TestCase):
def setup(self):
self.all_trailers = Trailers(res = "720", verbose = True)
def test_has_trailers(self):
self.failUnless(len(self.all_trailers) > 1)
# ..more tests..
</code></pre>
<p>This works fine, but the <code>Trailers()</code> call takes about 2 seconds to run.. Given that <code>setUp()</code> is called before each test is run, the tests now take almost 10 seconds to run (with only 3 test functions)</p>
<p>What is the correct way of caching the <code>self.all_trailers</code> variable between tests?</p>
<p>Removing the setUp function, and doing..</p>
<pre><code>class test_appletrailer(unittest.TestCase):
all_trailers = Trailers(res = "720", verbose = True)
</code></pre>
<p>..works, but then it claims "Ran 3 tests in 0.000s" which is incorrect.. The only other way I could think of is to have a cache_trailers global variable (which works correctly, but is rather horrible):</p>
<pre><code>cache_trailers = None
class test_appletrailer(unittest.TestCase):
def setUp(self):
global cache_trailers
if cache_trailers is None:
cache_trailers = self.all_trailers = all_trailers = Trailers(res = "720", verbose = True)
else:
self.all_trailers = cache_trailers
</code></pre>
| 7 | 2008-12-31T07:43:31Z | 5,539,791 | <p>If you are using Python >= 2.7 you can use the <a href="http://docs.python.org/library/unittest.html#unittest.TestCase.setUpClass" rel="nofollow"><code>setUpClass</code></a> method that is called only once for the whole unit test.</p>
<pre><code>import unittest
from trailers import Trailers
class AppleTrailerTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
# only initialize all_trailers once
cls.all_trailers = Trailers(res='720', verbose=True)
@classmethod
def tearDownClass(cls):
# drop the reference explicitly to let the Trailers object be garbage
# collected
cls.all_trailers = None
def test_one(self):
# ...
def test_two(self):
# ...
</code></pre>
| 4 | 2011-04-04T14:16:46Z | [
"python",
"unit-testing"
] |
How to determine the variable type in Python? | 402,504 | <p>How do I see the type of a variable whether it is unsigned 32 bit, signed 16 bit, etc.?</p>
<p>How do I view it?</p>
| 607 | 2008-12-31T07:58:57Z | 402,507 | <p>You may be looking for the <code>type()</code> function.</p>
<p>See the examples below, but there's no "unsigned" type in Python just like Java.</p>
<p>Positive integer:</p>
<pre><code>>>> v = 10
>>> type(v)
<type 'int'>
</code></pre>
<p><em>Large</em> positive integer:</p>
<pre><code>>>> v = 100000000000000
>>> type(v)
<type 'long'>
</code></pre>
<p>Negative integer:</p>
<pre><code>>>> v = -10
>>> type(v)
<type 'int'>
</code></pre>
<p>Literal sequence of characters:</p>
<pre><code>>>> v = 'hi'
>>> type(v)
<type 'str'>
</code></pre>
| 172 | 2008-12-31T08:02:04Z | [
"python",
"types",
"unsigned",
"signed",
"16-bit"
] |
How to determine the variable type in Python? | 402,504 | <p>How do I see the type of a variable whether it is unsigned 32 bit, signed 16 bit, etc.?</p>
<p>How do I view it?</p>
| 607 | 2008-12-31T07:58:57Z | 402,508 | <pre><code>print type(variable_name)
</code></pre>
<p>I also highly recommend the <a href="http://ipython.scipy.org/">IPython</a> interactive interpreter when dealing with questions like this. It lets you type <code>variable_name?</code> and will return a whole list of information about the object including the type and the doc string for the type.</p>
<p>e.g.</p>
<pre><code>In [9]: var = 123
In [10]: var?
Type: int
Base Class: <type 'int'>
String Form: 123
Namespace: Interactive
Docstring:
int(x[, base]) -> integer
Convert a string or number to an integer, if possible. A floating point
argument will be truncated towards zero (this does not include a string
representation of a floating point number!) When converting a string, use
the optional base. It is an error to supply a base when converting a
non-string. If the argument is outside the integer range a long object
will be returned instead.
</code></pre>
| 9 | 2008-12-31T08:02:11Z | [
"python",
"types",
"unsigned",
"signed",
"16-bit"
] |
How to determine the variable type in Python? | 402,504 | <p>How do I see the type of a variable whether it is unsigned 32 bit, signed 16 bit, etc.?</p>
<p>How do I view it?</p>
| 607 | 2008-12-31T07:58:57Z | 402,511 | <p>The question is somewhat ambiguous -- I'm not sure what you mean by "view". If you are trying to <em>query</em> the type of a native Python object, <a href="http://stackoverflow.com/questions/402504/how-to-determine-the-variable-type-in-python#402516">@atzz</a>'s answer will steer you in the right direction.</p>
<p>However, if you are trying to <em>generate</em> Python objects that have the semantics of primitive C-types, (such as <code>uint32_t</code>, <code>int16_t</code>), use the <a href="http://docs.python.org/library/struct.html#struct.calcsize"><code>struct</code></a> module. You can determine the number of bits in a given C-type primitive thusly:</p>
<pre><code>>>> struct.calcsize('c') # char
1
>>> struct.calcsize('h') # short
2
>>> struct.calcsize('i') # int
4
>>> struct.calcsize('l') # long
4
</code></pre>
<p>This is also reflected in the <code>array</code> module, which can make arrays of these lower-level types:</p>
<pre><code>>>> array.array('c').itemsize # char
1
</code></pre>
<p>The maximum integer supported (Python 2's <code>int</code>) is given by <a href="http://docs.python.org/library/sys.html#sys.maxsize">sys.maxint</a>.</p>
<pre><code>>>> import sys, math
>>> math.ceil(math.log(sys.maxint, 2)) + 1 # Signedness
32.0
</code></pre>
<p>There is also <a href="http://docs.python.org/library/sys.html#sys.getsizeof">sys.getsizeof</a>, which returns the actual size of the <em>Python</em> object in residual memory:</p>
<pre><code>>>> a = 5
>>> sys.getsizeof(a) # Residual memory.
12
</code></pre>
<p>For float data and precision data, use <a href="http://docs.python.org/library/sys.html#sys.float_info">sys.float_info</a>:</p>
<pre><code>>>> sys.float_info
sys.floatinfo(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.2204460492503131e-16, radix=2, rounds=1)
</code></pre>
| 20 | 2008-12-31T08:08:06Z | [
"python",
"types",
"unsigned",
"signed",
"16-bit"
] |
How to determine the variable type in Python? | 402,504 | <p>How do I see the type of a variable whether it is unsigned 32 bit, signed 16 bit, etc.?</p>
<p>How do I view it?</p>
| 607 | 2008-12-31T07:58:57Z | 402,515 | <p>Do you mean in <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29">Python</a> or using <a href="http://www.python.org/doc/2.5/lib/module-ctypes.html">ctypes</a>?</p>
<p>In the first case, you simply cannot - because Python does not have signed/unsigned, 16/32 bit integers.</p>
<p>In the second case, you can use <code>type()</code>:</p>
<pre><code>>>> import ctypes
>>> a = ctypes.c_uint() # unsigned int
>>> type(a)
<class 'ctypes.c_ulong'>
</code></pre>
<p>For more reference on ctypes, an its type, see <a href="http://docs.python.org/library/ctypes.html">the official documentation</a>.</p>
| 12 | 2008-12-31T08:10:54Z | [
"python",
"types",
"unsigned",
"signed",
"16-bit"
] |
How to determine the variable type in Python? | 402,504 | <p>How do I see the type of a variable whether it is unsigned 32 bit, signed 16 bit, etc.?</p>
<p>How do I view it?</p>
| 607 | 2008-12-31T07:58:57Z | 402,516 | <p>Python doesn't have such types as you describe. There are two types used to represent integral values: <code>int</code>, which corresponds to platform's int type in C, and <code>long</code>, which is an arbitrary precision integer (i.e. it grows as needed and doesn't have an upper limit). <code>int</code>s are silently converted to <code>long</code> if an expression produces result which cannot be stored in <code>int</code>.</p>
| 10 | 2008-12-31T08:12:34Z | [
"python",
"types",
"unsigned",
"signed",
"16-bit"
] |
How to determine the variable type in Python? | 402,504 | <p>How do I see the type of a variable whether it is unsigned 32 bit, signed 16 bit, etc.?</p>
<p>How do I view it?</p>
| 607 | 2008-12-31T07:58:57Z | 402,704 | <p>Python doesn't have the same types as C/C++, which appears to be your question.</p>
<p>Try this:</p>
<pre><code>>>> i = 123
>>> type(i)
<type 'int'>
>>> type(i) is int
True
>>> i = 123456789L
>>> type(i)
<type 'long'>
>>> type(i) is long
True
>>> i = 123.456
>>> type(i)
<type 'float'>
>>> type(i) is float
True
</code></pre>
<p>The distinction between int and long goes away in Python 3.0, though.</p>
| 582 | 2008-12-31T10:43:07Z | [
"python",
"types",
"unsigned",
"signed",
"16-bit"
] |
How to determine the variable type in Python? | 402,504 | <p>How do I see the type of a variable whether it is unsigned 32 bit, signed 16 bit, etc.?</p>
<p>How do I view it?</p>
| 607 | 2008-12-31T07:58:57Z | 403,093 | <p>It really depends on what level you mean. In Python 2.x, there are two integer types, <code>int</code> (constrained to <code>sys.maxint</code>) and <code>long</code> (unlimited precision), for historical reasons. In Python code, this shouldn't make a bit of difference because the interpreter automatically converts to long when a number is too large. If you want to know about the actual data types used in the underlying interpreter, that's implementation dependent. (CPython's are located in Objects/intobject.c and Objects/longobject.c.) To find out about the systems types look at cdleary answer for using the struct module.</p>
| 5 | 2008-12-31T14:36:51Z | [
"python",
"types",
"unsigned",
"signed",
"16-bit"
] |
How to determine the variable type in Python? | 402,504 | <p>How do I see the type of a variable whether it is unsigned 32 bit, signed 16 bit, etc.?</p>
<p>How do I view it?</p>
| 607 | 2008-12-31T07:58:57Z | 18,224,831 | <p>It may be little irrelevant. but you can check types of an object with <code>isinstance(object, type)</code> as mentioned <a href="http://stackoverflow.com/questions/2225038/python-determine-the-type-of-an-object" title="Object type in python">here</a>.</p>
| 9 | 2013-08-14T06:39:32Z | [
"python",
"types",
"unsigned",
"signed",
"16-bit"
] |
How to determine the variable type in Python? | 402,504 | <p>How do I see the type of a variable whether it is unsigned 32 bit, signed 16 bit, etc.?</p>
<p>How do I view it?</p>
| 607 | 2008-12-31T07:58:57Z | 29,113,307 | <p>One more way using <code>__class__</code>:</p>
<pre><code>>>> a = [1, 2, 3, 4]
>>> a.__class__
<type 'list'>
>>> b = {'key1': 'val1'}
>>> b.__class__
<type 'dict'>
>>> c = 12
>>> c.__class__
<type 'int'>
</code></pre>
| 26 | 2015-03-18T02:48:04Z | [
"python",
"types",
"unsigned",
"signed",
"16-bit"
] |
How to determine the variable type in Python? | 402,504 | <p>How do I see the type of a variable whether it is unsigned 32 bit, signed 16 bit, etc.?</p>
<p>How do I view it?</p>
| 607 | 2008-12-31T07:58:57Z | 32,885,953 | <p>It is so simple. You do it like this.</p>
<pre><code>print type(variable_name)
</code></pre>
| 55 | 2015-10-01T11:02:32Z | [
"python",
"types",
"unsigned",
"signed",
"16-bit"
] |
How to determine the variable type in Python? | 402,504 | <p>How do I see the type of a variable whether it is unsigned 32 bit, signed 16 bit, etc.?</p>
<p>How do I view it?</p>
| 607 | 2008-12-31T07:58:57Z | 39,921,486 | <blockquote>
<h1>How to determine the variable type in Python?</h1>
<p>How do I see the type of a variable whether it is unsigned 32 bit, signed 16 bit, etc.?</p>
</blockquote>
<p>So if you have a variable, for example:</p>
<pre><code>one = 1
</code></pre>
<p>You want to know its type?</p>
<p>There are right ways and wrong ways to do just about everything in Python. When I see questions like this, I will always see at least one wrong-way upvoted.</p>
<h2>Use <code>type</code></h2>
<pre><code>>>> type(one)
<type 'int'>
</code></pre>
<p>You can use the <code>__name__</code> attribute to get the name of the object. (This is one of the few special attributes that you need to use the <code>__dunder__</code> name to get to - there's not even a method for it in the <code>inspect</code> module.)</p>
<pre><code>>>> type(one).__name__
'int'
</code></pre>
<h2>Don't use <code>__class__</code></h2>
<p>Since <code>type</code> gives us the class of the object, we should avoid getting this directly:</p>
<pre><code>>>> one.__class__
</code></pre>
<p>This is usually the first idea people have when accessing the type of an object in a method - they're already looking for attributes, so type seems weird. For example:</p>
<pre><code>class Foo(object):
def foo(self):
self.__class__
</code></pre>
<p>Don't. Instead, do type(self):</p>
<pre><code>class Foo(object):
def foo(self):
type(self)
</code></pre>
<h2>Conclusion</h2>
<p>Don't use <code>__class__</code>. Use <code>type</code> instead.</p>
| -1 | 2016-10-07T16:02:24Z | [
"python",
"types",
"unsigned",
"signed",
"16-bit"
] |
How to sort a list of objects in Python, based on an attribute of the objects? | 403,421 | <p>I've got a list of Python objects that I'd like to sort by an attribute of the objects themselves. The list looks like:</p>
<pre><code>>>> ut
[<Tag: 128>, <Tag: 2008>, <Tag: <>, <Tag: actionscript>, <Tag: addresses>, <Tag: aes>, <Tag: ajax> ...]
</code></pre>
<p>Each object has a count:</p>
<pre><code>>>> ut[1].count
1L
</code></pre>
<p>I need to sort the list by number of counts descending.</p>
<p>I've seen several methods for this, but I'm looking for best practice in Python.</p>
| 310 | 2008-12-31T16:41:32Z | 403,426 | <pre><code># To sort the list in place...
ut.sort(key=lambda x: x.count, reverse=True)
# To return a new list, use the sorted() built-in function...
newlist = sorted(ut, key=lambda x: x.count, reverse=True)
</code></pre>
<p>More on <a href="http://wiki.python.org/moin/HowTo/Sorting#Sortingbykeys">sorting by keys »</a> </p>
| 531 | 2008-12-31T16:42:59Z | [
"python",
"sorting",
"count"
] |
How to sort a list of objects in Python, based on an attribute of the objects? | 403,421 | <p>I've got a list of Python objects that I'd like to sort by an attribute of the objects themselves. The list looks like:</p>
<pre><code>>>> ut
[<Tag: 128>, <Tag: 2008>, <Tag: <>, <Tag: actionscript>, <Tag: addresses>, <Tag: aes>, <Tag: ajax> ...]
</code></pre>
<p>Each object has a count:</p>
<pre><code>>>> ut[1].count
1L
</code></pre>
<p>I need to sort the list by number of counts descending.</p>
<p>I've seen several methods for this, but I'm looking for best practice in Python.</p>
| 310 | 2008-12-31T16:41:32Z | 403,437 | <p>Add rich comparison operators to the object class, then use sort() method of the list.<br>
See <a href="http://docs.python.org/reference/datamodel.html#object.__lt__">rich comparison in python</a>.</p>
<p><hr /></p>
<p><strong>Update</strong>: Although this method would work, I think solution from Triptych is better suited to your case because way simpler.</p>
| 5 | 2008-12-31T16:45:15Z | [
"python",
"sorting",
"count"
] |
How to sort a list of objects in Python, based on an attribute of the objects? | 403,421 | <p>I've got a list of Python objects that I'd like to sort by an attribute of the objects themselves. The list looks like:</p>
<pre><code>>>> ut
[<Tag: 128>, <Tag: 2008>, <Tag: <>, <Tag: actionscript>, <Tag: addresses>, <Tag: aes>, <Tag: ajax> ...]
</code></pre>
<p>Each object has a count:</p>
<pre><code>>>> ut[1].count
1L
</code></pre>
<p>I need to sort the list by number of counts descending.</p>
<p>I've seen several methods for this, but I'm looking for best practice in Python.</p>
| 310 | 2008-12-31T16:41:32Z | 403,496 | <p>It looks much like a list of Django ORM model instances.</p>
<p>Why not sort them on query like this:</p>
<pre><code>ut = Tag.objects.order_by('-count')
</code></pre>
| 9 | 2008-12-31T17:10:00Z | [
"python",
"sorting",
"count"
] |
How to sort a list of objects in Python, based on an attribute of the objects? | 403,421 | <p>I've got a list of Python objects that I'd like to sort by an attribute of the objects themselves. The list looks like:</p>
<pre><code>>>> ut
[<Tag: 128>, <Tag: 2008>, <Tag: <>, <Tag: actionscript>, <Tag: addresses>, <Tag: aes>, <Tag: ajax> ...]
</code></pre>
<p>Each object has a count:</p>
<pre><code>>>> ut[1].count
1L
</code></pre>
<p>I need to sort the list by number of counts descending.</p>
<p>I've seen several methods for this, but I'm looking for best practice in Python.</p>
| 310 | 2008-12-31T16:41:32Z | 403,607 | <p>A way that can be fastest, especially if your list has a lot of records, is to use <code>operator.attrgetter("count")</code>. However, this might run on an pre-operator version of Python, so it would be nice to have a fallback mechanism. You might want to do the following, then:</p>
<pre><code>try: import operator
except ImportError: cmpfun= lambda x: x.count # use a lambda if no operator module
else: cmpfun= operator.attrgetter("count") # use operator since it's faster than lambda
ut.sort(key=cmpfun, reverse=True) # sort in-place
</code></pre>
| 38 | 2008-12-31T17:48:21Z | [
"python",
"sorting",
"count"
] |
How to sort a list of objects in Python, based on an attribute of the objects? | 403,421 | <p>I've got a list of Python objects that I'd like to sort by an attribute of the objects themselves. The list looks like:</p>
<pre><code>>>> ut
[<Tag: 128>, <Tag: 2008>, <Tag: <>, <Tag: actionscript>, <Tag: addresses>, <Tag: aes>, <Tag: ajax> ...]
</code></pre>
<p>Each object has a count:</p>
<pre><code>>>> ut[1].count
1L
</code></pre>
<p>I need to sort the list by number of counts descending.</p>
<p>I've seen several methods for this, but I'm looking for best practice in Python.</p>
| 310 | 2008-12-31T16:41:32Z | 403,795 | <pre><code>from operator import attrgetter
ut.sort(key = attrgetter('count'), reverse = True)
</code></pre>
| 10 | 2008-12-31T19:00:33Z | [
"python",
"sorting",
"count"
] |
How to sort a list of objects in Python, based on an attribute of the objects? | 403,421 | <p>I've got a list of Python objects that I'd like to sort by an attribute of the objects themselves. The list looks like:</p>
<pre><code>>>> ut
[<Tag: 128>, <Tag: 2008>, <Tag: <>, <Tag: actionscript>, <Tag: addresses>, <Tag: aes>, <Tag: ajax> ...]
</code></pre>
<p>Each object has a count:</p>
<pre><code>>>> ut[1].count
1L
</code></pre>
<p>I need to sort the list by number of counts descending.</p>
<p>I've seen several methods for this, but I'm looking for best practice in Python.</p>
| 310 | 2008-12-31T16:41:32Z | 988,728 | <p>Readers should notice that the key= method:</p>
<pre><code>ut.sort(key=lambda x: x.count, reverse=True)
</code></pre>
<p>is many times faster than adding rich comparison operators to the objects. I was surprised to read this (page 485 of "Python in a Nutshell"). You can confirm this by running tests on this little program:</p>
<pre><code>#!/usr/bin/env python
import random
class C:
def __init__(self,count):
self.count = count
def __cmp__(self,other):
return cmp(self.count,other.count)
longList = [C(random.random()) for i in xrange(1000000)] #about 6.1 secs
longList2 = longList[:]
longList.sort() #about 52 - 6.1 = 46 secs
longList2.sort(key = lambda c: c.count) #about 9 - 6.1 = 3 secs
</code></pre>
<p>My, very minimal, tests show the first sort is more than 10 times slower, but the book says it is only about 5 times slower in general. The reason they say is due to the highly optimizes sort algorithm used in python (<strong>timsort</strong>).</p>
<p>Still, its very odd that .sort(lambda) is faster than plain old .sort(). I hope they fix that.</p>
| 26 | 2009-06-12T19:54:58Z | [
"python",
"sorting",
"count"
] |
Making the value of a table equal to another value in a different table | 403,433 | <p>I have a small problem with a program that im writing. I have a table - stocks which contains information(products, barcodes etc.) about items stored in a fridge. I then have another table - shop which acts like a shop,containing loads of products and their barcodes.some of the products in the shop table are in the stock table at the moment, and there is a boolenan field called stock which tells us if that product is in the stock table or not, if its equal to 1, it is in the fridge, if it is equal to 0, it is not in the fridge. Two fields in the stocks table are amount and quantity. The amount is what is in the fridge at the moment, the quantity is what has to be in the fridge at all times. When something is taken out of the fridge, that product's amount amount drops by 1. Each barcode in the stocks table has a matching one in the shop table. I need to make a query to the database from a python program which will order products from the shops table when the amount (whats in the fridge) is less than the quantity (whats meant to be in the fridge at all times). So you need to take the barcode of a row in the stocks table where the amount is less than the quantity and match that up to the barcode in the shops table. Then in the row of that matching barcode you need to set stock = 1.</p>
<p>I would be really happy if somebody could help me with this as I really am finding it difficult to write this function. Below is the checkin and checkout functions if that will help.</p>
<p><strong>checkin</strong></p>
<pre><code>def check_in():
db = MySQLdb.connect(host='localhost', user='root', passwd='$$', db='fillmyfridge')
cursor=db.cursor(MySQLdb.cursors.DictCursor)
user_input=raw_input('please enter the product barcode that you wish to checkin to the fridge: \n')
cursor.execute("""update shop set stock = 1 where barcode = %s""", (user_input))
db.commit()
numrows = int(cursor.rowcount)
if numrows >= 1:
row = cursor.fetchone()
print row["product"]
cursor.execute('update stock set amount = amount + 1 where product = %s', row["product"])
db.commit()
cursor.execute('udpate shop set stock = 1 where barcode = user_input')
db.commit()
else:
new_prodname = raw_input('what is the name of the product and press enter: \n')
cursor.execute('insert into shop (product, barcode, category) values (%s, %s, %s)', (new_prodname, user_input, new_prodname))
cursor = db.cursor()
query = ('select * from shop where product = %s', (new_prodname))
cursor.execute(query):
db.commit()
numrows = int(cursor.rowcount)
if numrows<1:
cursor.execute('insert into atock (barcode, quantity, amount, product) values (%s, 1, 1, %s)', (user_input, new_prodname))
db.commit()
cursor.execute('insert into shop (product, barcode, category, stock) values (%s, %s, %s, 1)', (new_prodname, user_input, new_prodname))
print new_prodname
print 'has been added to the fridge stock'
else:
cursor.execute('update atock set amount = amount + 1 where product = %s', (new_prodname))
db.commit()
cursor.execute('insert into shop (product, barcode, category, stock) values (%s, %s, %s, 1)', (new_prodname, user_input, new_prodname))
print new_prodname
print 'has been added to the fridge stock'
</code></pre>
<p><strong>checkout</strong></p>
<pre><code>import MySQLdb
def check_out():
db = MySQLdb.connect(host='localhost', user='root', passwd='$$', db='fillmyfridge')
cursor=db.cursor()
user_input=raw_input('please enter the product barcode you wish to remove from the fridge: \n')
query = cursor.execute('update stock set instock=0, howmanytoorder=howmanytoorder + 1, amount = amount - 1 where barcode = %s', (user_input))
if cursor.execute(query):
db.commit()
print 'the following product has been removed from the fridge nd needs to be ordered'
cursor.execute('update shop set stock = 0 where barcode = %s' (user_input)
db.commit()
else:
return 0
</code></pre>
| -1 | 2008-12-31T16:44:27Z | 403,491 | <p>Try to make the question shorter. That will generate more responses, I guess.</p>
| 0 | 2008-12-31T17:08:00Z | [
"python",
"mysql"
] |
Making the value of a table equal to another value in a different table | 403,433 | <p>I have a small problem with a program that im writing. I have a table - stocks which contains information(products, barcodes etc.) about items stored in a fridge. I then have another table - shop which acts like a shop,containing loads of products and their barcodes.some of the products in the shop table are in the stock table at the moment, and there is a boolenan field called stock which tells us if that product is in the stock table or not, if its equal to 1, it is in the fridge, if it is equal to 0, it is not in the fridge. Two fields in the stocks table are amount and quantity. The amount is what is in the fridge at the moment, the quantity is what has to be in the fridge at all times. When something is taken out of the fridge, that product's amount amount drops by 1. Each barcode in the stocks table has a matching one in the shop table. I need to make a query to the database from a python program which will order products from the shops table when the amount (whats in the fridge) is less than the quantity (whats meant to be in the fridge at all times). So you need to take the barcode of a row in the stocks table where the amount is less than the quantity and match that up to the barcode in the shops table. Then in the row of that matching barcode you need to set stock = 1.</p>
<p>I would be really happy if somebody could help me with this as I really am finding it difficult to write this function. Below is the checkin and checkout functions if that will help.</p>
<p><strong>checkin</strong></p>
<pre><code>def check_in():
db = MySQLdb.connect(host='localhost', user='root', passwd='$$', db='fillmyfridge')
cursor=db.cursor(MySQLdb.cursors.DictCursor)
user_input=raw_input('please enter the product barcode that you wish to checkin to the fridge: \n')
cursor.execute("""update shop set stock = 1 where barcode = %s""", (user_input))
db.commit()
numrows = int(cursor.rowcount)
if numrows >= 1:
row = cursor.fetchone()
print row["product"]
cursor.execute('update stock set amount = amount + 1 where product = %s', row["product"])
db.commit()
cursor.execute('udpate shop set stock = 1 where barcode = user_input')
db.commit()
else:
new_prodname = raw_input('what is the name of the product and press enter: \n')
cursor.execute('insert into shop (product, barcode, category) values (%s, %s, %s)', (new_prodname, user_input, new_prodname))
cursor = db.cursor()
query = ('select * from shop where product = %s', (new_prodname))
cursor.execute(query):
db.commit()
numrows = int(cursor.rowcount)
if numrows<1:
cursor.execute('insert into atock (barcode, quantity, amount, product) values (%s, 1, 1, %s)', (user_input, new_prodname))
db.commit()
cursor.execute('insert into shop (product, barcode, category, stock) values (%s, %s, %s, 1)', (new_prodname, user_input, new_prodname))
print new_prodname
print 'has been added to the fridge stock'
else:
cursor.execute('update atock set amount = amount + 1 where product = %s', (new_prodname))
db.commit()
cursor.execute('insert into shop (product, barcode, category, stock) values (%s, %s, %s, 1)', (new_prodname, user_input, new_prodname))
print new_prodname
print 'has been added to the fridge stock'
</code></pre>
<p><strong>checkout</strong></p>
<pre><code>import MySQLdb
def check_out():
db = MySQLdb.connect(host='localhost', user='root', passwd='$$', db='fillmyfridge')
cursor=db.cursor()
user_input=raw_input('please enter the product barcode you wish to remove from the fridge: \n')
query = cursor.execute('update stock set instock=0, howmanytoorder=howmanytoorder + 1, amount = amount - 1 where barcode = %s', (user_input))
if cursor.execute(query):
db.commit()
print 'the following product has been removed from the fridge nd needs to be ordered'
cursor.execute('update shop set stock = 0 where barcode = %s' (user_input)
db.commit()
else:
return 0
</code></pre>
| -1 | 2008-12-31T16:44:27Z | 403,493 | <p>So, if I got that right you have the following tables:</p>
<p><strong>Stock</strong> with at least a <em>barcode</em>, <em>amount</em> and <em>quantity</em> column</p>
<p><strong>Shop</strong> with at least a <em>barcode</em> and a <em>stock</em> column</p>
<p>I don't understand why you need that <em>stock</em> column in the shop table, because you could easily get the products which are in stock by using a join like this:</p>
<pre><code>SELECT barcode, ... FROM Stock ST JOIN Shop SH ON ST.barcode = SH.barcode;
</code></pre>
<p>Obviously you should also select some other columns from the Shop table or otherwise you could just select everything from the Stock table.</p>
<p>You can get a list of products which need to be ordered (where the amount is less than the quantity):</p>
<pre><code>SELECT barcode FROM Stock ST WHERE ST.amount < ST.quantity;
</code></pre>
| 1 | 2008-12-31T17:08:34Z | [
"python",
"mysql"
] |
Making a SQL Query in two tables | 403,527 | <p>I'm wondering, is it possible to make an sql query that does the same function as
<code>'select products where barcode in table1 = barcode in table2</code>'. I am writing this function in a python program. Once that function is called will the table be joined permanently or just while that function is running?
thanks. </p>
| 0 | 2008-12-31T17:20:11Z | 403,530 | <p>Something like:</p>
<pre><code>SELECT * FROM table1 WHERE barcode IN (SELECT barcode FROM table2)
</code></pre>
<p>Is that what you're looking for?</p>
| 1 | 2008-12-31T17:21:53Z | [
"python",
"sql"
] |
Making a SQL Query in two tables | 403,527 | <p>I'm wondering, is it possible to make an sql query that does the same function as
<code>'select products where barcode in table1 = barcode in table2</code>'. I am writing this function in a python program. Once that function is called will the table be joined permanently or just while that function is running?
thanks. </p>
| 0 | 2008-12-31T17:20:11Z | 403,533 | <p>I think you want to join two tables:</p>
<p><a href="http://www.w3schools.com/Sql/sql_join.asp" rel="nofollow">http://www.w3schools.com/Sql/sql_join.asp</a></p>
| 7 | 2008-12-31T17:22:26Z | [
"python",
"sql"
] |
Making a SQL Query in two tables | 403,527 | <p>I'm wondering, is it possible to make an sql query that does the same function as
<code>'select products where barcode in table1 = barcode in table2</code>'. I am writing this function in a python program. Once that function is called will the table be joined permanently or just while that function is running?
thanks. </p>
| 0 | 2008-12-31T17:20:11Z | 403,535 | <pre><code>SELECT t1.products
FROM [Table1] t1
INNER JOIN [Table2] t2 ON t2.barcode = t1.barcode
</code></pre>
| 10 | 2008-12-31T17:22:52Z | [
"python",
"sql"
] |
Making a SQL Query in two tables | 403,527 | <p>I'm wondering, is it possible to make an sql query that does the same function as
<code>'select products where barcode in table1 = barcode in table2</code>'. I am writing this function in a python program. Once that function is called will the table be joined permanently or just while that function is running?
thanks. </p>
| 0 | 2008-12-31T17:20:11Z | 403,628 | <pre><code>SELECT table1.*, table2.* FROM table1 left join table2 on table1.barcode = table2.barcode
</code></pre>
| 0 | 2008-12-31T17:57:07Z | [
"python",
"sql"
] |
Making a SQL Query in two tables | 403,527 | <p>I'm wondering, is it possible to make an sql query that does the same function as
<code>'select products where barcode in table1 = barcode in table2</code>'. I am writing this function in a python program. Once that function is called will the table be joined permanently or just while that function is running?
thanks. </p>
| 0 | 2008-12-31T17:20:11Z | 403,666 | <p>For those who need to understand joins visually
<a href="http://www.codinghorror.com/blog/archives/000976.html" rel="nofollow">http://www.codinghorror.com/blog/archives/000976.html</a></p>
| 0 | 2008-12-31T18:12:08Z | [
"python",
"sql"
] |
Making a SQL Query in two tables | 403,527 | <p>I'm wondering, is it possible to make an sql query that does the same function as
<code>'select products where barcode in table1 = barcode in table2</code>'. I am writing this function in a python program. Once that function is called will the table be joined permanently or just while that function is running?
thanks. </p>
| 0 | 2008-12-31T17:20:11Z | 403,848 | <p>Here is an example of inner joining two tables based on a common field in both tables.</p>
<p>SELECT table1.Products
FROM table1
INNER JOIN table2 on table1.barcode = table2.barcode
WHERE table1.Products is not null</p>
| 0 | 2008-12-31T19:26:14Z | [
"python",
"sql"
] |
Making a SQL Query in two tables | 403,527 | <p>I'm wondering, is it possible to make an sql query that does the same function as
<code>'select products where barcode in table1 = barcode in table2</code>'. I am writing this function in a python program. Once that function is called will the table be joined permanently or just while that function is running?
thanks. </p>
| 0 | 2008-12-31T17:20:11Z | 403,904 | <p>Here's a way to talk yourself through table design in these cases, based on Object Role Modeling. (Yes, I realize this is only indirectly related to the question.)</p>
<p>You have products and barcodes. Products are uniquely identified by Product Code (e.g. 'A2111'; barcodes are uniquely identified by Value (e.g. 1002155061).</p>
<p>A Product has a Barcode. Questions: Can a product have no barcode? Can the same product have multiple barcodes? Can multiple products have the same barcode? (If you have any experience with UPC labels, you know the answer to all these is TRUE.)</p>
<p>So you can make some assertions: </p>
<p>A Product (code) has zero or more Barcode (value).<br />
A Barcode (value) has one or more Product (code). -- assumption: we barcodes don't have independent existence if they aren't/haven't been/won't be related to products).</p>
<p>Which leads directly (via your ORM model) to a schema with two tables: </p>
<p>Product<br />
ProductCode(PK) Description etc</p>
<p>ProductBarcode<br />
ProductCode(FK) BarcodeValue<br />
-- with a two-part natural primary key, ProductCode + BarcodeValue </p>
<p>and you tie them together as described in the other answers.</p>
<p>Similar assertions can be used to determine which fields go into various tables in your design.</p>
| 0 | 2008-12-31T19:48:49Z | [
"python",
"sql"
] |
Optimization in Python - do's, don'ts and rules of thumb | 403,794 | <p>Well I was reading this <a href="http://handyfloss.wordpress.com/2008/02/17/summary-of-my-python-optimization-adventures/">post</a> and then I came across a code which was:</p>
<pre><code>jokes=range(1000000)
domain=[(0,(len(jokes)*2)-i-1) for i in range(0,len(jokes)*2)]
</code></pre>
<p>I thought wouldn't it be better to calculate the value of len(jokes) once outside the list comprehension?</p>
<p>Well I tried it and timed three codes</p>
<pre><code>jv@Pioneer:~$ python -m timeit -s 'jokes=range(1000000);domain=[(0,(len(jokes)*2)-i-1) for i in range(0,len(jokes)*2)]'
10000000 loops, best of 3: 0.0352 usec per loop
jv@Pioneer:~$ python -m timeit -s 'jokes=range(1000000);l=len(jokes);domain=[(0,(l*2)-i-1) for i in range(0,l*2)]'
10000000 loops, best of 3: 0.0343 usec per loop
jv@Pioneer:~$ python -m timeit -s 'jokes=range(1000000);l=len(jokes)*2;domain=[(0,l-i-1) for i in range(0,l)]'
10000000 loops, best of 3: 0.0333 usec per loop
</code></pre>
<p>Observing the marginal difference 2.55% between the first and the second made me think - is the first list comprehension </p>
<pre><code>domain=[(0,(len(jokes)*2)-i-1) for i in range(0,len(jokes)*2)]
</code></pre>
<p>optimized internally by python? or is 2.55% a big enough optimization (given that the len(jokes)=1000000)?</p>
<p>If this is - What are the other implicit/internal optimizations in Python ?</p>
<p>What are the <code>developer's rules of thumb for optimization in Python</code>?</p>
<p><strong>Edit1</strong>: Since most of the answers are "don't optimize, do it later if its slow" and I got some tips and links from <code>Triptych</code> and <code>Ali A</code> for the <strong>do's</strong>.
I will change the question a bit and request for <strong>don'ts</strong>. </p>
<p>Can we have some experiences from people who faced the '<strong>slowness</strong>', what was the problem and how it was corrected? </p>
<p><strong>Edit2</strong>: For those who haven't here is an <a href="http://www.python.org/doc/essays/list2str/">interesting read</a></p>
<p><strong>Edit3:</strong> Incorrect usage of <code>timeit</code> in question please see <strong>dF's</strong> answer for correct usage and hence timings for the three codes.</p>
| 8 | 2008-12-31T18:57:59Z | 403,801 | <p>On a tangentially related note, chaining together generators is much more efficient than chaining together list comprehensions, and often more intuitive.</p>
<p>As for the developer's rules of thumb for optimization in Python, they're the same as they are in all languages.</p>
<ol>
<li>Don't optimize.</li>
<li>(advanced) Optimize later.</li>
</ol>
| 1 | 2008-12-31T19:03:40Z | [
"python",
"optimization"
] |
Optimization in Python - do's, don'ts and rules of thumb | 403,794 | <p>Well I was reading this <a href="http://handyfloss.wordpress.com/2008/02/17/summary-of-my-python-optimization-adventures/">post</a> and then I came across a code which was:</p>
<pre><code>jokes=range(1000000)
domain=[(0,(len(jokes)*2)-i-1) for i in range(0,len(jokes)*2)]
</code></pre>
<p>I thought wouldn't it be better to calculate the value of len(jokes) once outside the list comprehension?</p>
<p>Well I tried it and timed three codes</p>
<pre><code>jv@Pioneer:~$ python -m timeit -s 'jokes=range(1000000);domain=[(0,(len(jokes)*2)-i-1) for i in range(0,len(jokes)*2)]'
10000000 loops, best of 3: 0.0352 usec per loop
jv@Pioneer:~$ python -m timeit -s 'jokes=range(1000000);l=len(jokes);domain=[(0,(l*2)-i-1) for i in range(0,l*2)]'
10000000 loops, best of 3: 0.0343 usec per loop
jv@Pioneer:~$ python -m timeit -s 'jokes=range(1000000);l=len(jokes)*2;domain=[(0,l-i-1) for i in range(0,l)]'
10000000 loops, best of 3: 0.0333 usec per loop
</code></pre>
<p>Observing the marginal difference 2.55% between the first and the second made me think - is the first list comprehension </p>
<pre><code>domain=[(0,(len(jokes)*2)-i-1) for i in range(0,len(jokes)*2)]
</code></pre>
<p>optimized internally by python? or is 2.55% a big enough optimization (given that the len(jokes)=1000000)?</p>
<p>If this is - What are the other implicit/internal optimizations in Python ?</p>
<p>What are the <code>developer's rules of thumb for optimization in Python</code>?</p>
<p><strong>Edit1</strong>: Since most of the answers are "don't optimize, do it later if its slow" and I got some tips and links from <code>Triptych</code> and <code>Ali A</code> for the <strong>do's</strong>.
I will change the question a bit and request for <strong>don'ts</strong>. </p>
<p>Can we have some experiences from people who faced the '<strong>slowness</strong>', what was the problem and how it was corrected? </p>
<p><strong>Edit2</strong>: For those who haven't here is an <a href="http://www.python.org/doc/essays/list2str/">interesting read</a></p>
<p><strong>Edit3:</strong> Incorrect usage of <code>timeit</code> in question please see <strong>dF's</strong> answer for correct usage and hence timings for the three codes.</p>
| 8 | 2008-12-31T18:57:59Z | 403,807 | <p>len for lists is O(1). It doesn't need to scan the whole list to find the length, because the size of the list is stored for lookup. But apparently, it is still slightly faster to extract it into a local variable. </p>
<p>To answer your question though, I would never care about performance variations on the order of 5%, unless I was doing some crazy tight inner loop optimizations in some simulation or something. And in that case, you could speed this up much more by not using range at all.</p>
| 1 | 2008-12-31T19:05:23Z | [
"python",
"optimization"
] |
Optimization in Python - do's, don'ts and rules of thumb | 403,794 | <p>Well I was reading this <a href="http://handyfloss.wordpress.com/2008/02/17/summary-of-my-python-optimization-adventures/">post</a> and then I came across a code which was:</p>
<pre><code>jokes=range(1000000)
domain=[(0,(len(jokes)*2)-i-1) for i in range(0,len(jokes)*2)]
</code></pre>
<p>I thought wouldn't it be better to calculate the value of len(jokes) once outside the list comprehension?</p>
<p>Well I tried it and timed three codes</p>
<pre><code>jv@Pioneer:~$ python -m timeit -s 'jokes=range(1000000);domain=[(0,(len(jokes)*2)-i-1) for i in range(0,len(jokes)*2)]'
10000000 loops, best of 3: 0.0352 usec per loop
jv@Pioneer:~$ python -m timeit -s 'jokes=range(1000000);l=len(jokes);domain=[(0,(l*2)-i-1) for i in range(0,l*2)]'
10000000 loops, best of 3: 0.0343 usec per loop
jv@Pioneer:~$ python -m timeit -s 'jokes=range(1000000);l=len(jokes)*2;domain=[(0,l-i-1) for i in range(0,l)]'
10000000 loops, best of 3: 0.0333 usec per loop
</code></pre>
<p>Observing the marginal difference 2.55% between the first and the second made me think - is the first list comprehension </p>
<pre><code>domain=[(0,(len(jokes)*2)-i-1) for i in range(0,len(jokes)*2)]
</code></pre>
<p>optimized internally by python? or is 2.55% a big enough optimization (given that the len(jokes)=1000000)?</p>
<p>If this is - What are the other implicit/internal optimizations in Python ?</p>
<p>What are the <code>developer's rules of thumb for optimization in Python</code>?</p>
<p><strong>Edit1</strong>: Since most of the answers are "don't optimize, do it later if its slow" and I got some tips and links from <code>Triptych</code> and <code>Ali A</code> for the <strong>do's</strong>.
I will change the question a bit and request for <strong>don'ts</strong>. </p>
<p>Can we have some experiences from people who faced the '<strong>slowness</strong>', what was the problem and how it was corrected? </p>
<p><strong>Edit2</strong>: For those who haven't here is an <a href="http://www.python.org/doc/essays/list2str/">interesting read</a></p>
<p><strong>Edit3:</strong> Incorrect usage of <code>timeit</code> in question please see <strong>dF's</strong> answer for correct usage and hence timings for the three codes.</p>
| 8 | 2008-12-31T18:57:59Z | 403,808 | <p>Read this: <a href="http://wiki.python.org/moin/PythonSpeed/PerformanceTips" rel="nofollow">Python Speed / Performance Tips</a></p>
<p>Also, in your example, the total time is so short that the margin of error will outweigh any actual difference in speed.</p>
| 4 | 2008-12-31T19:05:40Z | [
"python",
"optimization"
] |
Optimization in Python - do's, don'ts and rules of thumb | 403,794 | <p>Well I was reading this <a href="http://handyfloss.wordpress.com/2008/02/17/summary-of-my-python-optimization-adventures/">post</a> and then I came across a code which was:</p>
<pre><code>jokes=range(1000000)
domain=[(0,(len(jokes)*2)-i-1) for i in range(0,len(jokes)*2)]
</code></pre>
<p>I thought wouldn't it be better to calculate the value of len(jokes) once outside the list comprehension?</p>
<p>Well I tried it and timed three codes</p>
<pre><code>jv@Pioneer:~$ python -m timeit -s 'jokes=range(1000000);domain=[(0,(len(jokes)*2)-i-1) for i in range(0,len(jokes)*2)]'
10000000 loops, best of 3: 0.0352 usec per loop
jv@Pioneer:~$ python -m timeit -s 'jokes=range(1000000);l=len(jokes);domain=[(0,(l*2)-i-1) for i in range(0,l*2)]'
10000000 loops, best of 3: 0.0343 usec per loop
jv@Pioneer:~$ python -m timeit -s 'jokes=range(1000000);l=len(jokes)*2;domain=[(0,l-i-1) for i in range(0,l)]'
10000000 loops, best of 3: 0.0333 usec per loop
</code></pre>
<p>Observing the marginal difference 2.55% between the first and the second made me think - is the first list comprehension </p>
<pre><code>domain=[(0,(len(jokes)*2)-i-1) for i in range(0,len(jokes)*2)]
</code></pre>
<p>optimized internally by python? or is 2.55% a big enough optimization (given that the len(jokes)=1000000)?</p>
<p>If this is - What are the other implicit/internal optimizations in Python ?</p>
<p>What are the <code>developer's rules of thumb for optimization in Python</code>?</p>
<p><strong>Edit1</strong>: Since most of the answers are "don't optimize, do it later if its slow" and I got some tips and links from <code>Triptych</code> and <code>Ali A</code> for the <strong>do's</strong>.
I will change the question a bit and request for <strong>don'ts</strong>. </p>
<p>Can we have some experiences from people who faced the '<strong>slowness</strong>', what was the problem and how it was corrected? </p>
<p><strong>Edit2</strong>: For those who haven't here is an <a href="http://www.python.org/doc/essays/list2str/">interesting read</a></p>
<p><strong>Edit3:</strong> Incorrect usage of <code>timeit</code> in question please see <strong>dF's</strong> answer for correct usage and hence timings for the three codes.</p>
| 8 | 2008-12-31T18:57:59Z | 403,821 | <p>You're not using <a href="http://docs.python.org/library/timeit.html"><code>timeit</code></a> correctly: the argument to <code>-s</code> (setup) is a statement to be executed once initially, so you're really just testing an empty statement. You want to do</p>
<pre><code>$ python -m timeit -s "jokes=range(1000000)" "domain=[(0,(len(jokes)*2)-i-1) for i in range(0, len(jokes)*2)]"
10 loops, best of 3: 1.08 sec per loop
$ python -m timeit -s "jokes=range(1000000)" "l=len(jokes);domain=[(0,(l*2)-i-1) for i in range(0, l*2)]"
10 loops, best of 3: 908 msec per loop
$ python -m timeit -s "jokes=range(1000000)" "l=len(jokes*2);domain=[(0,l-i-1) for i in range(0, l)]"
10 loops, best of 3: 813 msec per loop
</code></pre>
<p>While the speedup is still not dramatic, it's more significant (16% and 25% respectively). So since it doesn't make the code any more complicated, this simple optimization is probably worth it.</p>
<p>To address the actual question... the usual rule of thumb in Python is to </p>
<ol>
<li><p>Favor straightforward and readable code over optimization when coding. </p></li>
<li><p>Profile your code (<a href="http://docs.python.org/library/profile.html"><code>profile / cProfile</code> and <code>pstats</code></a> are your friends) to figure out what you need to optimize (usually things like tight loops). </p></li>
<li><p>As a last resort, re-implement these as C extensions, which is made much easier with tools like <a href="http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/">pyrex</a> and <a href="http://www.cython.org/">cython</a>.</p></li>
</ol>
<p>One thing to watch out for: compared to many other languages, function calls are relatively expensive in Python which is why the optimization in your example made a difference even though <code>len</code> is O(1) for lists.</p>
| 12 | 2008-12-31T19:13:19Z | [
"python",
"optimization"
] |
Optimization in Python - do's, don'ts and rules of thumb | 403,794 | <p>Well I was reading this <a href="http://handyfloss.wordpress.com/2008/02/17/summary-of-my-python-optimization-adventures/">post</a> and then I came across a code which was:</p>
<pre><code>jokes=range(1000000)
domain=[(0,(len(jokes)*2)-i-1) for i in range(0,len(jokes)*2)]
</code></pre>
<p>I thought wouldn't it be better to calculate the value of len(jokes) once outside the list comprehension?</p>
<p>Well I tried it and timed three codes</p>
<pre><code>jv@Pioneer:~$ python -m timeit -s 'jokes=range(1000000);domain=[(0,(len(jokes)*2)-i-1) for i in range(0,len(jokes)*2)]'
10000000 loops, best of 3: 0.0352 usec per loop
jv@Pioneer:~$ python -m timeit -s 'jokes=range(1000000);l=len(jokes);domain=[(0,(l*2)-i-1) for i in range(0,l*2)]'
10000000 loops, best of 3: 0.0343 usec per loop
jv@Pioneer:~$ python -m timeit -s 'jokes=range(1000000);l=len(jokes)*2;domain=[(0,l-i-1) for i in range(0,l)]'
10000000 loops, best of 3: 0.0333 usec per loop
</code></pre>
<p>Observing the marginal difference 2.55% between the first and the second made me think - is the first list comprehension </p>
<pre><code>domain=[(0,(len(jokes)*2)-i-1) for i in range(0,len(jokes)*2)]
</code></pre>
<p>optimized internally by python? or is 2.55% a big enough optimization (given that the len(jokes)=1000000)?</p>
<p>If this is - What are the other implicit/internal optimizations in Python ?</p>
<p>What are the <code>developer's rules of thumb for optimization in Python</code>?</p>
<p><strong>Edit1</strong>: Since most of the answers are "don't optimize, do it later if its slow" and I got some tips and links from <code>Triptych</code> and <code>Ali A</code> for the <strong>do's</strong>.
I will change the question a bit and request for <strong>don'ts</strong>. </p>
<p>Can we have some experiences from people who faced the '<strong>slowness</strong>', what was the problem and how it was corrected? </p>
<p><strong>Edit2</strong>: For those who haven't here is an <a href="http://www.python.org/doc/essays/list2str/">interesting read</a></p>
<p><strong>Edit3:</strong> Incorrect usage of <code>timeit</code> in question please see <strong>dF's</strong> answer for correct usage and hence timings for the three codes.</p>
| 8 | 2008-12-31T18:57:59Z | 403,828 | <p>This applies to all programming, not just Python:</p>
<ol>
<li>Profile</li>
<li>Identify bottlenecks</li>
<li>Optimize</li>
</ol>
<p>And I would even add not to bother doing any of that unless you have a slowness issue that is causing you pain.</p>
<p>And perhaps most important is that Unit tests will help you during the actual process.</p>
| 2 | 2008-12-31T19:18:08Z | [
"python",
"optimization"
] |
Optimization in Python - do's, don'ts and rules of thumb | 403,794 | <p>Well I was reading this <a href="http://handyfloss.wordpress.com/2008/02/17/summary-of-my-python-optimization-adventures/">post</a> and then I came across a code which was:</p>
<pre><code>jokes=range(1000000)
domain=[(0,(len(jokes)*2)-i-1) for i in range(0,len(jokes)*2)]
</code></pre>
<p>I thought wouldn't it be better to calculate the value of len(jokes) once outside the list comprehension?</p>
<p>Well I tried it and timed three codes</p>
<pre><code>jv@Pioneer:~$ python -m timeit -s 'jokes=range(1000000);domain=[(0,(len(jokes)*2)-i-1) for i in range(0,len(jokes)*2)]'
10000000 loops, best of 3: 0.0352 usec per loop
jv@Pioneer:~$ python -m timeit -s 'jokes=range(1000000);l=len(jokes);domain=[(0,(l*2)-i-1) for i in range(0,l*2)]'
10000000 loops, best of 3: 0.0343 usec per loop
jv@Pioneer:~$ python -m timeit -s 'jokes=range(1000000);l=len(jokes)*2;domain=[(0,l-i-1) for i in range(0,l)]'
10000000 loops, best of 3: 0.0333 usec per loop
</code></pre>
<p>Observing the marginal difference 2.55% between the first and the second made me think - is the first list comprehension </p>
<pre><code>domain=[(0,(len(jokes)*2)-i-1) for i in range(0,len(jokes)*2)]
</code></pre>
<p>optimized internally by python? or is 2.55% a big enough optimization (given that the len(jokes)=1000000)?</p>
<p>If this is - What are the other implicit/internal optimizations in Python ?</p>
<p>What are the <code>developer's rules of thumb for optimization in Python</code>?</p>
<p><strong>Edit1</strong>: Since most of the answers are "don't optimize, do it later if its slow" and I got some tips and links from <code>Triptych</code> and <code>Ali A</code> for the <strong>do's</strong>.
I will change the question a bit and request for <strong>don'ts</strong>. </p>
<p>Can we have some experiences from people who faced the '<strong>slowness</strong>', what was the problem and how it was corrected? </p>
<p><strong>Edit2</strong>: For those who haven't here is an <a href="http://www.python.org/doc/essays/list2str/">interesting read</a></p>
<p><strong>Edit3:</strong> Incorrect usage of <code>timeit</code> in question please see <strong>dF's</strong> answer for correct usage and hence timings for the three codes.</p>
| 8 | 2008-12-31T18:57:59Z | 403,840 | <p>The most important thing to do is to write idiomatic, clear, and beautiful Python code. Many common tasks are already found in the stdlib, so you don't have to rewrite a slower version. (I'm thinking of string methods and itertools specifically here.) Make liberal use of Python's builtin containers, too. dict for example has had "the snot optimized" out of it, and it's said that Python code using dicts will be faster than plain C!</p>
<p>If that's not already fast enough, there are some hacks you can use, but it's also signal that you probably should be offloading some work to C extension modules.</p>
<p>Regarding list comprehensions: CPython is able to do a few optimizations over regular accumulator loops. Namely the LIST_APPEND opcode makes appending to a list native operation.</p>
| 1 | 2008-12-31T19:22:57Z | [
"python",
"optimization"
] |
Optimization in Python - do's, don'ts and rules of thumb | 403,794 | <p>Well I was reading this <a href="http://handyfloss.wordpress.com/2008/02/17/summary-of-my-python-optimization-adventures/">post</a> and then I came across a code which was:</p>
<pre><code>jokes=range(1000000)
domain=[(0,(len(jokes)*2)-i-1) for i in range(0,len(jokes)*2)]
</code></pre>
<p>I thought wouldn't it be better to calculate the value of len(jokes) once outside the list comprehension?</p>
<p>Well I tried it and timed three codes</p>
<pre><code>jv@Pioneer:~$ python -m timeit -s 'jokes=range(1000000);domain=[(0,(len(jokes)*2)-i-1) for i in range(0,len(jokes)*2)]'
10000000 loops, best of 3: 0.0352 usec per loop
jv@Pioneer:~$ python -m timeit -s 'jokes=range(1000000);l=len(jokes);domain=[(0,(l*2)-i-1) for i in range(0,l*2)]'
10000000 loops, best of 3: 0.0343 usec per loop
jv@Pioneer:~$ python -m timeit -s 'jokes=range(1000000);l=len(jokes)*2;domain=[(0,l-i-1) for i in range(0,l)]'
10000000 loops, best of 3: 0.0333 usec per loop
</code></pre>
<p>Observing the marginal difference 2.55% between the first and the second made me think - is the first list comprehension </p>
<pre><code>domain=[(0,(len(jokes)*2)-i-1) for i in range(0,len(jokes)*2)]
</code></pre>
<p>optimized internally by python? or is 2.55% a big enough optimization (given that the len(jokes)=1000000)?</p>
<p>If this is - What are the other implicit/internal optimizations in Python ?</p>
<p>What are the <code>developer's rules of thumb for optimization in Python</code>?</p>
<p><strong>Edit1</strong>: Since most of the answers are "don't optimize, do it later if its slow" and I got some tips and links from <code>Triptych</code> and <code>Ali A</code> for the <strong>do's</strong>.
I will change the question a bit and request for <strong>don'ts</strong>. </p>
<p>Can we have some experiences from people who faced the '<strong>slowness</strong>', what was the problem and how it was corrected? </p>
<p><strong>Edit2</strong>: For those who haven't here is an <a href="http://www.python.org/doc/essays/list2str/">interesting read</a></p>
<p><strong>Edit3:</strong> Incorrect usage of <code>timeit</code> in question please see <strong>dF's</strong> answer for correct usage and hence timings for the three codes.</p>
| 8 | 2008-12-31T18:57:59Z | 404,012 | <blockquote>
<p>Can we have some experiences from
people who faced the 'slowness', what
was the problem and how it was
corrected?</p>
</blockquote>
<p>The problem was slow data retrieval in a GUI app. I gained a 50x speedup by adding an index to the table, and was widely hailed as a hero and savior.</p>
| 0 | 2008-12-31T20:52:32Z | [
"python",
"optimization"
] |
Optimization in Python - do's, don'ts and rules of thumb | 403,794 | <p>Well I was reading this <a href="http://handyfloss.wordpress.com/2008/02/17/summary-of-my-python-optimization-adventures/">post</a> and then I came across a code which was:</p>
<pre><code>jokes=range(1000000)
domain=[(0,(len(jokes)*2)-i-1) for i in range(0,len(jokes)*2)]
</code></pre>
<p>I thought wouldn't it be better to calculate the value of len(jokes) once outside the list comprehension?</p>
<p>Well I tried it and timed three codes</p>
<pre><code>jv@Pioneer:~$ python -m timeit -s 'jokes=range(1000000);domain=[(0,(len(jokes)*2)-i-1) for i in range(0,len(jokes)*2)]'
10000000 loops, best of 3: 0.0352 usec per loop
jv@Pioneer:~$ python -m timeit -s 'jokes=range(1000000);l=len(jokes);domain=[(0,(l*2)-i-1) for i in range(0,l*2)]'
10000000 loops, best of 3: 0.0343 usec per loop
jv@Pioneer:~$ python -m timeit -s 'jokes=range(1000000);l=len(jokes)*2;domain=[(0,l-i-1) for i in range(0,l)]'
10000000 loops, best of 3: 0.0333 usec per loop
</code></pre>
<p>Observing the marginal difference 2.55% between the first and the second made me think - is the first list comprehension </p>
<pre><code>domain=[(0,(len(jokes)*2)-i-1) for i in range(0,len(jokes)*2)]
</code></pre>
<p>optimized internally by python? or is 2.55% a big enough optimization (given that the len(jokes)=1000000)?</p>
<p>If this is - What are the other implicit/internal optimizations in Python ?</p>
<p>What are the <code>developer's rules of thumb for optimization in Python</code>?</p>
<p><strong>Edit1</strong>: Since most of the answers are "don't optimize, do it later if its slow" and I got some tips and links from <code>Triptych</code> and <code>Ali A</code> for the <strong>do's</strong>.
I will change the question a bit and request for <strong>don'ts</strong>. </p>
<p>Can we have some experiences from people who faced the '<strong>slowness</strong>', what was the problem and how it was corrected? </p>
<p><strong>Edit2</strong>: For those who haven't here is an <a href="http://www.python.org/doc/essays/list2str/">interesting read</a></p>
<p><strong>Edit3:</strong> Incorrect usage of <code>timeit</code> in question please see <strong>dF's</strong> answer for correct usage and hence timings for the three codes.</p>
| 8 | 2008-12-31T18:57:59Z | 2,792,015 | <p>I have a program that parses log files and generates a data warehouse. A typical run involves around 200M log file lines, and runs for the better part of a day. Well worth optimizing!</p>
<p>Since it's a parser, and parsing some rather variable and idiosyncratic and untrustworthy text at that, there are around 100 regular expressions, dutifully re.compiled() in advance, and applied to each of the 200M log file lines. I was pretty sure they were my bottleneck, and had been pondering how to improve that situation. Had some ideas: on the one hand, make fewer, fancier REs; on the other, more and simpler; stuff like that.</p>
<p>I profiled with CProfile, and looked at the result in "runsnake".</p>
<p>RE processing was only about 10% of code execution time. That's not it!</p>
<p>In fact, a large square blob in the runsnake display instantly told me that about 60% of my time was spent in one of those infamous "one line changes" I'd added one day, eliminating non-printing characters (which appear occasionally, but always represent something so bogus I really don't care about it). These were confusing my parse and throwing exceptions, which I <em>did</em> care about because it halted my day of log file analysis.</p>
<blockquote>
<p>line = ''.join([c for c in line if curses.ascii.isprint(c) ])</p>
</blockquote>
<p>There you go: that line touches every <strong>byte</strong> of every one of those 200M lines (and the lines average a couple hundred bytes long). No wonder it's 60% of my execution time!</p>
<p>There are better ways to handle this, I now know, such as str.translate(). But such lines are rare, and I don't care about them anyway, and they end up throwing an exception: now I just catch the exception at the right spot and skip the line. Voila! the program's around 3X faster, instantly!</p>
<p>So the profiling</p>
<ol>
<li>highlighted, in around one second, where the problem actually was</li>
<li>drew my attention away from a mistaken assumption about where the problem was (which might be the even greater pay-off)</li>
</ol>
| 1 | 2010-05-07T22:18:16Z | [
"python",
"optimization"
] |
Calling from a parent file in python | 403,822 | <p>I have a file called main.py and a file called classes.py</p>
<p>main.py contains the application and what's happening while class.py contains some classes.</p>
<p>main.py has the following code</p>
<p><strong>main.py</strong></p>
<pre><code>import classes
def addItem(text):
print text
myClass = classes.ExampleClass()
</code></pre>
<p>And then we have classes.py</p>
<p><strong>classes.py</strong></p>
<pre><code>class ExampleClass (object):
def __init__(self):
addItem('bob')
</code></pre>
<p>Surprisingly enough that's not the actual code I am using because I've stripped out anything that'd get in the way of you seeing what I want to do. I want to be able to call a method that's defined in main.py from a class within classes.py. How do I do this?</p>
<p>Thanks in advance</p>
| 3 | 2008-12-31T19:14:59Z | 403,832 | <p>I couldn't answer this any better than <a href="http://mail.python.org/pipermail/python-list/2000-December/059926.html" rel="nofollow">this post by Alex Martelli</a>. Basically any way you try to do this will lead to trouble and you are much better off refactoring the code to avoid mutual dependencies between two modules... </p>
<p>If you have two modules A and B which depend on each other, the easiest way is to isolate a part of the code that they both depend on into a third module C, and have both of them import C.</p>
| 9 | 2008-12-31T19:20:03Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.