title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Django Passing Custom Form Parameters to Formset
622,982
<blockquote> <p>This was fixed in Django 1.9 with <a href="https://docs.djangoproject.com/en/1.9/topics/forms/formsets/#passing-custom-parameters-to-formset-forms">form_kwargs</a>.</p> </blockquote> <p>I have a Django Form that looks like this:</p> <pre><code>class ServiceForm(forms.Form): option = forms.ModelChoiceField(queryset=ServiceOption.objects.none()) rate = forms.DecimalField(widget=custom_widgets.SmallField()) units = forms.IntegerField(min_value=1, widget=custom_widgets.SmallField()) def __init__(self, *args, **kwargs): affiliate = kwargs.pop('affiliate') super(ServiceForm, self).__init__(*args, **kwargs) self.fields["option"].queryset = ServiceOption.objects.filter(affiliate=affiliate) </code></pre> <p>I call this form with something like this:</p> <pre><code>form = ServiceForm(affiliate=request.affiliate) </code></pre> <p>Where <code>request.affiliate</code> is the logged in user. This works as intended.</p> <p>My problem is that I now want to turn this single form into a formset. What I can't figure out is how I can pass the affiliate information to the individual forms when creating the formset. According to the docs to make a formset out of this I need to do something like this:</p> <pre><code>ServiceFormSet = forms.formsets.formset_factory(ServiceForm, extra=3) </code></pre> <p>And then I need to create it like this:</p> <pre><code>formset = ServiceFormSet() </code></pre> <p>Now how can I pass affiliate=request.affiliate to the individual forms this way?</p>
113
2009-03-08T03:36:08Z
623,198
<p>I like the closure solution for being "cleaner" and more Pythonic (so +1 to mmarshall answer) but Django forms also have a callback mechanism you can use for filtering querysets in formsets.</p> <p>It's also not documented, which I think is an indicator the Django devs might not like it as much.</p> <p>So you basically create your formset the same but add the callback:</p> <pre><code>ServiceFormSet = forms.formsets.formset_factory( ServiceForm, extra=3, formfield_callback=Callback('option', affiliate).cb) </code></pre> <p>This is creating an instance of a class that looks like this:</p> <pre><code>class Callback(object): def __init__(self, field_name, aff): self._field_name = field_name self._aff = aff def cb(self, field, **kwargs): nf = field.formfield(**kwargs) if field.name == self._field_name: # this is 'options' field nf.queryset = ServiceOption.objects.filter(affiliate=self._aff) return nf </code></pre> <p>This should give you the general idea. It's a little more complex making the callback an object method like this, but gives you a little more flexibility as opposed to doing a simple function callback.</p>
9
2009-03-08T07:08:41Z
[ "python", "django", "forms", "django-forms" ]
Django Passing Custom Form Parameters to Formset
622,982
<blockquote> <p>This was fixed in Django 1.9 with <a href="https://docs.djangoproject.com/en/1.9/topics/forms/formsets/#passing-custom-parameters-to-formset-forms">form_kwargs</a>.</p> </blockquote> <p>I have a Django Form that looks like this:</p> <pre><code>class ServiceForm(forms.Form): option = forms.ModelChoiceField(queryset=ServiceOption.objects.none()) rate = forms.DecimalField(widget=custom_widgets.SmallField()) units = forms.IntegerField(min_value=1, widget=custom_widgets.SmallField()) def __init__(self, *args, **kwargs): affiliate = kwargs.pop('affiliate') super(ServiceForm, self).__init__(*args, **kwargs) self.fields["option"].queryset = ServiceOption.objects.filter(affiliate=affiliate) </code></pre> <p>I call this form with something like this:</p> <pre><code>form = ServiceForm(affiliate=request.affiliate) </code></pre> <p>Where <code>request.affiliate</code> is the logged in user. This works as intended.</p> <p>My problem is that I now want to turn this single form into a formset. What I can't figure out is how I can pass the affiliate information to the individual forms when creating the formset. According to the docs to make a formset out of this I need to do something like this:</p> <pre><code>ServiceFormSet = forms.formsets.formset_factory(ServiceForm, extra=3) </code></pre> <p>And then I need to create it like this:</p> <pre><code>formset = ServiceFormSet() </code></pre> <p>Now how can I pass affiliate=request.affiliate to the individual forms this way?</p>
113
2009-03-08T03:36:08Z
624,013
<p>I would use <a href="http://docs.python.org/2/library/functools.html#functools.partial">functools.partial</a> and <a href="http://docs.python.org/2/library/functools.html#functools.wraps">functools.wraps</a>:</p> <pre><code>from functools import partial, wraps from django.forms.formsets import formset_factory ServiceFormSet = formset_factory(wraps(ServiceForm)(partial(ServiceForm, affiliate=request.affiliate)), extra=3) </code></pre> <p>I think this is the cleanest approach, and doesn't affect ServiceForm in any way (i.e. by making it difficult to subclass).</p>
92
2009-03-08T18:00:26Z
[ "python", "django", "forms", "django-forms" ]
Django Passing Custom Form Parameters to Formset
622,982
<blockquote> <p>This was fixed in Django 1.9 with <a href="https://docs.djangoproject.com/en/1.9/topics/forms/formsets/#passing-custom-parameters-to-formset-forms">form_kwargs</a>.</p> </blockquote> <p>I have a Django Form that looks like this:</p> <pre><code>class ServiceForm(forms.Form): option = forms.ModelChoiceField(queryset=ServiceOption.objects.none()) rate = forms.DecimalField(widget=custom_widgets.SmallField()) units = forms.IntegerField(min_value=1, widget=custom_widgets.SmallField()) def __init__(self, *args, **kwargs): affiliate = kwargs.pop('affiliate') super(ServiceForm, self).__init__(*args, **kwargs) self.fields["option"].queryset = ServiceOption.objects.filter(affiliate=affiliate) </code></pre> <p>I call this form with something like this:</p> <pre><code>form = ServiceForm(affiliate=request.affiliate) </code></pre> <p>Where <code>request.affiliate</code> is the logged in user. This works as intended.</p> <p>My problem is that I now want to turn this single form into a formset. What I can't figure out is how I can pass the affiliate information to the individual forms when creating the formset. According to the docs to make a formset out of this I need to do something like this:</p> <pre><code>ServiceFormSet = forms.formsets.formset_factory(ServiceForm, extra=3) </code></pre> <p>And then I need to create it like this:</p> <pre><code>formset = ServiceFormSet() </code></pre> <p>Now how can I pass affiliate=request.affiliate to the individual forms this way?</p>
113
2009-03-08T03:36:08Z
813,647
<p>I wanted to place this as a comment to Carl Meyers answer, but since that requires points I just placed it here. This took me 2 hours to figure out so I hope it will help someone.</p> <p>A note about using the inlineformset_factory.</p> <p>I used that solution my self and it worked perfect, until I tried it with the inlineformset_factory. I was running Django 1.0.2 and got some strange KeyError exception. I upgraded to latest trunk and it worked direct.</p> <p>I can now use it similar to this:</p> <pre><code>BookFormSet = inlineformset_factory(Author, Book, form=BookForm) BookFormSet.form = staticmethod(curry(BookForm, user=request.user)) </code></pre>
9
2009-05-01T23:00:06Z
[ "python", "django", "forms", "django-forms" ]
Django Passing Custom Form Parameters to Formset
622,982
<blockquote> <p>This was fixed in Django 1.9 with <a href="https://docs.djangoproject.com/en/1.9/topics/forms/formsets/#passing-custom-parameters-to-formset-forms">form_kwargs</a>.</p> </blockquote> <p>I have a Django Form that looks like this:</p> <pre><code>class ServiceForm(forms.Form): option = forms.ModelChoiceField(queryset=ServiceOption.objects.none()) rate = forms.DecimalField(widget=custom_widgets.SmallField()) units = forms.IntegerField(min_value=1, widget=custom_widgets.SmallField()) def __init__(self, *args, **kwargs): affiliate = kwargs.pop('affiliate') super(ServiceForm, self).__init__(*args, **kwargs) self.fields["option"].queryset = ServiceOption.objects.filter(affiliate=affiliate) </code></pre> <p>I call this form with something like this:</p> <pre><code>form = ServiceForm(affiliate=request.affiliate) </code></pre> <p>Where <code>request.affiliate</code> is the logged in user. This works as intended.</p> <p>My problem is that I now want to turn this single form into a formset. What I can't figure out is how I can pass the affiliate information to the individual forms when creating the formset. According to the docs to make a formset out of this I need to do something like this:</p> <pre><code>ServiceFormSet = forms.formsets.formset_factory(ServiceForm, extra=3) </code></pre> <p>And then I need to create it like this:</p> <pre><code>formset = ServiceFormSet() </code></pre> <p>Now how can I pass affiliate=request.affiliate to the individual forms this way?</p>
113
2009-03-08T03:36:08Z
1,341,544
<p>I spent some time trying to figure out this problem before I saw this posting.</p> <p>The solution I came up with was the closure solution (and it is a solution I've used before with Django model forms).</p> <p>I tried the curry() method as described above, but I just couldn't get it to work with Django 1.0 so in the end I reverted to the closure method.</p> <p>The closure method is very neat and the only slight oddness is that the class definition is nested inside the view or another function. I think the fact that this looks odd to me is a hangup from my previous programming experience and I think someone with a background in more dynamic languages wouldn't bat an eyelid!</p>
1
2009-08-27T14:38:38Z
[ "python", "django", "forms", "django-forms" ]
Django Passing Custom Form Parameters to Formset
622,982
<blockquote> <p>This was fixed in Django 1.9 with <a href="https://docs.djangoproject.com/en/1.9/topics/forms/formsets/#passing-custom-parameters-to-formset-forms">form_kwargs</a>.</p> </blockquote> <p>I have a Django Form that looks like this:</p> <pre><code>class ServiceForm(forms.Form): option = forms.ModelChoiceField(queryset=ServiceOption.objects.none()) rate = forms.DecimalField(widget=custom_widgets.SmallField()) units = forms.IntegerField(min_value=1, widget=custom_widgets.SmallField()) def __init__(self, *args, **kwargs): affiliate = kwargs.pop('affiliate') super(ServiceForm, self).__init__(*args, **kwargs) self.fields["option"].queryset = ServiceOption.objects.filter(affiliate=affiliate) </code></pre> <p>I call this form with something like this:</p> <pre><code>form = ServiceForm(affiliate=request.affiliate) </code></pre> <p>Where <code>request.affiliate</code> is the logged in user. This works as intended.</p> <p>My problem is that I now want to turn this single form into a formset. What I can't figure out is how I can pass the affiliate information to the individual forms when creating the formset. According to the docs to make a formset out of this I need to do something like this:</p> <pre><code>ServiceFormSet = forms.formsets.formset_factory(ServiceForm, extra=3) </code></pre> <p>And then I need to create it like this:</p> <pre><code>formset = ServiceFormSet() </code></pre> <p>Now how can I pass affiliate=request.affiliate to the individual forms this way?</p>
113
2009-03-08T03:36:08Z
4,033,007
<p>I had to do a similar thing. This is similar to the <code>curry</code> solution:</p> <pre><code>def form_with_my_variable(myvar): class MyForm(ServiceForm): def __init__(self, myvar=myvar, *args, **kwargs): super(SeriveForm, self).__init__(myvar=myvar, *args, **kwargs) return MyForm factory = inlineformset_factory(..., form=form_with_my_variable(myvar), ... ) </code></pre>
0
2010-10-27T12:12:55Z
[ "python", "django", "forms", "django-forms" ]
Django Passing Custom Form Parameters to Formset
622,982
<blockquote> <p>This was fixed in Django 1.9 with <a href="https://docs.djangoproject.com/en/1.9/topics/forms/formsets/#passing-custom-parameters-to-formset-forms">form_kwargs</a>.</p> </blockquote> <p>I have a Django Form that looks like this:</p> <pre><code>class ServiceForm(forms.Form): option = forms.ModelChoiceField(queryset=ServiceOption.objects.none()) rate = forms.DecimalField(widget=custom_widgets.SmallField()) units = forms.IntegerField(min_value=1, widget=custom_widgets.SmallField()) def __init__(self, *args, **kwargs): affiliate = kwargs.pop('affiliate') super(ServiceForm, self).__init__(*args, **kwargs) self.fields["option"].queryset = ServiceOption.objects.filter(affiliate=affiliate) </code></pre> <p>I call this form with something like this:</p> <pre><code>form = ServiceForm(affiliate=request.affiliate) </code></pre> <p>Where <code>request.affiliate</code> is the logged in user. This works as intended.</p> <p>My problem is that I now want to turn this single form into a formset. What I can't figure out is how I can pass the affiliate information to the individual forms when creating the formset. According to the docs to make a formset out of this I need to do something like this:</p> <pre><code>ServiceFormSet = forms.formsets.formset_factory(ServiceForm, extra=3) </code></pre> <p>And then I need to create it like this:</p> <pre><code>formset = ServiceFormSet() </code></pre> <p>Now how can I pass affiliate=request.affiliate to the individual forms this way?</p>
113
2009-03-08T03:36:08Z
9,206,827
<p>Carl Meyer's solution looks very elegant. I tried implementing it for modelformsets. I was under the impression that I could not call staticmethods within a class, but the following inexplicably works:</p> <pre><code>class MyModel(models.Model): myField = models.CharField(max_length=10) class MyForm(ModelForm): _request = None class Meta: model = MyModel def __init__(self,*args,**kwargs): self._request = kwargs.pop('request', None) super(MyForm,self).__init__(*args,**kwargs) class MyFormsetBase(BaseModelFormSet): _request = None def __init__(self,*args,**kwargs): self._request = kwargs.pop('request', None) subFormClass = self.form self.form = curry(subFormClass,request=self._request) super(MyFormsetBase,self).__init__(*args,**kwargs) MyFormset = modelformset_factory(MyModel,formset=MyFormsetBase,extra=1,max_num=10,can_delete=True) MyFormset.form = staticmethod(curry(MyForm,request=MyFormsetBase._request)) </code></pre> <p>In my view, if I do something like this:</p> <pre><code>formset = MyFormset(request.POST,queryset=MyModel.objects.all(),request=request) </code></pre> <p>Then the "request" keyword gets propagated to all of the member forms of my formset. I'm pleased, but I have no idea why this is working - it seems wrong. Any suggestions?</p>
3
2012-02-09T07:16:01Z
[ "python", "django", "forms", "django-forms" ]
Django Passing Custom Form Parameters to Formset
622,982
<blockquote> <p>This was fixed in Django 1.9 with <a href="https://docs.djangoproject.com/en/1.9/topics/forms/formsets/#passing-custom-parameters-to-formset-forms">form_kwargs</a>.</p> </blockquote> <p>I have a Django Form that looks like this:</p> <pre><code>class ServiceForm(forms.Form): option = forms.ModelChoiceField(queryset=ServiceOption.objects.none()) rate = forms.DecimalField(widget=custom_widgets.SmallField()) units = forms.IntegerField(min_value=1, widget=custom_widgets.SmallField()) def __init__(self, *args, **kwargs): affiliate = kwargs.pop('affiliate') super(ServiceForm, self).__init__(*args, **kwargs) self.fields["option"].queryset = ServiceOption.objects.filter(affiliate=affiliate) </code></pre> <p>I call this form with something like this:</p> <pre><code>form = ServiceForm(affiliate=request.affiliate) </code></pre> <p>Where <code>request.affiliate</code> is the logged in user. This works as intended.</p> <p>My problem is that I now want to turn this single form into a formset. What I can't figure out is how I can pass the affiliate information to the individual forms when creating the formset. According to the docs to make a formset out of this I need to do something like this:</p> <pre><code>ServiceFormSet = forms.formsets.formset_factory(ServiceForm, extra=3) </code></pre> <p>And then I need to create it like this:</p> <pre><code>formset = ServiceFormSet() </code></pre> <p>Now how can I pass affiliate=request.affiliate to the individual forms this way?</p>
113
2009-03-08T03:36:08Z
18,348,930
<p>I'm a newbie here so I can't add comment. I hope this code will work too:</p> <pre><code>ServiceFormSet = formset_factory(ServiceForm, extra=3) ServiceFormSet.formset = staticmethod(curry(ServiceForm, affiliate=request.affiliate)) </code></pre> <p>as for adding additional parameters to the formset's <code>BaseFormSet</code> instead of form.</p>
0
2013-08-21T04:36:35Z
[ "python", "django", "forms", "django-forms" ]
Django Passing Custom Form Parameters to Formset
622,982
<blockquote> <p>This was fixed in Django 1.9 with <a href="https://docs.djangoproject.com/en/1.9/topics/forms/formsets/#passing-custom-parameters-to-formset-forms">form_kwargs</a>.</p> </blockquote> <p>I have a Django Form that looks like this:</p> <pre><code>class ServiceForm(forms.Form): option = forms.ModelChoiceField(queryset=ServiceOption.objects.none()) rate = forms.DecimalField(widget=custom_widgets.SmallField()) units = forms.IntegerField(min_value=1, widget=custom_widgets.SmallField()) def __init__(self, *args, **kwargs): affiliate = kwargs.pop('affiliate') super(ServiceForm, self).__init__(*args, **kwargs) self.fields["option"].queryset = ServiceOption.objects.filter(affiliate=affiliate) </code></pre> <p>I call this form with something like this:</p> <pre><code>form = ServiceForm(affiliate=request.affiliate) </code></pre> <p>Where <code>request.affiliate</code> is the logged in user. This works as intended.</p> <p>My problem is that I now want to turn this single form into a formset. What I can't figure out is how I can pass the affiliate information to the individual forms when creating the formset. According to the docs to make a formset out of this I need to do something like this:</p> <pre><code>ServiceFormSet = forms.formsets.formset_factory(ServiceForm, extra=3) </code></pre> <p>And then I need to create it like this:</p> <pre><code>formset = ServiceFormSet() </code></pre> <p>Now how can I pass affiliate=request.affiliate to the individual forms this way?</p>
113
2009-03-08T03:36:08Z
25,766,319
<p>As of commit e091c18f50266097f648efc7cac2503968e9d217 on Tue Aug 14 23:44:46 2012 +0200 the accepted solution can't work anymore. </p> <p>The current version of django.forms.models.modelform_factory() function uses a "type construction technique", calling the type() function on the passed form to get the metaclass type, then using the result to construct a class-object of its type on the fly::</p> <pre><code># Instatiate type(form) in order to use the same metaclass as form. return type(form)(class_name, (form,), form_class_attrs) </code></pre> <p>This means even a <code>curry</code>ed or <code>partial</code> object passed instead of a form "causes the duck to bite you" so to speak: it'll call a function with the construction parameters of a <code>ModelFormClass</code> object, returning the error message::</p> <pre><code>function() argument 1 must be code, not str </code></pre> <p>To work around this I wrote a generator function that uses a closure to return a subclass of any class specified as first parameter, that then calls <code>super.__init__</code> after <code>update</code>ing the kwargs with the ones supplied on the generator function's call::</p> <pre><code>def class_gen_with_kwarg(cls, **additionalkwargs): """class generator for subclasses with additional 'stored' parameters (in a closure) This is required to use a formset_factory with a form that need additional initialization parameters (see http://stackoverflow.com/questions/622982/django-passing-custom-form-parameters-to-formset) """ class ClassWithKwargs(cls): def __init__(self, *args, **kwargs): kwargs.update(additionalkwargs) super(ClassWithKwargs, self).__init__(*args, **kwargs) return ClassWithKwargs </code></pre> <p>Then in your code you'll call the form factory as::</p> <pre><code>MyFormSet = inlineformset_factory(ParentModel, Model,form = class_gen_with_kwarg(MyForm, user=self.request.user)) </code></pre> <p>caveats:</p> <ul> <li>this received very little testing, at least for now</li> <li>supplied parameters could clash and overwrite those used by whatever code will use the object returned by the constructor</li> </ul>
8
2014-09-10T13:09:20Z
[ "python", "django", "forms", "django-forms" ]
Django Passing Custom Form Parameters to Formset
622,982
<blockquote> <p>This was fixed in Django 1.9 with <a href="https://docs.djangoproject.com/en/1.9/topics/forms/formsets/#passing-custom-parameters-to-formset-forms">form_kwargs</a>.</p> </blockquote> <p>I have a Django Form that looks like this:</p> <pre><code>class ServiceForm(forms.Form): option = forms.ModelChoiceField(queryset=ServiceOption.objects.none()) rate = forms.DecimalField(widget=custom_widgets.SmallField()) units = forms.IntegerField(min_value=1, widget=custom_widgets.SmallField()) def __init__(self, *args, **kwargs): affiliate = kwargs.pop('affiliate') super(ServiceForm, self).__init__(*args, **kwargs) self.fields["option"].queryset = ServiceOption.objects.filter(affiliate=affiliate) </code></pre> <p>I call this form with something like this:</p> <pre><code>form = ServiceForm(affiliate=request.affiliate) </code></pre> <p>Where <code>request.affiliate</code> is the logged in user. This works as intended.</p> <p>My problem is that I now want to turn this single form into a formset. What I can't figure out is how I can pass the affiliate information to the individual forms when creating the formset. According to the docs to make a formset out of this I need to do something like this:</p> <pre><code>ServiceFormSet = forms.formsets.formset_factory(ServiceForm, extra=3) </code></pre> <p>And then I need to create it like this:</p> <pre><code>formset = ServiceFormSet() </code></pre> <p>Now how can I pass affiliate=request.affiliate to the individual forms this way?</p>
113
2009-03-08T03:36:08Z
25,915,489
<p>This is what worked for me, Django 1.7:</p> <pre><code>from django.utils.functional import curry lols = {'lols':'lols'} formset = modelformset_factory(MyModel, form=myForm, extra=0) formset.form = staticmethod(curry(MyForm, lols=lols)) return formset #form.py class MyForm(forms.ModelForm): def __init__(self, lols, *args, **kwargs): </code></pre> <p>Hope it helps someone, took me long enough to figure it out ;)</p>
12
2014-09-18T14:29:59Z
[ "python", "django", "forms", "django-forms" ]
Django Passing Custom Form Parameters to Formset
622,982
<blockquote> <p>This was fixed in Django 1.9 with <a href="https://docs.djangoproject.com/en/1.9/topics/forms/formsets/#passing-custom-parameters-to-formset-forms">form_kwargs</a>.</p> </blockquote> <p>I have a Django Form that looks like this:</p> <pre><code>class ServiceForm(forms.Form): option = forms.ModelChoiceField(queryset=ServiceOption.objects.none()) rate = forms.DecimalField(widget=custom_widgets.SmallField()) units = forms.IntegerField(min_value=1, widget=custom_widgets.SmallField()) def __init__(self, *args, **kwargs): affiliate = kwargs.pop('affiliate') super(ServiceForm, self).__init__(*args, **kwargs) self.fields["option"].queryset = ServiceOption.objects.filter(affiliate=affiliate) </code></pre> <p>I call this form with something like this:</p> <pre><code>form = ServiceForm(affiliate=request.affiliate) </code></pre> <p>Where <code>request.affiliate</code> is the logged in user. This works as intended.</p> <p>My problem is that I now want to turn this single form into a formset. What I can't figure out is how I can pass the affiliate information to the individual forms when creating the formset. According to the docs to make a formset out of this I need to do something like this:</p> <pre><code>ServiceFormSet = forms.formsets.formset_factory(ServiceForm, extra=3) </code></pre> <p>And then I need to create it like this:</p> <pre><code>formset = ServiceFormSet() </code></pre> <p>Now how can I pass affiliate=request.affiliate to the individual forms this way?</p>
113
2009-03-08T03:36:08Z
35,811,020
<p>Django 1.9:</p> <pre><code>ArticleFormSet = formset_factory(MyArticleForm) formset = ArticleFormSet(form_kwargs={'user': request.user}) </code></pre> <p><a href="https://docs.djangoproject.com/en/1.9/topics/forms/formsets/#passing-custom-parameters-to-formset-forms" rel="nofollow">https://docs.djangoproject.com/en/1.9/topics/forms/formsets/#passing-custom-parameters-to-formset-forms</a></p>
4
2016-03-05T06:41:12Z
[ "python", "django", "forms", "django-forms" ]
Django Passing Custom Form Parameters to Formset
622,982
<blockquote> <p>This was fixed in Django 1.9 with <a href="https://docs.djangoproject.com/en/1.9/topics/forms/formsets/#passing-custom-parameters-to-formset-forms">form_kwargs</a>.</p> </blockquote> <p>I have a Django Form that looks like this:</p> <pre><code>class ServiceForm(forms.Form): option = forms.ModelChoiceField(queryset=ServiceOption.objects.none()) rate = forms.DecimalField(widget=custom_widgets.SmallField()) units = forms.IntegerField(min_value=1, widget=custom_widgets.SmallField()) def __init__(self, *args, **kwargs): affiliate = kwargs.pop('affiliate') super(ServiceForm, self).__init__(*args, **kwargs) self.fields["option"].queryset = ServiceOption.objects.filter(affiliate=affiliate) </code></pre> <p>I call this form with something like this:</p> <pre><code>form = ServiceForm(affiliate=request.affiliate) </code></pre> <p>Where <code>request.affiliate</code> is the logged in user. This works as intended.</p> <p>My problem is that I now want to turn this single form into a formset. What I can't figure out is how I can pass the affiliate information to the individual forms when creating the formset. According to the docs to make a formset out of this I need to do something like this:</p> <pre><code>ServiceFormSet = forms.formsets.formset_factory(ServiceForm, extra=3) </code></pre> <p>And then I need to create it like this:</p> <pre><code>formset = ServiceFormSet() </code></pre> <p>Now how can I pass affiliate=request.affiliate to the individual forms this way?</p>
113
2009-03-08T03:36:08Z
39,229,572
<p>based on <a href="http://stackoverflow.com/questions/622982/django-passing-custom-form-parameters-to-formset/#answer-623198">this answer</a> I found more clear solution:</p> <pre><code>class ServiceForm(forms.Form): option = forms.ModelChoiceField( queryset=ServiceOption.objects.filter(affiliate=self.affiliate)) rate = forms.DecimalField(widget=custom_widgets.SmallField()) units = forms.IntegerField(min_value=1, widget=custom_widgets.SmallField()) @staticmethod def make_service_form(affiliate): self.affiliate = affiliate return ServiceForm </code></pre> <p>And run it in view like</p> <pre><code>formset_factory(form=ServiceForm.make_service_form(affiliate)) </code></pre>
0
2016-08-30T13:59:30Z
[ "python", "django", "forms", "django-forms" ]
For my app, how many threads would be optimal?
623,054
<p>I have a simple Python web crawler. It uses SQLite to store its output and also to keep a queue. I want to make the crawler multi-threaded so that it can crawl several pages at a time. I figured i would make a thread and just run several instances of the class at once, so they all run concurrently. But the question is, how many should i run at once? should i stick to two? can i go higher? what would be a reasonable limit for a number of threads? Keep in mind that each thread goes out to a web page, downloads the html, runs a few regex searches through it, stores the info it finds in a SQLite db, and then pops the next url off the queue.</p>
3
2009-03-08T04:44:41Z
623,064
<p>It's usually simpler to make multiple concurrent processes. Simply use subprocess to create as many Popens as you feel it necessary to run concurrently.</p> <p>There's no "optimal" number. Generally, when you run just one crawler, your PC spends a lot of time waiting. How much? Hard to say.</p> <p>When you're running some small number of concurrent crawlers, you'll see that they take about the same amount of time as one. Your CPU switches among the various processes, filling up the wait time on one with work on the others.</p> <p>You you run some larger number, you see that the overall elapsed time is longer because there's now more to do than your CPU can manage. So the overall process takes longer.</p> <p>You can create a graph that shows how the process scales. Based on this you can balance the number of processes and your desirable elapsed time.</p> <p>Think of it this way. </p> <p>1 crawler does it's job in 1 minute. 100 pages done serially could take a 100 minutes. 100 crawlers concurrently might take on hour. Let's say that 25 crawlers finishes the job in 50 minutes.</p> <p>You don't know what's optimal until you run various combinations and compare the results.</p>
3
2009-03-08T04:55:05Z
[ "python", "multithreading" ]
For my app, how many threads would be optimal?
623,054
<p>I have a simple Python web crawler. It uses SQLite to store its output and also to keep a queue. I want to make the crawler multi-threaded so that it can crawl several pages at a time. I figured i would make a thread and just run several instances of the class at once, so they all run concurrently. But the question is, how many should i run at once? should i stick to two? can i go higher? what would be a reasonable limit for a number of threads? Keep in mind that each thread goes out to a web page, downloads the html, runs a few regex searches through it, stores the info it finds in a SQLite db, and then pops the next url off the queue.</p>
3
2009-03-08T04:44:41Z
623,070
<p>You will probably find your application is bandwidth limited not CPU or I/O limited.</p> <p>As such, add as many as you like until performance begins to degrade.</p> <p>You may come up against other limits depending on your network setup. Like if you're behind an ADSL router, there will be a limit on the number of concurrent NAT sessions, which may impact making too many HTTP requests at once. Make too many and your provider may treat you as being infected by a virus or the like.</p> <p>There's also the issue of how many requests the server you're crawling can handle and how much of a load you want to put on it.</p> <p>I wrote a crawler once that used just one thread. It took about a day to process all the information I wanted at about one page every two seconds. I could've done it faster but I figured this was less of a burden for the server.</p> <p>So really theres no hard and fast answer. Assuming a 1-5 megabit connection I'd say you could easily have up to 20-30 threads without any problems.</p>
13
2009-03-08T04:57:01Z
[ "python", "multithreading" ]
For my app, how many threads would be optimal?
623,054
<p>I have a simple Python web crawler. It uses SQLite to store its output and also to keep a queue. I want to make the crawler multi-threaded so that it can crawl several pages at a time. I figured i would make a thread and just run several instances of the class at once, so they all run concurrently. But the question is, how many should i run at once? should i stick to two? can i go higher? what would be a reasonable limit for a number of threads? Keep in mind that each thread goes out to a web page, downloads the html, runs a few regex searches through it, stores the info it finds in a SQLite db, and then pops the next url off the queue.</p>
3
2009-03-08T04:44:41Z
623,073
<p>You can go higher that two. How much higher depends entirely on the hardware of the system you're running this on, how much processing is going on after the network operations, and what else is running on the machine at the time.</p> <p>Since it's being written in Python (and being called "simple") I'm going to assume you're not exactly concerned with squeezing every ounce of performance out of the thing. In that case, I'd suggest just running some tests under common working conditions and seeing how it performs. I'd guess around 5-10 is probably reasonable, but that's a complete stab in the dark.</p> <p>Since you're using a dual-core machine, I'd highly recommend checking out the <a href="http://docs.python.org/library/multiprocessing.html" rel="nofollow">Python multiprocessing module</a> (in Python 2.6). It will let you take advantage of multiple processors on your machine, which would be a significant performance boost.</p>
1
2009-03-08T04:58:47Z
[ "python", "multithreading" ]
For my app, how many threads would be optimal?
623,054
<p>I have a simple Python web crawler. It uses SQLite to store its output and also to keep a queue. I want to make the crawler multi-threaded so that it can crawl several pages at a time. I figured i would make a thread and just run several instances of the class at once, so they all run concurrently. But the question is, how many should i run at once? should i stick to two? can i go higher? what would be a reasonable limit for a number of threads? Keep in mind that each thread goes out to a web page, downloads the html, runs a few regex searches through it, stores the info it finds in a SQLite db, and then pops the next url off the queue.</p>
3
2009-03-08T04:44:41Z
623,098
<p>Threading isn't necessary in this case. Your program is <strong>I/O bound</strong> rather than CPU bound. The networking part would probably be <strong>better done using select()</strong> on the sockets. This reduces the overhead of creating and maintaining threads. I haven't used <a href="http://twistedmatrix.com" rel="nofollow">Twisted</a>, but I heard it has really good support for <strong>asynchronous networking</strong>. This would allow you you to specify the URLs you wish to download and register a callback for each. When each is downloaded you the callback will be called, and the page can be processed. In order to allow multiple sites to be downloaded, without waiting for each to be processed, a second "worker" thread can be created with a queue. The callback would add the site's contents to the queue. The "worker" thread would do the actual processing.</p> <p>As already stated in some answers, the optimal amount of simultaneous downloads depends on your bandwidth.</p> <p>I'd use <strong>one or two threads</strong> - one for the actual crawling and the other (with a queue) for processing.</p>
0
2009-03-08T05:16:08Z
[ "python", "multithreading" ]
For my app, how many threads would be optimal?
623,054
<p>I have a simple Python web crawler. It uses SQLite to store its output and also to keep a queue. I want to make the crawler multi-threaded so that it can crawl several pages at a time. I figured i would make a thread and just run several instances of the class at once, so they all run concurrently. But the question is, how many should i run at once? should i stick to two? can i go higher? what would be a reasonable limit for a number of threads? Keep in mind that each thread goes out to a web page, downloads the html, runs a few regex searches through it, stores the info it finds in a SQLite db, and then pops the next url off the queue.</p>
3
2009-03-08T04:44:41Z
623,138
<p>I would use one thread and <a href="http://twistedmatrix.com/">twisted</a> with either a deferred semaphore or a task cooperator if you already have an easy way to feed an arbitrarily long list of URLs in.</p> <p>It's extremely unlikely you'll be able to make a multi-threaded crawler that's faster or smaller than a twisted-based crawler.</p>
7
2009-03-08T05:54:32Z
[ "python", "multithreading" ]
For my app, how many threads would be optimal?
623,054
<p>I have a simple Python web crawler. It uses SQLite to store its output and also to keep a queue. I want to make the crawler multi-threaded so that it can crawl several pages at a time. I figured i would make a thread and just run several instances of the class at once, so they all run concurrently. But the question is, how many should i run at once? should i stick to two? can i go higher? what would be a reasonable limit for a number of threads? Keep in mind that each thread goes out to a web page, downloads the html, runs a few regex searches through it, stores the info it finds in a SQLite db, and then pops the next url off the queue.</p>
3
2009-03-08T04:44:41Z
623,496
<p>cletus's answer is the one you want.</p> <p>A couple of people proposed an alternate solution using asynchronous I/O, especially looking at Twisted. If you decide to go that route, a different solution is <a href="http://pycurl.sourceforge.net/" rel="nofollow">pycurl</a>, which is a thin wrapper to libcurl, which is a widely used URL transfer library. PyCurl's home page has a '<a href="https://github.com/pycurl/pycurl/blob/master/examples/retriever-multi.py" rel="nofollow">retriever-multi.py</a>' example of how to fetch multiple pages in parallel, in about 120 lines of code.</p>
3
2009-03-08T12:24:00Z
[ "python", "multithreading" ]
For my app, how many threads would be optimal?
623,054
<p>I have a simple Python web crawler. It uses SQLite to store its output and also to keep a queue. I want to make the crawler multi-threaded so that it can crawl several pages at a time. I figured i would make a thread and just run several instances of the class at once, so they all run concurrently. But the question is, how many should i run at once? should i stick to two? can i go higher? what would be a reasonable limit for a number of threads? Keep in mind that each thread goes out to a web page, downloads the html, runs a few regex searches through it, stores the info it finds in a SQLite db, and then pops the next url off the queue.</p>
3
2009-03-08T04:44:41Z
623,515
<p>One thing you should keep in mind is that some servers may interpret too many concurrent requests from the same IP address as a DoS attack and abort connections or return error pages for requests that would otherwise succeed.</p> <p>So it might be a good idea to limit the number of concurrent requests to the same server to a relatively low number (5 should be on the safe side).</p>
1
2009-03-08T12:44:01Z
[ "python", "multithreading" ]
How can I insert RTF into a wxpython RichTextCtrl?
623,384
<p>Is there a way to directly insert RTF text in a RichTextCtrl, ex:without going through <strong>BeginTextColour</strong>? I would like to use pygments together with the RichTextCtrl.</p>
1
2009-03-08T10:37:36Z
623,449
<p><strong>No.</strong> As authors admit in <a href="http://docs.wxwidgets.org/stable/wx%5Fwxrichtextctrloverview.html#topic17" rel="nofollow">wxRichTextCtrl roadmap</a>:</p> <blockquote> <p>This is a list of some of the features that have yet to be implemented. Help with them will be appreciated.</p> <ul> <li>RTF input and output </li> </ul> </blockquote>
2
2009-03-08T11:42:26Z
[ "python", "wxpython", "rtf", "richtextctrl" ]
Retrieving the latitude/longitude from Google Map Mobile 3.0's MyLocation feature
623,504
<p>I want to fetch my current latitude/longitude from Google Maps Mobile 3.0 with the help of some script, which I guess could be a Python one. Is this possible? And, more importantly: is the Google Maps Mobile API designed for such interaction? Any legal issues?</p> <p>Basically i have a S60 phone that doesnt have GPS,and I have found that Google maintains its own database to link Cell IDs with lat/longs so that depending on what Cell ID I am nearest to, it can approximate my current location. So only Cel ID info from the operator won't tell me where i am on Earth until such a linking between Cell ID and latitude/longitude is available (for which I am thinking of seeking help of GMM; of course, if it provides for this...).</p> <p>Secondly, the GMM 3.0 pushes my current latitude/longitude to the iGoogle Latitude gadget... so there should be some way by which I can fetch the same info by my custom gadget/script, right?</p>
1
2009-03-08T12:34:30Z
858,276
<p>No, you can't access it from a Python script or another S60 application because of platform security features of S60 3rd ed. Even if Google Maps application would write information to disk, your app is not able to access application specific files of other apps. </p> <p>Google Maps use cell-based locationing in addition to GPS or when GPS is not available. Google hasn't released any 3rd party API to do these cell-tower to lat-long conversions.</p>
1
2009-05-13T14:26:46Z
[ "python", "google-maps", "s60", "pys60" ]
Retrieving the latitude/longitude from Google Map Mobile 3.0's MyLocation feature
623,504
<p>I want to fetch my current latitude/longitude from Google Maps Mobile 3.0 with the help of some script, which I guess could be a Python one. Is this possible? And, more importantly: is the Google Maps Mobile API designed for such interaction? Any legal issues?</p> <p>Basically i have a S60 phone that doesnt have GPS,and I have found that Google maintains its own database to link Cell IDs with lat/longs so that depending on what Cell ID I am nearest to, it can approximate my current location. So only Cel ID info from the operator won't tell me where i am on Earth until such a linking between Cell ID and latitude/longitude is available (for which I am thinking of seeking help of GMM; of course, if it provides for this...).</p> <p>Secondly, the GMM 3.0 pushes my current latitude/longitude to the iGoogle Latitude gadget... so there should be some way by which I can fetch the same info by my custom gadget/script, right?</p>
1
2009-03-08T12:34:30Z
965,834
<p>About reading any file from the disk:</p> <p>Only when you have an <a href="https://rdcertification.nokia.com/rdcertification/app" rel="nofollow">R&amp;D (Research and Development) certificate</a> that grants you the <code>AllFiles</code> capability, can you access nearly any file.</p>
0
2009-06-08T16:44:29Z
[ "python", "google-maps", "s60", "pys60" ]
Retrieving the latitude/longitude from Google Map Mobile 3.0's MyLocation feature
623,504
<p>I want to fetch my current latitude/longitude from Google Maps Mobile 3.0 with the help of some script, which I guess could be a Python one. Is this possible? And, more importantly: is the Google Maps Mobile API designed for such interaction? Any legal issues?</p> <p>Basically i have a S60 phone that doesnt have GPS,and I have found that Google maintains its own database to link Cell IDs with lat/longs so that depending on what Cell ID I am nearest to, it can approximate my current location. So only Cel ID info from the operator won't tell me where i am on Earth until such a linking between Cell ID and latitude/longitude is available (for which I am thinking of seeking help of GMM; of course, if it provides for this...).</p> <p>Secondly, the GMM 3.0 pushes my current latitude/longitude to the iGoogle Latitude gadget... so there should be some way by which I can fetch the same info by my custom gadget/script, right?</p>
1
2009-03-08T12:34:30Z
1,467,215
<p>You don't have to do this through Google Maps. The mapping for Cell ID to latitude and longitude is available from <a href="http://www.opencellid.org" rel="nofollow">http://www.opencellid.org</a>.</p> <p>You can get the raw data file and then sample part of the data to the accuracy you need. Then, using the pys60 elocation api, you can grab the current Cell ID (you need to have the DevCert in order to do this).</p> <p>For more details take a look at this: <a href="http://discussion.forum.nokia.com/forum/showthread.php?t=112964" rel="nofollow">http://discussion.forum.nokia.com/forum/showthread.php?t=112964</a></p>
1
2009-09-23T16:38:44Z
[ "python", "google-maps", "s60", "pys60" ]
Why can't I directly add attributes to any python object?
623,520
<p>I have this code:</p> <pre><code>&gt;&gt;&gt; class G: ... def __init__(self): ... self.x = 20 ... &gt;&gt;&gt; gg = G() &gt;&gt;&gt; gg.x 20 &gt;&gt;&gt; gg.y = 2000 </code></pre> <p>And this code:</p> <pre><code>&gt;&gt;&gt; from datetime import datetime &gt;&gt;&gt; my_obj = datetime.now() &gt;&gt;&gt; my_obj.interesting = 1 *** AttributeError: 'datetime.datetime' object has no attribute 'interesting' </code></pre> <p>From my Python knowledge, I would say that <code>datetime</code> overrides <code>setattr</code>/<code>getattr</code>, but I am not sure. Could you shed some light here?</p> <p>EDIT: I'm not specifically interested in <code>datetime</code>. I was wondering about objects in general.</p>
21
2009-03-08T12:46:56Z
623,531
<p>My guess, is that the implementation of datetime uses <a href="http://docs.python.org/reference/datamodel.html#id3">__slots__</a> for better performance.</p> <p>When using <code>__slots__</code>, the interpreter reserves storage for just the attributes listed, nothing else. This gives better performance and uses less storage, but it also means you can't add new attributes at will.</p> <p>Read more here: <a href="http://docs.python.org/reference/datamodel.html">http://docs.python.org/reference/datamodel.html</a></p>
32
2009-03-08T12:54:54Z
[ "python", "attributes", "object" ]
Why can't I directly add attributes to any python object?
623,520
<p>I have this code:</p> <pre><code>&gt;&gt;&gt; class G: ... def __init__(self): ... self.x = 20 ... &gt;&gt;&gt; gg = G() &gt;&gt;&gt; gg.x 20 &gt;&gt;&gt; gg.y = 2000 </code></pre> <p>And this code:</p> <pre><code>&gt;&gt;&gt; from datetime import datetime &gt;&gt;&gt; my_obj = datetime.now() &gt;&gt;&gt; my_obj.interesting = 1 *** AttributeError: 'datetime.datetime' object has no attribute 'interesting' </code></pre> <p>From my Python knowledge, I would say that <code>datetime</code> overrides <code>setattr</code>/<code>getattr</code>, but I am not sure. Could you shed some light here?</p> <p>EDIT: I'm not specifically interested in <code>datetime</code>. I was wondering about objects in general.</p>
21
2009-03-08T12:46:56Z
623,544
<p>It's written in C</p> <p><a href="http://svn.python.org/view/python/trunk/Modules/datetimemodule.c?view=markup">http://svn.python.org/view/python/trunk/Modules/datetimemodule.c?view=markup</a></p> <p>It doesn't seem to implement setattr.</p>
18
2009-03-08T13:07:39Z
[ "python", "attributes", "object" ]
Why can't I directly add attributes to any python object?
623,520
<p>I have this code:</p> <pre><code>&gt;&gt;&gt; class G: ... def __init__(self): ... self.x = 20 ... &gt;&gt;&gt; gg = G() &gt;&gt;&gt; gg.x 20 &gt;&gt;&gt; gg.y = 2000 </code></pre> <p>And this code:</p> <pre><code>&gt;&gt;&gt; from datetime import datetime &gt;&gt;&gt; my_obj = datetime.now() &gt;&gt;&gt; my_obj.interesting = 1 *** AttributeError: 'datetime.datetime' object has no attribute 'interesting' </code></pre> <p>From my Python knowledge, I would say that <code>datetime</code> overrides <code>setattr</code>/<code>getattr</code>, but I am not sure. Could you shed some light here?</p> <p>EDIT: I'm not specifically interested in <code>datetime</code>. I was wondering about objects in general.</p>
21
2009-03-08T12:46:56Z
15,627,778
<p>While the question has already been answered; if anyone is interested in a workaround, here's an example --</p> <pre><code>mydate = datetime.date(2013, 3, 26) mydate.special = 'Some special date annotation' # doesn't work ... class CustomDate(datetime.date): pass mydate = datetime.date(2013, 3, 26) mydate = CustomDate(mydate.year, mydate.month, mydate.day) mydate.special = 'Some special date annotation' # works </code></pre>
2
2013-03-26T01:27:33Z
[ "python", "attributes", "object" ]
How do you add event to Trac event time line
623,822
<p>I am writing a plug-in for Trac. I would like to add an event to the time line each time the plug-in receives some data from a Git post-receive hook.</p> <p>Looking at <a href="http://trac.edgewall.org/browser/trunk/trac/timeline/api.py" rel="nofollow">the timeline API</a>, it seems you can only add new source of events. So you are responsible for retrieving and displaying the data. I would prefer saving my event to an existent source.</p> <p>Where should I look in the Trac API to save events?</p> <p>ps: my plan is to rely on a remote repository and remote web interface to the code like Github.</p> <p>pss: The time line has to display commits from the main project git repository and its clones. I don't want to host a copy of every repository that matter to the project.</p>
1
2009-03-08T16:30:07Z
636,842
<p>The timeline API is a level higher than what you need to do. There is a general VCS implementation of it in <a href="http://trac.edgewall.org/browser/trunk/trac/versioncontrol/web%5Fui/changeset.py" rel="nofollow">ChangesetModule</a>, which delegates the changeset (event) retrieval itself to a VCS-specific <code>Repository</code>. So you should implement <a href="http://trac.edgewall.org/browser/trunk/trac/versioncontrol/api.py" rel="nofollow">the versioncontrol API</a> instead.</p> <p>The API is designed for a “pull model”, in which Trac queries the VCS when constructing a timeline. If you really prefer a “push model” (why?), you could try working off <a href="http://trac.edgewall.org/browser/trunk/trac/versioncontrol/cache.py" rel="nofollow">the CacheRepository implementation</a> as a base, injecting your events into the cache, or just writing an event-storing repository from scratch. Be aware that this goes against the grain of the existing design, and will very probably be unnecessary extra effort.</p> <p>I suggest that you go with the normal pull model instead, it will be easier and cleaner. You could use <a href="http://trac.edgewall.org/browser/trunk/trac/versioncontrol/svn%5Ffs.py" rel="nofollow">the Subversion implementation</a> or <a href="http://trac.edgewall.org/browser/sandbox/mercurial-plugin/tracvc/hg/backend.py" rel="nofollow">the Mercurial implementation</a> as a reference, and probably use <a href="http://gitorious.org/projects/git-python/" rel="nofollow">GitPython</a> to talk to <code>git</code>.</p>
2
2009-03-11T23:57:51Z
[ "python", "plugins", "trac" ]
django login middleware not working as expected
624,043
<p>A quickie, and hopefully an easy one. I'm following the docs at <a href="http://docs.djangoproject.com/en/dev/topics/auth/" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/auth/</a> to get just some simple user authentication in place. I don't have any special requirements at all, I just need to know if a user is logged in or not, that's about it. I'm using the login_required decorator, and it's working exactly as I expected. I'm actually using the 'django.contrib.auth.views.login' for my login view, and the exact form they show in the docs:</p> <pre><code>{% if form.errors %} &lt;p&gt;Your username and password didn't match. Please try again.&lt;/p&gt; {% endif %} &lt;form method="post" action="."&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt;{{ form.username.label_tag }}&lt;/td&gt; &lt;td&gt;{{ form.username }}&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;{{ form.password.label_tag }}&lt;/td&gt; &lt;td&gt;{{ form.password }}&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;input type="submit" value="login" /&gt; &lt;input type="hidden" name="next" value="{{ next }}" /&gt; &lt;/form&gt; </code></pre> <p>What I guess I don't understand is why I can put whatever I want in the user/pass fields, and I never receive an error for invalid user/pass combo. I can put in non-existant users, correct users with right passwords, whatever I want basically, and it sends me off to whatever is in the 'next' variable. This leads me to believe that it's actually not doing anything whatsoever. I've checked what I'm sending via the request variables after logging in, and I'm always showing as an AnonymousUser, even though I "successfully logged in". Am I overlooking something blatantly obvious here? Seems like I've read that page on authentication 6 or 7 times now.</p> <p>Also, if I login as a user with "Staff Status", I show as authenticated without any issues. If the user doesn't have that status, then it doesn't work. </p>
1
2009-03-08T18:24:40Z
624,068
<p>I believe I fixed it:</p> <p>Right:</p> <pre><code>url(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'quiz/quiz_login.html'}) </code></pre> <p>Wrong:</p> <pre><code>url(r'^login$', 'django.contrib.auth.views.login', {'template_name': 'quiz/quiz_login.html'}) </code></pre> <p>Meh.</p>
0
2009-03-08T18:38:37Z
[ "python", "django", "django-authentication" ]
wx's idle and UI update events in PyQt
624,050
<p>wx (and wxPython) has two events I miss in PyQt: </p> <ul> <li><code>EVT_IDLE</code> that's being sent to a frame. It can be used to update the various widgets according to the application's state</li> <li><code>EVT_UPDATE_UI</code> that's being sent to a widget when it has to be repainted and updated, so I can compute its state in the handler</li> </ul> <p>Now, PyQt doesn't seem to have these, and the PyQt book suggests writing an <code>updateUi</code> method and calling it manually. I even ended up calling it from a timer once per 0.1 seconds, in order to avoid many manual calls from methods that may update the GUI. Am I missing something? Is there a better way to achieve this?</p> <p><hr /></p> <p>An example: I have a simple app with a Start button that initiates some processing. The start button should be enabled only when a file has been opened using the menu. In addition, there's a permanent widget on the status bar that displays information.</p> <p>My application has states:</p> <ol> <li>Before the file is opened (in this state the status bar show something special and the start button is disabled)</li> <li>File was opened and processing wasn't started: the start button is enabled, status bar shows something else</li> <li>The processing is running: the start button now says "Stop", and the status bar reports progress</li> </ol> <p>In Wx, I'd have the update UI event of the button handle its state: the text on it, and whether it's enabled, depending on the application state. The same for the status bar (or I'd use EVT_IDLE for that).</p> <p>In Qt, I have to update the button in several methods that may affect the state, or just create a update_ui method and call it periodically in a timer. What is the more "QT"-ish way?</p>
1
2009-03-08T18:26:51Z
624,282
<p>As far as I understand EVT_IDLE is sent when application message queue is empty. There is no such event in Qt, but if you need to execute something in Qt when there are no pending events, you should use QTimer with 0 timeout.</p>
1
2009-03-08T21:04:37Z
[ "python", "qt", "wxpython", "pyqt" ]
wx's idle and UI update events in PyQt
624,050
<p>wx (and wxPython) has two events I miss in PyQt: </p> <ul> <li><code>EVT_IDLE</code> that's being sent to a frame. It can be used to update the various widgets according to the application's state</li> <li><code>EVT_UPDATE_UI</code> that's being sent to a widget when it has to be repainted and updated, so I can compute its state in the handler</li> </ul> <p>Now, PyQt doesn't seem to have these, and the PyQt book suggests writing an <code>updateUi</code> method and calling it manually. I even ended up calling it from a timer once per 0.1 seconds, in order to avoid many manual calls from methods that may update the GUI. Am I missing something? Is there a better way to achieve this?</p> <p><hr /></p> <p>An example: I have a simple app with a Start button that initiates some processing. The start button should be enabled only when a file has been opened using the menu. In addition, there's a permanent widget on the status bar that displays information.</p> <p>My application has states:</p> <ol> <li>Before the file is opened (in this state the status bar show something special and the start button is disabled)</li> <li>File was opened and processing wasn't started: the start button is enabled, status bar shows something else</li> <li>The processing is running: the start button now says "Stop", and the status bar reports progress</li> </ol> <p>In Wx, I'd have the update UI event of the button handle its state: the text on it, and whether it's enabled, depending on the application state. The same for the status bar (or I'd use EVT_IDLE for that).</p> <p>In Qt, I have to update the button in several methods that may affect the state, or just create a update_ui method and call it periodically in a timer. What is the more "QT"-ish way?</p>
1
2009-03-08T18:26:51Z
624,734
<p>The use of EVT_UPDATE_UI in wxWidgets seems to highlight one of the fundamental differences in the way wxWidgets and Qt expect developers to handle events in their code.</p> <p>With Qt, you connect signals and slots between widgets in the user interface, either handling "business logic" in each slot or delegating it to a dedicated method. You typically don't worry about making separate changes to each widget in your GUI because any repaint requests will be placed in the event queue and delivered when control returns to the event loop. Some paint events may even be merged together for the sake of efficiency.</p> <p>So, in a normal Qt application where signals and slots are used to handle state changes, there's basically no need to have an idle mechanism that monitors the state of the application and update widgets because those updates should occur automatically.</p> <p>You would have to say a bit more about what you are doing to explain why you need an equivalent to this event in Qt.</p>
5
2009-03-09T01:40:31Z
[ "python", "qt", "wxpython", "pyqt" ]
wx's idle and UI update events in PyQt
624,050
<p>wx (and wxPython) has two events I miss in PyQt: </p> <ul> <li><code>EVT_IDLE</code> that's being sent to a frame. It can be used to update the various widgets according to the application's state</li> <li><code>EVT_UPDATE_UI</code> that's being sent to a widget when it has to be repainted and updated, so I can compute its state in the handler</li> </ul> <p>Now, PyQt doesn't seem to have these, and the PyQt book suggests writing an <code>updateUi</code> method and calling it manually. I even ended up calling it from a timer once per 0.1 seconds, in order to avoid many manual calls from methods that may update the GUI. Am I missing something? Is there a better way to achieve this?</p> <p><hr /></p> <p>An example: I have a simple app with a Start button that initiates some processing. The start button should be enabled only when a file has been opened using the menu. In addition, there's a permanent widget on the status bar that displays information.</p> <p>My application has states:</p> <ol> <li>Before the file is opened (in this state the status bar show something special and the start button is disabled)</li> <li>File was opened and processing wasn't started: the start button is enabled, status bar shows something else</li> <li>The processing is running: the start button now says "Stop", and the status bar reports progress</li> </ol> <p>In Wx, I'd have the update UI event of the button handle its state: the text on it, and whether it's enabled, depending on the application state. The same for the status bar (or I'd use EVT_IDLE for that).</p> <p>In Qt, I have to update the button in several methods that may affect the state, or just create a update_ui method and call it periodically in a timer. What is the more "QT"-ish way?</p>
1
2009-03-08T18:26:51Z
626,368
<p>I would send Qt signals to indicate state changes (e.g. fileOpened, processingStarted, processingDone). Slots in objects managing the start button and status bar widget (or subclasses) can be connected to those signals, rather than "polling" for current state in an idle event.</p> <p>If you want the signal to be deferred later on in the event loop rather than immediately (e.g. because it's going to take a bit of time to do something), you can use a "queued" signal-slot connection rather than the normal kind. </p> <p><a href="http://doc.trolltech.com/4.5/signalsandslots.html#signals" rel="nofollow">http://doc.trolltech.com/4.5/signalsandslots.html#signals</a></p> <p>The connection type is an optional parameter to the connect() function: <a href="http://doc.trolltech.com/4.5/qobject.html#connect" rel="nofollow">http://doc.trolltech.com/4.5/qobject.html#connect</a> , <a href="http://doc.trolltech.com/4.5/qt.html#ConnectionType-enum" rel="nofollow">http://doc.trolltech.com/4.5/qt.html#ConnectionType-enum</a></p>
2
2009-03-09T14:06:54Z
[ "python", "qt", "wxpython", "pyqt" ]
wx's idle and UI update events in PyQt
624,050
<p>wx (and wxPython) has two events I miss in PyQt: </p> <ul> <li><code>EVT_IDLE</code> that's being sent to a frame. It can be used to update the various widgets according to the application's state</li> <li><code>EVT_UPDATE_UI</code> that's being sent to a widget when it has to be repainted and updated, so I can compute its state in the handler</li> </ul> <p>Now, PyQt doesn't seem to have these, and the PyQt book suggests writing an <code>updateUi</code> method and calling it manually. I even ended up calling it from a timer once per 0.1 seconds, in order to avoid many manual calls from methods that may update the GUI. Am I missing something? Is there a better way to achieve this?</p> <p><hr /></p> <p>An example: I have a simple app with a Start button that initiates some processing. The start button should be enabled only when a file has been opened using the menu. In addition, there's a permanent widget on the status bar that displays information.</p> <p>My application has states:</p> <ol> <li>Before the file is opened (in this state the status bar show something special and the start button is disabled)</li> <li>File was opened and processing wasn't started: the start button is enabled, status bar shows something else</li> <li>The processing is running: the start button now says "Stop", and the status bar reports progress</li> </ol> <p>In Wx, I'd have the update UI event of the button handle its state: the text on it, and whether it's enabled, depending on the application state. The same for the status bar (or I'd use EVT_IDLE for that).</p> <p>In Qt, I have to update the button in several methods that may affect the state, or just create a update_ui method and call it periodically in a timer. What is the more "QT"-ish way?</p>
1
2009-03-08T18:26:51Z
627,484
<p>In general, the more Qt-ish way is to update the button/toolbar as necessary in whatever functions require the update, or to consolidate some of the functionality and directly call that function when the program needs it (such as an updateUi function).</p> <p>You should be aware that in Qt, changing an attribute of a Ui element doesn't cause an immediate redraw, but queues a redraw in the event system, and multiple redraw calls are compressed into one where possible.</p> <p>As for the multiple changes relating to state, have a look at <a href="http://labs.qtsoftware.com/blogs/2009/01/30/qt-state-machine-framework/" rel="nofollow">this blog post</a> about a hopefully-upcoming addition to Qt to more easily handle states. It looks like this would take care of a lot of your complaints, because in your multiple functions, you could just transition the state variable, and the other parts of the UI should update to match. It's not positive this will make it into the next Qt release (although I would bet on it, or something similar), and I have no idea how closely PyQt tracks the Qt releases. Or alternately, you could use the concept and create your own class to track the state as needed.</p>
1
2009-03-09T18:31:03Z
[ "python", "qt", "wxpython", "pyqt" ]
What should I be aware of when moving from asp.net to python for web development?
624,062
<p>I'm thinking about converting an app from Asp.net to python. I would like to know: what are the key comparisons to be aware of when moving a asp.net app to python(insert framework)?</p> <p>Does python have user controls? Master pages? </p>
3
2009-03-08T18:34:58Z
624,079
<p>First, Python is a language, while ASP.NET is a web framework. In fact, you can code ASP.NET applications using <a href="http://www.codeplex.com/IronPython" rel="nofollow">IronPython</a>.</p> <p>If you want to leave ASP.NET behind and go with the Python "stack," then you can choose from several different web application frameworks, including <a href="http://en.wikipedia.org/wiki/Django%5F%28web%5Fframework%29" rel="nofollow">Django</a> and <a href="http://en.wikipedia.org/wiki/Zope" rel="nofollow">Zope</a>.</p> <p>Zope, for example, offers a pluggable architecture where you can "add on" things like wikis, blogs, and so on. It also has page templates, which are somewhat similar to the ASP.NET master page.</p>
8
2009-03-08T18:44:05Z
[ "asp.net", "python" ]
What should I be aware of when moving from asp.net to python for web development?
624,062
<p>I'm thinking about converting an app from Asp.net to python. I would like to know: what are the key comparisons to be aware of when moving a asp.net app to python(insert framework)?</p> <p>Does python have user controls? Master pages? </p>
3
2009-03-08T18:34:58Z
624,119
<p>I second the note by Out Into Space on how python is a language versus a web framework; it's an important observation that underlies pretty much everything you will experience in moving from ASP.NET to Python.</p> <p>On a similar note, you will also find that the differences in language style and developer community between C#/VB.NET and Python influence the basic approach to developing web frameworks. This would be the same whether you were moving from web frameworks written in java, php, ruby, perl or any other language for that matter.</p> <p>The old "when you have a hammer, everything looks like a nail" adage really shows in the basic design of the frameworks :-) Because of this, though, you will find yourself with a few paradigm shifts to make when you substitute that hammer for a screwdriver.</p> <p>For example, Python web frameworks rely much less on declarative configuration than ASP.NET. Django, for example, has only a single config file that really has only a couple dozen lines (once you strip out the comments :-) ). Similarly, URL configuration and the page lifecycle are quite compact compared to ASP.NET, while being just as powerful. There's more "convention" over configuration (though much less so that Rails), and heavy use of the fact that modules in Python are top-level objects in the language... not everything has to be a class. This cuts down on the amount of code involved, and makes the application flow highly readable. </p> <p>As Out Into Space mentioned, zope's page templates are "somewhat" similar to ASP.NET master page, but not exactly. Django also offers page templates that inherit from each other, and they work very well, but not if you're trying to use them like an ASP.NET template.</p> <p>There also isn't a tradition of user controls in Python web frameworks a la .NET. The configuration machinery, request/response process indirection, handler complexity, and code-library size is just not part of the feel that python developers have for their toolset.</p> <p>We all argue that you can build the same web application, with probably less code, and more easily debuggable/maintainable using pythonic-tools :-) The main benefit here being that you also get to take advantage of the python language, and a pythonic framework, which is what makes python developers happy to go to work in the morning. YMMV, of course.</p> <p>All of which to say, you'll find you can do everything you've always done, just differently. Whether or not the differences please or frustrate you will determine if a python web framework is the right tool for you in the long run.</p>
4
2009-03-08T19:18:05Z
[ "asp.net", "python" ]
What should I be aware of when moving from asp.net to python for web development?
624,062
<p>I'm thinking about converting an app from Asp.net to python. I would like to know: what are the key comparisons to be aware of when moving a asp.net app to python(insert framework)?</p> <p>Does python have user controls? Master pages? </p>
3
2009-03-08T18:34:58Z
637,273
<p>Most frameworks for python has a 'templating' engine which provide similar functionality of ASP.NET's Master pages and User Controls. :)</p> <p>Thanks for the replies Out Of Space and Jarret Hardie</p>
0
2009-03-12T03:38:56Z
[ "asp.net", "python" ]
Twill/Mechanize access to html content
624,232
<p>Couple of questions regarding <a href="http://twill.idyll.org/" rel="nofollow">Twill</a> and <a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow">Mechanize</a>:</p> <ol> <li><p>Is Twill still relevant as a web-automation tool? If yes, then why is not currently maintained? If no, has Mechanize matured further to support Twill-style simple scripting? Or is there another package that has stepped up to fill the gap?</p></li> <li><p>I was able to very quickly setup a couple of test suites in python using Twill, but I'm a little confused on how to access the information that Twill spits out in my python program. That is, I can do showforms() and see the form values neatly listed and I can use fv to update the form values and submit. But how do I access one of those form values as a python var? How can I say something like: <code>someField1Value = fv("1","someField1")</code></p></li> </ol>
5
2009-03-08T20:30:54Z
1,718,676
<p>Twill is a <a href="http://twill.idyll.org/python-api.html" rel="nofollow">thin shell around the mechanize package</a>. You are right it does not appear to be actively maintained so I would stick with Mechanize.</p> <p>However Mechanize does not support the simple interface you are after. For that I would recommend <a href="http://groups.csail.mit.edu/uid/chickenfoot/quickstart.html" rel="nofollow">Chickenfoot</a>.</p>
1
2009-11-11T22:54:49Z
[ "python", "twill", "mechanize-python" ]
Twill/Mechanize access to html content
624,232
<p>Couple of questions regarding <a href="http://twill.idyll.org/" rel="nofollow">Twill</a> and <a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow">Mechanize</a>:</p> <ol> <li><p>Is Twill still relevant as a web-automation tool? If yes, then why is not currently maintained? If no, has Mechanize matured further to support Twill-style simple scripting? Or is there another package that has stepped up to fill the gap?</p></li> <li><p>I was able to very quickly setup a couple of test suites in python using Twill, but I'm a little confused on how to access the information that Twill spits out in my python program. That is, I can do showforms() and see the form values neatly listed and I can use fv to update the form values and submit. But how do I access one of those form values as a python var? How can I say something like: <code>someField1Value = fv("1","someField1")</code></p></li> </ol>
5
2009-03-08T20:30:54Z
22,848,600
<p>This question is old, but ranking high on google.</p> <p>As of 2014 oficial twill seems quite dead, also the mailing list.</p> <p>There are forks on github:</p> <p><a href="https://github.com/zenoss/twill" rel="nofollow">https://github.com/zenoss/twill</a></p> <p><a href="https://github.com/ctb/twill" rel="nofollow">https://github.com/ctb/twill</a></p>
0
2014-04-03T20:42:59Z
[ "python", "twill", "mechanize-python" ]
How do I make a Django ModelForm menu item selected by default?
624,265
<p>I am working on a Django app. One of my models, "User", includes a "gender" field, as defined below:</p> <pre><code>GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True) </code></pre> <p>I am using a ModelForm to generate a "new user" HTML form. My Google-fu seems to be failing me -- how can I make this HTML form have the "Male" item selected by default in the drop-down box? (i.e. so <code>selected="selected"</code> for this item.)</p>
9
2009-03-08T20:56:46Z
624,308
<p>Surely <code>default</code> will do the trick?</p> <p>e.g.</p> <pre><code>gender = models.CharField(max_length=1, choices=GENDER_CHOICES, default='M', null=True)</code></pre>
7
2009-03-08T21:19:46Z
[ "python", "django", "django-forms" ]
How do I make a Django ModelForm menu item selected by default?
624,265
<p>I am working on a Django app. One of my models, "User", includes a "gender" field, as defined below:</p> <pre><code>GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True) </code></pre> <p>I am using a ModelForm to generate a "new user" HTML form. My Google-fu seems to be failing me -- how can I make this HTML form have the "Male" item selected by default in the drop-down box? (i.e. so <code>selected="selected"</code> for this item.)</p>
9
2009-03-08T20:56:46Z
624,361
<p>If you need a blank form with a default value selected, then pass an 'initial' dictionary to the constructor of your model form using the name of your field as the key:</p> <pre><code>form = MyModelForm (initial={'gender':'M'}) </code></pre> <p>-OR-</p> <p>You can override certain attributes of a ModelForm using the declarative nature of the Forms API. However, this is probably a little cumbersome for this use case and I mention it only to show you that you can do it. You may find other uses for this in the future.</p> <pre><code>class MyModelForm (forms.ModelForm): gender = forms.ChoiceField (choices=..., initial='M', ...) class Meta: model=MyModel </code></pre> <p>-OR-</p> <p>If you want a ModelForm that is bound to a particular instance of your model, you can pass an 'instance' of your model which causes Django to pull the selected value from that model. </p> <pre><code>form = MyModelForm (instance=someinst) </code></pre>
15
2009-03-08T21:45:42Z
[ "python", "django", "django-forms" ]
How can I customize the output from pygments?
624,345
<p>If I run a python source file through pygments, it outputs html code whose elements class belong to some CSS file pygments is using. Could the style attributes be included in the outputted html so that I don't have to provide a CSS file?</p>
1
2009-03-08T21:37:16Z
624,477
<p>Usually, your code is only one of many things on a web page. You often want code to look different from the other content. You, generally, want to control the style of the code as part of the overall page style. CSS is your first, best choice for this.</p> <p>However, you can embed the styles in the HTML if that seems better. Here's an example that shows the <code>&lt;style&gt;</code> tag in the <code>&lt;head&gt;</code> tag.</p> <p><a href="http://www.w3schools.com/TAGS/tag_style.asp" rel="nofollow">http://www.w3schools.com/TAGS/tag_style.asp</a></p>
-2
2009-03-08T22:43:01Z
[ "python", "html", "css", "pygments" ]
How can I customize the output from pygments?
624,345
<p>If I run a python source file through pygments, it outputs html code whose elements class belong to some CSS file pygments is using. Could the style attributes be included in the outputted html so that I don't have to provide a CSS file?</p>
1
2009-03-08T21:37:16Z
624,532
<p>By setting the <strong>noclasses</strong> attribute to <strong>True</strong>, only inline styles will be generated. Here's a snippet that does the job just fine:</p> <pre><code> formatter = HtmlFormatter(style=MyStyle) formatter.noclasses = True print highlight(content,PythonLexer(),formatter) </code></pre>
5
2009-03-08T23:22:37Z
[ "python", "html", "css", "pygments" ]
How can I customize the output from pygments?
624,345
<p>If I run a python source file through pygments, it outputs html code whose elements class belong to some CSS file pygments is using. Could the style attributes be included in the outputted html so that I don't have to provide a CSS file?</p>
1
2009-03-08T21:37:16Z
624,717
<p>Pass full=True to the HtmlFormatter constructor.</p>
0
2009-03-09T01:29:47Z
[ "python", "html", "css", "pygments" ]
How can I customize the output from pygments?
624,345
<p>If I run a python source file through pygments, it outputs html code whose elements class belong to some CSS file pygments is using. Could the style attributes be included in the outputted html so that I don't have to provide a CSS file?</p>
1
2009-03-08T21:37:16Z
10,409,731
<p>@Ignacio: quite the opposite:</p> <pre><code>from pygments import highlight from pygments.lexers import PythonLexer from pygments.formatters import HtmlFormatter code = 'print "Hello World"' print highlight(code, PythonLexer(), HtmlFormatter(noclasses=True)) </code></pre> <p>[ ref.: <a href="http://pygments.org/docs/formatters/" rel="nofollow">http://pygments.org/docs/formatters/</a>, see HtmlFormatter ]</p> <p>( Basically it is the same as Tempus's answer, I just thought that a full code snippet may save a few seconds ) )</p> <p>PS. The ones who think that the original question is ill-posed, may imagine e.g. the task of pasting highlighted code into a blog entry hosted by a third-party service. </p>
0
2012-05-02T07:51:03Z
[ "python", "html", "css", "pygments" ]
Why am I getting an invalid syntax easy_install error?
624,492
<p>I need to use easy_install to install a package. I installed the enthought distribution, and popped into IDLE to say: </p> <pre><code>&gt;&gt;&gt; easy_install SQLobject SyntaxError: invalid syntax </code></pre> <p>What am I doing wrong? <code>easy_install</code> certainly exists, as does the package. help('easy_install') gives me some basic help. <code>import easy_install</code> doesn't change things either.</p> <p>Any hints? I know I'm missing something really basic here.</p>
4
2009-03-08T22:51:58Z
624,499
<p>easy_install is a shell command. You don't need to put it in a python script.</p> <pre><code>easy_install SQLobject </code></pre> <p>Type that straight into a bash (or other) shell, as long as easy_install is in your path.</p>
18
2009-03-08T22:58:13Z
[ "python", "easy-install" ]
Using Django admin look and feel in my own application
624,535
<p>I like the very simple but still really elegant look and feel of the django admin and I was wondering if there is a way to apply it to my own application.</p> <p>(I think that I've read something like that somewhere, but now I cannot find the page again.)</p> <p>(edited: what I am looking for is a way to do it automatically by extending templates, importing modules, or something similar, not just copy&amp;paste the css and javascript code)</p>
0
2009-03-08T23:22:51Z
625,235
<p>Are you sure you want to take every bit of admin-site's look &amp; feel?? I think you would need to customize some, as in header footer etc.</p> <p>To do that, just copy base.html from </p> <blockquote> <p>"djangosrc/contrib/admin/templates/admin/"</p> </blockquote> <p>and keep it in </p> <blockquote> <p>"your_template_dir/admin/base.html" or "your_template_dir/admin/mybase.html"</p> </blockquote> <p>Just change whatever HTML you want to customize and keep rest as it is (like CSS and Javascript) and keep on extending this template in other templates of your application. Your view should provide what it needs to render (take a look at any django view from source) and you'll have everything what admin look &amp; feel had. More you can do by extending base_site.html in same manner.</p> <blockquote> <p>(Note: if you keep the name 'base.html' the changes made in html will affect Django Admin too. As this is the way we change how Django Admin look itself.)</p> </blockquote>
4
2009-03-09T06:47:34Z
[ "python", "django", "django-admin", "styles", "look-and-feel" ]
Using Django admin look and feel in my own application
624,535
<p>I like the very simple but still really elegant look and feel of the django admin and I was wondering if there is a way to apply it to my own application.</p> <p>(I think that I've read something like that somewhere, but now I cannot find the page again.)</p> <p>(edited: what I am looking for is a way to do it automatically by extending templates, importing modules, or something similar, not just copy&amp;paste the css and javascript code)</p>
0
2009-03-08T23:22:51Z
625,891
<pre><code>{% extends "admin/base_site.html" %} </code></pre> <p>is usually a good place to start but do look at the templates in contrib/admin/templates and copy some of the techniques there. </p>
2
2009-03-09T11:34:30Z
[ "python", "django", "django-admin", "styles", "look-and-feel" ]
Unable to install python-setuptools: ./configure: No such file or directory
624,671
<p>The question is related to <a href="http://stackoverflow.com/questions/622744/unable-to-install-python-without-sudo-access/622810#622810">the answer to "Unable to install Python without sudo access"</a>.</p> <p>I need to install python-setuptools to install python modules. I have extracted the installation package.</p> <p>I get the following error when configuring</p> <pre><code>[~/wepapps/pythonModules/setuptools-0.6c9]# ./configure --prefix=/home/masi/.local -bash: ./configure: No such file or directory </code></pre> <p>I did not find the solution at <a href="http://peak.telecommunity.com/DevCenter/EasyInstall" rel="nofollow">the program's homepage</a>.</p> <p>How can I resolve this error?</p>
2
2009-03-09T01:06:48Z
624,731
<p>You might want to check <a href="http://peak.telecommunity.com/DevCenter/EasyInstall#custom-installation-locations" rel="nofollow">http://peak.telecommunity.com/DevCenter/EasyInstall#custom-installation-locations</a>.</p> <p>EasyInstall is a python module with some shell scripts (or some shell scripts with a python module?) and does not use the unix make tool that gets configured with the "./configure" command. It looks like your best bet is to try editing ~/.pydistutils.cfg to include:</p> <pre><code>[install] install_lib = /home/masi/.local/lib/python/site-packages/ install_scripts = /home/masi/.local/bin </code></pre> <p>You'll also presumably have made the ~/.local/bin/ folder part of your PATH so you can run the easy_install script. (I'm not sure exactly where the site-packages directory will be under .local, but it shouldn't be hard to find.)</p> <p>Hope this helps.</p>
1
2009-03-09T01:34:49Z
[ "python", "setuptools", "failed-installation" ]
Unable to install python-setuptools: ./configure: No such file or directory
624,671
<p>The question is related to <a href="http://stackoverflow.com/questions/622744/unable-to-install-python-without-sudo-access/622810#622810">the answer to "Unable to install Python without sudo access"</a>.</p> <p>I need to install python-setuptools to install python modules. I have extracted the installation package.</p> <p>I get the following error when configuring</p> <pre><code>[~/wepapps/pythonModules/setuptools-0.6c9]# ./configure --prefix=/home/masi/.local -bash: ./configure: No such file or directory </code></pre> <p>I did not find the solution at <a href="http://peak.telecommunity.com/DevCenter/EasyInstall" rel="nofollow">the program's homepage</a>.</p> <p>How can I resolve this error?</p>
2
2009-03-09T01:06:48Z
624,998
<p>As Noah states, setuptools isn't an automake package so doesn't use ‘./configure’. Instead it's a pure-Python-style ‘setup.py’ (distutils) script.</p> <p>You shouldn't normally need to play with .pydistutils.cfg, as long as you run it with the right version of Python. So if you haven't added the .local/bin folder to PATH, you'd have to say explicitly:</p> <pre><code>/home/masi/.local/bin/python setup.py install </code></pre> <p>AIUI this should Just Work.</p> <blockquote> <p>I did not find the solution at the program's homepage.</p> </blockquote> <p>Yeah, they want you to install it from a shell script egg which uses the default version of Python. Which you don't want.</p> <p>(Another approach if you can't get setuptools to work is to skip it and install each module and dependency manually. Personally I have a bit of an aversion to setuptools/egg, as it contains far too much “clever” magic for my tastes and makes a mess of my filesystem. But I'm an old curmudgeon like that. Most Python modules can be obtained as simple Python files or plain old distutils scripts, but unfortunately there are <em>some</em> that demand eggs.)</p>
2
2009-03-09T04:22:19Z
[ "python", "setuptools", "failed-installation" ]
Why aren't signals simply called events?
624,844
<p>From what I can tell, in Python and and Django, signals are simply delegated events. Is there anything that functionally differentiates them from the typical notion of events in C#, Java, ActionScript, etc?</p>
4
2009-03-09T02:42:37Z
624,855
<p>Signals typically have an association with an operating system facility and events are typically application-defined. In some technology stacks, the OS-level stuff may be hidden well enough that there isn't a difference in the API, but in others perhaps not.</p>
4
2009-03-09T02:47:44Z
[ "python", "signals", "django-signals" ]
Why aren't signals simply called events?
624,844
<p>From what I can tell, in Python and and Django, signals are simply delegated events. Is there anything that functionally differentiates them from the typical notion of events in C#, Java, ActionScript, etc?</p>
4
2009-03-09T02:42:37Z
624,860
<p>You might as well ask "Why aren't events simply called signals?". Differences in terminology happen.</p>
1
2009-03-09T02:49:20Z
[ "python", "signals", "django-signals" ]
Why aren't signals simply called events?
624,844
<p>From what I can tell, in Python and and Django, signals are simply delegated events. Is there anything that functionally differentiates them from the typical notion of events in C#, Java, ActionScript, etc?</p>
4
2009-03-09T02:42:37Z
624,861
<p>Afaik Qt had the first signal/slot implementation. <a href="http://doc.trolltech.com/4.4/signalsandslots.html" rel="nofollow">Qt's docs</a> explain the metaphor: "A signal is emitted when a particular event occurs". The distinction is so subtle that the nomenclature has been blurred.</p>
2
2009-03-09T02:51:10Z
[ "python", "signals", "django-signals" ]
Why aren't signals simply called events?
624,844
<p>From what I can tell, in Python and and Django, signals are simply delegated events. Is there anything that functionally differentiates them from the typical notion of events in C#, Java, ActionScript, etc?</p>
4
2009-03-09T02:42:37Z
624,865
<p>Actually, "signals" have been around longer than events have. In the earliest usage, a signal was an asynchronous way for processes to get notified that events had occurred. Since Unix is much older than Django (and since a lot of the Django work came from pydispatcher, where the original stuff was done), the name has stuck.</p> <p>Events are really signals, you might say!</p>
24
2009-03-09T02:52:18Z
[ "python", "signals", "django-signals" ]
how to detect whether a python variable is a function?
624,926
<p>I have a variable, <code>x</code>, and I want to know whether it is pointing to a function or not.</p> <p>I had hoped I could do something like:</p> <pre><code>&gt;&gt;&gt; isinstance(x, function) </code></pre> <p>But that gives me:</p> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? NameError: name 'function' is not defined </code></pre> <p>The reason I picked that is because </p> <pre><code>&gt;&gt;&gt; type(x) &lt;type 'function'&gt; </code></pre>
321
2009-03-09T03:31:30Z
624,930
<p>The following should return a boolean:</p> <pre><code>callable(x) </code></pre>
24
2009-03-09T03:33:49Z
[ "python" ]
how to detect whether a python variable is a function?
624,926
<p>I have a variable, <code>x</code>, and I want to know whether it is pointing to a function or not.</p> <p>I had hoped I could do something like:</p> <pre><code>&gt;&gt;&gt; isinstance(x, function) </code></pre> <p>But that gives me:</p> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? NameError: name 'function' is not defined </code></pre> <p>The reason I picked that is because </p> <pre><code>&gt;&gt;&gt; type(x) &lt;type 'function'&gt; </code></pre>
321
2009-03-09T03:31:30Z
624,933
<p>Try using <code>callable(x)</code>.</p>
6
2009-03-09T03:35:11Z
[ "python" ]
how to detect whether a python variable is a function?
624,926
<p>I have a variable, <code>x</code>, and I want to know whether it is pointing to a function or not.</p> <p>I had hoped I could do something like:</p> <pre><code>&gt;&gt;&gt; isinstance(x, function) </code></pre> <p>But that gives me:</p> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? NameError: name 'function' is not defined </code></pre> <p>The reason I picked that is because </p> <pre><code>&gt;&gt;&gt; type(x) &lt;type 'function'&gt; </code></pre>
321
2009-03-09T03:31:30Z
624,939
<p>If this is for Python 2.x or for Python 3.2+, you can also use <code>callable()</code>. It used to be deprecated, but is now undeprecated, so you can use it again. You can read the discussion here: <a href="http://bugs.python.org/issue10518">http://bugs.python.org/issue10518</a>. You can do this with:</p> <pre><code>callable(obj) </code></pre> <p>If this is for Python 3.x but before 3.2, check if the object has a <code>__call__</code> attribute. You can do this with:</p> <pre><code>hasattr(obj, '__call__') </code></pre> <p>The oft-suggested <code>types.FunctionTypes</code> approach is not correct because it fails to cover many cases that you would presumably want it to pass, like with builtins:</p> <pre><code>&gt;&gt;&gt; isinstance(open, types.FunctionType) False &gt;&gt;&gt; callable(open) True </code></pre> <p>The proper way to check properties of duck-typed objects is to ask them if they quack, not to see if they fit in a duck-sized container. Don't use <code>types.FunctionType</code> unless you have a very specific idea of what a function is.</p>
401
2009-03-09T03:39:02Z
[ "python" ]
how to detect whether a python variable is a function?
624,926
<p>I have a variable, <code>x</code>, and I want to know whether it is pointing to a function or not.</p> <p>I had hoped I could do something like:</p> <pre><code>&gt;&gt;&gt; isinstance(x, function) </code></pre> <p>But that gives me:</p> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? NameError: name 'function' is not defined </code></pre> <p>The reason I picked that is because </p> <pre><code>&gt;&gt;&gt; type(x) &lt;type 'function'&gt; </code></pre>
321
2009-03-09T03:31:30Z
624,948
<p>Builtin types that don't have constructors in the built-in namespace (e.g. functions, generators, methods) are in the <code>types</code> module. You can use <code>types.FunctionType</code> in an isinstance call.</p> <pre><code>In [1]: import types In [2]: types.FunctionType Out[2]: &lt;type 'function'&gt; In [3]: def f(): pass ...: In [4]: isinstance(f, types.FunctionType) Out[4]: True In [5]: isinstance(lambda x : None, types.FunctionType) Out[5]: True </code></pre>
198
2009-03-09T03:47:57Z
[ "python" ]
how to detect whether a python variable is a function?
624,926
<p>I have a variable, <code>x</code>, and I want to know whether it is pointing to a function or not.</p> <p>I had hoped I could do something like:</p> <pre><code>&gt;&gt;&gt; isinstance(x, function) </code></pre> <p>But that gives me:</p> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? NameError: name 'function' is not defined </code></pre> <p>The reason I picked that is because </p> <pre><code>&gt;&gt;&gt; type(x) &lt;type 'function'&gt; </code></pre>
321
2009-03-09T03:31:30Z
624,966
<p><code>callable(x)</code> <em>will</em> return true if the object passed can be called in Python, but the function does not exist in Python 3.0, and properly speaking will not distinguish between:</p> <pre><code>class A(object): def __call__(self): return 'Foo' def B(): return 'Bar' a = A() b = B print type(a), callable(a) print type(b), callable(b) </code></pre> <p>You'll get <code>&lt;class 'A'&gt; True</code> and <code>&lt;type function&gt; True</code> as output.</p> <p><code>isinstance</code> works perfectly well to determine if something is a function (try <code>isinstance(b, types.FunctionType)</code>); if you're really interested in knowing if something can be called, you can either use <code>hasattr(b, '__call__')</code> or just try it.</p> <pre><code>test_as_func = True try: b() except TypeError: test_as_func = False except: pass </code></pre> <p>This, of course, won't tell you whether it's callable but throws a <code>TypeError</code> when it executes, or isn't callable in the first place. That may not matter to you.</p>
16
2009-03-09T03:58:55Z
[ "python" ]
how to detect whether a python variable is a function?
624,926
<p>I have a variable, <code>x</code>, and I want to know whether it is pointing to a function or not.</p> <p>I had hoped I could do something like:</p> <pre><code>&gt;&gt;&gt; isinstance(x, function) </code></pre> <p>But that gives me:</p> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? NameError: name 'function' is not defined </code></pre> <p>The reason I picked that is because </p> <pre><code>&gt;&gt;&gt; type(x) &lt;type 'function'&gt; </code></pre>
321
2009-03-09T03:31:30Z
624,994
<p>A function is just a class with a <code>__call__</code> method, so you can do</p> <pre><code>hasattr(obj, '__call__') </code></pre> <p>For example:</p> <pre><code>&gt;&gt;&gt; hasattr(x, '__call__') True &gt;&gt;&gt; x = 2 &gt;&gt;&gt; hasattr(x, '__call__') False </code></pre> <p>That is the "best" way of doing it, but depending on why you need to know if it's callable or note, you could just put it in a try/execpt block:</p> <pre><code>try: x() except TypeError: print "was not callable" </code></pre> <p>It's arguable if try/except is more Python'y than doing <code>if hasattr(x, '__call__'): x()</code>.. I would say <code>hasattr</code> is more accurate, since you wont accidently catch the wrong TypeError, for example:</p> <pre><code>&gt;&gt;&gt; def x(): ... raise TypeError ... &gt;&gt;&gt; hasattr(x, '__call__') True # Correct &gt;&gt;&gt; try: ... x() ... except TypeError: ... print "x was not callable" ... x was not callable # Wrong! </code></pre>
3
2009-03-09T04:19:43Z
[ "python" ]
how to detect whether a python variable is a function?
624,926
<p>I have a variable, <code>x</code>, and I want to know whether it is pointing to a function or not.</p> <p>I had hoped I could do something like:</p> <pre><code>&gt;&gt;&gt; isinstance(x, function) </code></pre> <p>But that gives me:</p> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? NameError: name 'function' is not defined </code></pre> <p>The reason I picked that is because </p> <pre><code>&gt;&gt;&gt; type(x) &lt;type 'function'&gt; </code></pre>
321
2009-03-09T03:31:30Z
4,234,284
<p>Python's 2to3 tool (<a href="http://docs.python.org/dev/library/2to3.html">http://docs.python.org/dev/library/2to3.html</a>) suggests:</p> <pre><code>import collections isinstance(obj, collections.Callable) </code></pre> <p>It seems this was chosen instead of the <code>hasattr(x, '__call__')</code> method because of <a href="http://bugs.python.org/issue7006">http://bugs.python.org/issue7006</a>.</p>
20
2010-11-20T18:27:53Z
[ "python" ]
how to detect whether a python variable is a function?
624,926
<p>I have a variable, <code>x</code>, and I want to know whether it is pointing to a function or not.</p> <p>I had hoped I could do something like:</p> <pre><code>&gt;&gt;&gt; isinstance(x, function) </code></pre> <p>But that gives me:</p> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? NameError: name 'function' is not defined </code></pre> <p>The reason I picked that is because </p> <pre><code>&gt;&gt;&gt; type(x) &lt;type 'function'&gt; </code></pre>
321
2009-03-09T03:31:30Z
7,548,584
<p>In Python3 I came up with <code>type (f) == type (lambda x:x)</code> which yields <code>True</code> if <code>f</code> is a function and <code>False</code> if it is not. But I think I prefer <code>isinstance (f, types.FunctionType)</code>, which feels less ad hoc. I wanted to do <code>type (f) is function</code>, but that doesn't work. </p>
1
2011-09-25T21:02:46Z
[ "python" ]
how to detect whether a python variable is a function?
624,926
<p>I have a variable, <code>x</code>, and I want to know whether it is pointing to a function or not.</p> <p>I had hoped I could do something like:</p> <pre><code>&gt;&gt;&gt; isinstance(x, function) </code></pre> <p>But that gives me:</p> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? NameError: name 'function' is not defined </code></pre> <p>The reason I picked that is because </p> <pre><code>&gt;&gt;&gt; type(x) &lt;type 'function'&gt; </code></pre>
321
2009-03-09T03:31:30Z
8,302,728
<p><a href="http://docs.python.org/library/inspect.html#module-inspect">Since Python 2.1</a> you can import <code>isfunction</code> from the <a href="http://docs.python.org/library/inspect.html"><code>inspect</code></a> module.</p> <pre><code>&gt;&gt;&gt; from inspect import isfunction &gt;&gt;&gt; def f(): pass &gt;&gt;&gt; isfunction(f) True &gt;&gt;&gt; isfunction(lambda x: x) True </code></pre>
66
2011-11-28T21:40:27Z
[ "python" ]
how to detect whether a python variable is a function?
624,926
<p>I have a variable, <code>x</code>, and I want to know whether it is pointing to a function or not.</p> <p>I had hoped I could do something like:</p> <pre><code>&gt;&gt;&gt; isinstance(x, function) </code></pre> <p>But that gives me:</p> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? NameError: name 'function' is not defined </code></pre> <p>The reason I picked that is because </p> <pre><code>&gt;&gt;&gt; type(x) &lt;type 'function'&gt; </code></pre>
321
2009-03-09T03:31:30Z
13,605,330
<p>If you want to detect everything that syntactically looks like a function: a function, method, built-in fun/meth, lambda ... but <strong>exclude</strong> callable objects (objects with <code>__call__</code> method defined), then try this one:</p> <pre><code>import types isinstance(x, (types.FunctionType, types.BuiltinFunctionType, types.MethodType, types.BuiltinMethodType, types.UnboundMethodType)) </code></pre> <p>I compared this with the code of <code>is*()</code> checks in <code>inspect</code> module and the expression above is much more complete, especially if your goal is filtering out any functions or detecting regular properties of an object.</p>
9
2012-11-28T12:42:38Z
[ "python" ]
how to detect whether a python variable is a function?
624,926
<p>I have a variable, <code>x</code>, and I want to know whether it is pointing to a function or not.</p> <p>I had hoped I could do something like:</p> <pre><code>&gt;&gt;&gt; isinstance(x, function) </code></pre> <p>But that gives me:</p> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? NameError: name 'function' is not defined </code></pre> <p>The reason I picked that is because </p> <pre><code>&gt;&gt;&gt; type(x) &lt;type 'function'&gt; </code></pre>
321
2009-03-09T03:31:30Z
17,008,232
<p>Following previous replies, I came up with this:</p> <pre><code>from pprint import pprint def print_callables_of(obj): li = [] for name in dir(obj): attr = getattr(obj, name) if hasattr(attr, '__call__'): li.append(name) pprint(li) </code></pre>
0
2013-06-09T09:26:26Z
[ "python" ]
how to detect whether a python variable is a function?
624,926
<p>I have a variable, <code>x</code>, and I want to know whether it is pointing to a function or not.</p> <p>I had hoped I could do something like:</p> <pre><code>&gt;&gt;&gt; isinstance(x, function) </code></pre> <p>But that gives me:</p> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? NameError: name 'function' is not defined </code></pre> <p>The reason I picked that is because </p> <pre><code>&gt;&gt;&gt; type(x) &lt;type 'function'&gt; </code></pre>
321
2009-03-09T03:31:30Z
18,419,706
<p>Whatever function is a class so you can take the name of the class of instance x and compare:</p> <pre><code> if(x.__class__.__name__ == 'function'): print "it's a function" </code></pre>
1
2013-08-24T14:38:39Z
[ "python" ]
how to detect whether a python variable is a function?
624,926
<p>I have a variable, <code>x</code>, and I want to know whether it is pointing to a function or not.</p> <p>I had hoped I could do something like:</p> <pre><code>&gt;&gt;&gt; isinstance(x, function) </code></pre> <p>But that gives me:</p> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? NameError: name 'function' is not defined </code></pre> <p>The reason I picked that is because </p> <pre><code>&gt;&gt;&gt; type(x) &lt;type 'function'&gt; </code></pre>
321
2009-03-09T03:31:30Z
18,703,281
<p>Instead of checking for <code>'__call__'</code> (which is not exclusive to functions), you can check whether a user-defined function has attributes <code>func_name</code>, <code>func_doc</code>, etc. This does not work for methods. </p> <pre><code>&gt;&gt;&gt; def x(): pass ... &gt;&gt;&gt; hasattr(x, 'func_name') True </code></pre> <p>Another way of checking is using the <code>isfunction()</code> method from the <code>inspect</code> module.</p> <pre><code>&gt;&gt;&gt; import inspect &gt;&gt;&gt; inspect.isfunction(x) True </code></pre> <p>To check if an object is a method, use <code>inspect.ismethod()</code></p>
1
2013-09-09T16:59:39Z
[ "python" ]
how to detect whether a python variable is a function?
624,926
<p>I have a variable, <code>x</code>, and I want to know whether it is pointing to a function or not.</p> <p>I had hoped I could do something like:</p> <pre><code>&gt;&gt;&gt; isinstance(x, function) </code></pre> <p>But that gives me:</p> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? NameError: name 'function' is not defined </code></pre> <p>The reason I picked that is because </p> <pre><code>&gt;&gt;&gt; type(x) &lt;type 'function'&gt; </code></pre>
321
2009-03-09T03:31:30Z
18,704,793
<p>The accepted answer was at the time it was offered thought to be correct; As it turns out, there is <em>no substitute</em> for <code>callable()</code>, which is back in python 3.2: Specifically, <code>callable()</code> checks the <code>tp_call</code> field of the object being tested. There is no plain python equivalent. Most of the suggested tests are correct most of the time:</p> <pre><code>&gt;&gt;&gt; class Spam(object): ... def __call__(self): ... return 'OK' &gt;&gt;&gt; can_o_spam = Spam() &gt;&gt;&gt; can_o_spam() 'OK' &gt;&gt;&gt; callable(can_o_spam) True &gt;&gt;&gt; hasattr(can_o_spam, '__call__') True &gt;&gt;&gt; import collections &gt;&gt;&gt; isinstance(can_o_spam, collections.Callable) True </code></pre> <p>We can throw a monkey-wrench into this by removing the <code>__call__</code> from the class. And just to keep things extra exciting, add a fake <code>__call__</code> to the instance!</p> <pre><code>&gt;&gt;&gt; del Spam.__call__ &gt;&gt;&gt; can_o_spam.__call__ = lambda *args: 'OK?' </code></pre> <p>Notice this really isn't callable:</p> <pre><code>&gt;&gt;&gt; can_o_spam() Traceback (most recent call last): ... TypeError: 'Spam' object is not callable </code></pre> <p><code>callable()</code> returns the correct result:</p> <pre><code>&gt;&gt;&gt; callable(can_o_spam) False </code></pre> <p>But <code>hasattr</code> is <em>wrong</em>:</p> <pre><code>&gt;&gt;&gt; hasattr(can_o_spam, '__call__') True </code></pre> <p><code>can_o_spam</code> does have that attribute after all, its just not used when calling the instance.</p> <p>Even more subtle, <code>isinstance()</code> also gets this wrong:</p> <pre><code>&gt;&gt;&gt; isinstance(can_o_spam, collections.Callable) True </code></pre> <p>Because we used this check earlier and later deleted the method, <code>abc.ABCMeta</code> caches the result. Arguably this is a bug in <code>abc.ABCMeta</code>. That said, there's really no possible way it <em>could</em> produce a more accurate result than the result than by using <code>callable()</code> itself, since the <code>typeobject-&gt;tp_call</code> slot method is not accessible in any other way.</p> <p>Just use <code>callable()</code></p>
30
2013-09-09T18:42:29Z
[ "python" ]
how to detect whether a python variable is a function?
624,926
<p>I have a variable, <code>x</code>, and I want to know whether it is pointing to a function or not.</p> <p>I had hoped I could do something like:</p> <pre><code>&gt;&gt;&gt; isinstance(x, function) </code></pre> <p>But that gives me:</p> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? NameError: name 'function' is not defined </code></pre> <p>The reason I picked that is because </p> <pre><code>&gt;&gt;&gt; type(x) &lt;type 'function'&gt; </code></pre>
321
2009-03-09T03:31:30Z
19,898,483
<p>If the code will go on to perform the call if the value is callable, just perform the call and catch <code>TypeError</code>.</p> <pre><code>def myfunc(x): try: x() except TypeError: raise Exception("Not callable") </code></pre>
1
2013-11-11T03:45:17Z
[ "python" ]
how to detect whether a python variable is a function?
624,926
<p>I have a variable, <code>x</code>, and I want to know whether it is pointing to a function or not.</p> <p>I had hoped I could do something like:</p> <pre><code>&gt;&gt;&gt; isinstance(x, function) </code></pre> <p>But that gives me:</p> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? NameError: name 'function' is not defined </code></pre> <p>The reason I picked that is because </p> <pre><code>&gt;&gt;&gt; type(x) &lt;type 'function'&gt; </code></pre>
321
2009-03-09T03:31:30Z
20,291,931
<p>The solutions using <code>hasattr(obj, '__call__')</code> and <code>callable(.)</code> mentioned in some of the answers have a main drawback: both also return <code>True</code> for classes and instances of classes with a <code>__call__()</code> method. Eg.</p> <pre><code>&gt;&gt;&gt; import collections &gt;&gt;&gt; Test = collections.namedtuple('Test', []) &gt;&gt;&gt; callable(Test) True &gt;&gt;&gt; hasattr(Test, '__call__') True </code></pre> <p>One proper way of checking if an object is a user-defined function (and nothing but a that) is to use <code>isfunction(.)</code>:</p> <pre><code>&gt;&gt;&gt; import inspect &gt;&gt;&gt; inspect.isfunction(Test) False &gt;&gt;&gt; def t(): pass &gt;&gt;&gt; inspect.isfunction(t) True </code></pre> <p>If you need to check for other types, have a look at <a href="http://docs.python.org/3/library/inspect.html" rel="nofollow">inspect — Inspect live objects</a>.</p>
2
2013-11-29T19:00:03Z
[ "python" ]
how to detect whether a python variable is a function?
624,926
<p>I have a variable, <code>x</code>, and I want to know whether it is pointing to a function or not.</p> <p>I had hoped I could do something like:</p> <pre><code>&gt;&gt;&gt; isinstance(x, function) </code></pre> <p>But that gives me:</p> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? NameError: name 'function' is not defined </code></pre> <p>The reason I picked that is because </p> <pre><code>&gt;&gt;&gt; type(x) &lt;type 'function'&gt; </code></pre>
321
2009-03-09T03:31:30Z
21,311,982
<p>Here's a couple of other ways:</p> <pre><code>def isFunction1(f) : return type(f) == type(lambda x: x); def isFunction2(f) : return 'function' in str(type(f)); </code></pre> <p>Here's how I came up with the second:</p> <pre><code>&gt;&gt;&gt; type(lambda x: x); &lt;type 'function'&gt; &gt;&gt;&gt; str(type(lambda x: x)); "&lt;type 'function'&gt;" # Look Maa, function! ... I ACTUALLY told my mom about this! </code></pre>
3
2014-01-23T15:08:58Z
[ "python" ]
how to detect whether a python variable is a function?
624,926
<p>I have a variable, <code>x</code>, and I want to know whether it is pointing to a function or not.</p> <p>I had hoped I could do something like:</p> <pre><code>&gt;&gt;&gt; isinstance(x, function) </code></pre> <p>But that gives me:</p> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? NameError: name 'function' is not defined </code></pre> <p>The reason I picked that is because </p> <pre><code>&gt;&gt;&gt; type(x) &lt;type 'function'&gt; </code></pre>
321
2009-03-09T03:31:30Z
27,432,144
<p>Since classes also have <code>__call__</code> method, I recommend another solution:</p> <pre><code>class A(object): def __init__(self): pass def __call__(self): print 'I am a Class' MyClass = A() def foo(): pass print hasattr(foo.__class__, 'func_name') # Returns True print hasattr(A.__class__, 'func_name') # Returns False as expected print hasattr(foo, '__call__') # Returns True print hasattr(A, '__call__') # (!) Returns True while it is not a function </code></pre>
3
2014-12-11T20:51:58Z
[ "python" ]
how to detect whether a python variable is a function?
624,926
<p>I have a variable, <code>x</code>, and I want to know whether it is pointing to a function or not.</p> <p>I had hoped I could do something like:</p> <pre><code>&gt;&gt;&gt; isinstance(x, function) </code></pre> <p>But that gives me:</p> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? NameError: name 'function' is not defined </code></pre> <p>The reason I picked that is because </p> <pre><code>&gt;&gt;&gt; type(x) &lt;type 'function'&gt; </code></pre>
321
2009-03-09T03:31:30Z
39,288,418
<p>Note that Python classes are also callable.</p> <p>To get functions (and by functions we mean standard functions and lambdas) use:</p> <pre><code>import types def is_func(obj): return isinstance(obj, (types.FunctionType, types.LambdaType)) def f(x): return x assert is_func(f) assert is_func(lambda x: x) </code></pre>
0
2016-09-02T09:02:19Z
[ "python" ]
What will be the upgrade path to Python 3.x for Google App Engine Applications?
625,042
<p>What is required to make the transition to Python 3.x for Google App Engine?</p> <p>I know Google App Engine requires the use of at least Python 2.5. Is it possible to use Python 3.0 already on Google App Engine?</p>
9
2009-03-09T04:43:51Z
625,119
<p>It is impossible to currently use Python 3.x applications on Google App Engine. It's simply not supported, and I'd expect to see support for Java (or Perl, or PHP) before Python 3.x.</p> <p>That said, the upgrade path is likely to be very simple from Python 2.5 to Python 3.x on App Engine. If/when the capability is added, as long as you've coded your application anticipating <a href="http://docs.python.org/dev/3.0/whatsnew/3.0.html">the changes in Python itself</a>, it should be very straightforward. The heavy lifting has to be done by the Google Engineers. And you'll no doubt be able to keep your application at Python 2.5 for a long while after Python 3.0 is available.</p>
5
2009-03-09T05:30:17Z
[ "python", "google-app-engine" ]
What will be the upgrade path to Python 3.x for Google App Engine Applications?
625,042
<p>What is required to make the transition to Python 3.x for Google App Engine?</p> <p>I know Google App Engine requires the use of at least Python 2.5. Is it possible to use Python 3.0 already on Google App Engine?</p>
9
2009-03-09T04:43:51Z
625,130
<p>At least at the being, Guido was working closely with the team at Google who is building AppEngine. When this option does become available, you will have to <strong>edit your main XAML file</strong>.</p> <p>I agree with Chris B. that Python 3.0 support may not be forthcoming too soon, but I'm not sure I agree that it will come sooner than Perl or PHP. At the Google I/O conference last year, they were very mum on what future languages they would support on AppEngine but they were pretty clear on the fact that they're actively exploring how to safely allow other code to run. One of the main reason they chose to support Python is that they due to it's dynamically compiled nature, they could support 3rd party library extensions with the minimal restriction that all add-ons must be in pure Python.</p> <p>I wouldn't be surprised if Python 3.0 support was introduced sooner than new languages.</p>
1
2009-03-09T05:37:58Z
[ "python", "google-app-engine" ]
What will be the upgrade path to Python 3.x for Google App Engine Applications?
625,042
<p>What is required to make the transition to Python 3.x for Google App Engine?</p> <p>I know Google App Engine requires the use of at least Python 2.5. Is it possible to use Python 3.0 already on Google App Engine?</p>
9
2009-03-09T04:43:51Z
625,632
<p>The app.yaml syntax already supports multiple languages and multiple API versions, though only one of each (Python, API version 1) is currently supported. Presumably, one of those extension mechanisms will be used to specify that you want Python 3, and it'll be up to you to port your app over to work in Python 3, then change that setting.</p>
1
2009-03-09T10:04:23Z
[ "python", "google-app-engine" ]
What will be the upgrade path to Python 3.x for Google App Engine Applications?
625,042
<p>What is required to make the transition to Python 3.x for Google App Engine?</p> <p>I know Google App Engine requires the use of at least Python 2.5. Is it possible to use Python 3.0 already on Google App Engine?</p>
9
2009-03-09T04:43:51Z
4,182,126
<p>As it does not look like that google updates app engine to python 3 soon it might be worth to keep an eye on <a href="http://wiki.python.org/jython/RoadMap" rel="nofollow">Jython</a>. As of now they still work on 2.6, but that would already be better than 2.5.</p>
1
2010-11-15T07:03:40Z
[ "python", "google-app-engine" ]
Python __init__ and self what do they do?
625,083
<p>I'm learning the Python programming language, and I've come across certain things I don't fully understand. I'm coming from a C background, but I never went far with that either.</p> <p>What I'm trying to figure out is:</p> <p>In a method:</p> <pre><code>def method(self, blah): def __init__(?): .... .... </code></pre> <p>What does self do? what is it meant to be? and is it mandatory?</p> <p>What does the <code>__init__</code> method do? why is it necessary? etc</p> <p>I think they might be oop constructs, but I don't know very much..</p>
344
2009-03-09T05:09:51Z
625,095
<p>You would be correct, they are object-oriented constructs. Basically <code>self</code> is a reference (kind of like a pointer, but <code>self</code> is a special reference which you can't assign to) to an object, and <code>__init__</code> is a function which is called to initialize the object - that is, set the values of variables etc. - just after memory is allocated for it.</p>
6
2009-03-09T05:17:16Z
[ "python", "oop" ]
Python __init__ and self what do they do?
625,083
<p>I'm learning the Python programming language, and I've come across certain things I don't fully understand. I'm coming from a C background, but I never went far with that either.</p> <p>What I'm trying to figure out is:</p> <p>In a method:</p> <pre><code>def method(self, blah): def __init__(?): .... .... </code></pre> <p>What does self do? what is it meant to be? and is it mandatory?</p> <p>What does the <code>__init__</code> method do? why is it necessary? etc</p> <p>I think they might be oop constructs, but I don't know very much..</p>
344
2009-03-09T05:09:51Z
625,096
<p><code>__init__</code> does act like a constructor. You'll need to pass "self" to any class functions as the first argument if you want them to behave as non-static methods. "self" are instance variables for your class.</p>
14
2009-03-09T05:18:20Z
[ "python", "oop" ]
Python __init__ and self what do they do?
625,083
<p>I'm learning the Python programming language, and I've come across certain things I don't fully understand. I'm coming from a C background, but I never went far with that either.</p> <p>What I'm trying to figure out is:</p> <p>In a method:</p> <pre><code>def method(self, blah): def __init__(?): .... .... </code></pre> <p>What does self do? what is it meant to be? and is it mandatory?</p> <p>What does the <code>__init__</code> method do? why is it necessary? etc</p> <p>I think they might be oop constructs, but I don't know very much..</p>
344
2009-03-09T05:09:51Z
625,097
<p>Yep, you are right, these are oop constructs.</p> <p>init is the constructor for a class. The self parameter refers to the instance of the object (like <strong>this</strong> in C++).</p> <pre><code>class Point: def __init__(self, x, y): self._x = x self._y = y </code></pre> <p>The init method gets called when memory for the object is allocated:</p> <pre><code>x = Point(1,2) </code></pre> <p>It is important to use the self parameter inside an object's method if you want to persist the value with the object. If, for instance, you implement the init method like this:</p> <pre><code>class Point: def __init__(self, x, y): _x = x _y = y </code></pre> <p>Your x and y parameters would be stored in variables on the stack and would be discarded when the init method goes out of scope. Setting those variables as self._x sets those variables as members of the Point object (accessible for the lifetime of the object).</p>
92
2009-03-09T05:18:21Z
[ "python", "oop" ]
Python __init__ and self what do they do?
625,083
<p>I'm learning the Python programming language, and I've come across certain things I don't fully understand. I'm coming from a C background, but I never went far with that either.</p> <p>What I'm trying to figure out is:</p> <p>In a method:</p> <pre><code>def method(self, blah): def __init__(?): .... .... </code></pre> <p>What does self do? what is it meant to be? and is it mandatory?</p> <p>What does the <code>__init__</code> method do? why is it necessary? etc</p> <p>I think they might be oop constructs, but I don't know very much..</p>
344
2009-03-09T05:09:51Z
625,098
<p>In this code:</p> <pre><code>class A(object): def __init__(self): self.x = 'Hello' def method_a(self, foo): print self.x + ' ' + foo </code></pre> <p>... the <code>self</code> variable represents the instance of the object itself. Most object-oriented languages pass this as a hidden parameter to the methods defined on an object; Python does not. You have to declare it explicitly. When you create an instance of the <code>A</code> class and call its methods, it will be passed automatically, as in ...</p> <pre><code>a = A() # We do not pass any argument to the __init__ method a.method_a('Sailor!') # We only pass a single argument </code></pre> <p>The <code>__init__</code> method is roughly what represents a constructor in Python. When you call <code>A()</code> Python creates an object for you, and passes it as the first parameter to the <code>__init__</code> method. Any additional parameters (e.g., <code>A(24, 'Hello')</code>) will also get passed as arguments--in this case causing an exception to be raised, since the constructor isn't expecting them.</p>
315
2009-03-09T05:18:46Z
[ "python", "oop" ]
Python __init__ and self what do they do?
625,083
<p>I'm learning the Python programming language, and I've come across certain things I don't fully understand. I'm coming from a C background, but I never went far with that either.</p> <p>What I'm trying to figure out is:</p> <p>In a method:</p> <pre><code>def method(self, blah): def __init__(?): .... .... </code></pre> <p>What does self do? what is it meant to be? and is it mandatory?</p> <p>What does the <code>__init__</code> method do? why is it necessary? etc</p> <p>I think they might be oop constructs, but I don't know very much..</p>
344
2009-03-09T05:09:51Z
625,133
<p>In short:</p> <ol> <li><code>self</code> as it suggests, refers to <em>itself</em>- the object which has called the method. That is, if you have N objects calling the method, then <code>self.a</code> will refer to a separate instance of the variable for each of the N objects. Imagine N copies of the variable <code>a</code> for each object</li> <li><code>__init__</code> is what is called as a constructor in other OOP languages such as C++/Java. The basic idea is that it is a <em>special</em> method which is automatically called when an object of that Class is created</li> </ol>
21
2009-03-09T05:41:21Z
[ "python", "oop" ]
Python __init__ and self what do they do?
625,083
<p>I'm learning the Python programming language, and I've come across certain things I don't fully understand. I'm coming from a C background, but I never went far with that either.</p> <p>What I'm trying to figure out is:</p> <p>In a method:</p> <pre><code>def method(self, blah): def __init__(?): .... .... </code></pre> <p>What does self do? what is it meant to be? and is it mandatory?</p> <p>What does the <code>__init__</code> method do? why is it necessary? etc</p> <p>I think they might be oop constructs, but I don't know very much..</p>
344
2009-03-09T05:09:51Z
625,174
<p>The 'self' is a reference to the class instance</p> <pre><code>class foo: def bar(self): print "hi" </code></pre> <p>Now we can create an instance of foo and call the method on it, the self parameter is added by Python in this case:</p> <pre><code>f = foo() f.bar() </code></pre> <p>But it can be passed in as well if the method call isn't in the context of an instance of the class, the code below does the same thing</p> <pre><code>f = foo() foo.bar(f) </code></pre> <p>Interestingly the variable name 'self' is just a convention. The below definition will work exactly the same.. Having said that it is <strong>very strong convention</strong> which should be followed <strong>always</strong>, but it does say something about flexible nature of the language</p> <pre><code>class foo: def bar(s): print "hi" </code></pre>
9
2009-03-09T06:09:20Z
[ "python", "oop" ]
Python __init__ and self what do they do?
625,083
<p>I'm learning the Python programming language, and I've come across certain things I don't fully understand. I'm coming from a C background, but I never went far with that either.</p> <p>What I'm trying to figure out is:</p> <p>In a method:</p> <pre><code>def method(self, blah): def __init__(?): .... .... </code></pre> <p>What does self do? what is it meant to be? and is it mandatory?</p> <p>What does the <code>__init__</code> method do? why is it necessary? etc</p> <p>I think they might be oop constructs, but I don't know very much..</p>
344
2009-03-09T05:09:51Z
626,081
<p>note that <code>self</code> could actually be any valid python identifier. For example, we could just as easily write, from Chris B's example:</p> <pre><code>class A(object): def __init__(foo): foo.x = 'Hello' def method_a(bar, foo): print bar.x + ' ' + foo </code></pre> <p>and it would work exactly the same. It is however recommended to use self because other pythoners will recognize it more easily.</p>
11
2009-03-09T12:50:30Z
[ "python", "oop" ]
Python __init__ and self what do they do?
625,083
<p>I'm learning the Python programming language, and I've come across certain things I don't fully understand. I'm coming from a C background, but I never went far with that either.</p> <p>What I'm trying to figure out is:</p> <p>In a method:</p> <pre><code>def method(self, blah): def __init__(?): .... .... </code></pre> <p>What does self do? what is it meant to be? and is it mandatory?</p> <p>What does the <code>__init__</code> method do? why is it necessary? etc</p> <p>I think they might be oop constructs, but I don't know very much..</p>
344
2009-03-09T05:09:51Z
12,552,203
<p>Basically, you need to use the 'self' keyword when using a variable in multiple functions within the same class. As for <strong>init</strong>, it's used to setup default values incase no other functions from within that class are called.</p>
12
2012-09-23T12:02:55Z
[ "python", "oop" ]
Python __init__ and self what do they do?
625,083
<p>I'm learning the Python programming language, and I've come across certain things I don't fully understand. I'm coming from a C background, but I never went far with that either.</p> <p>What I'm trying to figure out is:</p> <p>In a method:</p> <pre><code>def method(self, blah): def __init__(?): .... .... </code></pre> <p>What does self do? what is it meant to be? and is it mandatory?</p> <p>What does the <code>__init__</code> method do? why is it necessary? etc</p> <p>I think they might be oop constructs, but I don't know very much..</p>
344
2009-03-09T05:09:51Z
16,474,519
<p>Try out this code. Hope it helps many C programmers like me to Learn Py.</p> <pre><code>#! /usr/bin/python2 class Person: '''Doc - Inside Class ''' def __init__(self, name): '''Doc - __init__ Constructor''' self.n_name = name def show(self, n1, n2): '''Doc - Inside Show''' print self.n_name print 'Sum = ', (n1 + n2) def __del__(self): print 'Destructor Deleting object - ', self.n_name p=Person('Jay') p.show(2, 3) print p.__doc__ print p.__init__.__doc__ print p.show.__doc__ </code></pre> <p>Output:</p> <p><code>Jay</code></p> <p><code>Sum = 5</code></p> <p><code>Doc - Inside Class</code></p> <p><code>Doc - __init__ Constructor</code></p> <p><code>Doc - Inside Show</code></p> <p><code>Destructor Deleting object - Jay</code></p>
13
2013-05-10T03:03:13Z
[ "python", "oop" ]
Python __init__ and self what do they do?
625,083
<p>I'm learning the Python programming language, and I've come across certain things I don't fully understand. I'm coming from a C background, but I never went far with that either.</p> <p>What I'm trying to figure out is:</p> <p>In a method:</p> <pre><code>def method(self, blah): def __init__(?): .... .... </code></pre> <p>What does self do? what is it meant to be? and is it mandatory?</p> <p>What does the <code>__init__</code> method do? why is it necessary? etc</p> <p>I think they might be oop constructs, but I don't know very much..</p>
344
2009-03-09T05:09:51Z
17,260,649
<h1>A brief illustrative example</h1> <p>In the hope it might help a little, here's a simple example I used to understand the difference between a variable declared inside a class, and a variable declared inside an <code>__init__</code> function:</p> <pre><code>class MyClass(object): i = 123 def __init__(self): self.i = 345 a = MyClass() print a.i 345 print MyClass.i 123 </code></pre>
74
2013-06-23T12:15:34Z
[ "python", "oop" ]
Python __init__ and self what do they do?
625,083
<p>I'm learning the Python programming language, and I've come across certain things I don't fully understand. I'm coming from a C background, but I never went far with that either.</p> <p>What I'm trying to figure out is:</p> <p>In a method:</p> <pre><code>def method(self, blah): def __init__(?): .... .... </code></pre> <p>What does self do? what is it meant to be? and is it mandatory?</p> <p>What does the <code>__init__</code> method do? why is it necessary? etc</p> <p>I think they might be oop constructs, but I don't know very much..</p>
344
2009-03-09T05:09:51Z
21,032,703
<p>Had trouble undestanding this myself. Even after reading the answers here. </p> <p>To properly understand the <code>__init__</code> method you need to understand self. </p> <p><strong>The self Parameter</strong></p> <p>The arguments accepted by the <code>__init__</code> method are :</p> <pre><code>def __init__(self, arg1, arg2): </code></pre> <p>But we only actually pass it two arguments :</p> <pre><code>instance = OurClass('arg1', 'arg2') </code></pre> <p>Where has the extra argument come from ?</p> <p>When we access attributes of an object we do it by name (or by reference). Here instance is a reference to our new object. We access the printargs method of the instance object using instance.printargs.</p> <p>In order to access object attributes from within the <code>__init__</code> method we need a reference to the object.</p> <p><em><strong>Whenever a method is called, a reference to the main object is passed as the first argument.</em></strong> By convention you always call this first argument to your methods self.</p> <p>This means in the <code>__init__</code> method we can do :</p> <pre><code>self.arg1 = arg1 self.arg2 = arg2 </code></pre> <p><em><strong>Here we are setting attributes on the object.</em></strong> You can verify this by doing the following :</p> <pre><code>instance = OurClass('arg1', 'arg2') print instance.arg1 arg1 </code></pre> <p>values like this are known as object attributes. <strong><em>Here the <code>__init__</code> method sets the arg1 and arg2 attributes of the instance.</em></strong></p> <p>source: <a href="http://www.voidspace.org.uk/python/articles/OOP.shtml#the-init-method">http://www.voidspace.org.uk/python/articles/OOP.shtml#the-init-method</a></p>
11
2014-01-09T22:39:09Z
[ "python", "oop" ]
Python __init__ and self what do they do?
625,083
<p>I'm learning the Python programming language, and I've come across certain things I don't fully understand. I'm coming from a C background, but I never went far with that either.</p> <p>What I'm trying to figure out is:</p> <p>In a method:</p> <pre><code>def method(self, blah): def __init__(?): .... .... </code></pre> <p>What does self do? what is it meant to be? and is it mandatory?</p> <p>What does the <code>__init__</code> method do? why is it necessary? etc</p> <p>I think they might be oop constructs, but I don't know very much..</p>
344
2009-03-09T05:09:51Z
28,946,924
<p>Section 9.3 in <a href="https://docs.python.org/2/tutorial/classes.html" rel="nofollow">this Python tutorial</a> gives a short introduction to the basic elements of a Python class: class variables, class methods and the roles of<code>__init__</code> and <code>__self__</code>.</p>
3
2015-03-09T16:23:06Z
[ "python", "oop" ]
Python __init__ and self what do they do?
625,083
<p>I'm learning the Python programming language, and I've come across certain things I don't fully understand. I'm coming from a C background, but I never went far with that either.</p> <p>What I'm trying to figure out is:</p> <p>In a method:</p> <pre><code>def method(self, blah): def __init__(?): .... .... </code></pre> <p>What does self do? what is it meant to be? and is it mandatory?</p> <p>What does the <code>__init__</code> method do? why is it necessary? etc</p> <p>I think they might be oop constructs, but I don't know very much..</p>
344
2009-03-09T05:09:51Z
31,988,134
<p>Here, the guy has written pretty well and simple: <a href="https://www.jeffknupp.com/blog/2014/06/18/improve-your-python-python-classes-and-object-oriented-programming/" rel="nofollow">https://www.jeffknupp.com/blog/2014/06/18/improve-your-python-python-classes-and-object-oriented-programming/</a></p> <p>Read above link as a reference to this:</p> <blockquote> <p><code>self</code>? So what's with that self parameter to all of the Customer methods? What is it? Why, it's the instance, of course! Put another way, a method like withdraw defines the instructions for withdrawing money from some abstract customer's account. Calling jeff.withdraw(100.0) puts those instructions to use on the jeff instance.</p> <p>So when we say def withdraw(self, amount):, we're saying, "here's how you withdraw money from a Customer object (which we'll call self) and a dollar figure (which we'll call amount). self is the instance of the Customer that withdraw is being called on. That's not me making analogies, either. jeff.withdraw(100.0) is just shorthand for Customer.withdraw(jeff, 100.0), which is perfectly valid (if not often seen) code.</p> <p><strong>init</strong> self may make sense for other methods, but what about <strong>init</strong>? When we call <strong>init</strong>, we're in the process of creating an object, so how can there already be a self? Python allows us to extend the self pattern to when objects are constructed as well, even though it doesn't exactly fit. Just imagine that jeff = Customer('Jeff Knupp', 1000.0) is the same as calling jeff = Customer(jeff, 'Jeff Knupp', 1000.0); the jeff that's passed in is also made the result.</p> <p>This is why when we call <strong>init</strong>, we initialize objects by saying things like self.name = name. Remember, since self is the instance, this is equivalent to saying jeff.name = name, which is the same as jeff.name = 'Jeff Knupp. Similarly, self.balance = balance is the same as jeff.balance = 1000.0. After these two lines, we consider the Customer object "initialized" and ready for use.</p> <p><strong>Be careful what you <code>__init__</code></strong></p> <p>After <strong>init</strong> has finished, the caller can rightly assume that the object is ready to use. That is, after jeff = Customer('Jeff Knupp', 1000.0), we can start making deposit and withdraw calls on jeff; jeff is a fully-initialized object.</p> </blockquote>
3
2015-08-13T12:22:15Z
[ "python", "oop" ]
Python __init__ and self what do they do?
625,083
<p>I'm learning the Python programming language, and I've come across certain things I don't fully understand. I'm coming from a C background, but I never went far with that either.</p> <p>What I'm trying to figure out is:</p> <p>In a method:</p> <pre><code>def method(self, blah): def __init__(?): .... .... </code></pre> <p>What does self do? what is it meant to be? and is it mandatory?</p> <p>What does the <code>__init__</code> method do? why is it necessary? etc</p> <p>I think they might be oop constructs, but I don't know very much..</p>
344
2009-03-09T05:09:51Z
32,214,839
<p>In this code:</p> <p><code>class Cat: def __init__(self, name): self.name = name def info(self): print 'I am a cat and I am called', self.name</code></p> <p>Here <code>__init__</code> acts as a constructor for the class and when an object is instantiated, this function is called. <code>self</code> represents the instantiating object.</p> <p><code>c = Cat('Kitty') c.info()</code></p> <p>The result of the above statements will be as follows:</p> <p><code>I am a cat and I am called Kitty</code></p>
4
2015-08-25T22:02:29Z
[ "python", "oop" ]
Python __init__ and self what do they do?
625,083
<p>I'm learning the Python programming language, and I've come across certain things I don't fully understand. I'm coming from a C background, but I never went far with that either.</p> <p>What I'm trying to figure out is:</p> <p>In a method:</p> <pre><code>def method(self, blah): def __init__(?): .... .... </code></pre> <p>What does self do? what is it meant to be? and is it mandatory?</p> <p>What does the <code>__init__</code> method do? why is it necessary? etc</p> <p>I think they might be oop constructs, but I don't know very much..</p>
344
2009-03-09T05:09:51Z
32,386,319
<ol> <li><strong><code>__init__</code></strong> is basically a function which will <strong>"initialize"</strong>/<strong>"activate"</strong> the properties of the class for a specific object, once created and matched to the corresponding class..</li> <li><strong><code>self</code></strong> represents that object which will inherit those properties.</li> </ol>
7
2015-09-03T22:19:24Z
[ "python", "oop" ]
Python __init__ and self what do they do?
625,083
<p>I'm learning the Python programming language, and I've come across certain things I don't fully understand. I'm coming from a C background, but I never went far with that either.</p> <p>What I'm trying to figure out is:</p> <p>In a method:</p> <pre><code>def method(self, blah): def __init__(?): .... .... </code></pre> <p>What does self do? what is it meant to be? and is it mandatory?</p> <p>What does the <code>__init__</code> method do? why is it necessary? etc</p> <p>I think they might be oop constructs, but I don't know very much..</p>
344
2009-03-09T05:09:51Z
38,156,406
<pre><code># Source: Class and Instance Variables # https://docs.python.org/2/tutorial/classes.html#class-and-instance-variables class MyClass(object): # class variable my_CLS_var = 10 # sets "init'ial" state to objects/instances, use self argument def __init__(self): # self usage =&gt; instance variable (per object) self.my_OBJ_var = 15 # also possible, class name is used =&gt; init class variable MyClass.my_CLS_var = 20 def run_example_func(): # PRINTS 10 (class variable) print MyClass.my_CLS_var # executes __init__ for obj1 instance # NOTE: __init__ changes class variable above obj1 = MyClass() # PRINTS 15 (instance variable) print obj1.my_OBJ_var # PRINTS 20 (class variable, changed value) print MyClass.my_CLS_var run_example_func() </code></pre>
1
2016-07-02T04:15:17Z
[ "python", "oop" ]
Select mails from inbox alone via poplib
625,148
<p>I need to download emails from the gmail inbox only using poplib.Unfortunately I do not see any option to select Inbox alone, and poplib gives me emails from sent items too.</p> <p>How do I select emails only from inbox?</p> <p>I dont want to use any gmail specific libraries.</p>
1
2009-03-09T05:49:32Z
625,175
<p>POP3 has no concept of 'folders'. If gmail is showing you both 'sent' as well as 'received' mail, then you really don't have any option but to receive all that email.</p> <p>Perhaps you would be better off using IMAP4 instead of POP3. Python has libraries that will work with gmail's IMAP4 server.</p>
3
2009-03-09T06:09:32Z
[ "python", "gmail", "pop3", "poplib" ]
Select mails from inbox alone via poplib
625,148
<p>I need to download emails from the gmail inbox only using poplib.Unfortunately I do not see any option to select Inbox alone, and poplib gives me emails from sent items too.</p> <p>How do I select emails only from inbox?</p> <p>I dont want to use any gmail specific libraries.</p>
1
2009-03-09T05:49:32Z
625,191
<p>This Java code would suggest that you can select a particular "folder" to download, even when using POP3. Again, this is using Java, not Python so YMMV.</p> <p><a href="http://blog.prolificprogrammer.com/2008/04/04/how-to-search-gmail-from-the-comfort-of-your-command-line" rel="nofollow">How to download message from GMail using Java (blog post discusses pushing content into a Lucene search engine locally)</a></p>
1
2009-03-09T06:18:44Z
[ "python", "gmail", "pop3", "poplib" ]
Select mails from inbox alone via poplib
625,148
<p>I need to download emails from the gmail inbox only using poplib.Unfortunately I do not see any option to select Inbox alone, and poplib gives me emails from sent items too.</p> <p>How do I select emails only from inbox?</p> <p>I dont want to use any gmail specific libraries.</p>
1
2009-03-09T05:49:32Z
627,402
<p>I assume you have enabled POP3/IMAP access to your GMail account.</p> <p>This is sample code:</p> <pre><code>import imaplib conn= imaplib.IMAP4_SSL('imap.googlemail.com') conn.login('yourusername', 'yourpassword') code, dummy= conn.select('INBOX') if code != 'OK': raise RuntimeError, "Failed to select inbox" code, data= self.conn.search(None, ALL) if code == 'OK': msgid_list= data[0].split() else: raise RuntimeError, "Failed to get message IDs" for msgid in msgid_list: code, data= conn.fetch(msgid, '(RFC822)') # you can also use '(RFC822.HEADER)' only for headers if code == 'OK': pass # your code here else: raise RuntimeError, "could not retrieve msgid %r" % msgid conn.close() conn.logout() </code></pre> <p>or something like this.</p>
2
2009-03-09T18:09:55Z
[ "python", "gmail", "pop3", "poplib" ]
Best practice for integrating CherryPy web-framework, SQLAlchemy sessions and lighttpd to serve a high-load webservice
625,288
<p>I'm developing a CherryPy FastCGI server behind lighttpd with the following setup to enable using ORM SQLAlchemy sessions inside CherryPy controllers. However, when I run stress tests with 14 concurrent requests for about 500 loops, it starts to give errors like <code>AttributeError: '_ThreadData' object has no attribute 'scoped_session_class'</code> in <code>open_dbsession()</code> or <code>AttributeError: 'Request' object has no attribute 'scoped_session_class'</code> in <code>close_dbsession()</code> after a while. The error rate is around 50% in total.</p> <p>This happens only when I run the server behind lighttpd, not when it's run directly through <code>cherrypy.engine.start()</code>. It's confirmed that <code>connect()</code> isn't raising exceptions.</p> <p>I also tried assigning the return value of <code>scoped_session</code> to <code>GlobalSession</code> (like it does <a href="http://code.google.com/p/webpyte/source/browse/trunk/webpyte/sqlalchemy%5Ftool.py">here</a>), but then it gave out errors like <code>UnboundExceptionError</code> and other SA-level errors. (Concurrency: 10, loops: 1000, error rate: 16%. Occurs even when run directly.)</p> <p>There are some possible causes but I lack sufficient knowledge to pick one.<br /> 1. Are <code>start_thread</code> subscriptions unreliable under FastCGI environment? It seems that <code>open_dbsession()</code> is called before <code>connect()</code><br /> 2. Does <code>cherrypy.thread_data</code> get cleared for some reason?</p> <h3>server code</h3> <pre><code>import sqlalchemy as sa from sqlalchemy.orm import session_maker, scoped_session engine = sa.create_engine(dburi, strategy="threadlocal") GlobalSession = session_maker(bind=engine, transactional=False) def connect(thread_index): cherrypy.thread_data.scoped_session_class = scoped_session(GlobalSession) def open_dbsession(): cherrypy.request.scoped_session_class = cherrypy.thread_data.scoped_session_class def close_dbsession(): cherrypy.request.scoped_session_class.remove() cherrypy.tools.dbsession_open = cherrypy.Tool('on_start_resource', open_dbsession) cherrypy.tools.dbsession_close = cherrypy.Tool('on_end_resource', close_dbsession) cherrypy.engine.subscribe('start_thread', connect) </code></pre> <h3>lighttpd fastcgi config</h3> <pre><code>... var.server_name = "test" var.server_root = "/path/to/root" var.svc_env = "test" fastcgi.server = ( "/" =&gt; ( "cherry.fcgi" =&gt; ( "bin-path" =&gt; server_root + "/fcgi_" + server_name + ".fcgi", "bin-environment" =&gt; ( "SVC_ENV" =&gt; svc_env ), "bin-copy-environment" =&gt; ("PATH", "LC_CTYPE"), "socket" =&gt; "/tmp/cherry_" + server_name + "." + svc_env + ".sock", "check-local" =&gt; "disable", "disable-time" =&gt; 1, "min-procs" =&gt; 1, "max-procs" =&gt; 4, ), ), ) </code></pre> <h3>edits</h3> <ul> <li>Restored the missing <code>thread_index</code> argument in the code example from the original source code (thanks to the comment)</li> <li>Clarified that errors do not occur immediately</li> <li>Narrowed down the conditions to lighttpd</li> </ul>
6
2009-03-09T07:28:24Z
627,335
<p>If you look at <code>plugins.ThreadManager.acquire_thread</code>, you'll see the line <code>self.bus.publish('start_thread', i)</code>, where <code>i</code> is the array index of the seen thread. Any listener subscribed to the <code>start_thread</code> channel needs to accept that <code>i</code> value as a positional argument. So rewrite your connect function to read: <code>def connect(i):</code></p> <p>My guess it that's failing silently somehow; I'll see if I can track that down, test and fix it.</p>
1
2009-03-09T17:55:32Z
[ "python", "sqlalchemy", "lighttpd", "cherrypy" ]
Best practice for integrating CherryPy web-framework, SQLAlchemy sessions and lighttpd to serve a high-load webservice
625,288
<p>I'm developing a CherryPy FastCGI server behind lighttpd with the following setup to enable using ORM SQLAlchemy sessions inside CherryPy controllers. However, when I run stress tests with 14 concurrent requests for about 500 loops, it starts to give errors like <code>AttributeError: '_ThreadData' object has no attribute 'scoped_session_class'</code> in <code>open_dbsession()</code> or <code>AttributeError: 'Request' object has no attribute 'scoped_session_class'</code> in <code>close_dbsession()</code> after a while. The error rate is around 50% in total.</p> <p>This happens only when I run the server behind lighttpd, not when it's run directly through <code>cherrypy.engine.start()</code>. It's confirmed that <code>connect()</code> isn't raising exceptions.</p> <p>I also tried assigning the return value of <code>scoped_session</code> to <code>GlobalSession</code> (like it does <a href="http://code.google.com/p/webpyte/source/browse/trunk/webpyte/sqlalchemy%5Ftool.py">here</a>), but then it gave out errors like <code>UnboundExceptionError</code> and other SA-level errors. (Concurrency: 10, loops: 1000, error rate: 16%. Occurs even when run directly.)</p> <p>There are some possible causes but I lack sufficient knowledge to pick one.<br /> 1. Are <code>start_thread</code> subscriptions unreliable under FastCGI environment? It seems that <code>open_dbsession()</code> is called before <code>connect()</code><br /> 2. Does <code>cherrypy.thread_data</code> get cleared for some reason?</p> <h3>server code</h3> <pre><code>import sqlalchemy as sa from sqlalchemy.orm import session_maker, scoped_session engine = sa.create_engine(dburi, strategy="threadlocal") GlobalSession = session_maker(bind=engine, transactional=False) def connect(thread_index): cherrypy.thread_data.scoped_session_class = scoped_session(GlobalSession) def open_dbsession(): cherrypy.request.scoped_session_class = cherrypy.thread_data.scoped_session_class def close_dbsession(): cherrypy.request.scoped_session_class.remove() cherrypy.tools.dbsession_open = cherrypy.Tool('on_start_resource', open_dbsession) cherrypy.tools.dbsession_close = cherrypy.Tool('on_end_resource', close_dbsession) cherrypy.engine.subscribe('start_thread', connect) </code></pre> <h3>lighttpd fastcgi config</h3> <pre><code>... var.server_name = "test" var.server_root = "/path/to/root" var.svc_env = "test" fastcgi.server = ( "/" =&gt; ( "cherry.fcgi" =&gt; ( "bin-path" =&gt; server_root + "/fcgi_" + server_name + ".fcgi", "bin-environment" =&gt; ( "SVC_ENV" =&gt; svc_env ), "bin-copy-environment" =&gt; ("PATH", "LC_CTYPE"), "socket" =&gt; "/tmp/cherry_" + server_name + "." + svc_env + ".sock", "check-local" =&gt; "disable", "disable-time" =&gt; 1, "min-procs" =&gt; 1, "max-procs" =&gt; 4, ), ), ) </code></pre> <h3>edits</h3> <ul> <li>Restored the missing <code>thread_index</code> argument in the code example from the original source code (thanks to the comment)</li> <li>Clarified that errors do not occur immediately</li> <li>Narrowed down the conditions to lighttpd</li> </ul>
6
2009-03-09T07:28:24Z
628,823
<blockquote> <p>I also tried assigning the return value of scoped_session to GlobalSession (like it does here), but then it gave out errors like UnboundExceptionError and other SA-level errors. (Concurrency: 10, loops: 1000, error rate: 16%)</p> </blockquote> <p>This error did not occur if I didn't instantiate the scoped_session class explicitly.</p> <p>i.e. </p> <pre><code>GlobalSession = scoped_session(session_maker(bind=engine, transactional=False)) def connect(thread_index): cherrypy.thread_data.scoped_session_class = GlobalSession def open_dbsession(): cherrypy.request.scoped_session_class = cherrypy.thread_data.scoped_session_class def close_dbsession(): cherrypy.request.scoped_session_class.remove() </code></pre>
0
2009-03-10T03:13:21Z
[ "python", "sqlalchemy", "lighttpd", "cherrypy" ]
Dump memcache keys from GAE SDK Console?
625,314
<p>In the "Memcache Viewer", is there any way to dump a list of existing keys? Just for debugging, of course, not for use in any scripts!</p> <p>I ask because it doesn't seem like the GAE SDK is using a "real" memcache server, so I'm guessing it's emulated in Python (for simplicity, as it's just a development server).. This would mean there is a dict somewhere with the keys/values..</p>
1
2009-03-09T07:49:02Z
625,331
<p>No. I did not found such functionality in memcached too.</p> <p>Thinking about this issue, I found this limitation understandable - it would require keeping a registry of keys with all related problems like key expiration, invalidation and of course locking. Such system would not be as fast as memcaches are intended to be.</p>
4
2009-03-09T08:02:17Z
[ "python", "google-app-engine", "memcached" ]
Dump memcache keys from GAE SDK Console?
625,314
<p>In the "Memcache Viewer", is there any way to dump a list of existing keys? Just for debugging, of course, not for use in any scripts!</p> <p>I ask because it doesn't seem like the GAE SDK is using a "real" memcache server, so I'm guessing it's emulated in Python (for simplicity, as it's just a development server).. This would mean there is a dict somewhere with the keys/values..</p>
1
2009-03-09T07:49:02Z
626,458
<p>Memcache is designed to be quick and there's no convincing use case for this functionality which would justify the overhead required for a command that is so at odds with the rest of memcached.</p> <p>The GAE SDK is simulating memcached, so it doesn't offer this functionality either.</p>
0
2009-03-09T14:29:07Z
[ "python", "google-app-engine", "memcached" ]
Dump memcache keys from GAE SDK Console?
625,314
<p>In the "Memcache Viewer", is there any way to dump a list of existing keys? Just for debugging, of course, not for use in any scripts!</p> <p>I ask because it doesn't seem like the GAE SDK is using a "real" memcache server, so I'm guessing it's emulated in Python (for simplicity, as it's just a development server).. This would mean there is a dict somewhere with the keys/values..</p>
1
2009-03-09T07:49:02Z
626,559
<p>People ask for this on the memcached list a lot, sometimes with the same type of "just in case I want to look around to debug something" sentiment.</p> <p>The best way to handle this is to know how you generate your keys, and just go look stuff up when you want to know what's stored for a given value.</p> <p>If you have too many things using memcached to do that within the scope of your debugging session, then start logging access.</p> <p>But keep in mind -- memcached is fast because it doesn't allow for such things in general. The community server does have limited functionality to get a subset of the keys available within a given slab class, but it's probably not what you really want, and hopefully google doesn't implement it in theirs. :)</p>
8
2009-03-09T14:56:16Z
[ "python", "google-app-engine", "memcached" ]
Dump memcache keys from GAE SDK Console?
625,314
<p>In the "Memcache Viewer", is there any way to dump a list of existing keys? Just for debugging, of course, not for use in any scripts!</p> <p>I ask because it doesn't seem like the GAE SDK is using a "real" memcache server, so I'm guessing it's emulated in Python (for simplicity, as it's just a development server).. This would mean there is a dict somewhere with the keys/values..</p>
1
2009-03-09T07:49:02Z
660,458
<p>The easiest way that I could think of, would be to maintain a memcache key at a known ID, and then append to it every time you insert a new key. This way you could just query for the single key to get a list of existing keys.</p>
0
2009-03-18T23:12:49Z
[ "python", "google-app-engine", "memcached" ]
Dump memcache keys from GAE SDK Console?
625,314
<p>In the "Memcache Viewer", is there any way to dump a list of existing keys? Just for debugging, of course, not for use in any scripts!</p> <p>I ask because it doesn't seem like the GAE SDK is using a "real" memcache server, so I'm guessing it's emulated in Python (for simplicity, as it's just a development server).. This would mean there is a dict somewhere with the keys/values..</p>
1
2009-03-09T07:49:02Z
5,171,815
<p>Here is a possible work around. I am unfamiliar with Google App Engine but on a regular memcache server you can list out all the keys through telnet like so:</p> <pre><code>telnet 127.0.0.1 11211 stats items STAT items:7:number 5 STAT items:7:age 88779 STAT items:7:evicted 0 STAT items:7:evicted_time 0 STAT items:7:outofmemory 0 STAT items:7:tailrepairs 0 ... etc END stats cachedump 7 100 ITEM __builtin__.str_is_browser_supported·user_agent_hash=5706b885fdad3f7049dfb39455dfa7ab10086d97 [269 b; 1298926467 s] END </code></pre> <p>Thanks to <a href="http://www.darkcoding.net/software/memcached-list-all-keys/" rel="nofollow">Graham King's blog post</a> for that nice little recipe.</p>
0
2011-03-02T18:36:18Z
[ "python", "google-app-engine", "memcached" ]