title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Proper way to handle multiple forms on one page in Django | 1,395,807 | <p>I have a template page expecting two forms. If I just use one form, things are fine as in this typical example:</p>
<pre><code>if request.method == 'POST':
form = AuthorForm(request.POST,)
if form.is_valid():
form.save()
# do something.
else:
form = AuthorForm()
</code></pre>
<p>If I want to work with multiple forms however, how do I let the view know that I'm submitting only one of the forms and not the other (i.e. it's still request.POST but I only want to process the form for which the submit happened)?</p>
<hr>
<p><strong>This is the solution</strong> based on the answer where <em>expectedphrase</em> and <em>bannedphrase</em> are the names of the submit buttons for the different forms and <em>expectedphraseform</em> and <em>bannedphraseform</em> are the forms.</p>
<pre><code>if request.method == 'POST':
if 'bannedphrase' in request.POST:
bannedphraseform = BannedPhraseForm(request.POST, prefix='banned')
if bannedphraseform.is_valid():
bannedphraseform.save()
expectedphraseform = ExpectedPhraseForm(prefix='expected')
elif 'expectedphrase' in request.POST:
expectedphraseform = ExpectedPhraseForm(request.POST, prefix='expected')
if expectedphraseform.is_valid():
expectedphraseform.save()
bannedphraseform = BannedPhraseForm(prefix='banned')
else:
bannedphraseform = BannedPhraseForm(prefix='banned')
expectedphraseform = ExpectedPhraseForm(prefix='expected')
</code></pre>
| 123 | 2009-09-08T19:17:09Z | 1,395,866 | <p>You have a few options:</p>
<ol>
<li><p>Put different URLs in the action for the two forms. Then you'll have two different view functions to deal with the two different forms.</p></li>
<li><p>Read the submit button values from the POST data. You can tell which submit button was clicked: <a href="http://stackoverflow.com/questions/866272/how-can-i-build-multiple-submit-buttons-django-form">How can I build multiple submit buttons django form?</a></p></li>
</ol>
| 81 | 2009-09-08T19:29:10Z | [
"python",
"django",
"forms"
] |
Proper way to handle multiple forms on one page in Django | 1,395,807 | <p>I have a template page expecting two forms. If I just use one form, things are fine as in this typical example:</p>
<pre><code>if request.method == 'POST':
form = AuthorForm(request.POST,)
if form.is_valid():
form.save()
# do something.
else:
form = AuthorForm()
</code></pre>
<p>If I want to work with multiple forms however, how do I let the view know that I'm submitting only one of the forms and not the other (i.e. it's still request.POST but I only want to process the form for which the submit happened)?</p>
<hr>
<p><strong>This is the solution</strong> based on the answer where <em>expectedphrase</em> and <em>bannedphrase</em> are the names of the submit buttons for the different forms and <em>expectedphraseform</em> and <em>bannedphraseform</em> are the forms.</p>
<pre><code>if request.method == 'POST':
if 'bannedphrase' in request.POST:
bannedphraseform = BannedPhraseForm(request.POST, prefix='banned')
if bannedphraseform.is_valid():
bannedphraseform.save()
expectedphraseform = ExpectedPhraseForm(prefix='expected')
elif 'expectedphrase' in request.POST:
expectedphraseform = ExpectedPhraseForm(request.POST, prefix='expected')
if expectedphraseform.is_valid():
expectedphraseform.save()
bannedphraseform = BannedPhraseForm(prefix='banned')
else:
bannedphraseform = BannedPhraseForm(prefix='banned')
expectedphraseform = ExpectedPhraseForm(prefix='expected')
</code></pre>
| 123 | 2009-09-08T19:17:09Z | 1,395,970 | <p>A method for future reference is something like this. bannedphraseform is the first form and expectedphraseform is the second. If the first one is hit, the second one is skipped (which is a reasonable assumption in this case):</p>
<pre><code>if request.method == 'POST':
bannedphraseform = BannedPhraseForm(request.POST, prefix='banned')
if bannedphraseform.is_valid():
bannedphraseform.save()
else:
bannedphraseform = BannedPhraseForm(prefix='banned')
if request.method == 'POST' and not bannedphraseform.is_valid():
expectedphraseform = ExpectedPhraseForm(request.POST, prefix='expected')
bannedphraseform = BannedPhraseForm(prefix='banned')
if expectedphraseform.is_valid():
expectedphraseform.save()
else:
expectedphraseform = ExpectedPhraseForm(prefix='expected')
</code></pre>
| 30 | 2009-09-08T19:50:05Z | [
"python",
"django",
"forms"
] |
Proper way to handle multiple forms on one page in Django | 1,395,807 | <p>I have a template page expecting two forms. If I just use one form, things are fine as in this typical example:</p>
<pre><code>if request.method == 'POST':
form = AuthorForm(request.POST,)
if form.is_valid():
form.save()
# do something.
else:
form = AuthorForm()
</code></pre>
<p>If I want to work with multiple forms however, how do I let the view know that I'm submitting only one of the forms and not the other (i.e. it's still request.POST but I only want to process the form for which the submit happened)?</p>
<hr>
<p><strong>This is the solution</strong> based on the answer where <em>expectedphrase</em> and <em>bannedphrase</em> are the names of the submit buttons for the different forms and <em>expectedphraseform</em> and <em>bannedphraseform</em> are the forms.</p>
<pre><code>if request.method == 'POST':
if 'bannedphrase' in request.POST:
bannedphraseform = BannedPhraseForm(request.POST, prefix='banned')
if bannedphraseform.is_valid():
bannedphraseform.save()
expectedphraseform = ExpectedPhraseForm(prefix='expected')
elif 'expectedphrase' in request.POST:
expectedphraseform = ExpectedPhraseForm(request.POST, prefix='expected')
if expectedphraseform.is_valid():
expectedphraseform.save()
bannedphraseform = BannedPhraseForm(prefix='banned')
else:
bannedphraseform = BannedPhraseForm(prefix='banned')
expectedphraseform = ExpectedPhraseForm(prefix='expected')
</code></pre>
| 123 | 2009-09-08T19:17:09Z | 17,303,425 | <p>Django's class based views provide a generic FormView but for all intents and purposes it is designed to only handle one form. </p>
<p>One way to handle multiple forms with same target action url using Django's generic views is to extend the 'TemplateView' as shown below; I use this approach often enough that I have made it into an Eclipse IDE template.</p>
<pre><code>class NegotiationGroupMultifacetedView(TemplateView):
### TemplateResponseMixin
template_name = 'offers/offer_detail.html'
### ContextMixin
def get_context_data(self, **kwargs):
""" Adds extra content to our template """
context = super(NegotiationGroupDetailView, self).get_context_data(**kwargs)
...
context['negotiation_bid_form'] = NegotiationBidForm(
prefix='NegotiationBidForm',
...
# Multiple 'submit' button paths should be handled in form's .save()/clean()
data = self.request.POST if bool(set(['NegotiationBidForm-submit-counter-bid',
'NegotiationBidForm-submit-approve-bid',
'NegotiationBidForm-submit-decline-further-bids']).intersection(
self.request.POST)) else None,
)
context['offer_attachment_form'] = NegotiationAttachmentForm(
prefix='NegotiationAttachment',
...
data = self.request.POST if 'NegotiationAttachment-submit' in self.request.POST else None,
files = self.request.FILES if 'NegotiationAttachment-submit' in self.request.POST else None
)
context['offer_contact_form'] = NegotiationContactForm()
return context
### NegotiationGroupDetailView
def post(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs)
if context['negotiation_bid_form'].is_valid():
instance = context['negotiation_bid_form'].save()
messages.success(request, 'Your offer bid #{0} has been submitted.'.format(instance.pk))
elif context['offer_attachment_form'].is_valid():
instance = context['offer_attachment_form'].save()
messages.success(request, 'Your offer attachment #{0} has been submitted.'.format(instance.pk))
# advise of any errors
else
messages.error('Error(s) encountered during form processing, please review below and re-submit')
return self.render_to_response(context)
</code></pre>
<p>The html template is to the following effect:</p>
<pre><code>...
<form id='offer_negotiation_form' class="content-form" action='./' enctype="multipart/form-data" method="post" accept-charset="utf-8">
{% csrf_token %}
{{ negotiation_bid_form.as_p }}
...
<input type="submit" name="{{ negotiation_bid_form.prefix }}-submit-counter-bid"
title="Submit a counter bid"
value="Counter Bid" />
</form>
...
<form id='offer-attachment-form' class="content-form" action='./' enctype="multipart/form-data" method="post" accept-charset="utf-8">
{% csrf_token %}
{{ offer_attachment_form.as_p }}
<input name="{{ offer_attachment_form.prefix }}-submit" type="submit" value="Submit" />
</form>
...
</code></pre>
| 9 | 2013-06-25T17:09:50Z | [
"python",
"django",
"forms"
] |
Proper way to handle multiple forms on one page in Django | 1,395,807 | <p>I have a template page expecting two forms. If I just use one form, things are fine as in this typical example:</p>
<pre><code>if request.method == 'POST':
form = AuthorForm(request.POST,)
if form.is_valid():
form.save()
# do something.
else:
form = AuthorForm()
</code></pre>
<p>If I want to work with multiple forms however, how do I let the view know that I'm submitting only one of the forms and not the other (i.e. it's still request.POST but I only want to process the form for which the submit happened)?</p>
<hr>
<p><strong>This is the solution</strong> based on the answer where <em>expectedphrase</em> and <em>bannedphrase</em> are the names of the submit buttons for the different forms and <em>expectedphraseform</em> and <em>bannedphraseform</em> are the forms.</p>
<pre><code>if request.method == 'POST':
if 'bannedphrase' in request.POST:
bannedphraseform = BannedPhraseForm(request.POST, prefix='banned')
if bannedphraseform.is_valid():
bannedphraseform.save()
expectedphraseform = ExpectedPhraseForm(prefix='expected')
elif 'expectedphrase' in request.POST:
expectedphraseform = ExpectedPhraseForm(request.POST, prefix='expected')
if expectedphraseform.is_valid():
expectedphraseform.save()
bannedphraseform = BannedPhraseForm(prefix='banned')
else:
bannedphraseform = BannedPhraseForm(prefix='banned')
expectedphraseform = ExpectedPhraseForm(prefix='expected')
</code></pre>
| 123 | 2009-09-08T19:17:09Z | 26,551,263 | <p>This is a bit late, but this is the best solution I found. You make a look-up dictionary for the form name and its class, you also have to add an attribute to identify the form, and in your views you have to add it as a hidden field, with the <code>form.formlabel</code>.</p>
<pre><code># form holder
form_holder = {
'majeur': {
'class': FormClass1,
},
'majsoft': {
'class': FormClass2,
},
'tiers1': {
'class': FormClass3,
},
'tiers2': {
'class': FormClass4,
},
'tiers3': {
'class': FormClass5,
},
'tiers4': {
'class': FormClass6,
},
}
for key in form_holder.keys():
# If the key is the same as the formlabel, we should use the posted data
if request.POST.get('formlabel', None) == key:
# Get the form and initate it with the sent data
form = form_holder.get(key).get('class')(
data=request.POST
)
# Validate the form
if form.is_valid():
# Correct data entries
messages.info(request, _(u"Configuration validée."))
if form.save():
# Save succeeded
messages.success(
request,
_(u"Données enregistrées avec succès.")
)
else:
# Save failed
messages.warning(
request,
_(u"Un problème est survenu pendant l'enregistrement "
u"des données, merci de réessayer plus tard.")
)
else:
# Form is not valid, show feedback to the user
messages.error(
request,
_(u"Merci de corriger les erreurs suivantes.")
)
else:
# Just initiate the form without data
form = form_holder.get(key).get('class')(key)()
# Add the attribute for the name
setattr(form, 'formlabel', key)
# Append it to the tempalte variable that will hold all the forms
forms.append(form)
</code></pre>
<p>I hope this will help in the future.</p>
| 1 | 2014-10-24T15:32:55Z | [
"python",
"django",
"forms"
] |
Proper way to handle multiple forms on one page in Django | 1,395,807 | <p>I have a template page expecting two forms. If I just use one form, things are fine as in this typical example:</p>
<pre><code>if request.method == 'POST':
form = AuthorForm(request.POST,)
if form.is_valid():
form.save()
# do something.
else:
form = AuthorForm()
</code></pre>
<p>If I want to work with multiple forms however, how do I let the view know that I'm submitting only one of the forms and not the other (i.e. it's still request.POST but I only want to process the form for which the submit happened)?</p>
<hr>
<p><strong>This is the solution</strong> based on the answer where <em>expectedphrase</em> and <em>bannedphrase</em> are the names of the submit buttons for the different forms and <em>expectedphraseform</em> and <em>bannedphraseform</em> are the forms.</p>
<pre><code>if request.method == 'POST':
if 'bannedphrase' in request.POST:
bannedphraseform = BannedPhraseForm(request.POST, prefix='banned')
if bannedphraseform.is_valid():
bannedphraseform.save()
expectedphraseform = ExpectedPhraseForm(prefix='expected')
elif 'expectedphrase' in request.POST:
expectedphraseform = ExpectedPhraseForm(request.POST, prefix='expected')
if expectedphraseform.is_valid():
expectedphraseform.save()
bannedphraseform = BannedPhraseForm(prefix='banned')
else:
bannedphraseform = BannedPhraseForm(prefix='banned')
expectedphraseform = ExpectedPhraseForm(prefix='expected')
</code></pre>
| 123 | 2009-09-08T19:17:09Z | 27,836,159 | <p>Here is simple way to handle the above.</p>
<p>In Html Template we put Post</p>
<pre><code><form action="/useradd/addnewroute/" method="post" id="login-form">{% csrf_token %}
<!-- add details of form here-->
<form>
<form action="/useradd/addarea/" method="post" id="login-form">{% csrf_token %}
<!-- add details of form here-->
<form>
</code></pre>
<p>In View </p>
<pre><code> def addnewroute(request):
if request.method == "POST":
# do something
def addarea(request):
if request.method == "POST":
# do something
</code></pre>
<p>In URL
Give needed info like </p>
<pre><code>urlpatterns = patterns('',
url(r'^addnewroute/$', views.addnewroute, name='addnewroute'),
url(r'^addarea/', include('usermodules.urls')),
</code></pre>
| 1 | 2015-01-08T08:54:06Z | [
"python",
"django",
"forms"
] |
Proper way to handle multiple forms on one page in Django | 1,395,807 | <p>I have a template page expecting two forms. If I just use one form, things are fine as in this typical example:</p>
<pre><code>if request.method == 'POST':
form = AuthorForm(request.POST,)
if form.is_valid():
form.save()
# do something.
else:
form = AuthorForm()
</code></pre>
<p>If I want to work with multiple forms however, how do I let the view know that I'm submitting only one of the forms and not the other (i.e. it's still request.POST but I only want to process the form for which the submit happened)?</p>
<hr>
<p><strong>This is the solution</strong> based on the answer where <em>expectedphrase</em> and <em>bannedphrase</em> are the names of the submit buttons for the different forms and <em>expectedphraseform</em> and <em>bannedphraseform</em> are the forms.</p>
<pre><code>if request.method == 'POST':
if 'bannedphrase' in request.POST:
bannedphraseform = BannedPhraseForm(request.POST, prefix='banned')
if bannedphraseform.is_valid():
bannedphraseform.save()
expectedphraseform = ExpectedPhraseForm(prefix='expected')
elif 'expectedphrase' in request.POST:
expectedphraseform = ExpectedPhraseForm(request.POST, prefix='expected')
if expectedphraseform.is_valid():
expectedphraseform.save()
bannedphraseform = BannedPhraseForm(prefix='banned')
else:
bannedphraseform = BannedPhraseForm(prefix='banned')
expectedphraseform = ExpectedPhraseForm(prefix='expected')
</code></pre>
| 123 | 2009-09-08T19:17:09Z | 33,028,994 | <p>I needed multiple forms that are independently validated on the same page. The key concepts I was missing were 1) using the form prefix for the submit button name and 2) an unbounded form does not trigger validation. If it helps anyone else, here is my simplified example of two forms AForm and BForm using TemplateView based on the answers by @adam-nelson and @daniel-sokolowski and comment by @zeraien (<a href="http://stackoverflow.com/a/17303480/2680349">http://stackoverflow.com/a/17303480/2680349</a>):</p>
<pre><code># views.py
def _get_form(request, formcls, prefix):
data = request.POST if prefix in request.POST else None
return formcls(data, prefix=prefix)
class MyView(TemplateView):
template_name = 'mytemplate.html'
def get(self, request, *args, **kwargs):
return self.render_to_response({'aform': AForm(prefix='aform_pre'), 'bform': BForm(prefix='bform_pre')})
def post(self, request, *args, **kwargs):
aform = _get_form(request, AForm, 'aform_pre')
bform = _get_form(request, BForm, 'bform_pre')
if aform.is_bound and aform.is_valid():
# Process aform and render response
elif bform.is_bound and bform.is_valid():
# Process bform and render response
return self.render_to_response({'aform': aform, 'bform': bform})
# mytemplate.html
<form action="" method="post">
{% csrf_token %}
{{ aform.as_p }}
<input type="submit" name="{{aform.prefix}}" value="Submit" />
{{ bform.as_p }}
<input type="submit" name="{{bform.prefix}}" value="Submit" />
</form>
</code></pre>
| 2 | 2015-10-09T02:36:25Z | [
"python",
"django",
"forms"
] |
How to drop into REPL (Read, Eval, Print, Loop) from Python code | 1,395,913 | <p>Is there a way to programmatically force a Python script to drop into a REPL at an arbitrary point in its execution, even if the script was launched from the command line?</p>
<p>I'm writing a quick and dirty plotting program, which I want to read data from stdin or a file, plot it, and then drop into the REPL to allow for the plot to be customized.</p>
| 66 | 2009-09-08T19:40:33Z | 1,395,925 | <p>You can launch the debugger:</p>
<pre><code>import pdb;pdb.set_trace()
</code></pre>
<p>Not sure what you want the REPL for, but the debugger is very similar.</p>
| 14 | 2009-09-08T19:42:26Z | [
"python",
"interactive"
] |
How to drop into REPL (Read, Eval, Print, Loop) from Python code | 1,395,913 | <p>Is there a way to programmatically force a Python script to drop into a REPL at an arbitrary point in its execution, even if the script was launched from the command line?</p>
<p>I'm writing a quick and dirty plotting program, which I want to read data from stdin or a file, plot it, and then drop into the REPL to allow for the plot to be customized.</p>
| 66 | 2009-09-08T19:40:33Z | 1,396,190 | <p>Here's how you should do it (IPython > v0.11):</p>
<pre><code>import IPython
IPython.embed()
</code></pre>
<p>For IPython <= v0.11:</p>
<pre><code>from IPython.Shell import IPShellEmbed
ipshell = IPShellEmbed()
ipshell() # this call anywhere in your program will start IPython
</code></pre>
<p>You should use IPython, the Cadillac of Python REPLs. See <a href="http://ipython.org/ipython-doc/stable/interactive/reference.html#embedding-ipython">http://ipython.org/ipython-doc/stable/interactive/reference.html#embedding-ipython</a></p>
<p>From the documentation:</p>
<blockquote>
<p>It can also be useful in scientific
computing situations where it is
common to need to do some automatic,
computationally intensive part and
then stop to look at data, plots, etc.
Opening an IPython instance will give
you full access to your data and
functions, and you can resume program
execution once you are done with the
interactive part (perhaps to stop
again later, as many times as needed).</p>
</blockquote>
| 27 | 2009-09-08T20:31:58Z | [
"python",
"interactive"
] |
How to drop into REPL (Read, Eval, Print, Loop) from Python code | 1,395,913 | <p>Is there a way to programmatically force a Python script to drop into a REPL at an arbitrary point in its execution, even if the script was launched from the command line?</p>
<p>I'm writing a quick and dirty plotting program, which I want to read data from stdin or a file, plot it, and then drop into the REPL to allow for the plot to be customized.</p>
| 66 | 2009-09-08T19:40:33Z | 1,396,199 | <p>You could try using the interactive option for python:</p>
<pre><code>python -i program.py
</code></pre>
<p>This will execute the code in program.py, then go to the REPL. Anything you define or import in the top level of program.py will be available.</p>
| 50 | 2009-09-08T20:34:12Z | [
"python",
"interactive"
] |
How to drop into REPL (Read, Eval, Print, Loop) from Python code | 1,395,913 | <p>Is there a way to programmatically force a Python script to drop into a REPL at an arbitrary point in its execution, even if the script was launched from the command line?</p>
<p>I'm writing a quick and dirty plotting program, which I want to read data from stdin or a file, plot it, and then drop into the REPL to allow for the plot to be customized.</p>
| 66 | 2009-09-08T19:40:33Z | 1,396,386 | <p>I frequently use this:</p>
<pre><code>def interact():
import code
code.InteractiveConsole(locals=globals()).interact()
</code></pre>
| 87 | 2009-09-08T21:18:44Z | [
"python",
"interactive"
] |
How to drop into REPL (Read, Eval, Print, Loop) from Python code | 1,395,913 | <p>Is there a way to programmatically force a Python script to drop into a REPL at an arbitrary point in its execution, even if the script was launched from the command line?</p>
<p>I'm writing a quick and dirty plotting program, which I want to read data from stdin or a file, plot it, and then drop into the REPL to allow for the plot to be customized.</p>
| 66 | 2009-09-08T19:40:33Z | 1,396,504 | <p>To get use of iPython and functionality of debugger you should use <a href="http://pypi.python.org/pypi/ipdb/">ipdb</a>, </p>
<p>You can use it in the same way as pdb, with the addition of :</p>
<pre><code>import ipdb
ipdb.set_trace()
</code></pre>
| 13 | 2009-09-08T21:48:45Z | [
"python",
"interactive"
] |
How to drop into REPL (Read, Eval, Print, Loop) from Python code | 1,395,913 | <p>Is there a way to programmatically force a Python script to drop into a REPL at an arbitrary point in its execution, even if the script was launched from the command line?</p>
<p>I'm writing a quick and dirty plotting program, which I want to read data from stdin or a file, plot it, and then drop into the REPL to allow for the plot to be customized.</p>
| 66 | 2009-09-08T19:40:33Z | 22,339,942 | <p>I just did this in one of my own scripts (it runs inside an automation framework that is a huge PITA to instrument):</p>
<pre><code>x = 0 # exit loop counter
while x == 0:
user_input = raw_input("Please enter a command, or press q to quit: ")
if user_input[0] == "q":
x = 1
else:
try:
print eval(user_input)
except:
print "I can't do that, Dave."
continue
</code></pre>
<p>Just place this wherever you want a breakpoint, and you can check the state using the same syntax as the python interpreter (although it doesn't seem to let you do module imports).
It's not very elegant, but it doesn't require any other setup. </p>
| 0 | 2014-03-12T01:01:18Z | [
"python",
"interactive"
] |
Unexpected results feeding Django File upload object to Python CSV module | 1,396,126 | <p>I have no problems getting the file to upload and if I save it to disk, all formatting is intact.</p>
<p>I wrote a function to read in the the file within Django using:</p>
<pre><code>data = csv.reader(f.read())
</code></pre>
<p>where f is the Django file object that I get from 'form.cleaned_data['file']' and yes the file is already bound to the form.</p>
<p>When I try to read the file using</p>
<pre><code>for row in data:
logging.debug(row)
</code></pre>
<p>I get an unexpected result in that it appears to be producing small packs of the data almost as if its reading some buffer. for example, for my float fields I get this when I log each row:</p>
<p>['0'] ['.'] ['0'] ['5']['', ''] ['0'] ['.'] ['2'] etc etc... where each item between the square bracket is actually from one row (ie. a newline)</p>
<p>csv.reader requires the object it takes to support the iterator protocol which I believe the Django File object <a href="http://docs.djangoproject.com/en/dev/ref/files/file/" rel="nofollow">does</a> </p>
<p>So what am I doing wrong?</p>
| 0 | 2009-09-08T20:19:40Z | 1,396,259 | <p>What happens if you try reading in the whole file, logging its first few bytes, and then passing it into the parser? Perhaps the file isn't being uploaded as you expect? An http form-encoding issue, perhaps?</p>
| 0 | 2009-09-08T20:48:38Z | [
"python",
"django",
"csv",
"iterator"
] |
Unexpected results feeding Django File upload object to Python CSV module | 1,396,126 | <p>I have no problems getting the file to upload and if I save it to disk, all formatting is intact.</p>
<p>I wrote a function to read in the the file within Django using:</p>
<pre><code>data = csv.reader(f.read())
</code></pre>
<p>where f is the Django file object that I get from 'form.cleaned_data['file']' and yes the file is already bound to the form.</p>
<p>When I try to read the file using</p>
<pre><code>for row in data:
logging.debug(row)
</code></pre>
<p>I get an unexpected result in that it appears to be producing small packs of the data almost as if its reading some buffer. for example, for my float fields I get this when I log each row:</p>
<p>['0'] ['.'] ['0'] ['5']['', ''] ['0'] ['.'] ['2'] etc etc... where each item between the square bracket is actually from one row (ie. a newline)</p>
<p>csv.reader requires the object it takes to support the iterator protocol which I believe the Django File object <a href="http://docs.djangoproject.com/en/dev/ref/files/file/" rel="nofollow">does</a> </p>
<p>So what am I doing wrong?</p>
| 0 | 2009-09-08T20:19:40Z | 1,396,735 | <p>You're actually passing the wrong iterable to <code>csv.reader()</code>. Try changing that line to:</p>
<pre><code>data = csv.reader(f)
</code></pre>
<p>What you're doing is passing the whole contents of the file to the <code>csv.reader()</code> function, which will cause it to iterate over every individual character, treating each of them as a separate line. If you pass the actual file object to the function, it will iterate over the lines in that file, as you expect.</p>
| 1 | 2009-09-08T22:44:59Z | [
"python",
"django",
"csv",
"iterator"
] |
Efficient Python Data Storage (Abstract Data Types?) | 1,396,241 | <p>Pardon the ambiguity in the title- I wasn't quite sure how to phrase my question.</p>
<p>Given a string: </p>
<pre><code>blah = "There are three cats in the hat"
</code></pre>
<p>and the (I'm not quite sure which data structure to use for this) "userInfo":</p>
<pre><code>cats -> ("tim", "1 infinite loop")
three -> ("sally", "123 fake st")
three -> ("tim", "1 infinite loop")
three cats -> ("john", "123 fake st")
four cats -> ("albert", "345 real road")
dogs -> ("tim", "1 infinite loop")
cats hat -> ("janet", NULL)
</code></pre>
<p>The proper output should be:</p>
<pre><code>tim (since 'cats' exists)
sally (since 'three' exists)
tim (since 'three' exists)
john (since both 'three' and 'cats' exist)
janet (since both 'cats' and 'hat' exist somewhere in the string blah)
</code></pre>
<p>I want an efficient way of storing this data. There is a possibility for multiple 'three' strings that can be matched (i.e., 150 people will have that string.) Should I just have a list with all this data and duplicate the "keys"?</p>
| -1 | 2009-09-08T20:42:32Z | 1,396,268 | <p>I'm not sure what exactly you're trying to do, but maybe you're looking for something like this:</p>
<pre><code>userinfo = {
"tim": "1 infinite loop",
"sally": "123 fake st",
"john": "123 fake st",
"albert": "345 real road",
"janet": None
}
conditions = {
"cats": ["tim"],
"three": ["sally", "tim"],
"three cats": ["john"],
"four cats": ["albert"],
"dogs": ["tim"],
"cats hat": ["janet"]
}
for c in conditions:
if all_words_are_in_the_sentence(c):
for p in conditions[c]:
print p, "because of", c
print "additional info:", userinfo[p]
</code></pre>
| 0 | 2009-09-08T20:50:47Z | [
"python",
"data-structures"
] |
Efficient Python Data Storage (Abstract Data Types?) | 1,396,241 | <p>Pardon the ambiguity in the title- I wasn't quite sure how to phrase my question.</p>
<p>Given a string: </p>
<pre><code>blah = "There are three cats in the hat"
</code></pre>
<p>and the (I'm not quite sure which data structure to use for this) "userInfo":</p>
<pre><code>cats -> ("tim", "1 infinite loop")
three -> ("sally", "123 fake st")
three -> ("tim", "1 infinite loop")
three cats -> ("john", "123 fake st")
four cats -> ("albert", "345 real road")
dogs -> ("tim", "1 infinite loop")
cats hat -> ("janet", NULL)
</code></pre>
<p>The proper output should be:</p>
<pre><code>tim (since 'cats' exists)
sally (since 'three' exists)
tim (since 'three' exists)
john (since both 'three' and 'cats' exist)
janet (since both 'cats' and 'hat' exist somewhere in the string blah)
</code></pre>
<p>I want an efficient way of storing this data. There is a possibility for multiple 'three' strings that can be matched (i.e., 150 people will have that string.) Should I just have a list with all this data and duplicate the "keys"?</p>
| -1 | 2009-09-08T20:42:32Z | 1,396,276 | <p>I haven't got the slightest clue of what you actually are trying to do, but if you have a lot of data, and you need to store it, and you need to search in it, some sort of database with indexing capabilities seems to be the way to go.</p>
<p>ZODB, CouchBD or SQL is a matter of taste. I seriously doubt you need to care about efficiency in disk space as much as in speed for searching and lookups anyway.</p>
| 1 | 2009-09-08T20:52:18Z | [
"python",
"data-structures"
] |
Efficient Python Data Storage (Abstract Data Types?) | 1,396,241 | <p>Pardon the ambiguity in the title- I wasn't quite sure how to phrase my question.</p>
<p>Given a string: </p>
<pre><code>blah = "There are three cats in the hat"
</code></pre>
<p>and the (I'm not quite sure which data structure to use for this) "userInfo":</p>
<pre><code>cats -> ("tim", "1 infinite loop")
three -> ("sally", "123 fake st")
three -> ("tim", "1 infinite loop")
three cats -> ("john", "123 fake st")
four cats -> ("albert", "345 real road")
dogs -> ("tim", "1 infinite loop")
cats hat -> ("janet", NULL)
</code></pre>
<p>The proper output should be:</p>
<pre><code>tim (since 'cats' exists)
sally (since 'three' exists)
tim (since 'three' exists)
john (since both 'three' and 'cats' exist)
janet (since both 'cats' and 'hat' exist somewhere in the string blah)
</code></pre>
<p>I want an efficient way of storing this data. There is a possibility for multiple 'three' strings that can be matched (i.e., 150 people will have that string.) Should I just have a list with all this data and duplicate the "keys"?</p>
| -1 | 2009-09-08T20:42:32Z | 1,396,305 | <p>Something like this?</p>
<pre><code>class Content( object ):
def __init__( self, content, maps_to ):
self.content= content.split()
self.maps_to = maps_to
def matches( self, words ):
return all( c in words for c in self.content )
def __str__( self ):
return "%s -> %r" % ( " ".join(self.content), self.maps_to )
rules = [
Content('cats',("tim", "1 infinite loop")),
Content('three',("sally", "123 fake st")),
Content('three',("tim", "1 infinite loop")),
Content('three cats',("john", "123 fake st")),
Content('four cats',("albert", "345 real road")),
Content('dogs',("tim", "1 infinite loop")),
Content('cats hat', ("janet", None)),
]
blah = "There are three cats in the hat"
for r in rules:
if r.matches(blah.split()):
print r
</code></pre>
<p>Output</p>
<pre><code>cats -> ('tim', '1 infinite loop')
three -> ('sally', '123 fake st')
three -> ('tim', '1 infinite loop')
three cats -> ('john', '123 fake st')
cats hat -> ('janet', None)
</code></pre>
| 6 | 2009-09-08T20:58:44Z | [
"python",
"data-structures"
] |
How to using widget PlainTextEdit or TextEdit for output and input text? | 1,396,339 | <p>How to using widget PlainTextEdit or TextEdit for output and input text? I'm interested PyQt4.</p>
| -1 | 2009-09-08T21:08:19Z | 1,396,360 | <p><a href="http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qplaintextedit.html" rel="nofollow">PlainTextEdit</a></p>
<p><a href="http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qtextedit.html" rel="nofollow">TextEdit</a></p>
| 3 | 2009-09-08T21:13:14Z | [
"python",
"user-interface",
"qt"
] |
How to using widget PlainTextEdit or TextEdit for output and input text? | 1,396,339 | <p>How to using widget PlainTextEdit or TextEdit for output and input text? I'm interested PyQt4.</p>
| -1 | 2009-09-08T21:08:19Z | 1,401,466 | <p>You need to be more specific, but anyways, the following code will create a dialog with a TextEdit that will show the input file:
<code>
from PyQt4 import QtCore, QtGui</p>
<pre><code>def read_file(file):
"""
Returns all contents of file
"""
result = ""
with open(file) as f:
for line in f:
result+= line
return result
class ExampleDialog(QtGui.QDialog):
def __init__(Self, parent, file):
QtGui.QDialog.__init__(self, parent)
# create main layout of the dialog
layout = QtGui.QVBoxLayout()
layout.addWidget(QLabel(self.tr("Contents of file:"))
edit = QtGui.QPlainTextEdit(self)
# read the file and get the content
edit.appendPlainText(read_file(file))
layout.addWidget(edit)
self.setLayout(layout)
file = "hello.txt"
dialog = ExampleDialog(None, file)
dialog.exec_()
</code></pre>
<p></code>
The above is just an example with a QDialog, but should be more than enough for you to get started. </p>
<p>Hope it helps!</p>
| 0 | 2009-09-09T19:04:07Z | [
"python",
"user-interface",
"qt"
] |
ctypes pointer question | 1,396,533 | <p>I was reading the ctypes tutorial, and I came across this:</p>
<pre><code>s = "Hello, World"
c_s = c_char_p(s)
print c_s
c_s.value = "Hi, there"
</code></pre>
<p>But I had been using pointers like this:</p>
<pre><code>s = "Hello, World!"
c_s = c_char_p()
c_s = s
print c_s
c_s.value
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
c_s.value
AttributeError: 'str' object has no attribute 'value'
</code></pre>
<p>Why is it that when I do it one way, I can access c_s.value, and when I do it the other way, there is no value object?</p>
<p>Thanks all!</p>
| 1 | 2009-09-08T21:55:07Z | 1,396,730 | <p>In your second example, you've got the statements:</p>
<pre><code>c_s = c_char_p()
c_s = s
</code></pre>
<p>The <code>ctypes</code> module can't break the <a href="http://docs.python.org/reference/executionmodel.html" rel="nofollow">rules of Python assignments</a>, and in the above case the second assignment <em>rebinds</em> the <code>c_s</code> name from the just-created <code>c_char_p</code> object to the <code>s</code> object. In effect, this throws away the newly created <code>c_char_p</code> object, and your code produces the error in your question because a regular Python string doesn't have a <code>.value</code> property.</p>
<p>Try instead:</p>
<pre><code>c_s = c_char_p()
c_s.value = s
</code></pre>
<p>and see whether that aligns with your expectations.</p>
| 3 | 2009-09-08T22:44:10Z | [
"python",
"object",
"pointers",
"declaration",
"ctypes"
] |
Customizing how Python's `copy` module treats my objects | 1,396,547 | <p>From the <a href="http://docs.python.org/library/copy.html" rel="nofollow"><code>copy</code> documentation</a>:</p>
<blockquote>
<p>Classes can use the same interfaces to control copying that they use to control pickling.</p>
<p>[...]</p>
<p>In order for a class to define its own copy implementation, it can define special methods <code>__copy__()</code> and <code>__deepcopy__()</code></p>
</blockquote>
<p>So which one is it? <code>__setstate__()</code> and <code>__getstate__()</code> that are used when pickling, or <code>__copy__()</code> and <code>__deepcopy__()</code>?</p>
| 3 | 2009-09-08T21:58:48Z | 1,396,683 | <p><code>__setstate__()</code> and <code>__getstate__()</code>.</p>
<p>Notice that the copy documentation says that they <em>can</em> use the same interface, but they don't necessarily have do so. </p>
<p>See <a href="http://books.google.com/books?id=vpTAq4dnmuAC&pg=PA283&lpg=PA283&dq=pickle+setstate&source=bl&ots=AOP7A0L9BA&sig=qXdc-g4OWnbJWBbKI2EvX114qYE&hl=en&ei=Y9imSubHDojANoPioKQI&sa=X&oi=book%5Fresult&ct=result&resnum=8#v=onepage&q=pickle%20setstate&f=false" rel="nofollow">this excerpt</a> from <a href="http://rads.stackoverflow.com/amzn/click/0596001886" rel="nofollow">Python in a Nutshell</a>, or <a href="http://mail.python.org/pipermail/python-list/1999-June/005827.html" rel="nofollow">this explanation</a> on the Python Mailing List.</p>
| 1 | 2009-09-08T22:32:50Z | [
"python",
"copy",
"pickle"
] |
Customizing how Python's `copy` module treats my objects | 1,396,547 | <p>From the <a href="http://docs.python.org/library/copy.html" rel="nofollow"><code>copy</code> documentation</a>:</p>
<blockquote>
<p>Classes can use the same interfaces to control copying that they use to control pickling.</p>
<p>[...]</p>
<p>In order for a class to define its own copy implementation, it can define special methods <code>__copy__()</code> and <code>__deepcopy__()</code></p>
</blockquote>
<p>So which one is it? <code>__setstate__()</code> and <code>__getstate__()</code> that are used when pickling, or <code>__copy__()</code> and <code>__deepcopy__()</code>?</p>
| 3 | 2009-09-08T21:58:48Z | 1,397,416 | <p>It works as follows: if a class defines <code>__copy__</code>, that takes precedence for <code>copy.copy</code> purposes (and similarly <code>__deepcopy__</code> takes precedence for <code>copy.deepcopy</code> purposes). If these very specific special methods are not defined, then the same mechanisms as for pickling and unpickling are tested (this includes, but is not limited to, <code>__getstate__</code> and <code>__setstate__</code>; I've written more about this in my book "Python in a Nutshell" (which @ilfaraone quotes only partially).</p>
| 7 | 2009-09-09T03:33:51Z | [
"python",
"copy",
"pickle"
] |
Why is subtraction faster than addition in Python? | 1,396,564 | <p>I was optimising some Python code, and tried the following experiment:</p>
<pre><code>import time
start = time.clock()
x = 0
for i in range(10000000):
x += 1
end = time.clock()
print '+=',end-start
start = time.clock()
x = 0
for i in range(10000000):
x -= -1
end = time.clock()
print '-=',end-start
</code></pre>
<p>The second loop is reliably faster, anywhere from a whisker to 10%, depending on the system I run it on. I've tried varying the order of the loops, number of executions etc, and it still seems to work.</p>
<p>Stranger,</p>
<pre><code>for i in range(10000000, 0, -1):
</code></pre>
<p>(ie running the loop backwards) is faster than</p>
<pre><code>for i in range(10000000):
</code></pre>
<p>even when loop contents are identical.</p>
<p>What gives, and is there a more general programming lesson here?</p>
| 32 | 2009-09-08T22:01:59Z | 1,396,597 | <pre><code>$ python -m timeit -s "x=0" "x+=1"
10000000 loops, best of 3: 0.151 usec per loop
$ python -m timeit -s "x=0" "x-=-1"
10000000 loops, best of 3: 0.154 usec per loop
</code></pre>
<p>Looks like you've some <a href="http://www-plan.cs.colorado.edu/diwan/asplos09.pdf">measurement bias</a></p>
| 13 | 2009-09-08T22:09:23Z | [
"python",
"performance",
"addition",
"subtraction"
] |
Why is subtraction faster than addition in Python? | 1,396,564 | <p>I was optimising some Python code, and tried the following experiment:</p>
<pre><code>import time
start = time.clock()
x = 0
for i in range(10000000):
x += 1
end = time.clock()
print '+=',end-start
start = time.clock()
x = 0
for i in range(10000000):
x -= -1
end = time.clock()
print '-=',end-start
</code></pre>
<p>The second loop is reliably faster, anywhere from a whisker to 10%, depending on the system I run it on. I've tried varying the order of the loops, number of executions etc, and it still seems to work.</p>
<p>Stranger,</p>
<pre><code>for i in range(10000000, 0, -1):
</code></pre>
<p>(ie running the loop backwards) is faster than</p>
<pre><code>for i in range(10000000):
</code></pre>
<p>even when loop contents are identical.</p>
<p>What gives, and is there a more general programming lesson here?</p>
| 32 | 2009-09-08T22:01:59Z | 1,396,614 | <p>The running loop backwards is faster because the computer has an easier time comparing if a number is equal to 0.</p>
| -1 | 2009-09-08T22:12:52Z | [
"python",
"performance",
"addition",
"subtraction"
] |
Why is subtraction faster than addition in Python? | 1,396,564 | <p>I was optimising some Python code, and tried the following experiment:</p>
<pre><code>import time
start = time.clock()
x = 0
for i in range(10000000):
x += 1
end = time.clock()
print '+=',end-start
start = time.clock()
x = 0
for i in range(10000000):
x -= -1
end = time.clock()
print '-=',end-start
</code></pre>
<p>The second loop is reliably faster, anywhere from a whisker to 10%, depending on the system I run it on. I've tried varying the order of the loops, number of executions etc, and it still seems to work.</p>
<p>Stranger,</p>
<pre><code>for i in range(10000000, 0, -1):
</code></pre>
<p>(ie running the loop backwards) is faster than</p>
<pre><code>for i in range(10000000):
</code></pre>
<p>even when loop contents are identical.</p>
<p>What gives, and is there a more general programming lesson here?</p>
| 32 | 2009-09-08T22:01:59Z | 1,396,671 | <p>I think the "general programming lesson" is that it is <em>really</em> hard to predict, solely by looking at the source code, which sequence of statements will be the fastest. Programmers at all levels frequently get caught up by this sort of "intuitive" optimisation. What you think you know may not necessarily be true.</p>
<p>There is simply no substitute for actually <em>measuring</em> your program performance. Kudos for doing so; answering <em>why</em> undoubtedly requires delving deep into the implementation of Python, in this case.</p>
<p>With byte-compiled languages such as Java, Python, and .NET, it is not even sufficient to measure performance on just one machine. Differences between VM versions, native code translation implementations, CPU-specific optimisations, and so on will make this sort of question ever more tricky to answer.</p>
| 7 | 2009-09-08T22:27:52Z | [
"python",
"performance",
"addition",
"subtraction"
] |
Why is subtraction faster than addition in Python? | 1,396,564 | <p>I was optimising some Python code, and tried the following experiment:</p>
<pre><code>import time
start = time.clock()
x = 0
for i in range(10000000):
x += 1
end = time.clock()
print '+=',end-start
start = time.clock()
x = 0
for i in range(10000000):
x -= -1
end = time.clock()
print '-=',end-start
</code></pre>
<p>The second loop is reliably faster, anywhere from a whisker to 10%, depending on the system I run it on. I've tried varying the order of the loops, number of executions etc, and it still seems to work.</p>
<p>Stranger,</p>
<pre><code>for i in range(10000000, 0, -1):
</code></pre>
<p>(ie running the loop backwards) is faster than</p>
<pre><code>for i in range(10000000):
</code></pre>
<p>even when loop contents are identical.</p>
<p>What gives, and is there a more general programming lesson here?</p>
| 32 | 2009-09-08T22:01:59Z | 1,396,704 | <p>With Python 2.5 the biggest problem here is using range, which will allocate a list that big to iterate over it. When using xrange, whichever is done second is a tiny bit faster for me. (Not sure if range has become a generator in Python 3.)</p>
| 0 | 2009-09-08T22:39:06Z | [
"python",
"performance",
"addition",
"subtraction"
] |
Why is subtraction faster than addition in Python? | 1,396,564 | <p>I was optimising some Python code, and tried the following experiment:</p>
<pre><code>import time
start = time.clock()
x = 0
for i in range(10000000):
x += 1
end = time.clock()
print '+=',end-start
start = time.clock()
x = 0
for i in range(10000000):
x -= -1
end = time.clock()
print '-=',end-start
</code></pre>
<p>The second loop is reliably faster, anywhere from a whisker to 10%, depending on the system I run it on. I've tried varying the order of the loops, number of executions etc, and it still seems to work.</p>
<p>Stranger,</p>
<pre><code>for i in range(10000000, 0, -1):
</code></pre>
<p>(ie running the loop backwards) is faster than</p>
<pre><code>for i in range(10000000):
</code></pre>
<p>even when loop contents are identical.</p>
<p>What gives, and is there a more general programming lesson here?</p>
| 32 | 2009-09-08T22:01:59Z | 1,396,740 | <p>It's always a good idea when asking a question to say what platform and what version of Python you are using. Sometimes it does't matter. This is NOT one of those times:</p>
<ol>
<li><p><code>time.clock()</code> is appropriate only on Windows. Throw away your own measuring code and use <code>-m timeit</code> as demonstrated in pixelbeat's answer.</p></li>
<li><p>Python 2.X's <code>range()</code> builds a list. If you are using Python 2.x, replace <code>range</code> with <code>xrange</code> and see what happens.</p></li>
<li><p>Python 3.X's <code>int</code> is Python2.X's <code>long</code>.</p></li>
</ol>
| 4 | 2009-09-08T22:46:51Z | [
"python",
"performance",
"addition",
"subtraction"
] |
Why is subtraction faster than addition in Python? | 1,396,564 | <p>I was optimising some Python code, and tried the following experiment:</p>
<pre><code>import time
start = time.clock()
x = 0
for i in range(10000000):
x += 1
end = time.clock()
print '+=',end-start
start = time.clock()
x = 0
for i in range(10000000):
x -= -1
end = time.clock()
print '-=',end-start
</code></pre>
<p>The second loop is reliably faster, anywhere from a whisker to 10%, depending on the system I run it on. I've tried varying the order of the loops, number of executions etc, and it still seems to work.</p>
<p>Stranger,</p>
<pre><code>for i in range(10000000, 0, -1):
</code></pre>
<p>(ie running the loop backwards) is faster than</p>
<pre><code>for i in range(10000000):
</code></pre>
<p>even when loop contents are identical.</p>
<p>What gives, and is there a more general programming lesson here?</p>
| 32 | 2009-09-08T22:01:59Z | 1,396,744 | <p>I can reproduce this on my Q6600 (Python 2.6.2); increasing the range to 100000000:</p>
<pre><code>('+=', 11.370000000000001)
('-=', 10.769999999999998)
</code></pre>
<p>First, some observations:</p>
<ul>
<li>This is 5% for a trivial operation. That's significant.</li>
<li>The speed of the native addition and subtraction opcodes is irrelevant. It's in the noise floor, completely dwarfed by the bytecode evaluation. That's talking about one or two native instructions around thousands.</li>
<li>The bytecode generates exactly the same number of instructions; the only difference is <code>INPLACE_ADD</code> vs. <code>INPLACE_SUBTRACT</code> and +1 vs -1.</li>
</ul>
<p>Looking at the Python source, I can make a guess. This is handled in ceval.c, in <code>PyEval_EvalFrameEx</code>. <code>INPLACE_ADD</code> has a significant extra block of code, to handle string concatenation. That block doesn't exist in <code>INPLACE_SUBTRACT</code>, since you can't subtract strings. That means <code>INPLACE_ADD</code> contains more native code. Depending (heavily!) on how the code is being generated by the compiler, this extra code may be inline with the rest of the INPLACE_ADD code, which means additions can hit the instruction cache harder than subtraction. This <em>could</em> be causing extra L2 cache hits, which could cause a significant performance difference.</p>
<p>This is heavily dependent on the system you're on (different processors have different amounts of cache and cache architectures), the compiler in use, including the particular version and compilation options (different compilers will decide differently which bits of code are on the critical path, which determines how assembly code is lumped together), and so on.</p>
<p>Also, the difference is reversed in Python 3.0.1 (+: 15.66, -: 16.71); no doubt this critical function has changed a lot.</p>
| 71 | 2009-09-08T22:47:51Z | [
"python",
"performance",
"addition",
"subtraction"
] |
Why is subtraction faster than addition in Python? | 1,396,564 | <p>I was optimising some Python code, and tried the following experiment:</p>
<pre><code>import time
start = time.clock()
x = 0
for i in range(10000000):
x += 1
end = time.clock()
print '+=',end-start
start = time.clock()
x = 0
for i in range(10000000):
x -= -1
end = time.clock()
print '-=',end-start
</code></pre>
<p>The second loop is reliably faster, anywhere from a whisker to 10%, depending on the system I run it on. I've tried varying the order of the loops, number of executions etc, and it still seems to work.</p>
<p>Stranger,</p>
<pre><code>for i in range(10000000, 0, -1):
</code></pre>
<p>(ie running the loop backwards) is faster than</p>
<pre><code>for i in range(10000000):
</code></pre>
<p>even when loop contents are identical.</p>
<p>What gives, and is there a more general programming lesson here?</p>
| 32 | 2009-09-08T22:01:59Z | 1,397,046 | <p>Your experiment is faulty. The way this experiment should be designed is to write 2 different programs - 1 for addition, 1 for subtraction. They should be exactly the same and run under the same conditions with the data being put to file. Then you need to average the runs (at least several thousand), but you'd need a statistician to tell you an appropriate number.</p>
<p>If you wanted to analyze different methods of addition, subtraction, and looping, again each of those should be a separate program.</p>
<p>Experimental error might arise from heat of processor and other activity going on the cpu, so i'd execute the runs in a variety of patterns...</p>
| 0 | 2009-09-09T00:37:51Z | [
"python",
"performance",
"addition",
"subtraction"
] |
Why is subtraction faster than addition in Python? | 1,396,564 | <p>I was optimising some Python code, and tried the following experiment:</p>
<pre><code>import time
start = time.clock()
x = 0
for i in range(10000000):
x += 1
end = time.clock()
print '+=',end-start
start = time.clock()
x = 0
for i in range(10000000):
x -= -1
end = time.clock()
print '-=',end-start
</code></pre>
<p>The second loop is reliably faster, anywhere from a whisker to 10%, depending on the system I run it on. I've tried varying the order of the loops, number of executions etc, and it still seems to work.</p>
<p>Stranger,</p>
<pre><code>for i in range(10000000, 0, -1):
</code></pre>
<p>(ie running the loop backwards) is faster than</p>
<pre><code>for i in range(10000000):
</code></pre>
<p>even when loop contents are identical.</p>
<p>What gives, and is there a more general programming lesson here?</p>
| 32 | 2009-09-08T22:01:59Z | 1,397,081 | <blockquote>
<p>"The second loop is reliably faster ..."</p>
</blockquote>
<p>That's your explanation right there. Re-order your script so the subtraction test is timed first, <em>then</em> the addition, and suddenly addition becomes the faster operation again:</p>
<pre><code>-= 3.05
+= 2.84
</code></pre>
<p>Obviously something happens to the second half of the script that makes it faster. My <em>guess</em> is that the first call to <code>range()</code> is slower because python needs to allocate enough memory for such a long list, but it is able to re-use that memory for the second call to <code>range()</code>:</p>
<pre><code>import time
start = time.clock()
x = range(10000000)
end = time.clock()
del x
print 'first range()',end-start
start = time.clock()
x = range(10000000)
end = time.clock()
print 'second range()',end-start
</code></pre>
<p>A few runs of this script show that the extra time needed for the first <code>range()</code> accounts for nearly all of the time difference between '+=' and '-=' seen above:</p>
<pre><code>first range() 0.4
second range() 0.23
</code></pre>
| 5 | 2009-09-09T00:55:59Z | [
"python",
"performance",
"addition",
"subtraction"
] |
Why is subtraction faster than addition in Python? | 1,396,564 | <p>I was optimising some Python code, and tried the following experiment:</p>
<pre><code>import time
start = time.clock()
x = 0
for i in range(10000000):
x += 1
end = time.clock()
print '+=',end-start
start = time.clock()
x = 0
for i in range(10000000):
x -= -1
end = time.clock()
print '-=',end-start
</code></pre>
<p>The second loop is reliably faster, anywhere from a whisker to 10%, depending on the system I run it on. I've tried varying the order of the loops, number of executions etc, and it still seems to work.</p>
<p>Stranger,</p>
<pre><code>for i in range(10000000, 0, -1):
</code></pre>
<p>(ie running the loop backwards) is faster than</p>
<pre><code>for i in range(10000000):
</code></pre>
<p>even when loop contents are identical.</p>
<p>What gives, and is there a more general programming lesson here?</p>
| 32 | 2009-09-08T22:01:59Z | 1,399,677 | <p>That would be remarkable, so I have thoroughly evaluated your code and also setup the expiriment as I would find it more <em>correct</em> (all declarations and function calls outside the loop). Both versions I have run five times.</p>
<ul>
<li>Running your code validated your claims:
-= takes constantly less time; 3.6% on average</li>
<li>Running my code, though, contradicts the outcome of your experiment:
+= takes on average (not always) 0.5% less time.</li>
</ul>
<p>To show all results I have put plots online:</p>
<ul>
<li>Your evaluation: <a href="http://bayimg.com/kadAeaAcN" rel="nofollow">http://bayimg.com/kadAeaAcN</a></li>
<li>My evaluation: <a href="http://bayimg.com/KadaAaAcN" rel="nofollow">http://bayimg.com/KadaAaAcN</a></li>
</ul>
<p>So, I conclude that your experiment has a bias, and it is significant.</p>
<p>Finally here is my code:</p>
<pre><code>import time
addtimes = [0.] * 100
subtracttimes = [0.] * 100
range100 = range(100)
range10000000 = range(10000000)
j = 0
i = 0
x = 0
start = 0.
for j in range100:
start = time.clock()
x = 0
for i in range10000000:
x += 1
addtimes[j] = time.clock() - start
for j in range100:
start = time.clock()
x = 0
for i in range10000000:
x -= -1
subtracttimes[j] = time.clock() - start
print '+=', sum(addtimes)
print '-=', sum(subtracttimes)
</code></pre>
| 0 | 2009-09-09T13:26:04Z | [
"python",
"performance",
"addition",
"subtraction"
] |
Why is subtraction faster than addition in Python? | 1,396,564 | <p>I was optimising some Python code, and tried the following experiment:</p>
<pre><code>import time
start = time.clock()
x = 0
for i in range(10000000):
x += 1
end = time.clock()
print '+=',end-start
start = time.clock()
x = 0
for i in range(10000000):
x -= -1
end = time.clock()
print '-=',end-start
</code></pre>
<p>The second loop is reliably faster, anywhere from a whisker to 10%, depending on the system I run it on. I've tried varying the order of the loops, number of executions etc, and it still seems to work.</p>
<p>Stranger,</p>
<pre><code>for i in range(10000000, 0, -1):
</code></pre>
<p>(ie running the loop backwards) is faster than</p>
<pre><code>for i in range(10000000):
</code></pre>
<p>even when loop contents are identical.</p>
<p>What gives, and is there a more general programming lesson here?</p>
| 32 | 2009-09-08T22:01:59Z | 4,078,287 | <blockquote>Is there a more general programming lesson here?</blockquote>
<p>The more general programming lesson here is that intuition is a poor guide when predicting run-time performance of computer code.</p>
<p>One can reason about algorithmic complexity, hypothesise about compiler optimisations, estimate cache performance and so on. However, since these things can interact in non-trivial ways, the only way to be sure about how fast a particular piece of code is going to be is to benchmark it in the target environment (as you have rightfully done.)</p>
| 2 | 2010-11-02T13:46:31Z | [
"python",
"performance",
"addition",
"subtraction"
] |
python and mechanize.open() | 1,396,646 | <p>I have some code that is using mechanize and a password protected site. I can login just fine and get the results I expect. However, once I log in I don't want to "click" links I want to iterate through a list of URLs. Unfortunately each .open() call simply gets a re-direct to the login page, which is the behaviour I would expect if I had logged out or tried to login with a different browser. This leads me to believe it is cookie handling of some sort but I'm at a loss.</p>
<pre><code>def main():
browser = mechanize.Browser()
browser.set_handle_robots(False)
# The below code works perfectly
page_stats = login_to_BOE(browser)
print page_stats
# This code ALWAYS gets the login page again NOT the desired
# behaviour of getting the new URL. This is the behaviour I would
# expect if I had logged out of our site.
for page in PAGES:
print '%s%s' % (SITE, page)
page = browser.open('%s%s' % (SITE, page))
page_stats = get_page_statistics(page.get_data())
print page_stats
</code></pre>
| 2 | 2009-09-08T22:20:09Z | 1,396,706 | <p>This isn't an answer, but it might lead you in the right direction. Try turning on Mechanize's extensive debugging facilities, using some combination of the statements below:</p>
<pre><code>browser.set_debug_redirects(True)
browser.set_debug_responses(True)
browser.set_debug_http(True)
</code></pre>
<p>This will provide a flood of HTTP information, which I found very useful when I developed my one and only Mechanize-based application.</p>
<p>I should note that I'm not doing much (if anything) different in my application than what you showed in your question. I create a browser object the same way, then pass it to this login function:</p>
<pre><code>def login(browser):
browser.open(config.login_url)
browser.select_form(nr=0)
browser[config.username_field] = config.username
browser[config.password_field] = config.password
browser.submit()
return browser
</code></pre>
<p>I can then open authentication-required pages with browser.open(url) and all of the cookie handling is handled transparently and automatically for me.</p>
| 1 | 2009-09-08T22:40:27Z | [
"python",
"mechanize"
] |
python and mechanize.open() | 1,396,646 | <p>I have some code that is using mechanize and a password protected site. I can login just fine and get the results I expect. However, once I log in I don't want to "click" links I want to iterate through a list of URLs. Unfortunately each .open() call simply gets a re-direct to the login page, which is the behaviour I would expect if I had logged out or tried to login with a different browser. This leads me to believe it is cookie handling of some sort but I'm at a loss.</p>
<pre><code>def main():
browser = mechanize.Browser()
browser.set_handle_robots(False)
# The below code works perfectly
page_stats = login_to_BOE(browser)
print page_stats
# This code ALWAYS gets the login page again NOT the desired
# behaviour of getting the new URL. This is the behaviour I would
# expect if I had logged out of our site.
for page in PAGES:
print '%s%s' % (SITE, page)
page = browser.open('%s%s' % (SITE, page))
page_stats = get_page_statistics(page.get_data())
print page_stats
</code></pre>
| 2 | 2009-09-08T22:20:09Z | 1,396,801 | <p>Instead of using for each link:</p>
<pre><code>browser.open('www.google.com')
</code></pre>
<p>Try using the following after doing the initial login:</p>
<pre><code>browser.follow_link(text = 'a href text')
</code></pre>
<p>My guess is that calling open is what is resetting your cookies.</p>
| 2 | 2009-09-08T23:06:00Z | [
"python",
"mechanize"
] |
python and mechanize.open() | 1,396,646 | <p>I have some code that is using mechanize and a password protected site. I can login just fine and get the results I expect. However, once I log in I don't want to "click" links I want to iterate through a list of URLs. Unfortunately each .open() call simply gets a re-direct to the login page, which is the behaviour I would expect if I had logged out or tried to login with a different browser. This leads me to believe it is cookie handling of some sort but I'm at a loss.</p>
<pre><code>def main():
browser = mechanize.Browser()
browser.set_handle_robots(False)
# The below code works perfectly
page_stats = login_to_BOE(browser)
print page_stats
# This code ALWAYS gets the login page again NOT the desired
# behaviour of getting the new URL. This is the behaviour I would
# expect if I had logged out of our site.
for page in PAGES:
print '%s%s' % (SITE, page)
page = browser.open('%s%s' % (SITE, page))
page_stats = get_page_statistics(page.get_data())
print page_stats
</code></pre>
| 2 | 2009-09-08T22:20:09Z | 1,396,826 | <p>Will,</p>
<p>Your suggestion pointed me in exactly the right direction.</p>
<p>Every web browser I have ever used responded to something like the following correct:</p>
<pre><code>http://www.foo.com//bar/baz/trool.html
</code></pre>
<p>Since I hate getting things concatenated incorrectly my SITE variable was "http://www.foo.com/"</p>
<p>In addition all the other URLS were "/bar/baz/trool.html"</p>
<p>My calls to open ended up being <code>.open('<a href="http://www.foo.com//bar/baz/trool.html" rel="nofollow">http://www.foo.com//bar/baz/trool.html</a>')</code> and the mechanize browser obviously doesn't massage that like a "real" browser would. Apache didn't like the urls.</p>
| 2 | 2009-09-08T23:13:39Z | [
"python",
"mechanize"
] |
Python: Get object by id | 1,396,668 | <p>Let's say I have an id of a Python object, which I retrieved by doing <code>id(thing)</code>. How do I find <code>thing</code> again by the id number I was given?</p>
| 63 | 2009-09-08T22:26:56Z | 1,396,690 | <p>You can use the <a href="http://docs.python.org/library/gc.html">gc</a> module to get all the objects currently tracked by the Python garbage collector.</p>
<pre><code>import gc
def objects_by_id(id_):
for obj in gc.get_objects():
if id(obj) == id_:
return obj
raise Exception("No found")
</code></pre>
| 29 | 2009-09-08T22:34:56Z | [
"python"
] |
Python: Get object by id | 1,396,668 | <p>Let's say I have an id of a Python object, which I retrieved by doing <code>id(thing)</code>. How do I find <code>thing</code> again by the id number I was given?</p>
| 63 | 2009-09-08T22:26:56Z | 1,396,696 | <p>Short answer, you can't.</p>
<p>Long answer, you can maintain a dict for mapping IDs to objects, or look the ID up by exhaustive search of <code>gc.get_objects()</code>, but this will create one of two problems: either the dict's reference will keep the object alive and prevent GC, or (if it's a WeakValue dict or you use <code>gc.get_objects()</code>) the ID may be deallocated and reused for a completely different object.</p>
<p>Basically, if you're trying to do this, you probably need to do something differently.</p>
| 34 | 2009-09-08T22:37:30Z | [
"python"
] |
Python: Get object by id | 1,396,668 | <p>Let's say I have an id of a Python object, which I retrieved by doing <code>id(thing)</code>. How do I find <code>thing</code> again by the id number I was given?</p>
| 63 | 2009-09-08T22:26:56Z | 1,396,731 | <p>eGenix mxTools library does provide such a function, although marked as "expert-only": <a href="http://www.egenix.com/products/python/mxBase/mxTools/doc/#%5FToc199521822" rel="nofollow"><code>mx.Tools.makeref(id)</code></a> </p>
| 2 | 2009-09-08T22:44:18Z | [
"python"
] |
Python: Get object by id | 1,396,668 | <p>Let's say I have an id of a Python object, which I retrieved by doing <code>id(thing)</code>. How do I find <code>thing</code> again by the id number I was given?</p>
| 63 | 2009-09-08T22:26:56Z | 1,396,739 | <p>You'll probably want to consider implementing it another way. Are you aware of the weakref module?</p>
<p>(Edited) The Python <a href="http://docs.python.org/library/weakref.html">weakref module</a> lets you keep references, dictionary references, and proxies to objects without having those references count in the reference counter. They're like symbolic links.</p>
| 20 | 2009-09-08T22:46:31Z | [
"python"
] |
Python: Get object by id | 1,396,668 | <p>Let's say I have an id of a Python object, which I retrieved by doing <code>id(thing)</code>. How do I find <code>thing</code> again by the id number I was given?</p>
| 63 | 2009-09-08T22:26:56Z | 1,397,628 | <p>Just mentioning this module for completeness. <a href="http://www.friday.com/bbum/2007/08/24/python-di/" rel="nofollow">This code by Bill Bumgarner</a> includes a C extension to do what you want without looping throughout every object in existence.</p>
<p>The code for the function is quite straightforward. Every Python object is represented in C by a pointer to <a href="http://docs.python.org/2/c-api/structures.html" rel="nofollow">a <code>PyObject</code> struct</a>. Because <code>id(x)</code> is just the memory address of this struct, we can retrieve the Python object just by treating <code>x</code> as a pointer to a <code>PyObject</code>, then calling <code>Py_INCREF</code> to tell the garbage collector that we're creating a new reference to the object.</p>
<pre><code>static PyObject *
di_di(PyObject *self, PyObject *args)
{
PyObject *obj;
if (!PyArg_ParseTuple(args, "l:di", &obj))
return NULL;
Py_INCREF(obj);
return obj;
}
</code></pre>
<p>If the original object no longer exists then the result is undefined. It may crash, but it could also return a reference to a new object that's taken the location of the old one in memory.</p>
| 5 | 2009-09-09T05:01:52Z | [
"python"
] |
Python: Get object by id | 1,396,668 | <p>Let's say I have an id of a Python object, which I retrieved by doing <code>id(thing)</code>. How do I find <code>thing</code> again by the id number I was given?</p>
| 63 | 2009-09-08T22:26:56Z | 15,702,647 | <p>This can be done easily by <code>ctypes</code>:</p>
<pre><code>import ctypes
a = "hello world"
print ctypes.cast(id(a), ctypes.py_object).value
</code></pre>
<p>output:</p>
<pre><code>hello world
</code></pre>
| 72 | 2013-03-29T11:51:23Z | [
"python"
] |
How to install 64-bit Python on Solaris? | 1,396,678 | <p>I am trying to install Python 2.6 on <a href="http://en.wikipedia.org/wiki/Solaris%5F%28operating%5Fsystem%29" rel="nofollow">Solaris</a> by building the source on Solaris machine. I installed one this way and it appears that it is 32-bit. I downloaded some source tar ball as Linux or Unix for this purpose. Everything works well but I need 64-bit Python. </p>
<p>I looked up the Python download site and there is no separate installation for a 64-bit Python.
That makes me think that there must be some option while running configure and/or install commands to install Python. I tried reading README.txt of the installation but could not find any info. I am very new to installations on "Unix" like systems.</p>
<p>How can I install 64-bit Python on Solaris?</p>
| 0 | 2009-09-08T22:30:50Z | 1,396,693 | <p>It's currently an <a href="http://bugs.python.org/issue1306248" rel="nofollow">acknowledged bug</a> that Solaris 64-bit support is suboptimal, but that bug report looks to contain some flags that you might want to use. See also <a href="http://code.activestate.com/lists/python-list/540079/" rel="nofollow">this mailing list posting</a>.</p>
| 2 | 2009-09-08T22:35:46Z | [
"python",
"solaris"
] |
How to install 64-bit Python on Solaris? | 1,396,678 | <p>I am trying to install Python 2.6 on <a href="http://en.wikipedia.org/wiki/Solaris%5F%28operating%5Fsystem%29" rel="nofollow">Solaris</a> by building the source on Solaris machine. I installed one this way and it appears that it is 32-bit. I downloaded some source tar ball as Linux or Unix for this purpose. Everything works well but I need 64-bit Python. </p>
<p>I looked up the Python download site and there is no separate installation for a 64-bit Python.
That makes me think that there must be some option while running configure and/or install commands to install Python. I tried reading README.txt of the installation but could not find any info. I am very new to installations on "Unix" like systems.</p>
<p>How can I install 64-bit Python on Solaris?</p>
| 0 | 2009-09-08T22:30:50Z | 1,592,707 | <p>I would strongly suggest seeing if you can get away with the 32 bit version of Python. If your new to compiling stuff on Solaris, this will save you <em>many</em> headaches. However, it is possible, and I do have a working 64 bit version of Python. I'm using <em>cc: Sun C 5.8 2005/10/13</em> to compile. Additionally, I've already compiled 64-bit version of readline and ncurses.</p>
<p>My configure line looks like this:</p>
<pre><code>../Python-2.6.1/configure CCSHARED="-KPIC" LDSHARED="cc -xarch=generic64 -G -KPIC" LDFLAGS="-xarch=generic64 -L/opt/tools/lib -R/opt/tools/lib -L/opt/tools/ssl/lib -ltermcap -lz -R $ORIGIN/../lib" CC="cc" CPP="cc -xarch=generic64 -E -I/opt/tools/include -I/opt/tools/include/ncurses -I/opt/tools/include/readline" BASECFLAGS="-xarch=generic64 -I/opt/tools/include -I/opt/tools/include/ncurses" OPT="-xO5" CFLAGS="-xarch=generic64 -I/opt/tools/include -I/opt/tools/include/ncurses -I/opt/tools/include/readline" CXX="CC -xarch=generic64 -I/opt/tools/include -I/opt/tools/include/ncurses" --prefix=/opt/tools/python-2.6.1 --enable-64-bit --without-gcc --disable-ipv6 --with-ssl=openssl --with-ncurses --with-readline
</code></pre>
<p>Additionally, I modified these two lines in Modules/Setup.local to include the required locations:</p>
<pre><code>readline readline.c -I/opt/tools/include/readline -L/opt/tools/lib -lreadline -ltermcap
_ssl _ssl.c -I/opt/tools/ssl/include -L/opt/tools/ssl/lib -lssl -lcrypto
</code></pre>
<p>Now, just pray you don't need to compile in some Sybase bindings or some other 64-bit libraries.</p>
| 3 | 2009-10-20T05:54:29Z | [
"python",
"solaris"
] |
apt like column output - python library | 1,396,820 | <p>Debian's apt tool outputs results in uniform width columns. For instance, try running "aptitude search svn" .. and all names appear in the first column of the same width.</p>
<p>Now if you resize the terminal, the column width is adjusted accordingly.</p>
<p>Is there a Python library that enables one to do this? Note that the library has to be aware of the terminal width and take a table as input - which could be, for instance, <code>[('rapidsvn', 'A GUI client for subversion'), ...]</code> .. and you may also specify a max-width for the first column (or any column). Also note how the string in the second column below is trimmed if exceeds the terminal width .. thus not introducing the undesired second line.</p>
<pre><code>$ aptitude search svn
[...]
p python-svn-dbg - A(nother) Python interface to Subversion (d
v python2.5-svn -
v python2.6-svn -
p rapidsvn - A GUI client for subversion
p statsvn - SVN repository statistics
p svn-arch-mirror - one-way mirroring from Subversion to Arch r
p svn-autoreleasedeb - Automatically release/upload debian package
p svn-buildpackage - helper programs to maintain Debian packages
p svn-load - An enhanced import facility for Subversion
p svn-workbench - A Workbench for Subversion
p svnmailer - extensible Subversion commit notification t
p websvn - interface for subversion repositories writt
$
</code></pre>
<p><strong>EDIT</strong>: (in response to Alex's answer below) ... the output will be similar to 'aptitude search' in that 1) only the last column (which is the only column with the longest string in a row) is to be trimmed, 2) there are typically 2-4 columns only, but the last column ("description") is expected to take at least half the terminal width. 3) all rows contain equal number of columns, 4) all entries are strings only</p>
| 2 | 2009-09-08T23:12:30Z | 1,397,122 | <p>Well, aptitude uses <a href="http://cwidget.alioth.debian.org/" rel="nofollow"><code>cwidget</code></a> to format the columns in the text-only display. You could call into <code>cwidget</code> writing a python extension for it, but I don't think it is worth the trouble... You can use your preferred method of getting the actual horizontal size in chars and calculate yourself.</p>
| 2 | 2009-09-09T01:17:06Z | [
"python",
"table",
"formatting",
"terminal",
"apt"
] |
apt like column output - python library | 1,396,820 | <p>Debian's apt tool outputs results in uniform width columns. For instance, try running "aptitude search svn" .. and all names appear in the first column of the same width.</p>
<p>Now if you resize the terminal, the column width is adjusted accordingly.</p>
<p>Is there a Python library that enables one to do this? Note that the library has to be aware of the terminal width and take a table as input - which could be, for instance, <code>[('rapidsvn', 'A GUI client for subversion'), ...]</code> .. and you may also specify a max-width for the first column (or any column). Also note how the string in the second column below is trimmed if exceeds the terminal width .. thus not introducing the undesired second line.</p>
<pre><code>$ aptitude search svn
[...]
p python-svn-dbg - A(nother) Python interface to Subversion (d
v python2.5-svn -
v python2.6-svn -
p rapidsvn - A GUI client for subversion
p statsvn - SVN repository statistics
p svn-arch-mirror - one-way mirroring from Subversion to Arch r
p svn-autoreleasedeb - Automatically release/upload debian package
p svn-buildpackage - helper programs to maintain Debian packages
p svn-load - An enhanced import facility for Subversion
p svn-workbench - A Workbench for Subversion
p svnmailer - extensible Subversion commit notification t
p websvn - interface for subversion repositories writt
$
</code></pre>
<p><strong>EDIT</strong>: (in response to Alex's answer below) ... the output will be similar to 'aptitude search' in that 1) only the last column (which is the only column with the longest string in a row) is to be trimmed, 2) there are typically 2-4 columns only, but the last column ("description") is expected to take at least half the terminal width. 3) all rows contain equal number of columns, 4) all entries are strings only</p>
| 2 | 2009-09-08T23:12:30Z | 1,397,365 | <p>First, use <code>ioctl</code> to get the size of the TTY:</p>
<pre><code>import termios, fcntl, struct, sys
def get_tty_size():
s = struct.pack("HHHH", 0, 0, 0, 0)
fd_stdout = sys.stdout.fileno()
size = fcntl.ioctl(fd_stdout, termios.TIOCGWINSZ, s)
return struct.unpack("HHHH", size)[:2]
print get_tty_size()
</code></pre>
<p>Then use a function like this to make columns:</p>
<pre><code>pad = lambda s, n=20: "%s%s" % (s,' '*(n-len(s)))
</code></pre>
<p>Put those together and you've got resizing columns for the console!</p>
| 2 | 2009-09-09T03:14:57Z | [
"python",
"table",
"formatting",
"terminal",
"apt"
] |
apt like column output - python library | 1,396,820 | <p>Debian's apt tool outputs results in uniform width columns. For instance, try running "aptitude search svn" .. and all names appear in the first column of the same width.</p>
<p>Now if you resize the terminal, the column width is adjusted accordingly.</p>
<p>Is there a Python library that enables one to do this? Note that the library has to be aware of the terminal width and take a table as input - which could be, for instance, <code>[('rapidsvn', 'A GUI client for subversion'), ...]</code> .. and you may also specify a max-width for the first column (or any column). Also note how the string in the second column below is trimmed if exceeds the terminal width .. thus not introducing the undesired second line.</p>
<pre><code>$ aptitude search svn
[...]
p python-svn-dbg - A(nother) Python interface to Subversion (d
v python2.5-svn -
v python2.6-svn -
p rapidsvn - A GUI client for subversion
p statsvn - SVN repository statistics
p svn-arch-mirror - one-way mirroring from Subversion to Arch r
p svn-autoreleasedeb - Automatically release/upload debian package
p svn-buildpackage - helper programs to maintain Debian packages
p svn-load - An enhanced import facility for Subversion
p svn-workbench - A Workbench for Subversion
p svnmailer - extensible Subversion commit notification t
p websvn - interface for subversion repositories writt
$
</code></pre>
<p><strong>EDIT</strong>: (in response to Alex's answer below) ... the output will be similar to 'aptitude search' in that 1) only the last column (which is the only column with the longest string in a row) is to be trimmed, 2) there are typically 2-4 columns only, but the last column ("description") is expected to take at least half the terminal width. 3) all rows contain equal number of columns, 4) all entries are strings only</p>
| 2 | 2009-09-08T23:12:30Z | 1,397,382 | <p>I don't think there's a general, cross-platform way to "get the width of the terminal" -- <strong>most definitely NOT</strong> "look at the COLUMNS environment variable" (see my comment on the question). On Linux and Mac OS X (and I expect all modern Unix versions),</p>
<pre><code>curses.wrapper(lambda _: curses.tigetnum('cols'))
</code></pre>
<p>returns the number of columns; but I don't know if <a href="http://code.google.com/p/wcurses/" rel="nofollow">wcurses</a> supports this in Windows.</p>
<p>Once you do have (from os.environ['COLUMNS'] if you insist, or via curses, or from an oracle, or defaulted to 80, or any other way you like) the desired output width, the rest is
quite feasible. It's finnicky work, with many chances for off-by-one kinds of errors, and very vulnerable to a lot of detailed specs that you don't make entirely clear, such as: which column gets cut to avoid wrapping -- it it always the last one, or...? How come you're showing 3 columns in the sample output when according to your question only two are passed in...? what is supposed to happen if not all rows have the same number of columns? must all entries in table be strings? and many, many other mysteries of this ilk.</p>
<p>So, taking somewhat-arbitrary guesses for all the specs that you don't express, one approach might be something like...:</p>
<pre><code>import sys
def colprint(totwidth, table):
numcols = max(len(row) for row in table)
# ensure all rows have >= numcols columns, maybe empty
padded = [row+numcols*('',) for row in table]
# compute col widths, including separating space (except for last one)
widths = [ 1 + max(len(x) for x in column) for column in zip(*padded)]
widths[-1] -= 1
# drop or truncate columns from the right in order to fit
while sum(widths) > totwidth:
mustlose = sum(widths) - totwidth
if widths[-1] <= mustlose:
del widths[-1]
else:
widths[-1] -= mustlose
break
# and finally, the output phase!
for row in padded:
for w, i in zip(widths, row):
sys.stdout.write('%*s' % (-w, i[:w]))
sys.stdout.write('\n')
</code></pre>
| 2 | 2009-09-09T03:19:43Z | [
"python",
"table",
"formatting",
"terminal",
"apt"
] |
apt like column output - python library | 1,396,820 | <p>Debian's apt tool outputs results in uniform width columns. For instance, try running "aptitude search svn" .. and all names appear in the first column of the same width.</p>
<p>Now if you resize the terminal, the column width is adjusted accordingly.</p>
<p>Is there a Python library that enables one to do this? Note that the library has to be aware of the terminal width and take a table as input - which could be, for instance, <code>[('rapidsvn', 'A GUI client for subversion'), ...]</code> .. and you may also specify a max-width for the first column (or any column). Also note how the string in the second column below is trimmed if exceeds the terminal width .. thus not introducing the undesired second line.</p>
<pre><code>$ aptitude search svn
[...]
p python-svn-dbg - A(nother) Python interface to Subversion (d
v python2.5-svn -
v python2.6-svn -
p rapidsvn - A GUI client for subversion
p statsvn - SVN repository statistics
p svn-arch-mirror - one-way mirroring from Subversion to Arch r
p svn-autoreleasedeb - Automatically release/upload debian package
p svn-buildpackage - helper programs to maintain Debian packages
p svn-load - An enhanced import facility for Subversion
p svn-workbench - A Workbench for Subversion
p svnmailer - extensible Subversion commit notification t
p websvn - interface for subversion repositories writt
$
</code></pre>
<p><strong>EDIT</strong>: (in response to Alex's answer below) ... the output will be similar to 'aptitude search' in that 1) only the last column (which is the only column with the longest string in a row) is to be trimmed, 2) there are typically 2-4 columns only, but the last column ("description") is expected to take at least half the terminal width. 3) all rows contain equal number of columns, 4) all entries are strings only</p>
| 2 | 2009-09-08T23:12:30Z | 1,446,973 | <p><strong>Update</strong>: The <code>colprint</code> routine is now available in the <a href="http://code.activestate.com/pypm/applib/" rel="nofollow">applib</a> Python library <a href="https://github.com/ActiveState/applib/blob/master/applib/textui.py#L213" rel="nofollow">hosted in GitHub</a>. </p>
<p>Here's the complete program for those of you interested:</p>
<pre><code># This function was written by Alex Martelli
# http://stackoverflow.com/questions/1396820/
def colprint(table, totwidth=None):
"""Print the table in terminal taking care of wrapping/alignment
- `table`: A table of strings. Elements must not be `None`
- `totwidth`: If None, console width is used
"""
if not table: return
if totwidth is None:
totwidth = find_console_width()
totwidth -= 1 # for not printing an extra empty line on windows
numcols = max(len(row) for row in table)
# ensure all rows have >= numcols columns, maybe empty
padded = [row+numcols*('',) for row in table]
# compute col widths, including separating space (except for last one)
widths = [ 1 + max(len(x) for x in column) for column in zip(*padded)]
widths[-1] -= 1
# drop or truncate columns from the right in order to fit
while sum(widths) > totwidth:
mustlose = sum(widths) - totwidth
if widths[-1] <= mustlose:
del widths[-1]
else:
widths[-1] -= mustlose
break
# and finally, the output phase!
for row in padded:
print(''.join([u'%*s' % (-w, i[:w])
for w, i in zip(widths, row)]))
def find_console_width():
if sys.platform.startswith('win'):
return _find_windows_console_width()
else:
return _find_unix_console_width()
def _find_unix_console_width():
"""Return the width of the Unix terminal
If `stdout` is not a real terminal, return the default value (80)
"""
import termios, fcntl, struct, sys
# fcntl.ioctl will fail if stdout is not a tty
if not sys.stdout.isatty():
return 80
s = struct.pack("HHHH", 0, 0, 0, 0)
fd_stdout = sys.stdout.fileno()
size = fcntl.ioctl(fd_stdout, termios.TIOCGWINSZ, s)
height, width = struct.unpack("HHHH", size)[:2]
return width
def _find_windows_console_width():
"""Return the width of the Windows console
If the width cannot be determined, return the default value (80)
"""
# http://code.activestate.com/recipes/440694/
from ctypes import windll, create_string_buffer
STDIN, STDOUT, STDERR = -10, -11, -12
h = windll.kernel32.GetStdHandle(STDERR)
csbi = create_string_buffer(22)
res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
if res:
import struct
(bufx, bufy, curx, cury, wattr,
left, top, right, bottom,
maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
sizex = right - left + 1
sizey = bottom - top + 1
else:
sizex, sizey = 80, 25
return sizex
</code></pre>
| 4 | 2009-09-18T21:45:44Z | [
"python",
"table",
"formatting",
"terminal",
"apt"
] |
How Do I Select all Objects via a Relationship Model | 1,396,985 | <p>Given the Model:</p>
<pre><code>class Profile(models.Model):
user = models.ForeignKey(User, unique=True)
class Thingie(models.Model):
children = models.ManyToManyField('self', blank=True, symmetrical=False)
class Relation(models.Model):
profile = models.ForeignKey(Profile)
thingie = models.ForeignKey(Thingie)
</code></pre>
<p>How would one return a QuerySet containing all Profile instances related to a given Thingie? That is, every Profile that has a foreign key pointing to it from a Relation and to the given thingie. </p>
<p>I know all about select_related(), and how I could use it to do this by iterating but i find iterating irritating (badoop bah!). Also, values_list() has been looked at, but it doesn't quite do the right thing. </p>
<p>Please help! Thanks!</p>
| 1 | 2009-09-09T00:15:11Z | 1,397,159 | <p>Did you read the Django doc on <a href="http://docs.djangoproject.com/en/dev/topics/db/queries/" rel="nofollow">Making queries</a>? It has a simple example of achieving what you want, more specifically <a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships" rel="nofollow">Lookups that span relationships</a>. Make sure you refer the code snippets in the latter link to the model code at the beginning of the page.</p>
| 0 | 2009-09-09T01:33:48Z | [
"python",
"django",
"django-queryset"
] |
How Do I Select all Objects via a Relationship Model | 1,396,985 | <p>Given the Model:</p>
<pre><code>class Profile(models.Model):
user = models.ForeignKey(User, unique=True)
class Thingie(models.Model):
children = models.ManyToManyField('self', blank=True, symmetrical=False)
class Relation(models.Model):
profile = models.ForeignKey(Profile)
thingie = models.ForeignKey(Thingie)
</code></pre>
<p>How would one return a QuerySet containing all Profile instances related to a given Thingie? That is, every Profile that has a foreign key pointing to it from a Relation and to the given thingie. </p>
<p>I know all about select_related(), and how I could use it to do this by iterating but i find iterating irritating (badoop bah!). Also, values_list() has been looked at, but it doesn't quite do the right thing. </p>
<p>Please help! Thanks!</p>
| 1 | 2009-09-09T00:15:11Z | 1,397,299 | <p>Without defining a direct relationship between Profile and Thingie, you can't.</p>
<p>The best way would be to add a ManyToMany to Thingie that points to Profile and use the <code>through</code> argument (<a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ManyToManyField.through" rel="nofollow">django docs</a>) on the ManyToMany to specify your Relation model/table.</p>
<p>That way you can do a direct filter operation on Thingie to get your profiles and still store your intermediate Relation data.</p>
| 0 | 2009-09-09T02:41:36Z | [
"python",
"django",
"django-queryset"
] |
How Do I Select all Objects via a Relationship Model | 1,396,985 | <p>Given the Model:</p>
<pre><code>class Profile(models.Model):
user = models.ForeignKey(User, unique=True)
class Thingie(models.Model):
children = models.ManyToManyField('self', blank=True, symmetrical=False)
class Relation(models.Model):
profile = models.ForeignKey(Profile)
thingie = models.ForeignKey(Thingie)
</code></pre>
<p>How would one return a QuerySet containing all Profile instances related to a given Thingie? That is, every Profile that has a foreign key pointing to it from a Relation and to the given thingie. </p>
<p>I know all about select_related(), and how I could use it to do this by iterating but i find iterating irritating (badoop bah!). Also, values_list() has been looked at, but it doesn't quite do the right thing. </p>
<p>Please help! Thanks!</p>
| 1 | 2009-09-09T00:15:11Z | 1,397,323 | <p>Do you definitely need it to be a queryset? If you only need it to be an iterable, a simple expression for your purposes is:</p>
<pre><code>profiles = [r.profile for r in thingie.relation_set.all()]
</code></pre>
<p>I'm not sure if a list comprehension counts as irritating iterating, but to me this is a perfectly intuitive, pythonic approach. Of course if you need it to be a queryset, you're going to do something messier with two queries, eg:</p>
<pre><code>relation_values = thingie.relation_set.all().values_list('pk', flat=True)
profiles = Profile.objects.filter(relation__in=relation_values)
</code></pre>
<p>See the "<a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#in" rel="nofollow">in</a>" documentation for more. I prefer the first approach, if you don't need a queryset. Oh and if you only want distinct profiles you can just take <code>set(profiles)</code> in the first approach or use the <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#distinct" rel="nofollow"><code>distinct()</code></a> queryset method in the second approach.</p>
| 2 | 2009-09-09T02:55:40Z | [
"python",
"django",
"django-queryset"
] |
Polymorphism in Django | 1,397,537 | <p>I have the following models. How do I get access to the <strong>unicode</strong> of the inheriting tables (Team and Athete) from the Entity table? I'm trying to display a list of all the Entities that displays 'name' if Team and 'firstname' and 'lastname' if Athlete.</p>
<pre><code>class Entity(models.Model):
entity_type_list = (('T', 'Team'), ('A', 'Athlete'))
type = models.CharField(max_length=2, choices=entity_type_list,default='P')
pictureurl = models.URLField('Picture Url', verify_exists=False, max_length=255, null=True, blank=True)
class Team(Entity):
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class Athlete(Entity):
firstname = models.CharField(max_length=100)
lastname = models.CharField(max_length=100)
def __unicode__(self):
return '%s %s' % (self.firstname, self.lastname)
</code></pre>
| 1 | 2009-09-09T04:34:18Z | 1,397,598 | <p>Loop over all the entities... if entity.<strong>class</strong> == 'Athlete' and entity.firstname and entity.lastname: blah</p>
<p>Hope this helps.</p>
<p>Edit: hmmm looks like I forgot about actually getting the combined list of both entities. Not sure I know of a slick way to do that.</p>
| 0 | 2009-09-09T04:54:44Z | [
"python",
"django",
"inheritance"
] |
Polymorphism in Django | 1,397,537 | <p>I have the following models. How do I get access to the <strong>unicode</strong> of the inheriting tables (Team and Athete) from the Entity table? I'm trying to display a list of all the Entities that displays 'name' if Team and 'firstname' and 'lastname' if Athlete.</p>
<pre><code>class Entity(models.Model):
entity_type_list = (('T', 'Team'), ('A', 'Athlete'))
type = models.CharField(max_length=2, choices=entity_type_list,default='P')
pictureurl = models.URLField('Picture Url', verify_exists=False, max_length=255, null=True, blank=True)
class Team(Entity):
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class Athlete(Entity):
firstname = models.CharField(max_length=100)
lastname = models.CharField(max_length=100)
def __unicode__(self):
return '%s %s' % (self.firstname, self.lastname)
</code></pre>
| 1 | 2009-09-09T04:34:18Z | 1,397,610 | <p>I answered a similar question a while ago. Have a look, I think one of the answers probably solves your problem as well.</p>
<p><a href="http://stackoverflow.com/questions/929029/how-do-i-access-the-child-classes-of-an-object-in-django-without-knowing-the-name">http://stackoverflow.com/questions/929029/how-do-i-access-the-child-classes-of-an-object-in-django-without-knowing-the-name</a></p>
<p>My answer from there was to add this to the parent class:</p>
<pre><code>def get_children(self):
rel_objs = self._meta.get_all_related_objects()
return [getattr(self, x.get_accessor_name()) for x in rel_objs if x.model != type(self)]
</code></pre>
<p>Then you can call that function to get the children objects (in your case you will only have one) and then call the unicode function from that object.</p>
| 0 | 2009-09-09T04:57:51Z | [
"python",
"django",
"inheritance"
] |
Polymorphism in Django | 1,397,537 | <p>I have the following models. How do I get access to the <strong>unicode</strong> of the inheriting tables (Team and Athete) from the Entity table? I'm trying to display a list of all the Entities that displays 'name' if Team and 'firstname' and 'lastname' if Athlete.</p>
<pre><code>class Entity(models.Model):
entity_type_list = (('T', 'Team'), ('A', 'Athlete'))
type = models.CharField(max_length=2, choices=entity_type_list,default='P')
pictureurl = models.URLField('Picture Url', verify_exists=False, max_length=255, null=True, blank=True)
class Team(Entity):
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class Athlete(Entity):
firstname = models.CharField(max_length=100)
lastname = models.CharField(max_length=100)
def __unicode__(self):
return '%s %s' % (self.firstname, self.lastname)
</code></pre>
| 1 | 2009-09-09T04:34:18Z | 1,397,616 | <p>I am not very clear what you want to do, but in any case you can add a criteria in dervied class instead of checking <strong>unicode</strong> method of derived classes</p>
<p>e.g. you can ask the class isTypeA ? or why don't you check the type?</p>
| 0 | 2009-09-09T04:58:52Z | [
"python",
"django",
"inheritance"
] |
Polymorphism in Django | 1,397,537 | <p>I have the following models. How do I get access to the <strong>unicode</strong> of the inheriting tables (Team and Athete) from the Entity table? I'm trying to display a list of all the Entities that displays 'name' if Team and 'firstname' and 'lastname' if Athlete.</p>
<pre><code>class Entity(models.Model):
entity_type_list = (('T', 'Team'), ('A', 'Athlete'))
type = models.CharField(max_length=2, choices=entity_type_list,default='P')
pictureurl = models.URLField('Picture Url', verify_exists=False, max_length=255, null=True, blank=True)
class Team(Entity):
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class Athlete(Entity):
firstname = models.CharField(max_length=100)
lastname = models.CharField(max_length=100)
def __unicode__(self):
return '%s %s' % (self.firstname, self.lastname)
</code></pre>
| 1 | 2009-09-09T04:34:18Z | 1,398,317 | <p>This is a little ugly, but I think it should work:</p>
<pre><code>entities = Entity.objects.all()
for entity in entities:
try:
print entity.team
except:
print entity.athlete
</code></pre>
<p>Check out <a href="http://docs.djangoproject.com/en/1.0/topics/db/models/#id7" rel="nofollow">http://docs.djangoproject.com/en/1.0/topics/db/models/#id7</a> for more on multi-table inheritance. Just be careful, because the Django ORM is inevitably a leaky abstraction and things you might normally do with objects can get you in trouble, or do unexpected things.</p>
| 0 | 2009-09-09T08:30:02Z | [
"python",
"django",
"inheritance"
] |
Polymorphism in Django | 1,397,537 | <p>I have the following models. How do I get access to the <strong>unicode</strong> of the inheriting tables (Team and Athete) from the Entity table? I'm trying to display a list of all the Entities that displays 'name' if Team and 'firstname' and 'lastname' if Athlete.</p>
<pre><code>class Entity(models.Model):
entity_type_list = (('T', 'Team'), ('A', 'Athlete'))
type = models.CharField(max_length=2, choices=entity_type_list,default='P')
pictureurl = models.URLField('Picture Url', verify_exists=False, max_length=255, null=True, blank=True)
class Team(Entity):
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class Athlete(Entity):
firstname = models.CharField(max_length=100)
lastname = models.CharField(max_length=100)
def __unicode__(self):
return '%s %s' % (self.firstname, self.lastname)
</code></pre>
| 1 | 2009-09-09T04:34:18Z | 1,640,076 | <p>From pure Python, you can use the <code>isinstance</code> function:</p>
<pre><code>class Entity:
def __init__(self):
if isinstance(self, Team):
print 'is team'
elif isinstance(self, Athlete):
print 'is athlete'
class Team(Entity):
def __unicode__(self):
return 'Team'
class Athlete(Entity):
def __unicode__(self):
return 'Athlete'
</code></pre>
| 1 | 2009-10-28T20:57:39Z | [
"python",
"django",
"inheritance"
] |
Polymorphism in Django | 1,397,537 | <p>I have the following models. How do I get access to the <strong>unicode</strong> of the inheriting tables (Team and Athete) from the Entity table? I'm trying to display a list of all the Entities that displays 'name' if Team and 'firstname' and 'lastname' if Athlete.</p>
<pre><code>class Entity(models.Model):
entity_type_list = (('T', 'Team'), ('A', 'Athlete'))
type = models.CharField(max_length=2, choices=entity_type_list,default='P')
pictureurl = models.URLField('Picture Url', verify_exists=False, max_length=255, null=True, blank=True)
class Team(Entity):
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class Athlete(Entity):
firstname = models.CharField(max_length=100)
lastname = models.CharField(max_length=100)
def __unicode__(self):
return '%s %s' % (self.firstname, self.lastname)
</code></pre>
| 1 | 2009-09-09T04:34:18Z | 1,966,064 | <p>If I undestand correctly, you are simply asking how to call the <code>__unicode__</code> method of a given object. </p>
<p>Use <code>unicode(instance)</code> and depending on the type of entity, the appropriate implementation will be called polymorphically.</p>
| 0 | 2009-12-27T14:27:33Z | [
"python",
"django",
"inheritance"
] |
Polymorphism in Django | 1,397,537 | <p>I have the following models. How do I get access to the <strong>unicode</strong> of the inheriting tables (Team and Athete) from the Entity table? I'm trying to display a list of all the Entities that displays 'name' if Team and 'firstname' and 'lastname' if Athlete.</p>
<pre><code>class Entity(models.Model):
entity_type_list = (('T', 'Team'), ('A', 'Athlete'))
type = models.CharField(max_length=2, choices=entity_type_list,default='P')
pictureurl = models.URLField('Picture Url', verify_exists=False, max_length=255, null=True, blank=True)
class Team(Entity):
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class Athlete(Entity):
firstname = models.CharField(max_length=100)
lastname = models.CharField(max_length=100)
def __unicode__(self):
return '%s %s' % (self.firstname, self.lastname)
</code></pre>
| 1 | 2009-09-09T04:34:18Z | 1,978,733 | <p>I don't believe you have to do anything. If <code>Entity</code> is never instantiated directly, you will never call the non-existent <code>Entity.__unicode__</code> method. However, if you'd like to play it save, you could add a stub method in your <code>Entity</code> class:</p>
<pre><code>class Entity(models.Model):
def __unicode__(self):
pass
class Team(Entity):
def __unicode__(self):
return self.name
class Athlete(Entity):
def __unicode__(self):
return '%s %s' % (self.firstname, self.lastname)
</code></pre>
<p>You are now assured that any class which inherits from <code>Entity</code> will have a <code>__unicode__</code> method, and you can simply traverse them:</p>
<pre><code>for thing in [TeamA(), AthleteA(), TeamB(), AthleteB()]:
print unicode(thing)
</code></pre>
| 0 | 2009-12-30T06:36:34Z | [
"python",
"django",
"inheritance"
] |
Polymorphism in Django | 1,397,537 | <p>I have the following models. How do I get access to the <strong>unicode</strong> of the inheriting tables (Team and Athete) from the Entity table? I'm trying to display a list of all the Entities that displays 'name' if Team and 'firstname' and 'lastname' if Athlete.</p>
<pre><code>class Entity(models.Model):
entity_type_list = (('T', 'Team'), ('A', 'Athlete'))
type = models.CharField(max_length=2, choices=entity_type_list,default='P')
pictureurl = models.URLField('Picture Url', verify_exists=False, max_length=255, null=True, blank=True)
class Team(Entity):
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class Athlete(Entity):
firstname = models.CharField(max_length=100)
lastname = models.CharField(max_length=100)
def __unicode__(self):
return '%s %s' % (self.firstname, self.lastname)
</code></pre>
| 1 | 2009-09-09T04:34:18Z | 1,996,019 | <p>This <a href="http://stackoverflow.com/questions/929029/how-do-i-access-the-child-classes-of-an-object-in-django-without-knowing-the-name/929982#929982">answer from Carl Meyer</a> to the question mentioned earlier by Paul McMillan might be what your looking for. A subtlety to this problem not captured in some of the answers is how to get at derived class instances from a QuerySet on Entity.</p>
<p><strong>The Problem</strong></p>
<pre><code>for entity in Entity.objects.all()
print unicode(entity) # Calls the Entity class unicode, which is not what you want.
</code></pre>
<p><strong>A Solution</strong></p>
<p>Use the <code>InheritanceCastModel</code> mixin in the answer linked above as a base class for Entity. You can then cast from Entity instances to the actual derived class instances. This is particularly handy when you want to use querysets on your parent class (Entity) but access the derived class instances. </p>
<pre><code>class Entity(InheritanceCastModel):
# your model definition. You can get rid of the entity_type_list and type, as the
# real_type provided by InheritanceCastModel provides this info
class Athlete(Entity):
# unchanged
class Team(Entity):
# unchanged
for entity in Entity.objects.all():
actual_entity = entity.cast()
print unicode(actual_entity) # actual entity is a a Team or Athlete
</code></pre>
| 5 | 2010-01-03T19:35:06Z | [
"python",
"django",
"inheritance"
] |
embedding plot within Qt gui | 1,397,553 | <p>How do you embed a vpython plot (animated) within your Qt GUI? so that it has its own display area and would not need to created a new window anymore.</p>
| 2 | 2009-09-09T04:40:56Z | 1,397,627 | <p>vpython's <a href="http://vpython.org/contents/FAQ.html" rel="nofollow">FAQs</a> claim that vpython's architecture make any embedding a problem...:</p>
<p><strong>Q: Is there a way to embed VPython in another environment?</strong></p>
<blockquote>
<p>This is difficult because VPython has
two threads, your computational thread
and a rendering thread which about 25
times per second paints the scene
using the current attributes of the
graphics objects. However, Stef
Mientki has managed to embed VPython
in a wxPython window on Windows; see
the contributed section.</p>
</blockquote>
<p>So if with wxPython it takes heroic efforts ("has managed to" doesn't sound like a trivial achievement;-) AND only works on a single platform, I fear it won't be any easier with Qt... one hard, uphill slog separately on each and every single platform.</p>
<p>If you're up for a SERIOUS challenge, deeply familiar with vpython, reasonably familiar with Qt, and acquainted with the underlying window-level architecture on all platforms you care about (and with a minor in wxPython), the place to start is <a href="http://mientki.ruhosting.nl/data%5Fwww/pylab%5Fworks/pw%5Fvpython%5Fdocking.html" rel="nofollow">Mientki</a>'s amazing contribution. He's actually working well below wxPython's level of abstraction, and in terms of <code>win32gui</code> calls, <code>win32con</code> constants, plus "a finite state-machine, clocked by a wx.Timer" at 100 milliseconds (though he does admit that the result from the latter Frankenstein surgery is... "not perfect";-). Extremely similar approaches should see you home (in a similarly "not perfect" way) on any other framework on Windows, including Qt.</p>
<p>However, nobody's yet offered any ports of this to Mac OS X, nor to any window manager of the many that are popular on Linux and Unix-like architectures (I'm not sure whether the feat could be achieved just at xlib level -- window decoration aspects do seem to be involved, and in the X11 world those DO tend to need window manager cooperation).</p>
<p>So, the literal answer to your question is, "with a huge amount of work requiring lots of skills and/or incredible perseverance, and probably in a platform-dependent way that will require redoing on each and every platform of interest"... sorry to be the bearer of pretty bad news, but I prefer to call them as I see them.</p>
| 3 | 2009-09-09T05:01:18Z | [
"python",
"user-interface",
"qt"
] |
embedding plot within Qt gui | 1,397,553 | <p>How do you embed a vpython plot (animated) within your Qt GUI? so that it has its own display area and would not need to created a new window anymore.</p>
| 2 | 2009-09-09T04:40:56Z | 1,414,819 | <p>I contacted maintainer of VPython and he confirmed, that he is not aware of any working solution where Visual is embedded into QT window.</p>
<p>That turned me to try VTK and so far I'm pretty happy, no problem with using VTK within PyQT framework.</p>
| 1 | 2009-09-12T10:30:49Z | [
"python",
"user-interface",
"qt"
] |
how to recover the binary stream(original form) from radix 64 encoding | 1,397,799 | <p>how to get the actual public key i.e its binary form i.e without radix 64 conversion .i need to extract the public key from radix64 encoding .the pgp server gives me the key in radix 64 format now i have to extract the public key from it.</p>
| 0 | 2009-09-09T06:08:13Z | 1,397,814 | <pre><code>import base64
decoded_bytes = base64.b64decode(ascii_chars)
</code></pre>
| 2 | 2009-09-09T06:14:38Z | [
"python",
"encoding"
] |
how to recover the binary stream(original form) from radix 64 encoding | 1,397,799 | <p>how to get the actual public key i.e its binary form i.e without radix 64 conversion .i need to extract the public key from radix64 encoding .the pgp server gives me the key in radix 64 format now i have to extract the public key from it.</p>
| 0 | 2009-09-09T06:08:13Z | 1,397,861 | <p>base64_encoded_data.decode('base64')</p>
| 0 | 2009-09-09T06:32:06Z | [
"python",
"encoding"
] |
How to read formatted input in python? | 1,397,827 | <p>I want to read from stdin five numbers entered as follows:</p>
<p>3, 4, 5, 1, 8</p>
<p>into seperate variables a,b,c,d & e.</p>
<p>How do I do this in python?</p>
<p>I tried this:</p>
<pre><code>import string
a=input()
b=a.split(', ')
</code></pre>
<p>for two integers, but it does not work. I get:</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\Desktop\comb.py", line 3, in <module>
b=a.split(', ')
AttributeError: 'tuple' object has no attribute 'split'
</code></pre>
<p>How to do this? and suppose I have not a fixed but a variable number n integers. Then?</p>
| 7 | 2009-09-09T06:19:59Z | 1,397,838 | <p><strong>Under Python 2.x only</strong> (*)</p>
<p>after a = input()</p>
<p>a is a tuple with the 5 values readily parsed! </p>
<p>A quick way to assign these 5 values is</p>
<pre><code>a, b, c, d, e = a
</code></pre>
<p>(*) with Python version 3.0? or for sure 3.1, input() works more like the raw_input() method of 2.x, which makes it less confusing. (thank you mshsayem to point this out!)</p>
| 2 | 2009-09-09T06:23:38Z | [
"python",
"input"
] |
How to read formatted input in python? | 1,397,827 | <p>I want to read from stdin five numbers entered as follows:</p>
<p>3, 4, 5, 1, 8</p>
<p>into seperate variables a,b,c,d & e.</p>
<p>How do I do this in python?</p>
<p>I tried this:</p>
<pre><code>import string
a=input()
b=a.split(', ')
</code></pre>
<p>for two integers, but it does not work. I get:</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\Desktop\comb.py", line 3, in <module>
b=a.split(', ')
AttributeError: 'tuple' object has no attribute 'split'
</code></pre>
<p>How to do this? and suppose I have not a fixed but a variable number n integers. Then?</p>
| 7 | 2009-09-09T06:19:59Z | 1,397,841 | <p>Use <a href="http://docs.python.org/library/functions.html#raw%5Finput"><code>raw_input()</code></a> instead of <code>input()</code>.</p>
<pre><code># Python 2.5.4
>>> a = raw_input()
3, 4, 5
>>> a
'3, 4, 5'
>>> b = a.split(', ')
>>> b
['3', '4', '5']
>>> [s.strip() for s in raw_input().split(",")] # one liner
3, 4, 5
['3', '4', '5']
</code></pre>
<p>The misleadingly names <a href="http://docs.python.org/library/functions.html#input"><code>input</code></a> function does not do what you'd expect it to. It actually evaluates the input from stdin as python code.</p>
<p>In your case it turns out that what you then have is a tuple of numbers in <code>a</code>, all parsed and ready for work, but generally you don't really want to use this curious side effect. Other inputs can cause any number of things to happen.</p>
<p>Incidentally, in Python 3 they fixed this, and now the <a href="http://docs.python.org/3.1/library/functions.html#input"><code>input</code></a> function does what you'd expect.</p>
<p>Two more things:</p>
<ol>
<li>You don't need to <code>import string</code> to do simple string manipulations. </li>
<li>Like mjv <a href="http://#1397838">said</a>, to split a tuple or a list into several variables, you can 'unpack' it. This will not be feasible if you don't know how long the list will be, though.</li>
</ol>
<p>Unpacking:</p>
<pre><code>>>> l = (1,2,3,4,5)
>>> a,b,c,d,e = l
>>> e
5
</code></pre>
| 15 | 2009-09-09T06:24:52Z | [
"python",
"input"
] |
How to read formatted input in python? | 1,397,827 | <p>I want to read from stdin five numbers entered as follows:</p>
<p>3, 4, 5, 1, 8</p>
<p>into seperate variables a,b,c,d & e.</p>
<p>How do I do this in python?</p>
<p>I tried this:</p>
<pre><code>import string
a=input()
b=a.split(', ')
</code></pre>
<p>for two integers, but it does not work. I get:</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\Desktop\comb.py", line 3, in <module>
b=a.split(', ')
AttributeError: 'tuple' object has no attribute 'split'
</code></pre>
<p>How to do this? and suppose I have not a fixed but a variable number n integers. Then?</p>
| 7 | 2009-09-09T06:19:59Z | 1,397,847 | <p>If you print out a (the variable containing your input) you will find out, that a already contains a tuple. You do not have to split the contents.</p>
<blockquote>
<p>>>> a = input()<br />
3, 4, 5, 1, 8<br />
>>> print(a)<br />
(3, 4, 5, 1, 8)<br />
>>> type(a)<br />
<type 'tuple'><br />
>>> a[0]<br />
3<br />
>>> len(a)<br />
5</p>
</blockquote>
| 0 | 2009-09-09T06:27:46Z | [
"python",
"input"
] |
How to read formatted input in python? | 1,397,827 | <p>I want to read from stdin five numbers entered as follows:</p>
<p>3, 4, 5, 1, 8</p>
<p>into seperate variables a,b,c,d & e.</p>
<p>How do I do this in python?</p>
<p>I tried this:</p>
<pre><code>import string
a=input()
b=a.split(', ')
</code></pre>
<p>for two integers, but it does not work. I get:</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\Desktop\comb.py", line 3, in <module>
b=a.split(', ')
AttributeError: 'tuple' object has no attribute 'split'
</code></pre>
<p>How to do this? and suppose I have not a fixed but a variable number n integers. Then?</p>
| 7 | 2009-09-09T06:19:59Z | 2,591,151 | <pre><code>in = eval(input())
a, b, c, d, e = in
</code></pre>
| -2 | 2010-04-07T09:09:30Z | [
"python",
"input"
] |
What is the simplest way to implement a remote FIFO queue as a Python GAE application? | 1,397,864 | <p>What is the simplest way to implement a remote FIFO queue as a Python GAE application and then push/pull name-value pair dictionaries to and from it? </p>
<p>For example, when an http get is made to the GAE application, the GAE app would return the oldest collection of name-value pairs that were posted to the app which have not been previously pulled from the queue. These name-value pairs would then be re-instantiated as a dictionary on the client side. urllib.urlencode provides a simple mechanism to encode dictionaries as parameters, but what is the similarly simple approach to decode parameters into dictionaries when you http "get" them? When there are no items in the queue, the GAE app should return a null or some other more appropriate identifier the client could respond to. </p>
<pre><code>#A local python script
import urllib
targetURL="http://myapp.appspot.com/queue"
#Push to dictionary to GAE queue
params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
f = urllib.urlopen(targetURL, params)
print f.read()
params = urllib.urlencode({'foo': 1, 'bar': 2})
f = urllib.urlopen(targetURL, params)
print f.read()
#Pull oldest set of name-value pairs from the GAE queue and create a local dictionary from them.
#f = urllib.urlopen(targetURL, â¦â¦)
#returnedDictionary = ????
</code></pre>
<p>What would the simplest way to implement this short GAE application? </p>
<pre><code>#queue.py a url handler in a GAE application.
# For posts, create an object from the posted name-value pairs and insert it into the queue as the newest item in the queue
# For gets, return the name-value pairs for the oldest object in the queue and remove the object from the queue.
# If there are no items in the queue, return null
</code></pre>
| 1 | 2009-09-09T06:33:35Z | 1,398,656 | <p>The below assumes you're using the webapp framework. </p>
<p>The simple answer is that you just use self.request.GET, which is a MultiDict (which you can treat as a dict in many cases) containing the form data sent to the request.</p>
<p>Note that HTTP allows form data to contain the same key multiple times; if what you want isn't really a dict but a list of key-value pairs that have been sent to your application, you can get such a list with self.request.GET.items() (see <a href="http://pythonpaste.org/webob/reference.html#query-post-variables" rel="nofollow">http://pythonpaste.org/webob/reference.html#query-post-variables</a> ) and then add these pairs to your queue.</p>
| 0 | 2009-09-09T09:53:16Z | [
"python",
"google-app-engine"
] |
What is the simplest way to implement a remote FIFO queue as a Python GAE application? | 1,397,864 | <p>What is the simplest way to implement a remote FIFO queue as a Python GAE application and then push/pull name-value pair dictionaries to and from it? </p>
<p>For example, when an http get is made to the GAE application, the GAE app would return the oldest collection of name-value pairs that were posted to the app which have not been previously pulled from the queue. These name-value pairs would then be re-instantiated as a dictionary on the client side. urllib.urlencode provides a simple mechanism to encode dictionaries as parameters, but what is the similarly simple approach to decode parameters into dictionaries when you http "get" them? When there are no items in the queue, the GAE app should return a null or some other more appropriate identifier the client could respond to. </p>
<pre><code>#A local python script
import urllib
targetURL="http://myapp.appspot.com/queue"
#Push to dictionary to GAE queue
params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
f = urllib.urlopen(targetURL, params)
print f.read()
params = urllib.urlencode({'foo': 1, 'bar': 2})
f = urllib.urlopen(targetURL, params)
print f.read()
#Pull oldest set of name-value pairs from the GAE queue and create a local dictionary from them.
#f = urllib.urlopen(targetURL, â¦â¦)
#returnedDictionary = ????
</code></pre>
<p>What would the simplest way to implement this short GAE application? </p>
<pre><code>#queue.py a url handler in a GAE application.
# For posts, create an object from the posted name-value pairs and insert it into the queue as the newest item in the queue
# For gets, return the name-value pairs for the oldest object in the queue and remove the object from the queue.
# If there are no items in the queue, return null
</code></pre>
| 1 | 2009-09-09T06:33:35Z | 1,398,981 | <p>Something along these lines:</p>
<pre><code>from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import run_wsgi_app
class QueueItem(db.Model):
created = db.DateTimeProperty(required=True, auto_now_add=True)
data = db.BlobProperty(required=True)
@staticmethod
def push(data):
"""Add a new queue item."""
return QueueItem(data=data).put()
@staticmethod
def pop():
"""Pop the oldest item off the queue."""
def _tx_pop(candidate_key):
# Try and grab the candidate key for ourselves. This will fail if
# another task beat us to it.
task = QueueItem.get(candidate_key)
if task:
task.delete()
return task
# Grab some tasks and try getting them until we find one that hasn't been
# taken by someone else ahead of us
while True:
candidate_keys = QueueItem.all(keys_only=True).order('created').fetch(10)
if not candidate_keys:
# No tasks in queue
return None
for candidate_key in candidate_keys:
task = db.run_in_transaction(_tx_pop, candidate_key)
if task:
return task
class QueueHandler(webapp.RequestHandler):
def get(self):
"""Pop a request off the queue and return it."""
self.response.headers['Content-Type'] = 'application/x-www-form-urlencoded'
task = QueueItem.pop()
if not task:
self.error(404)
else:
self.response.out.write(task.data)
def post(self):
"""Add a request to the queue."""
QueueItem.push(self.request.body)
</code></pre>
<p>One caveat: Because queue ordering relies on the timestamp, it's possible for tasks that arrive very close together on separate machines to be enqueued out-of-order, since there's no global clock (only NFS synced servers). Probably not a real problem, depending on your use-case, though.</p>
| 3 | 2009-09-09T11:00:20Z | [
"python",
"google-app-engine"
] |
Are Python extensions produced by Cython/Pyrex threadsafe? | 1,397,977 | <p>If not, is there a way I can guarantee thread safety by programming a certain way?</p>
<p>To clarify, when talking about "threadsafe,' I mean Python threads, not OS-level threads.</p>
| 4 | 2009-09-09T07:04:54Z | 1,399,771 | <p>Python's global interpreter lock means that only one thread can be active in the interpreter at any one time. However, once control is passed out to a C extension another thread can be active within the interpreter. Multiple threads can be created, and nothing prevents a thread from being interrupted within the middle of a critical section. N</p>
<p>on thread-safe code can be implemented within the interpreter, so nothing about code running within the interpreter is inherently thread safe. Code in C or Pyrex modules can still modify data structures that are visible to python code. Native code can, of course, also have threading issues with native data structures.</p>
<p>You can't guarantee thread safety beyond using appropriate design and synchronisation - the GIL on the python interpreter doesn't materially change this.</p>
| 2 | 2009-09-09T13:45:23Z | [
"python",
"thread-safety",
"cython",
"pyrex"
] |
Are Python extensions produced by Cython/Pyrex threadsafe? | 1,397,977 | <p>If not, is there a way I can guarantee thread safety by programming a certain way?</p>
<p>To clarify, when talking about "threadsafe,' I mean Python threads, not OS-level threads.</p>
| 4 | 2009-09-09T07:04:54Z | 1,400,401 | <p>It all depends on the interaction between your Cython code and Python's GIL, as documented in detail <a href="http://docs.cython.org/src/userguide/external_C_code.html#acquiring-and-releasing-the-gil" rel="nofollow">here</a>. If you don't do anything special, Cython-generated code will respect the GIL (as will a C-coded extension that doesn't use the GIL-releasing macros); that makes such code "as threadsafe as Python code" -- which isn't much, but is easier to handle than completely free-threading code (you still need to architect multi-threaded cooperation and synchronization, ideally with Queue instances but possibly with locking &c).</p>
<p>Code that has relinquished the GIL and not yet acquired it back MUST NOT in any way interact with the Python runtime and the objects that the Python runtime uses -- this goes for Cython just as well as for C-coded extensions. The upside of it is of course that such code can run on a separate core (until it needs to sync up or in any way communicate with the Python runtime again, of course).</p>
| 5 | 2009-09-09T15:27:58Z | [
"python",
"thread-safety",
"cython",
"pyrex"
] |
looping over all member variables of a class in python | 1,398,022 | <p>How do you get a list of all variables in a class thats iteratable? Kind of like locals(), but for a class</p>
<pre><code>class Example(object):
bool143 = True
bool2 = True
blah = False
foo = True
foobar2000 = False
def as_list(self)
ret = []
for field in XXX:
if getattr(self, field):
ret.append(field)
return ",".join(ret)
</code></pre>
<p>this should return</p>
<pre><code>>>> e = Example()
>>> e.as_list()
bool143, bool2, foo
</code></pre>
| 40 | 2009-09-09T07:15:42Z | 1,398,049 | <pre><code>>>> a = Example()
>>> dir(a)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__',
'__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
'__sizeof__', '__str__', '__subclasshook__', 'bool143', 'bool2', 'blah',
'foo', 'foobar2000', 'as_list']
</code></pre>
<p>—as you see, that gives you <em>all</em> attributes, so you'll have to filter out a little bit. But basically, <code>dir()</code> is what you're looking for.</p>
| 5 | 2009-09-09T07:21:44Z | [
"python"
] |
looping over all member variables of a class in python | 1,398,022 | <p>How do you get a list of all variables in a class thats iteratable? Kind of like locals(), but for a class</p>
<pre><code>class Example(object):
bool143 = True
bool2 = True
blah = False
foo = True
foobar2000 = False
def as_list(self)
ret = []
for field in XXX:
if getattr(self, field):
ret.append(field)
return ",".join(ret)
</code></pre>
<p>this should return</p>
<pre><code>>>> e = Example()
>>> e.as_list()
bool143, bool2, foo
</code></pre>
| 40 | 2009-09-09T07:15:42Z | 1,398,059 | <pre><code>dir(obj)
</code></pre>
<p>gives you all attributes of the object.
You need to filter out the members from methods etc yourself:</p>
<pre><code>class Example(object):
bool143 = True
bool2 = True
blah = False
foo = True
foobar2000 = False
members = [attr for attr in dir(Example()) if not callable(attr) and not attr.startswith("__")]
print members
</code></pre>
<p>Will give you:</p>
<pre><code>['blah', 'bool143', 'bool2', 'foo', 'foobar2000']
</code></pre>
| 52 | 2009-09-09T07:23:45Z | [
"python"
] |
looping over all member variables of a class in python | 1,398,022 | <p>How do you get a list of all variables in a class thats iteratable? Kind of like locals(), but for a class</p>
<pre><code>class Example(object):
bool143 = True
bool2 = True
blah = False
foo = True
foobar2000 = False
def as_list(self)
ret = []
for field in XXX:
if getattr(self, field):
ret.append(field)
return ",".join(ret)
</code></pre>
<p>this should return</p>
<pre><code>>>> e = Example()
>>> e.as_list()
bool143, bool2, foo
</code></pre>
| 40 | 2009-09-09T07:15:42Z | 1,398,673 | <p>The easy way to do this is to save all instances of the class in a <code>list</code>.</p>
<pre><code>a = Example()
b = Example()
all_examples = [ a, b ]
</code></pre>
<p>Objects don't spring into existence spontaneously. Some part of your program created them for a reason. The creation is done for a reason. Collecting them in a list can also be done for a reason.</p>
<p>If you use a factory, you can do this.</p>
<pre><code>class ExampleFactory( object ):
def __init__( self ):
self.all_examples= []
def __call__( self, *args, **kw ):
e = Example( *args, **kw )
self.all_examples.append( e )
return e
def all( self ):
return all_examples
makeExample= ExampleFactory()
a = makeExample()
b = makeExample()
for i in makeExample.all():
print i
</code></pre>
| 0 | 2009-09-09T09:57:34Z | [
"python"
] |
looping over all member variables of a class in python | 1,398,022 | <p>How do you get a list of all variables in a class thats iteratable? Kind of like locals(), but for a class</p>
<pre><code>class Example(object):
bool143 = True
bool2 = True
blah = False
foo = True
foobar2000 = False
def as_list(self)
ret = []
for field in XXX:
if getattr(self, field):
ret.append(field)
return ",".join(ret)
</code></pre>
<p>this should return</p>
<pre><code>>>> e = Example()
>>> e.as_list()
bool143, bool2, foo
</code></pre>
| 40 | 2009-09-09T07:15:42Z | 1,939,279 | <p>@truppo: your answer is almost correct, but callable will always return false since you're just passing in a string. You need something like the following:</p>
<pre><code>[attr for attr in dir(obj()) if not callable(getattr(obj(),attr)) and not attr.startswith("__")]
</code></pre>
<p>which will filter out functions</p>
| 18 | 2009-12-21T10:14:47Z | [
"python"
] |
looping over all member variables of a class in python | 1,398,022 | <p>How do you get a list of all variables in a class thats iteratable? Kind of like locals(), but for a class</p>
<pre><code>class Example(object):
bool143 = True
bool2 = True
blah = False
foo = True
foobar2000 = False
def as_list(self)
ret = []
for field in XXX:
if getattr(self, field):
ret.append(field)
return ",".join(ret)
</code></pre>
<p>this should return</p>
<pre><code>>>> e = Example()
>>> e.as_list()
bool143, bool2, foo
</code></pre>
| 40 | 2009-09-09T07:15:42Z | 13,286,863 | <p>If you want only the variables (without functions) use:</p>
<pre><code>vars(your_object)
</code></pre>
| 41 | 2012-11-08T10:10:22Z | [
"python"
] |
Initialize a string variable in Python: "" or None? | 1,398,164 | <p>Suppose I have a class with a <strong>string</strong> instance attribute.
Should I initialize this attribute with <strong>""</strong> value or <strong>None</strong>? Is either okay?</p>
<pre><code>def __init__(self, mystr="")
self.mystr = mystr
</code></pre>
<p>or</p>
<pre><code>def __init__(self, mystr=None)
self.mystr = mystr
</code></pre>
<p><strong>Edit</strong>: What I thought is that if I use <strong>""</strong> as an initial value, I "<em>declare</em>" a variable to be of <strong>string</strong> type. And then I won't be able to assign any other type to it later. Am I right?</p>
<p><strong>Edit</strong>: I think it's important to note here, that my suggestion was WRONG. And there is no problem to assign another type to a variable. I liked a comment of <strong>S.Lott</strong>: "<em>Since nothing in Python is "declared", you're not thinking about this the right way.</em>"</p>
| 30 | 2009-09-09T07:49:17Z | 1,398,175 | <p>Since both None and "" are false, you can do both. See <a href="http://docs.python.org/library/stdtypes.html#truth-value-testing" rel="nofollow">6.1. Truth Value Testing</a>.</p>
<p><strong>Edit</strong></p>
<p>To answer the question in your edit: No, you can assign a different type.</p>
<pre><code>>>> a = ""
>>> type(a)
<type 'str'>
>>> a = 1
>>> type(a)
<type 'int'>
</code></pre>
| 1 | 2009-09-09T07:51:45Z | [
"python"
] |
Initialize a string variable in Python: "" or None? | 1,398,164 | <p>Suppose I have a class with a <strong>string</strong> instance attribute.
Should I initialize this attribute with <strong>""</strong> value or <strong>None</strong>? Is either okay?</p>
<pre><code>def __init__(self, mystr="")
self.mystr = mystr
</code></pre>
<p>or</p>
<pre><code>def __init__(self, mystr=None)
self.mystr = mystr
</code></pre>
<p><strong>Edit</strong>: What I thought is that if I use <strong>""</strong> as an initial value, I "<em>declare</em>" a variable to be of <strong>string</strong> type. And then I won't be able to assign any other type to it later. Am I right?</p>
<p><strong>Edit</strong>: I think it's important to note here, that my suggestion was WRONG. And there is no problem to assign another type to a variable. I liked a comment of <strong>S.Lott</strong>: "<em>Since nothing in Python is "declared", you're not thinking about this the right way.</em>"</p>
| 30 | 2009-09-09T07:49:17Z | 1,398,177 | <p>It depends. If you want to distinguish between no parameter passed in at all, and an empty string passed in, you could use None.</p>
| 4 | 2009-09-09T07:52:13Z | [
"python"
] |
Initialize a string variable in Python: "" or None? | 1,398,164 | <p>Suppose I have a class with a <strong>string</strong> instance attribute.
Should I initialize this attribute with <strong>""</strong> value or <strong>None</strong>? Is either okay?</p>
<pre><code>def __init__(self, mystr="")
self.mystr = mystr
</code></pre>
<p>or</p>
<pre><code>def __init__(self, mystr=None)
self.mystr = mystr
</code></pre>
<p><strong>Edit</strong>: What I thought is that if I use <strong>""</strong> as an initial value, I "<em>declare</em>" a variable to be of <strong>string</strong> type. And then I won't be able to assign any other type to it later. Am I right?</p>
<p><strong>Edit</strong>: I think it's important to note here, that my suggestion was WRONG. And there is no problem to assign another type to a variable. I liked a comment of <strong>S.Lott</strong>: "<em>Since nothing in Python is "declared", you're not thinking about this the right way.</em>"</p>
| 30 | 2009-09-09T07:49:17Z | 1,398,178 | <p>If not having a value has a meaning in your program (e.g. an optional value), you should use None. That's its purpose anyway. </p>
<p>If the value must be provided by the caller of __init__, I would recommend not to initialize it.</p>
<p>If "" makes sense as a default value, use it.</p>
<p>In Python the type is deduced from the usage. Hence, you can change the type by just assigning a value of another type.</p>
<pre><code>>>> x = None
>>> print type(x)
<type 'NoneType'>
>>> x = "text"
>>> print type(x)
<type 'str'>
>>> x = 42
>>> print type(x)
<type 'int'>
</code></pre>
| 35 | 2009-09-09T07:52:45Z | [
"python"
] |
Initialize a string variable in Python: "" or None? | 1,398,164 | <p>Suppose I have a class with a <strong>string</strong> instance attribute.
Should I initialize this attribute with <strong>""</strong> value or <strong>None</strong>? Is either okay?</p>
<pre><code>def __init__(self, mystr="")
self.mystr = mystr
</code></pre>
<p>or</p>
<pre><code>def __init__(self, mystr=None)
self.mystr = mystr
</code></pre>
<p><strong>Edit</strong>: What I thought is that if I use <strong>""</strong> as an initial value, I "<em>declare</em>" a variable to be of <strong>string</strong> type. And then I won't be able to assign any other type to it later. Am I right?</p>
<p><strong>Edit</strong>: I think it's important to note here, that my suggestion was WRONG. And there is no problem to assign another type to a variable. I liked a comment of <strong>S.Lott</strong>: "<em>Since nothing in Python is "declared", you're not thinking about this the right way.</em>"</p>
| 30 | 2009-09-09T07:49:17Z | 1,398,180 | <p>Either is fine, though <code>None</code> is more common as a convention - <code>None</code> indicates that no value was passed for the optional parameter.</p>
<p>There <em>will</em> be times when "" is the correct default value to use - in my experience, those times occur less often.</p>
| 2 | 2009-09-09T07:53:28Z | [
"python"
] |
Initialize a string variable in Python: "" or None? | 1,398,164 | <p>Suppose I have a class with a <strong>string</strong> instance attribute.
Should I initialize this attribute with <strong>""</strong> value or <strong>None</strong>? Is either okay?</p>
<pre><code>def __init__(self, mystr="")
self.mystr = mystr
</code></pre>
<p>or</p>
<pre><code>def __init__(self, mystr=None)
self.mystr = mystr
</code></pre>
<p><strong>Edit</strong>: What I thought is that if I use <strong>""</strong> as an initial value, I "<em>declare</em>" a variable to be of <strong>string</strong> type. And then I won't be able to assign any other type to it later. Am I right?</p>
<p><strong>Edit</strong>: I think it's important to note here, that my suggestion was WRONG. And there is no problem to assign another type to a variable. I liked a comment of <strong>S.Lott</strong>: "<em>Since nothing in Python is "declared", you're not thinking about this the right way.</em>"</p>
| 30 | 2009-09-09T07:49:17Z | 1,398,418 | <p>Either <em>might</em> be fine, but I don't think there is a definite answer.</p>
<ul>
<li>If you want to indicate that the value has not been set, comparing with <code>None</code> is better than comparing with <code>""</code>, since <code>""</code> might be a valid value,</li>
<li>If you just want a default value, <code>""</code> is probably better, because its actually a string, and you can call string methods on it. If you went with <code>None</code>, these would lead to exceptions.</li>
<li>If you wish to indicate to future maintainers that a string is required here, <code>""</code> can help with that.</li>
</ul>
<h3>Complete side note:</h3>
<p>If you have a loop, say:</p>
<pre><code>def myfunc (self, mystr = ""):
for other in self.strs:
mystr = self.otherfunc (mystr, other)
</code></pre>
<p>then a potential future optimizer would know that <code>str</code> is always a string. If you used <code>None</code>, then it might not be a string until the first iteration, which would require loop unrolling to get the same effects. While this isn't a hypothetical (it comes up a lot in my PHP compiler) you should certainly never write your code to take this into account. I just thought it might be interesting :)</p>
| 4 | 2009-09-09T08:54:49Z | [
"python"
] |
Initialize a string variable in Python: "" or None? | 1,398,164 | <p>Suppose I have a class with a <strong>string</strong> instance attribute.
Should I initialize this attribute with <strong>""</strong> value or <strong>None</strong>? Is either okay?</p>
<pre><code>def __init__(self, mystr="")
self.mystr = mystr
</code></pre>
<p>or</p>
<pre><code>def __init__(self, mystr=None)
self.mystr = mystr
</code></pre>
<p><strong>Edit</strong>: What I thought is that if I use <strong>""</strong> as an initial value, I "<em>declare</em>" a variable to be of <strong>string</strong> type. And then I won't be able to assign any other type to it later. Am I right?</p>
<p><strong>Edit</strong>: I think it's important to note here, that my suggestion was WRONG. And there is no problem to assign another type to a variable. I liked a comment of <strong>S.Lott</strong>: "<em>Since nothing in Python is "declared", you're not thinking about this the right way.</em>"</p>
| 30 | 2009-09-09T07:49:17Z | 1,398,596 | <p>For lists or dicts, the answer is more clear,
according to <a href="http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#default-parameter-values" rel="nofollow">http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#default-parameter-values</a>
use None as default parameter.</p>
<p>But also for strings, a (empty) string object is instanciated at runtime for
the keyword parameter.</p>
<p>The cleanest way is probably:</p>
<pre><code>def myfunc(self, my_string=None):
self.my_string = my_string or "" # or a if-else-branch, ...
</code></pre>
| 1 | 2009-09-09T09:41:19Z | [
"python"
] |
Initialize a string variable in Python: "" or None? | 1,398,164 | <p>Suppose I have a class with a <strong>string</strong> instance attribute.
Should I initialize this attribute with <strong>""</strong> value or <strong>None</strong>? Is either okay?</p>
<pre><code>def __init__(self, mystr="")
self.mystr = mystr
</code></pre>
<p>or</p>
<pre><code>def __init__(self, mystr=None)
self.mystr = mystr
</code></pre>
<p><strong>Edit</strong>: What I thought is that if I use <strong>""</strong> as an initial value, I "<em>declare</em>" a variable to be of <strong>string</strong> type. And then I won't be able to assign any other type to it later. Am I right?</p>
<p><strong>Edit</strong>: I think it's important to note here, that my suggestion was WRONG. And there is no problem to assign another type to a variable. I liked a comment of <strong>S.Lott</strong>: "<em>Since nothing in Python is "declared", you're not thinking about this the right way.</em>"</p>
| 30 | 2009-09-09T07:49:17Z | 1,398,628 | <p>None is used to indicate "not set", whereas any other value is used to indicate a "default" value.</p>
<p>Hence, if your class copes with empty strings and you like it as a default value, use "". If your class needs to check if the variable was set at all, use None.</p>
<p>Notice that it doesn't matter if your variable is a string initially. You can change it to any other type/value at any other moment.</p>
| 5 | 2009-09-09T09:48:34Z | [
"python"
] |
Initialize a string variable in Python: "" or None? | 1,398,164 | <p>Suppose I have a class with a <strong>string</strong> instance attribute.
Should I initialize this attribute with <strong>""</strong> value or <strong>None</strong>? Is either okay?</p>
<pre><code>def __init__(self, mystr="")
self.mystr = mystr
</code></pre>
<p>or</p>
<pre><code>def __init__(self, mystr=None)
self.mystr = mystr
</code></pre>
<p><strong>Edit</strong>: What I thought is that if I use <strong>""</strong> as an initial value, I "<em>declare</em>" a variable to be of <strong>string</strong> type. And then I won't be able to assign any other type to it later. Am I right?</p>
<p><strong>Edit</strong>: I think it's important to note here, that my suggestion was WRONG. And there is no problem to assign another type to a variable. I liked a comment of <strong>S.Lott</strong>: "<em>Since nothing in Python is "declared", you're not thinking about this the right way.</em>"</p>
| 30 | 2009-09-09T07:49:17Z | 18,683,729 | <p>Another way to initialize an empty string is by using the built-in <code>str()</code> function with no arguments.</p>
<blockquote>
<p>str(object='')</p>
<p>Return a string containing a nicely printable representation of an object.</p>
<p>...</p>
<p>If no argument is given, returns the empty string, ''.</p>
</blockquote>
<p>In the original example, that would look like this:</p>
<pre><code>def __init__(self, mystr=str())
self.mystr = mystr
</code></pre>
<p>Personally, I believe that this better conveys your intentions.</p>
<p>Notice by the way that <code>str()</code> itself sets a default parameter value of <code>''</code>.</p>
| 1 | 2013-09-08T12:34:55Z | [
"python"
] |
Django: show list of many to many items in the admin interface | 1,398,606 | <p>This might be a simple question, but i can't seem to grasp it.</p>
<p>I have two simple models in models.py: Service and Host. Host.services has a m2m relationship with Service.
In other words, a host has several services and one service can reside on multiple hosts; a basic m2m.</p>
<p>models.py</p>
<pre><code>class Service(models.Model):
servicename = models.CharField(max_length=50)
def __unicode__(self):
return self.servicename
class Admin:
pass
class Host(models.Model):
#...
hostname = models.CharField(max_length=200)
services = models.ManyToManyField(Service)
#...
def get_services(self):
return self.services.all()
def __unicode__(self):
return self.hostname
class Admin:
pass
</code></pre>
<p>admin.py</p>
<pre><code>from cmdb.hosts.models import Host
from django.contrib import admin
class HostAdmin(admin.ModelAdmin):
list_display = ('get_services',)
admin.site.register(Host, HostAdmin)
</code></pre>
<p>Now when i open the page where all the host's columns are listed the 'service' column displays the output like:</p>
<p>Get services</p>
<p><code>[<Service: the_service-1>, <Service: the_service-2>]</code></p>
<p>Instead of:</p>
<p>Services</p>
<p>the_service-1</p>
<p>the_service-2
etc.</p>
<p>What am i doing wrong?
Thank you for reading my question.</p>
| 8 | 2009-09-09T09:43:11Z | 1,398,652 | <p>You should change <code>get_services</code> to something like:</p>
<pre><code>def get_services(self):
return "\n".join([s.servicename for s in self.services.all()])
</code></pre>
<p><strong>Update:</strong> Try using <code>\n</code> as the separator rather than <code><br/></code>, as the output of get_services is being escaped.</p>
| 19 | 2009-09-09T09:52:52Z | [
"python",
"django"
] |
Python: display the time in a different time zone | 1,398,674 | <p>Is there an elegant way to display the current time in another time zone?</p>
<p>I would like to have something with the general spirit of:</p>
<pre><code>cur=<Get the current time, perhaps datetime.datetime.now()>
print "Local time ", cur
print "Pacific time ", <something like cur.tz('PST')>
print "Israeli time ", <something like cur.tz('IST')>
</code></pre>
<p>Any ideas?</p>
| 16 | 2009-09-09T09:57:52Z | 1,398,729 | <p>You could use the <a href="http://pytz.sourceforge.net/">pytz</a> library:</p>
<pre><code>>>> from datetime import datetime, timedelta
>>> from pytz import timezone
>>> import pytz
>>> utc = pytz.utc
>>> utc.zone
'UTC'
>>> eastern = timezone('US/Eastern')
>>> eastern.zone
'US/Eastern'
>>> amsterdam = timezone('Europe/Amsterdam')
>>> fmt = '%Y-%m-%d %H:%M:%S %Z%z'
>>> loc_dt = eastern.localize(datetime(2002, 10, 27, 6, 0, 0))
>>> print loc_dt.strftime(fmt)
2002-10-27 06:00:00 EST-0500
>>> ams_dt = loc_dt.astimezone(amsterdam)
>>> ams_dt.strftime(fmt)
'2002-10-27 12:00:00 CET+0100'
</code></pre>
| 24 | 2009-09-09T10:10:43Z | [
"python",
"time",
"timezone"
] |
Python: display the time in a different time zone | 1,398,674 | <p>Is there an elegant way to display the current time in another time zone?</p>
<p>I would like to have something with the general spirit of:</p>
<pre><code>cur=<Get the current time, perhaps datetime.datetime.now()>
print "Local time ", cur
print "Pacific time ", <something like cur.tz('PST')>
print "Israeli time ", <something like cur.tz('IST')>
</code></pre>
<p>Any ideas?</p>
| 16 | 2009-09-09T09:57:52Z | 1,398,732 | <p>You can check <a href="http://stackoverflow.com/questions/1301493/python-timezones">this question</a>.</p>
<p>Or try using <a href="http://pytz.sourceforge.net/" rel="nofollow">pytz</a>. Here you can find an installation guide with some usage examples.</p>
| 0 | 2009-09-09T10:11:27Z | [
"python",
"time",
"timezone"
] |
Python: display the time in a different time zone | 1,398,674 | <p>Is there an elegant way to display the current time in another time zone?</p>
<p>I would like to have something with the general spirit of:</p>
<pre><code>cur=<Get the current time, perhaps datetime.datetime.now()>
print "Local time ", cur
print "Pacific time ", <something like cur.tz('PST')>
print "Israeli time ", <something like cur.tz('IST')>
</code></pre>
<p>Any ideas?</p>
| 16 | 2009-09-09T09:57:52Z | 1,398,742 | <p>One way, through the timezone setting of the C library, is</p>
<pre><code>>>> cur=time.time()
>>> os.environ["TZ"]="US/Pacific"
>>> time.tzset()
>>> time.strftime("%T %Z", time.localtime(cur))
'03:09:51 PDT'
>>> os.environ["TZ"]="GMT"
>>> time.strftime("%T %Z", time.localtime(cur))
'10:09:51 GMT'
</code></pre>
| 2 | 2009-09-09T10:12:15Z | [
"python",
"time",
"timezone"
] |
Python: display the time in a different time zone | 1,398,674 | <p>Is there an elegant way to display the current time in another time zone?</p>
<p>I would like to have something with the general spirit of:</p>
<pre><code>cur=<Get the current time, perhaps datetime.datetime.now()>
print "Local time ", cur
print "Pacific time ", <something like cur.tz('PST')>
print "Israeli time ", <something like cur.tz('IST')>
</code></pre>
<p>Any ideas?</p>
| 16 | 2009-09-09T09:57:52Z | 5,096,669 | <p>A simpler method:</p>
<pre><code>from datetime import datetime
from pytz import timezone
south_africa = timezone('Africa/Johannesburg')
sa_time = datetime.now(south_africa)
print sa_time.strftime('%Y-%m-%d_%H-%M-%S')
</code></pre>
| 37 | 2011-02-23T20:26:12Z | [
"python",
"time",
"timezone"
] |
Python: display the time in a different time zone | 1,398,674 | <p>Is there an elegant way to display the current time in another time zone?</p>
<p>I would like to have something with the general spirit of:</p>
<pre><code>cur=<Get the current time, perhaps datetime.datetime.now()>
print "Local time ", cur
print "Pacific time ", <something like cur.tz('PST')>
print "Israeli time ", <something like cur.tz('IST')>
</code></pre>
<p>Any ideas?</p>
| 16 | 2009-09-09T09:57:52Z | 31,286,366 | <p>This is my implementation:</p>
<pre><code>from datetime import datetime
from pytz import timezone
def local_time(zone='Asia/Jerusalem'):
other_zone = timezone(zone)
other_zone_time = datetime.now(other_zone)
return other_zone_time.strftime('%T')
</code></pre>
| 0 | 2015-07-08T07:39:29Z | [
"python",
"time",
"timezone"
] |
Python: display the time in a different time zone | 1,398,674 | <p>Is there an elegant way to display the current time in another time zone?</p>
<p>I would like to have something with the general spirit of:</p>
<pre><code>cur=<Get the current time, perhaps datetime.datetime.now()>
print "Local time ", cur
print "Pacific time ", <something like cur.tz('PST')>
print "Israeli time ", <something like cur.tz('IST')>
</code></pre>
<p>Any ideas?</p>
| 16 | 2009-09-09T09:57:52Z | 35,274,555 | <p>I need time info all time time, so I have this neat .py script on my server that lets me just select and deselect what time zones I want to display in order of east->west. </p>
<p>It prints like this:</p>
<pre><code>Australia/Sydney : 2016-02-09 03:52:29 AEDT+1100
Asia/Singapore : 2016-02-09 00:52:29 SGT+0800
Asia/Hong_Kong : 2016-02-09 00:52:29 HKT+0800
EET : 2016-02-08 18:52:29 EET+0200
CET : 2016-02-08 17:52:29 CET+0100 <- you are HERE
UTC : 2016-02-08 16:52:29 UTC+0000
Europe/London : 2016-02-08 16:52:29 GMT+0000
America/New_York : 2016-02-08 11:52:29 EST-0500
America/Los_Angeles : 2016-02-08 08:52:29 PST-0800
</code></pre>
<p>Here source code is one .py file on my github here:
<a href="https://github.com/SpiRaiL/timezone" rel="nofollow">https://github.com/SpiRaiL/timezone</a>
Or the direct file link:
<a href="https://raw.githubusercontent.com/SpiRaiL/timezone/master/timezone.py" rel="nofollow">https://raw.githubusercontent.com/SpiRaiL/timezone/master/timezone.py</a></p>
<p>In the file is a list like this:
Just put a 'p' in the places you want printed.
Put a 'h' for your own time zone if you want it specially marked.</p>
<pre><code>(' ','America/Adak'), (' ','Africa/Abidjan'), (' ','Atlantic/Azores'), (' ','GB'),
(' ','America/Anchorage'), (' ','Africa/Accra'), (' ','Atlantic/Bermuda'), (' ','GB-Eire'),
(' ','America/Anguilla'), (' ','Africa/Addis_Ababa'), (' ','Atlantic/Canary'), (' ','GMT'),
(' ','America/Antigua'), (' ','Africa/Algiers'), (' ','Atlantic/Cape_Verde'), (' ','GMT+0'),
(' ','America/Araguaina'), (' ','Africa/Asmara'), (' ','Atlantic/Faeroe'), (' ','GMT-0'),
(' ','America/Argentina/Buenos_Aires'), (' ','Africa/Asmera'), (' ','Atlantic/Faroe'), (' ','GMT0'),
(' ','America/Argentina/Catamarca'), (' ','Africa/Bamako'), (' ','Atlantic/Jan_Mayen'), (' ','Greenwich'),
(' ','America/Argentina/ComodRivadavia'), (' ','Africa/Bangui'), (' ','Atlantic/Madeira'), (' ','HST'),
(' ','America/Argentina/Cordoba'), (' ','Africa/Banjul'), (' ','Atlantic/Reykjavik'), (' ','Hongkong'),
</code></pre>
| 0 | 2016-02-08T16:32:56Z | [
"python",
"time",
"timezone"
] |
Problems with Snow Leopard, Django & PIL | 1,398,701 | <p>I am having some trouble getting Django & PIL work properly since upgrading to Snow Leopard.</p>
<p>I have installed freetype, libjpeg and then PIL, which tells me:</p>
<pre><code>--- TKINTER support ok
--- JPEG support ok
--- ZLIB (PNG/ZIP) support ok
--- FREETYPE2 support ok
</code></pre>
<p>but when I try to upload a jpeg through the django admin interface I get:</p>
<blockquote>
<p>Upload a valid image. The file you
uploaded was either not an image or a
corrupted image.</p>
</blockquote>
<p>It works fine with PNG files.</p>
<p>Any Ideas?</p>
| 5 | 2009-09-09T10:05:13Z | 1,413,877 | <p>Cato</p>
<p>I had the same experience with Leopard 10.5.x
Here is what I did to fix it, (may not work for you).</p>
<ol>
<li>Go to your PIL working folder (where you unzipped PIL)
cd to your build folder
cd to your lib.macosx-10.* folder (specific to your os)
remove *.so
cd back to your PIL build folder
(I logged in as su for this, but you can sudo these if you like)</li>
<li>python setup.py clean</li>
<li>python setup.py build</li>
<li>python setup.py install </li>
</ol>
<p>This rebuilds PIL clean. The reason your jpeg reports ok, is that it just looks for the existence of the jpeg lib files, but not the dependency that happens from a clean build and install of PIL.</p>
<p>Hope this solves your problem, mine was more likely related to the order of installation but maybe it will help...</p>
<ul>
<li>Ken</li>
</ul>
| 14 | 2009-09-12T00:43:05Z | [
"python",
"django",
"osx-snow-leopard",
"python-imaging-library",
"libjpeg"
] |
Problems with Snow Leopard, Django & PIL | 1,398,701 | <p>I am having some trouble getting Django & PIL work properly since upgrading to Snow Leopard.</p>
<p>I have installed freetype, libjpeg and then PIL, which tells me:</p>
<pre><code>--- TKINTER support ok
--- JPEG support ok
--- ZLIB (PNG/ZIP) support ok
--- FREETYPE2 support ok
</code></pre>
<p>but when I try to upload a jpeg through the django admin interface I get:</p>
<blockquote>
<p>Upload a valid image. The file you
uploaded was either not an image or a
corrupted image.</p>
</blockquote>
<p>It works fine with PNG files.</p>
<p>Any Ideas?</p>
| 5 | 2009-09-09T10:05:13Z | 2,661,327 | <p>As a follow up to Ken's response, I had the same problem with Snow Leopard 10.6.x which was caused by installing PIL before libjpeg. After installing libjpeg, I reinstalled PIL by doing the following.</p>
<ol>
<li>cd to PIL working folder</li>
<li>python setup.py clean</li>
<li>python setup.py build_ext -i <-- This rebuilds PIL</li>
<li>python selftest.py - Run the selftest to confirm PIL is installed ok</li>
<li>python setup.py install</li>
</ol>
| 5 | 2010-04-18T06:16:25Z | [
"python",
"django",
"osx-snow-leopard",
"python-imaging-library",
"libjpeg"
] |
Problems with Snow Leopard, Django & PIL | 1,398,701 | <p>I am having some trouble getting Django & PIL work properly since upgrading to Snow Leopard.</p>
<p>I have installed freetype, libjpeg and then PIL, which tells me:</p>
<pre><code>--- TKINTER support ok
--- JPEG support ok
--- ZLIB (PNG/ZIP) support ok
--- FREETYPE2 support ok
</code></pre>
<p>but when I try to upload a jpeg through the django admin interface I get:</p>
<blockquote>
<p>Upload a valid image. The file you
uploaded was either not an image or a
corrupted image.</p>
</blockquote>
<p>It works fine with PNG files.</p>
<p>Any Ideas?</p>
| 5 | 2009-09-09T10:05:13Z | 5,903,771 | <p>I ran into a similar issue while on Ubuntu 8.04. I was able to get myself out of it by simply re-issuing my PIL install (via pip):</p>
<pre><code>pip install PIL --upgrade
</code></pre>
<p>Not sure what the issue was but I suspect it's similar to what others here reported.</p>
| 3 | 2011-05-05T20:37:54Z | [
"python",
"django",
"osx-snow-leopard",
"python-imaging-library",
"libjpeg"
] |
using cookies with twisted.web.client | 1,398,740 | <p>I'm trying to make a web client application using twisted but having some trouble with cookies. Does anyone have an example I can look at?</p>
| 3 | 2009-09-09T10:12:10Z | 1,399,641 | <p>Turns out there is no easy way afaict
The headers are stored in twisted.web.client.HTTPClientFactory but not available from twisted.web.client.getPage() which is the function designed for pulling back a web page. I ended up rewriting the function: </p>
<pre><code>from twisted.web import client
def getPage(url, contextFactory=None, *args, **kwargs):
fact = client._makeGetterFactory(
url,
HTTPClientFactory,
contextFactory=contextFactory,
*args, **kwargs)
return fact.deferred.addCallback(lambda data: (data, fact.response_headers))
</code></pre>
| 2 | 2009-09-09T13:18:38Z | [
"python",
"cookies",
"twisted"
] |
using cookies with twisted.web.client | 1,398,740 | <p>I'm trying to make a web client application using twisted but having some trouble with cookies. Does anyone have an example I can look at?</p>
| 3 | 2009-09-09T10:12:10Z | 1,687,928 | <p>While it's true that <code>getPage</code> doesn't easily allow direct access to the request or response headers (just one example of how <code>getPage</code> isn't a super awesome API), cookies are actually supported.</p>
<pre><code>cookies = {cookies: tosend}
d = getPage(url, cookies=cookies)
def cbPage(result):
print 'Look at my cookies:', cookies
d.addCallback(cbPage)
</code></pre>
<p>Any cookies in the dictionary when it is passed to <code>getPage</code> will be sent. Any new cookies the server sets in response to the request will be added to the dictionary.</p>
<p>You might have missed this feature when looking at <code>getPage</code> because the <code>getPage</code> signature doesn't have a <code>cookies</code> parameter anywhere in it! However, it does take <code>**kwargs</code>, and this is how <code>cookies</code> is supported: any extra arguments passed to <code>getPage</code> that it doesn't know about itself, it passes on to <code>HTTPClientFactory.__init__</code>. Take a look at that method's signature to see all of the things you can pass to <code>getPage</code>.</p>
| 7 | 2009-11-06T14:23:05Z | [
"python",
"cookies",
"twisted"
] |
using cookies with twisted.web.client | 1,398,740 | <p>I'm trying to make a web client application using twisted but having some trouble with cookies. Does anyone have an example I can look at?</p>
| 3 | 2009-09-09T10:12:10Z | 6,163,306 | <pre><code>from twisted.internet import reactor
from twisted.web import client
def getPage(url, contextFactory=None, *args, **kwargs):
return client._makeGetterFactory(
url,
CustomHTTPClientFactory,
contextFactory=contextFactory,
*args, **kwargs).deferred
class CustomHTTPClientFactory(client.HTTPClientFactory):
def __init__(self,url, method='GET', postdata=None, headers=None,
agent="Twisted PageGetter", timeout=0, cookies=None,
followRedirect=1, redirectLimit=20):
client.HTTPClientFactory.__init__(self, url, method, postdata,
headers, agent, timeout, cookies,
followRedirect, redirectLimit)
def page(self, page):
if self.waiting:
self.waiting = 0
res = {}
res['page'] = page
res['headers'] = self.response_headers
res['cookies'] = self.cookies
self.deferred.callback(res)
if __name__ == '__main__':
def cback(result):
for k in result:
print k, '==>', result[k]
reactor.stop()
def eback(error):
print error.getTraceback()
reactor.stop()
d = getPage('http://example.com', agent='example web client',
cookies={ 'some' : 'cookie' } )
d.addCallback(cback)
d.addErrback(eback)
reactor.run()
</code></pre>
| 1 | 2011-05-28T17:39:33Z | [
"python",
"cookies",
"twisted"
] |
Downloading file using IE from python | 1,398,780 | <p>I'm trying to download file with Python using IE:</p>
<pre><code>from win32com.client import DispatchWithEvents
class EventHandler(object):
def OnDownloadBegin(self):
pass
ie = DispatchWithEvents("InternetExplorer.Application", EventHandler)
ie.Visible = 0
ie.Navigate('http://website/file.xml')
</code></pre>
<p>After this, I'm getting a window asking the user where to save the file. How can I save this file automatically from python?</p>
<p>I need to <strong>use some browser</strong>, not urllib or mechanize, because <strong>before downloading file I need to interact with some ajax functionality</strong>.</p>
| 7 | 2009-09-09T10:18:42Z | 1,398,794 | <p>You don't need to use IE. You could use something like</p>
<pre><code>import urllib2
data = urllib2.urlopen("http://website/file.xml").read()
</code></pre>
<p><strong>Update:</strong> I see you've updated your question. If you need to use a browser, then clearly this answer isn't appropriate for you.</p>
<p><strong>Further update:</strong> When you click the button which is generated by JavaScript, if the URL retrieved is <em>not</em> computed by the JavaScript, and only the button is, then you can perhaps retrieve that URL via <code>urllib2</code>. On the other hand, you might also need to pass a session cookie from your authenticated session.</p>
| 1 | 2009-09-09T10:22:41Z | [
"python",
"internet-explorer",
"com"
] |
Downloading file using IE from python | 1,398,780 | <p>I'm trying to download file with Python using IE:</p>
<pre><code>from win32com.client import DispatchWithEvents
class EventHandler(object):
def OnDownloadBegin(self):
pass
ie = DispatchWithEvents("InternetExplorer.Application", EventHandler)
ie.Visible = 0
ie.Navigate('http://website/file.xml')
</code></pre>
<p>After this, I'm getting a window asking the user where to save the file. How can I save this file automatically from python?</p>
<p>I need to <strong>use some browser</strong>, not urllib or mechanize, because <strong>before downloading file I need to interact with some ajax functionality</strong>.</p>
| 7 | 2009-09-09T10:18:42Z | 1,398,819 | <p>If you can't control Internet Explorer using its COM interface, I suggest using the <a href="http://www.autoitscript.com/autoit3/" rel="nofollow">AutoIt</a> COM to control its GUI from Python.</p>
| 1 | 2009-09-09T10:27:29Z | [
"python",
"internet-explorer",
"com"
] |
Downloading file using IE from python | 1,398,780 | <p>I'm trying to download file with Python using IE:</p>
<pre><code>from win32com.client import DispatchWithEvents
class EventHandler(object):
def OnDownloadBegin(self):
pass
ie = DispatchWithEvents("InternetExplorer.Application", EventHandler)
ie.Visible = 0
ie.Navigate('http://website/file.xml')
</code></pre>
<p>After this, I'm getting a window asking the user where to save the file. How can I save this file automatically from python?</p>
<p>I need to <strong>use some browser</strong>, not urllib or mechanize, because <strong>before downloading file I need to interact with some ajax functionality</strong>.</p>
| 7 | 2009-09-09T10:18:42Z | 4,565,493 | <p>I don't know how to say this nicely, but this sounds like about the most foolhardy software idea in recent memory. Python is much more capable of performing AJAX calls than IE is.</p>
<p>To access the data, yes, you <em>can</em> use <code>urllib</code> and <code>urllib2</code> . If there is JSON data in the response, there's the <code>json</code> library; likewise for XML and HTML, there's <code>BeautifulSoup</code>. </p>
<p>For one project, I had to write a Python program that would simulate a browser and sign into any of <strong>20</strong> different social networks (remember Friendster? Orkut? CyberWorld? I do), and upload images and text into the user's account, even grasping CAPTCHAs and complex JavaScript interactions. Pure Python makes it (comparatively) easy; as you've already seen, trying to use IE makes it impossible.</p>
| 3 | 2010-12-30T19:15:39Z | [
"python",
"internet-explorer",
"com"
] |
Downloading file using IE from python | 1,398,780 | <p>I'm trying to download file with Python using IE:</p>
<pre><code>from win32com.client import DispatchWithEvents
class EventHandler(object):
def OnDownloadBegin(self):
pass
ie = DispatchWithEvents("InternetExplorer.Application", EventHandler)
ie.Visible = 0
ie.Navigate('http://website/file.xml')
</code></pre>
<p>After this, I'm getting a window asking the user where to save the file. How can I save this file automatically from python?</p>
<p>I need to <strong>use some browser</strong>, not urllib or mechanize, because <strong>before downloading file I need to interact with some ajax functionality</strong>.</p>
| 7 | 2009-09-09T10:18:42Z | 4,566,022 | <p>I have something like that (an awful 3rd part application with lots of weird dotnet 'ajax' controls), and I use iMacros plugin for Firefox to do some automation. But I'm doing batch inserts, not downloads.</p>
<p>You can try record, edit and replay the inputs sent thru a VNC session. Look at something like <a href="http://code.google.com/p/python-vnc-viewer/" rel="nofollow">http://code.google.com/p/python-vnc-viewer/</a> for inspiration.</p>
| 0 | 2010-12-30T20:29:08Z | [
"python",
"internet-explorer",
"com"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.