title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
Skipping Iterations in Python | 549,674 | 42 | 2009-02-14T19:48:04Z | 549,682 | 94 | 2009-02-14T19:50:46Z | [
"python",
"iteration",
"skip"
] | I have a loop going, but there is the possibility for exceptions to be raised inside the loop. This of course would stop my program all together. To prevent that I catch the exceptions and handle them. But then the rest of the iteration runs even though an exception occurred. Is there a keyword to use in my `except:` c... | You are lookin for [continue](http://docs.python.org/tutorial/controlflow.html). |
Skipping Iterations in Python | 549,674 | 42 | 2009-02-14T19:48:04Z | 549,688 | 26 | 2009-02-14T19:52:29Z | [
"python",
"iteration",
"skip"
] | I have a loop going, but there is the possibility for exceptions to be raised inside the loop. This of course would stop my program all together. To prevent that I catch the exceptions and handle them. But then the rest of the iteration runs even though an exception occurred. Is there a keyword to use in my `except:` c... | ```
for i in iterator:
try:
# Do something.
pass
except:
# Continue to next iteration.
continue
``` |
Fully transparent windows in Pygame? | 550,001 | 4 | 2009-02-14T23:40:50Z | 550,007 | 7 | 2009-02-14T23:48:12Z | [
"python",
"graphics",
"sdl",
"pygame"
] | Is it possible to get a fully transparent window in Pygame (see the desktop through it)? I've found how to create a window without a frame, but there doesn't seem to be any obvious way to make it transparent.
I'd be willing to tie into system-specific technology/frameworks as long as there are solutions for both Windo... | PyGame uses SDL, which does not support transparent windows. Although at least on Linux making it transparent is done by the window manager, not the application. |
Parsing "From" addresses from email text | 550,009 | 9 | 2009-02-14T23:49:22Z | 550,036 | 31 | 2009-02-15T00:15:07Z | [
"python",
"string",
"email",
"parsing",
"text"
] | I'm trying to extract email addresses from plain text transcripts of emails.
I've cobbled together a bit of code to find the addresses themselves, but I don't know how to make it discriminate between them; right now it just spits out all email addresses in the file. I'd like to make it so it only spits out addresses th... | Try this out:
```
>>> from email.utils import parseaddr
>>> parseaddr('From: vg@m.com')
('', 'vg@m.com')
>>> parseaddr('From: Van Gale <vg@m.com>')
('Van Gale', 'vg@m.com')
>>> parseaddr(' From: Van Gale <vg@m.com> ')
('Van Gale', 'vg@m.com')
>>> parseaddr('blah abdf From: Van Gale <vg@m.com> and this')
... |
Parsing "From" addresses from email text | 550,009 | 9 | 2009-02-14T23:49:22Z | 550,105 | 8 | 2009-02-15T01:14:59Z | [
"python",
"string",
"email",
"parsing",
"text"
] | I'm trying to extract email addresses from plain text transcripts of emails.
I've cobbled together a bit of code to find the addresses themselves, but I don't know how to make it discriminate between them; right now it just spits out all email addresses in the file. I'd like to make it so it only spits out addresses th... | ```
import email
msg = email.message_from_string(str)
# or
# f = open(file)
# msg = email.message_from_file(f)
msg['from']
# and optionally
from email.utils import parseaddr
addr = parseaddr(msg['from'])
``` |
What causes Python socket error? | 550,032 | 10 | 2009-02-15T00:12:53Z | 550,034 | 20 | 2009-02-15T00:14:39Z | [
"python",
"sockets",
"permissions"
] | ```
File "C:\Python25\lib\SocketServer.py", line 330, in __init__
self.server_bind()
File "C:\Python25\lib\BaseHTTPServer.py", line 101, in server_bind
SocketServer.TCPServer.server_bind(self)
File "C:\Python25\lib\SocketServer.py", line 341, in server_bind
self.socket.bind(self.server_address)
File... | It might be possible that you are trying to run on a port the current user account does not have permission to bind to. This could be port 80 or something. Try increasing the portnumber or use a user with sufficient privileges.
Hope this helps |
Removing the TK icon on a Tkinter window | 550,050 | 16 | 2009-02-15T00:27:10Z | 754,736 | 30 | 2009-04-16T04:11:48Z | [
"python",
"python-3.x",
"tkinter",
"tk"
] | Does anybody know how to make the icon not show up? I'm looking for a way to have no icon at all. | ### On Windows
**Step One:**
Create a transparent icon using either an icon editor, or a site like [rw-designer](http://www.rw-designer.com/online_icon_maker.php). Save it as `transparent.ico`.
**Step Two:**
```
from tkinter import *
tk = Tk()
tk.iconbitmap(default='transparent.ico')
lab = Label(tk, text='Window w... |
Does python have something like C++'s using keyword? | 550,148 | 6 | 2009-02-15T01:50:34Z | 550,161 | 17 | 2009-02-15T01:58:04Z | [
"python",
"namespaces",
"using"
] | In C++ you can often drastically improve the readability of your code by careful usage of the "using" keyword, for example:
```
void foo()
{
std::vector< std::map <int, std::string> > crazyVector;
std::cout << crazyVector[0].begin()->first;
}
```
becomes
```
void foo()
{
using namespace std; // limited i... | As Bill said, Python does have the construction
```
from X import *
```
but you can also explicitly specify which names you want imported from the module (namespace):
```
from X import foo, bar, blah
```
This tends to make the code even more readable/easier to understand, since someone seeing an identifier in the s... |
overload print python | 550,470 | 26 | 2009-02-15T07:26:05Z | 550,488 | 26 | 2009-02-15T07:37:01Z | [
"python",
"printing",
"overloading"
] | Am i able to overload the print function? and call the normal function? What i want to do is after a specific line i want print to call my print which will call the normal print and write a copy to file.
Also i dont know how to overload print. I dont know how to do variable length arguments. i'll look it up soon but <... | Overloading `print` is a design feature of python 3.0 to address your lack of ability to do so in python 2.x.
However, you can override sys.stdout. ([example](http://code.activestate.com/recipes/119404/).) Just assign it to another file-like object that does what you want.
Alternatively, you could just pipe your scri... |
overload print python | 550,470 | 26 | 2009-02-15T07:26:05Z | 688,816 | 9 | 2009-03-27T07:22:31Z | [
"python",
"printing",
"overloading"
] | Am i able to overload the print function? and call the normal function? What i want to do is after a specific line i want print to call my print which will call the normal print and write a copy to file.
Also i dont know how to overload print. I dont know how to do variable length arguments. i'll look it up soon but <... | I came across the same problem.
How about this:
```
class writer :
def __init__(self, *writers) :
self.writers = writers
def write(self, text) :
for w in self.writers :
w.write(text)
import sys
saved = sys.stdout
fout = file('out.log', 'w')
sys.stdout = writer(sys.stdout, fout)
print "There... |
overload print python | 550,470 | 26 | 2009-02-15T07:26:05Z | 10,106,489 | 32 | 2012-04-11T13:06:25Z | [
"python",
"printing",
"overloading"
] | Am i able to overload the print function? and call the normal function? What i want to do is after a specific line i want print to call my print which will call the normal print and write a copy to file.
Also i dont know how to overload print. I dont know how to do variable length arguments. i'll look it up soon but <... | For those reviewing the previously dated answers, as of version release "Python 2.6" there is a new answer to the original poster's question.
In Python 2.6 and up, you can disable the print statement in favor of the print function, and then override the print function with your own print function:
```
from __future__... |
Favorite Django Tips & Features? | 550,632 | 309 | 2009-02-15T10:06:22Z | 550,644 | 222 | 2009-02-15T10:15:52Z | [
"python",
"django",
"hidden-features"
] | Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
* Please, include only one tip per answer.
* Add Django version requirements if there are any. | I'm just going to start with a tip from myself :)
**Use os.path.dirname() in settings.py to avoid hardcoded dirnames.**
Don't hardcode path's in your settings.py if you want to run your project in different locations. Use the following code in settings.py if your templates and static files are located within the Djan... |
Favorite Django Tips & Features? | 550,632 | 309 | 2009-02-15T10:06:22Z | 551,114 | 119 | 2009-02-15T16:06:32Z | [
"python",
"django",
"hidden-features"
] | Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
* Please, include only one tip per answer.
* Add Django version requirements if there are any. | Use [django-annoying's](http://bitbucket.org/offline/django-annoying/wiki/Home) `render_to` decorator instead of `render_to_response`.
```
@render_to('template.html')
def foo(request):
bars = Bar.objects.all()
if request.user.is_authenticated():
return HttpResponseRedirect("/some/url/")
else:
... |
Favorite Django Tips & Features? | 550,632 | 309 | 2009-02-15T10:06:22Z | 551,139 | 37 | 2009-02-15T16:20:26Z | [
"python",
"django",
"hidden-features"
] | Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
* Please, include only one tip per answer.
* Add Django version requirements if there are any. | I like to use the Python debugger pdb to debug Django projects.
This is a helpful link for learning how to use it: <http://www.ferg.org/papers/debugging_in_python.html> |
Favorite Django Tips & Features? | 550,632 | 309 | 2009-02-15T10:06:22Z | 551,158 | 35 | 2009-02-15T16:30:50Z | [
"python",
"django",
"hidden-features"
] | Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
* Please, include only one tip per answer.
* Add Django version requirements if there are any. | Use [Jinja2](http://jinja.pocoo.org/2/) alongside Django.
If you find the Django template language extremely restricting (like me!) then you don't have to be stuck with it. Django is flexible, and the template language is loosely coupled to the rest of the system, so just plug-in another template language and use it t... |
Favorite Django Tips & Features? | 550,632 | 309 | 2009-02-15T10:06:22Z | 551,499 | 35 | 2009-02-15T20:06:58Z | [
"python",
"django",
"hidden-features"
] | Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
* Please, include only one tip per answer.
* Add Django version requirements if there are any. | Add `assert False` in your view code to dump debug information. |
Favorite Django Tips & Features? | 550,632 | 309 | 2009-02-15T10:06:22Z | 551,615 | 130 | 2009-02-15T21:18:14Z | [
"python",
"django",
"hidden-features"
] | Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
* Please, include only one tip per answer.
* Add Django version requirements if there are any. | Install [Django Command Extensions](http://code.google.com/p/django-command-extensions) and [pygraphviz](http://networkx.lanl.gov/pygraphviz/) and then issue the following command to get a really nice looking Django model visualization:
```
./manage.py graph_models -a -g -o my_project.png
``` |
Favorite Django Tips & Features? | 550,632 | 309 | 2009-02-15T10:06:22Z | 558,401 | 88 | 2009-02-17T19:34:58Z | [
"python",
"django",
"hidden-features"
] | Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
* Please, include only one tip per answer.
* Add Django version requirements if there are any. | Don't hard-code your URLs!
Use [url names](http://docs.djangoproject.com/en/dev/topics/http/urls/#id2) instead, and the [`reverse`](http://docs.djangoproject.com/en/dev/topics/http/urls/#reverse) function to get the URL itself.
When you define your URL mappings, give names to your URLs.
```
urlpatterns += ('project.... |
Favorite Django Tips & Features? | 550,632 | 309 | 2009-02-15T10:06:22Z | 559,972 | 80 | 2009-02-18T05:37:30Z | [
"python",
"django",
"hidden-features"
] | Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
* Please, include only one tip per answer.
* Add Django version requirements if there are any. | Don't write your own login pages. If you're using django.contrib.auth.
The real, dirty secret is that if you're also using django.contrib.admin, and django.template.loaders.app\_directories.load\_template\_source is in your template loaders, **you can get your templates free too!**
```
# somewhere in urls.py
urlpatte... |
Favorite Django Tips & Features? | 550,632 | 309 | 2009-02-15T10:06:22Z | 560,064 | 16 | 2009-02-18T06:44:49Z | [
"python",
"django",
"hidden-features"
] | Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
* Please, include only one tip per answer.
* Add Django version requirements if there are any. | [django.views.generic.list\_detail.object\_list](http://docs.djangoproject.com/en/dev/ref/generic-views/?from=olddocs#django-views-generic-list-detail-object-list) -- It provides all the logic & template variables for pagination (one of those I've-written-that-a-thousand-times-now drudgeries). [Wrapping it](http://www.... |
Favorite Django Tips & Features? | 550,632 | 309 | 2009-02-15T10:06:22Z | 560,111 | 33 | 2009-02-18T07:07:30Z | [
"python",
"django",
"hidden-features"
] | Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
* Please, include only one tip per answer.
* Add Django version requirements if there are any. | This adds to the reply above about [Django URL names and reverse URL dispatching](http://stackoverflow.com/questions/550632/favorite-django-tips-features/558401#558401).
The URL names can also be effectively used within templates. For example, for a given URL pattern:
```
url(r'(?P<project_id>\d+)/team/$', 'project_t... |
Favorite Django Tips & Features? | 550,632 | 309 | 2009-02-15T10:06:22Z | 562,998 | 57 | 2009-02-18T21:54:03Z | [
"python",
"django",
"hidden-features"
] | Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
* Please, include only one tip per answer.
* Add Django version requirements if there are any. | When I was starting out, I didn't know that there was a [Paginator](http://docs.djangoproject.com/en/dev/topics/pagination/#topics-pagination), make sure you know of its existence!! |
Favorite Django Tips & Features? | 550,632 | 309 | 2009-02-15T10:06:22Z | 709,180 | 37 | 2009-04-02T10:30:16Z | [
"python",
"django",
"hidden-features"
] | Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
* Please, include only one tip per answer.
* Add Django version requirements if there are any. | When trying to exchange data between Django and another application, `request.raw_post_data` is a good friend. Use it to receive and custom-process, say, XML data.
Documentation:
<http://docs.djangoproject.com/en/dev/ref/request-response/> |
Favorite Django Tips & Features? | 550,632 | 309 | 2009-02-15T10:06:22Z | 864,898 | 19 | 2009-05-14T18:19:48Z | [
"python",
"django",
"hidden-features"
] | Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
* Please, include only one tip per answer.
* Add Django version requirements if there are any. | `django.db.models.get_model` does allow you to retrieve a model without importing it.
James shows how handy it can be: ["Django tips: Write better template tags â Iteration 4 "](http://www.b-list.org/weblog/2006/jun/07/django-tips-write-better-template-tags/). |
Favorite Django Tips & Features? | 550,632 | 309 | 2009-02-15T10:06:22Z | 942,426 | 19 | 2009-06-02T23:32:21Z | [
"python",
"django",
"hidden-features"
] | Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
* Please, include only one tip per answer.
* Add Django version requirements if there are any. | The [webdesign app](http://docs.djangoproject.com/en/dev/ref/contrib/webdesign/#ref-contrib-webdesign) is very useful when starting to design your website. Once imported, you can add this to generate sample text:
```
{% load webdesign %}
{% lorem 5 p %}
``` |
Favorite Django Tips & Features? | 550,632 | 309 | 2009-02-15T10:06:22Z | 946,397 | 103 | 2009-06-03T18:34:02Z | [
"python",
"django",
"hidden-features"
] | Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
* Please, include only one tip per answer.
* Add Django version requirements if there are any. | There's a set of custom tags I use all over my site's templates. Looking for a way to autoload it (DRY, remember?), I found the following:
```
from django import template
template.add_to_builtins('project.app.templatetags.custom_tag_module')
```
If you put this in a module that's loaded by default (your main urlconf ... |
Favorite Django Tips & Features? | 550,632 | 309 | 2009-02-15T10:06:22Z | 946,443 | 97 | 2009-06-03T18:44:29Z | [
"python",
"django",
"hidden-features"
] | Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
* Please, include only one tip per answer.
* Add Django version requirements if there are any. | [Virtualenv](http://pypi.python.org/pypi/virtualenv#what-it-does) + Python = life saver if you are working on multiple Django projects and there is a possibility that they all don't depend on the same version of Django/an application. |
Favorite Django Tips & Features? | 550,632 | 309 | 2009-02-15T10:06:22Z | 946,497 | 82 | 2009-06-03T18:53:46Z | [
"python",
"django",
"hidden-features"
] | Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
* Please, include only one tip per answer.
* Add Django version requirements if there are any. | Use [django debug toolbar](http://github.com/robhudson/django-debug-toolbar/). For example, it allows to view all SQL queries performed while rendering view and you can also view stacktrace for any of them. |
Favorite Django Tips & Features? | 550,632 | 309 | 2009-02-15T10:06:22Z | 1,018,895 | 20 | 2009-06-19T16:35:18Z | [
"python",
"django",
"hidden-features"
] | Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
* Please, include only one tip per answer.
* Add Django version requirements if there are any. | I don't have enough reputation to reply to the comment in question, but it's important to note that if you're going to use [Jinja](http://en.wikipedia.org/wiki/Jinja%5F%28template%5Fengine%29), it does NOT support the '-' character in template block names, while Django does. This caused me a lot of problems and wasted ... |
Favorite Django Tips & Features? | 550,632 | 309 | 2009-02-15T10:06:22Z | 1,057,512 | 13 | 2009-06-29T10:01:07Z | [
"python",
"django",
"hidden-features"
] | Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
* Please, include only one tip per answer.
* Add Django version requirements if there are any. | Just found this link: <http://lincolnloop.com/django-best-practices/#table-of-contents> - "Django Best Practices". |
Favorite Django Tips & Features? | 550,632 | 309 | 2009-02-15T10:06:22Z | 1,067,267 | 41 | 2009-07-01T04:27:35Z | [
"python",
"django",
"hidden-features"
] | Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
* Please, include only one tip per answer.
* Add Django version requirements if there are any. | From the [django-admin documentation](http://docs.djangoproject.com/en/dev/ref/django-admin/):
If you use the Bash shell, consider installing the Django bash completion script, which lives in `extras/django_bash_completion` in the Django distribution. It enables tab-completion of `django-admin.py` and `manage.py` comm... |
Favorite Django Tips & Features? | 550,632 | 309 | 2009-02-15T10:06:22Z | 1,300,107 | 67 | 2009-08-19T13:53:50Z | [
"python",
"django",
"hidden-features"
] | Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
* Please, include only one tip per answer.
* Add Django version requirements if there are any. | ## Context processors are awesome.
Say you have a different user model and you want to include
that in every response. Instead of doing this:
```
def myview(request, arg, arg2=None, template='my/template.html'):
''' My view... '''
response = dict()
myuser = MyUser.objects.get(user=request.user)
respon... |
Favorite Django Tips & Features? | 550,632 | 309 | 2009-02-15T10:06:22Z | 1,346,574 | 18 | 2009-08-28T11:59:46Z | [
"python",
"django",
"hidden-features"
] | Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
* Please, include only one tip per answer.
* Add Django version requirements if there are any. | I learned this one from the documentation for the [sorl-thumbnails](http://code.google.com/p/sorl-thumbnail/) app. You can use the "as" keyword in template tags to use the results of the call elsewhere in your template.
For example:
```
{% url image-processor uid as img_src %}
<img src="{% thumbnail img_src 100x100 %... |
Favorite Django Tips & Features? | 550,632 | 309 | 2009-02-15T10:06:22Z | 1,359,196 | 27 | 2009-08-31T20:12:58Z | [
"python",
"django",
"hidden-features"
] | Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
* Please, include only one tip per answer.
* Add Django version requirements if there are any. | Since Django "views" only need to be callables that return an HttpResponse, you can easily create class-based views like those in Ruby on Rails and other frameworks.
There are several ways to create class-based views, here's my favorite:
```
from django import http
class RestView(object):
methods = ('GET', 'HEAD... |
Favorite Django Tips & Features? | 550,632 | 309 | 2009-02-15T10:06:22Z | 1,407,331 | 11 | 2009-09-10T19:46:16Z | [
"python",
"django",
"hidden-features"
] | Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
* Please, include only one tip per answer.
* Add Django version requirements if there are any. | Use [signals](http://docs.djangoproject.com/en/dev/topics/signals/) to add accessor-methods on-the-fly.
I saw this technique in [django-photologue](http://code.google.com/p/django-photologue): For any Size object added, the post\_init signal will add the corresponding methods to the Image model.
If you add a site *gia... |
Favorite Django Tips & Features? | 550,632 | 309 | 2009-02-15T10:06:22Z | 1,735,782 | 22 | 2009-11-14T22:15:03Z | [
"python",
"django",
"hidden-features"
] | Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
* Please, include only one tip per answer.
* Add Django version requirements if there are any. | Instead of using `render_to_response` to bind your context to a template and render it (which is what the Django docs usually show) use the generic view [`direct_to_template`](http://docs.djangoproject.com/en/dev/ref/generic-views/#django-views-generic-simple-direct-to-template). It does the same thing that `render_to_... |
Favorite Django Tips & Features? | 550,632 | 309 | 2009-02-15T10:06:22Z | 1,774,722 | 9 | 2009-11-21T06:29:49Z | [
"python",
"django",
"hidden-features"
] | Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
* Please, include only one tip per answer.
* Add Django version requirements if there are any. | Instead of running the Django dev server on localhost, run it on a proper network interface. For example:
```
python manage.py runserver 192.168.1.110:8000
```
or
```
python manage.py runserver 0.0.0.0:8000
```
Then you can not only easily use Fiddler (<http://www.fiddler2.com/fiddler2/>) or another tool like HTTP ... |
Favorite Django Tips & Features? | 550,632 | 309 | 2009-02-15T10:06:22Z | 1,837,525 | 47 | 2009-12-03T03:55:57Z | [
"python",
"django",
"hidden-features"
] | Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
* Please, include only one tip per answer.
* Add Django version requirements if there are any. | Use [IPython](http://ipython.scipy.org/moin/) to jump into your code at any level and debug using the power of IPython. Once you have installed IPython just put this code in wherever you want to debug:
```
from IPython.Shell import IPShellEmbed; IPShellEmbed()()
```
Then, refresh the page, go to your runserver window... |
Favorite Django Tips & Features? | 550,632 | 309 | 2009-02-15T10:06:22Z | 2,093,549 | 19 | 2010-01-19T12:57:39Z | [
"python",
"django",
"hidden-features"
] | Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
* Please, include only one tip per answer.
* Add Django version requirements if there are any. | Everybody knows there is a development server you can run with "manage.py runserver", but did you know that there is a development view for serving static files (CSS / JS / IMG) as well ?
Newcomers are always puzzled because Django doesn't come with any way to serve static files. This is because the dev team think it ... |
Favorite Django Tips & Features? | 550,632 | 309 | 2009-02-15T10:06:22Z | 2,260,327 | 43 | 2010-02-14T06:26:28Z | [
"python",
"django",
"hidden-features"
] | Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
* Please, include only one tip per answer.
* Add Django version requirements if there are any. | Run a development SMTP server that will just output whatever is sent to it (if you don't want to actually install SMTP on your dev server.)
command line:
```
python -m smtpd -n -c DebuggingServer localhost:1025
``` |
Favorite Django Tips & Features? | 550,632 | 309 | 2009-02-15T10:06:22Z | 2,740,163 | 7 | 2010-04-29T19:22:46Z | [
"python",
"django",
"hidden-features"
] | Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
* Please, include only one tip per answer.
* Add Django version requirements if there are any. | Use `wraps` decorator in custom views decorators to preserve view's name, module and docstring. E.g.
```
try:
from functools import wraps
except ImportError:
from django.utils.functional import wraps # Python 2.3, 2.4 fallback.
def view_decorator(fun):
@wraps(fun)
def wrapper():
# here goes y... |
Favorite Django Tips & Features? | 550,632 | 309 | 2009-02-15T10:06:22Z | 2,830,887 | 16 | 2010-05-13T23:04:24Z | [
"python",
"django",
"hidden-features"
] | Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
* Please, include only one tip per answer.
* Add Django version requirements if there are any. | [PyCharm IDE](http://www.jetbrains.com/pycharm/) is a nice environment to code and especially debug, with built-in support for Django. |
Favorite Django Tips & Features? | 550,632 | 309 | 2009-02-15T10:06:22Z | 2,832,479 | 7 | 2010-05-14T07:23:52Z | [
"python",
"django",
"hidden-features"
] | Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
* Please, include only one tip per answer.
* Add Django version requirements if there are any. | The [Django Debug Toolbar](http://github.com/robhudson/django-debug-toolbar) is really fantastic. Not really a toolbar, it actually brings up a sidepane that tells you all sorts of information about what brought you the page you're looking at - DB queries, the context variables sent to the template, signals, and more. |
Favorite Django Tips & Features? | 550,632 | 309 | 2009-02-15T10:06:22Z | 3,247,524 | 14 | 2010-07-14T15:06:49Z | [
"python",
"django",
"hidden-features"
] | Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
* Please, include only one tip per answer.
* Add Django version requirements if there are any. | Use [xml\_models](http://djangorestmodel.sourceforge.net/) to create Django models that use an XML REST API backend (instead of a SQL one). This is very useful especially when modelling third party APIs - you get all the same QuerySet syntax that you're used to. You can install it from PyPI.
XML from an API:
```
<pro... |
Favorite Django Tips & Features? | 550,632 | 309 | 2009-02-15T10:06:22Z | 4,007,078 | 11 | 2010-10-24T03:41:54Z | [
"python",
"django",
"hidden-features"
] | Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
* Please, include only one tip per answer.
* Add Django version requirements if there are any. | # Remove Database Access Information from settings.py
One thing I've done in my Django site's `settings.py` is load database access info from a file in `/etc`. This way the access setup (database host, port, username, password) can be different for each machine, and sensitive info like the password isn't in my project... |
Favorite Django Tips & Features? | 550,632 | 309 | 2009-02-15T10:06:22Z | 4,861,267 | 40 | 2011-02-01T10:11:58Z | [
"python",
"django",
"hidden-features"
] | Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
* Please, include only one tip per answer.
* Add Django version requirements if there are any. | The `./manage.py runserver_plus` facilty which comes with [django\_extensions](http://code.google.com/p/django-command-extensions/) is truly awesome.
It creates an enhanced debug page that, amongst other things, uses the Werkzeug debugger to create interactive debugging consoles for each point in the stack (see screen... |
Favorite Django Tips & Features? | 550,632 | 309 | 2009-02-15T10:06:22Z | 5,546,778 | 12 | 2011-04-05T03:12:34Z | [
"python",
"django",
"hidden-features"
] | Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
* Please, include only one tip per answer.
* Add Django version requirements if there are any. | Instead of evaluating whole queryset to check whether you got back any results, use .exists() in Django 1.2+ and .count() for previous versions.
Both exists() and count() clears order by clauses and retrieves a single integer from DB. However exists() will always return 1 where as count may return higher values on whi... |
Favorite Django Tips & Features? | 550,632 | 309 | 2009-02-15T10:06:22Z | 5,809,809 | 14 | 2011-04-27T19:59:16Z | [
"python",
"django",
"hidden-features"
] | Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
* Please, include only one tip per answer.
* Add Django version requirements if there are any. | Use database migrations. Use [South](http://south.aeracode.org). |
Favorite Django Tips & Features? | 550,632 | 309 | 2009-02-15T10:06:22Z | 6,169,597 | 12 | 2011-05-29T18:31:22Z | [
"python",
"django",
"hidden-features"
] | Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
* Please, include only one tip per answer.
* Add Django version requirements if there are any. | If you make changes into model
```
./manage.py dumpdata appname > appname_data.json
./manage.py reset appname
django-admin.py loaddata appname_data.json
``` |
Cross-platform way to get PIDs by process name in python | 550,653 | 36 | 2009-02-15T10:23:56Z | 1,226,643 | 10 | 2009-08-04T10:00:18Z | [
"python",
"cross-platform",
"jython",
"hp-ux"
] | Several processes with the same name are running on host. What is the cross-platform way to get PIDs of those processes by name using **python** or **jython**?
1. I want something like `pidof` but in python. (I don't have `pidof` anyway.)
2. I can't parse `/proc` because it might be unavailable (on HP-UX).
3. I do not... | There's no single cross-platform API, you'll have to check for OS. For posix based use /proc. For Windows use following code to get list of all pids with coresponding process names
```
from win32com.client import GetObject
WMI = GetObject('winmgmts:')
processes = WMI.InstancesOf('Win32_Process')
process_list = [(p.Pro... |
Cross-platform way to get PIDs by process name in python | 550,653 | 36 | 2009-02-15T10:23:56Z | 2,241,047 | 45 | 2010-02-10T23:12:17Z | [
"python",
"cross-platform",
"jython",
"hp-ux"
] | Several processes with the same name are running on host. What is the cross-platform way to get PIDs of those processes by name using **python** or **jython**?
1. I want something like `pidof` but in python. (I don't have `pidof` anyway.)
2. I can't parse `/proc` because it might be unavailable (on HP-UX).
3. I do not... | You can use psutil ( <https://github.com/giampaolo/psutil> ), which works on Windows and UNIX:
```
import psutil
PROCNAME = "python.exe"
for proc in psutil.process_iter():
if proc.name() == PROCNAME:
print(proc)
```
The code above prints the following on my machine:
```
psutil.Process (PID:2908; PPID:3... |
"Private" (implementation) class in Python | 551,038 | 50 | 2009-02-15T15:29:40Z | 551,048 | 89 | 2009-02-15T15:34:03Z | [
"python",
"design",
"access-modifiers"
] | I am coding a small Python module composed of two parts:
* some functions defining a public interface,
* an implementation class used by the above functions, but which is not meaningful outside the module.
At first, I decided to "hide" this implementation class by defining it inside the function using it, but this ha... | Use a single underscore prefix:
```
class _Internal:
...
```
This is the official Python convention for 'internal' symbols; "from module import \*" does not import underscore-prefixed objects. |
"Private" (implementation) class in Python | 551,038 | 50 | 2009-02-15T15:29:40Z | 551,054 | 22 | 2009-02-15T15:36:03Z | [
"python",
"design",
"access-modifiers"
] | I am coding a small Python module composed of two parts:
* some functions defining a public interface,
* an implementation class used by the above functions, but which is not meaningful outside the module.
At first, I decided to "hide" this implementation class by defining it inside the function using it, but this ha... | Define `__all__`, a list of names that you want to be exported ([see documentation](http://docs.python.org/tutorial/modules.html#importing-from-a-package)).
```
__all__ = ['public_class'] # don't add here the 'implementation_class'
``` |
"Private" (implementation) class in Python | 551,038 | 50 | 2009-02-15T15:29:40Z | 551,097 | 8 | 2009-02-15T15:58:49Z | [
"python",
"design",
"access-modifiers"
] | I am coding a small Python module composed of two parts:
* some functions defining a public interface,
* an implementation class used by the above functions, but which is not meaningful outside the module.
At first, I decided to "hide" this implementation class by defining it inside the function using it, but this ha... | A pattern that I sometimes use is this:
Define a class:
```
class x(object):
def doThis(self):
...
def doThat(self):
...
```
Create an instance of the class, overwriting the class name:
```
x = x()
```
Define symbols that expose the functionality:
```
doThis = x.doThis
doThat = x.doThat
``... |
"Private" (implementation) class in Python | 551,038 | 50 | 2009-02-15T15:29:40Z | 551,361 | 45 | 2009-02-15T18:31:49Z | [
"python",
"design",
"access-modifiers"
] | I am coding a small Python module composed of two parts:
* some functions defining a public interface,
* an implementation class used by the above functions, but which is not meaningful outside the module.
At first, I decided to "hide" this implementation class by defining it inside the function using it, but this ha... | In short:
1. **You cannot enforce privacy**. There are no private classes/methods/functions in Python. At least, not strict privacy as in other languages, such as Java.
2. **You can only indicate/suggest privacy**. This follows a convention. The python convention for marking a class/function/method as private is to pr... |
Deploying application with Python or another embedded scripting language | 551,227 | 14 | 2009-02-15T17:12:33Z | 551,252 | 8 | 2009-02-15T17:28:19Z | [
"c++",
"python",
"deployment",
"scripting-language",
"embedded-language"
] | I'm thinking about using Python as an **embedded scripting language** in a hobby project written in **C++**. I would not like to depend on separately installed Python distribution. Python documentation seems to be quite clear about general usage, but I couldn't find a clear answer to this.
Is it feasible to deploy a P... | The embedding process is fully documented : [Embedding Python in Another Application](http://docs.python.org/extending/embedding.html).
The documents suggests a few levels at which embedding is done, choose whatever best fits your requirements.
> A simple demo of embedding Python can be found in the directory Demo/emb... |
Deploying application with Python or another embedded scripting language | 551,227 | 14 | 2009-02-15T17:12:33Z | 551,533 | 14 | 2009-02-15T20:28:31Z | [
"c++",
"python",
"deployment",
"scripting-language",
"embedded-language"
] | I'm thinking about using Python as an **embedded scripting language** in a hobby project written in **C++**. I would not like to depend on separately installed Python distribution. Python documentation seems to be quite clear about general usage, but I couldn't find a clear answer to this.
Is it feasible to deploy a P... | Link your application to the python library (pythonXX.lib on Windows) and add the following to your main() function.
```
Py_NoSiteFlag = 1; // Disable importing site.py
Py_Initialize(); // Create a python interpreter
```
Put the python standard library bits you need into a zip file (called pythonXX.zip) and place... |
Getting "global name 'foo' is not defined" with Python's timeit | 551,797 | 58 | 2009-02-15T23:15:40Z | 551,804 | 67 | 2009-02-15T23:18:42Z | [
"python",
"scope",
"timeit"
] | I'm trying to find out how much time it takes to execute a Python statement, so I looked online and found that the standard library provides a module called [timeit](http://docs.python.org/library/timeit.html) that purports to do exactly that:
```
import timeit
def foo():
# ... contains code I want to time ...
d... | have you tried making this line:
```
t = timeit.Timer("foo()")
```
This:
```
t = timeit.Timer("foo()", "from __main__ import foo")
```
Check out the link you provided at the very bottom.
> To give the timeit module access to functions you define, you can pass a setup parameter which contains an import statement:
... |
Getting "global name 'foo' is not defined" with Python's timeit | 551,797 | 58 | 2009-02-15T23:15:40Z | 5,390,326 | 13 | 2011-03-22T11:16:51Z | [
"python",
"scope",
"timeit"
] | I'm trying to find out how much time it takes to execute a Python statement, so I looked online and found that the standard library provides a module called [timeit](http://docs.python.org/library/timeit.html) that purports to do exactly that:
```
import timeit
def foo():
# ... contains code I want to time ...
d... | You can try this hack:
```
import timeit
def foo():
print 'bar'
def dotime():
t = timeit.Timer("foo()")
time = t.timeit(1)
print "took %fs\n" % (time,)
import __builtin__
__builtin__.__dict__.update(locals())
dotime()
``` |
Help me implement Blackjack in Python (updated) | 551,840 | 3 | 2009-02-15T23:34:26Z | 551,852 | 14 | 2009-02-15T23:42:10Z | [
"python"
] | I am in the process of writing a blackjack code for python, and i was hoping someone would be able to tell me how to make it:
1. Recognize what someone has typed i.e. "Hit" or "Stand" and react accordingly.
2. Calculate what the player's score is and whether it is an ace and a jack together, and automatically wins.
O... | This can get you started:
<http://docs.python.org/library/random.html>
<http://docs.python.org/library/strings.html>
<http://docs.python.org/library/stdtypes.html>
<http://docs.python.org/reference/index.html>
I see you have added some code; that's good.
Think about the parts of your program that will need to exi... |
Help me implement Blackjack in Python (updated) | 551,840 | 3 | 2009-02-15T23:34:26Z | 552,111 | 9 | 2009-02-16T02:57:38Z | [
"python"
] | I am in the process of writing a blackjack code for python, and i was hoping someone would be able to tell me how to make it:
1. Recognize what someone has typed i.e. "Hit" or "Stand" and react accordingly.
2. Calculate what the player's score is and whether it is an ace and a jack together, and automatically wins.
O... | I've covered the entire thing as a (long) series of exercises.
<http://homepage.mac.com/s_lott/books/oodesign.html>
Just read and do the exercises in the book. You'll implement blackjack (and Craps and Roulette, too.) |
"Interfaces" in Python: Yea or Nay? | 552,058 | 16 | 2009-02-16T02:15:17Z | 552,087 | 10 | 2009-02-16T02:40:12Z | [
"python",
"documentation",
"interface",
"coding-style"
] | So I'm starting a project using Python after spending a significant amount of time in static land. I've seen some projects that make "interfaces" which are really just classes without any implementations. Before, I'd scoff at the idea and ignore that section of those projects. But now, I'm beginning to warm up to the i... | There are some cases where interfaces can be very handy. [Twisted](http://twistedmatrix.com/trac/) makes [fairly extensive use](http://twistedmatrix.com/projects/core/documentation/howto/components.html) of [Zope interfaces](http://wiki.zope.org/Interfaces/FrontPage), and in a project I was working on Zope interfaces w... |
"Interfaces" in Python: Yea or Nay? | 552,058 | 16 | 2009-02-16T02:15:17Z | 552,097 | 10 | 2009-02-16T02:46:40Z | [
"python",
"documentation",
"interface",
"coding-style"
] | So I'm starting a project using Python after spending a significant amount of time in static land. I've seen some projects that make "interfaces" which are really just classes without any implementations. Before, I'd scoff at the idea and ignore that section of those projects. But now, I'm beginning to warm up to the i... | The pythonic way is to "Ask for forgiveness rather than receive permission". Interfaces are *all* about receiving permission to perform some operation on an object. Python prefers this:
```
def quacker(duck):
try:
duck.quack():
except AttributeError:
raise ThisAintADuckException
``` |
"Interfaces" in Python: Yea or Nay? | 552,058 | 16 | 2009-02-16T02:15:17Z | 552,203 | 27 | 2009-02-16T03:50:38Z | [
"python",
"documentation",
"interface",
"coding-style"
] | So I'm starting a project using Python after spending a significant amount of time in static land. I've seen some projects that make "interfaces" which are really just classes without any implementations. Before, I'd scoff at the idea and ignore that section of those projects. But now, I'm beginning to warm up to the i... | I'm not sure what the point of that is. Interfaces (of this form, anyway) are largely to work around the lack of multiple inheritance. But Python has MI, so why not just make an abstract class?
```
class Something(object):
def some_method(self):
raise NotImplementedError()
def some_other_method(self, s... |
"Interfaces" in Python: Yea or Nay? | 552,058 | 16 | 2009-02-16T02:15:17Z | 552,917 | 11 | 2009-02-16T10:47:32Z | [
"python",
"documentation",
"interface",
"coding-style"
] | So I'm starting a project using Python after spending a significant amount of time in static land. I've seen some projects that make "interfaces" which are really just classes without any implementations. Before, I'd scoff at the idea and ignore that section of those projects. But now, I'm beginning to warm up to the i... | In Python 2.6 and later, you can use [abstract base classes](http://docs.python.org/library/abc.html) instead. These are useful, because you can then test to see if something implements a given ABC by using "isinstance". As usual in Python, the concept is not as strictly enforced as it would be in a strict language, bu... |
What's the best way to make a time from "Today" or "Yesterday" and a time in Python? | 552,073 | 9 | 2009-02-16T02:30:50Z | 552,229 | 18 | 2009-02-16T04:03:58Z | [
"python",
"datetime",
"parsing"
] | Python has pretty good date parsing but is the only way to recognize a datetime such as "Today 3:20 PM" or "Yesterday 11:06 AM" by creating a new date today and doing subtractions? | A library that I like a lot, and I'm seeing more and more people use, is [python-dateutil](http://labix.org/python-dateutil) but unfortunately neither it nor the other traditional big datetime parser, [mxDateTime from Egenix](http://www.egenix.com/products/python/mxBase/mxDateTime/) can parse the word "tomorrow" in spi... |
How do python classes work? | 552,329 | 4 | 2009-02-16T05:26:35Z | 552,363 | 9 | 2009-02-16T05:49:13Z | [
"python"
] | I have a code file from the boto framework pasted below, all of the print statements are mine, and the one commented out line is also mine, all else belongs to the attributed author.
My question is what is the order in which instantiations and allocations occur in python when instantiating a class? The author's code b... | **A few python notes**
When python executes the **class** block, it creates all of the "attributes" of that class as it encounters them. They are usually class variables as well as functions (methods), and the like.
So the value for "Manager.DefaultDomainName" is set when it is encountered in the class definition. Th... |
Use Python 2.6 subprocess module in Python 2.5 | 552,423 | 9 | 2009-02-16T06:41:55Z | 554,881 | 9 | 2009-02-16T22:43:43Z | [
"python",
"subprocess",
"python-2.5"
] | I would like to use Python 2.6's version of subprocess, because it allows the [Popen.terminate()](http://docs.python.org/library/subprocess.html#subprocess.Popen.terminate) function, but I'm stuck with Python 2.5. Is there some reasonably clean way to use the newer version of the module in my 2.5 code? Some sort of `fr... | I know this question has already been answered, but for what it's worth, I've used the `subprocess.py` that ships with Python 2.6 in Python 2.3 and it's worked fine. If you read the comments at the top of the file it says:
> `# This module should remain compatible with Python 2.2, see PEP 291.` |
Django Model returning NoneType | 552,521 | 2 | 2009-02-16T07:44:23Z | 552,530 | 7 | 2009-02-16T07:50:32Z | [
"python",
"django",
"django-views"
] | I have a model Product
it has two fields size & colours among others
```
colours = models.CharField(blank=True, null=True, max_length=500)
size = models.CharField(blank=True, null=True, max_length=500)
```
In my view I have
```
current_product = Product.objects.get(slug=title)
if len(current_product.size) != 0 :
... | `NoneType` is the type that the `None` value has. You want to change the second snippet to
```
if current_product.size: # This will evaluate as false if size is None or len(size) == 0.
blah blah
``` |
How do I profile memory usage in Python? | 552,744 | 87 | 2009-02-16T09:34:43Z | 552,810 | 66 | 2009-02-16T10:00:24Z | [
"python",
"memory",
"profiling"
] | I've recently become interested in algorithms and have begun exploring them by writing a naive implementation and then optimizing it in various ways.
I'm already familiar with the standard Python module for profiling runtime (for most things I've found the timeit magic function in IPython to be sufficient), but I'm al... | This one has been answered already here: [Python memory profiler](http://stackoverflow.com/questions/110259/python-memory-profiler)
Basically you do something like that (cited from [Guppy-PE](http://guppy-pe.sourceforge.net/#Heapy)):
```
>>> from guppy import hpy; h=hpy()
>>> h.heap()
Partition of a set of 48477 obje... |
How do I profile memory usage in Python? | 552,744 | 87 | 2009-02-16T09:34:43Z | 15,448,600 | 11 | 2013-03-16T11:19:27Z | [
"python",
"memory",
"profiling"
] | I've recently become interested in algorithms and have begun exploring them by writing a naive implementation and then optimizing it in various ways.
I'm already familiar with the standard Python module for profiling runtime (for most things I've found the timeit magic function in IPython to be sufficient), but I'm al... | For a really simple approach try:
```
import resource
def using(point=""):
usage=resource.getrusage(resource.RUSAGE_SELF)
return '''%s: usertime=%s systime=%s mem=%s mb
'''%(point,usage[0],usage[1],
(usage[2]*resource.getpagesize())/1000000.0 )
```
Just insert `using("Label")` where... |
Generate a random date between two other dates | 553,303 | 53 | 2009-02-16T13:30:04Z | 553,320 | 70 | 2009-02-16T13:35:08Z | [
"python",
"datetime",
"random"
] | How would I generate a random date that has to be between two other given dates?
The functions signature should something like this-
```
randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34)
^ ^ ^
date generated has date generated has random number
... | Convert both strings to timestamps (in your chosen resolution, e.g. milliseconds, seconds, hours, days, whatever), subtract the earlier from the later, multiply your random number (assuming it is distributed in the range [0, 1]) with that difference, and add again to the earlier one. Convert the timestamp back to date ... |
Generate a random date between two other dates | 553,303 | 53 | 2009-02-16T13:30:04Z | 553,448 | 67 | 2009-02-16T14:21:56Z | [
"python",
"datetime",
"random"
] | How would I generate a random date that has to be between two other given dates?
The functions signature should something like this-
```
randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34)
^ ^ ^
date generated has date generated has random number
... | ```
from random import randrange
from datetime import timedelta
def random_date(start, end):
"""
This function will return a random datetime between two datetime
objects.
"""
delta = end - start
int_delta = (delta.days * 24 * 60 * 60) + delta.seconds
random_second = randrange(int_delta)
... |
Generate a random date between two other dates | 553,303 | 53 | 2009-02-16T13:30:04Z | 8,170,651 | 43 | 2011-11-17T16:25:52Z | [
"python",
"datetime",
"random"
] | How would I generate a random date that has to be between two other given dates?
The functions signature should something like this-
```
randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34)
^ ^ ^
date generated has date generated has random number
... | A tiny version.
```
from datetime import timedelta
from random import randint
def random_date(start, end):
return start + timedelta(
seconds=randint(0, int((end - start).total_seconds())))
```
Note that both `start` and `end` arguments should be `datetime` objects. If you've got strings instead, it's fa... |
Generate a random date between two other dates | 553,303 | 53 | 2009-02-16T13:30:04Z | 17,193,251 | 12 | 2013-06-19T13:59:56Z | [
"python",
"datetime",
"random"
] | How would I generate a random date that has to be between two other given dates?
The functions signature should something like this-
```
randomDate("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", 0.34)
^ ^ ^
date generated has date generated has random number
... | It's very simple using radar
## Installation
$ pip install radar
## Usage
```
import datetime
import radar
# Generate random datetime (parsing dates from str values)
radar.random_datetime(start='2000-05-24', stop='2013-05-24T23:59:59')
# Generate random datetime from datetime.datetime values
radar.random_dateti... |
Can you use a string to instantiate a class in python? | 553,784 | 27 | 2009-02-16T16:00:26Z | 554,073 | 12 | 2009-02-16T18:17:22Z | [
"python",
"design-patterns",
"reflection"
] | I'm using a builder pattern to seperate a bunch of different configuration possibilities. Basically, I have a bunch of classes that are named an ID (something like ID12345). These all inherit from the base builder class. In my script, I need to instantiate an instance for each class (about 50) every time this app runs.... | **Never** use `eval()` if you can help it. Python has **so** many better options (dispatch dictionary, `getattr()`, etc.) that you should never have to use the security hole known as `eval()`. |
Can you use a string to instantiate a class in python? | 553,784 | 27 | 2009-02-16T16:00:26Z | 554,462 | 39 | 2009-02-16T20:34:50Z | [
"python",
"design-patterns",
"reflection"
] | I'm using a builder pattern to seperate a bunch of different configuration possibilities. Basically, I have a bunch of classes that are named an ID (something like ID12345). These all inherit from the base builder class. In my script, I need to instantiate an instance for each class (about 50) every time this app runs.... | If you wanted to avoid an eval(), you could just do:
```
id = "1234asdf"
constructor = globals()[id]
instance = constructor()
```
Provided that the class is defined in (or imported into) your current scope. |
Can you use a string to instantiate a class in python? | 553,784 | 27 | 2009-02-16T16:00:26Z | 554,812 | 13 | 2009-02-16T22:18:24Z | [
"python",
"design-patterns",
"reflection"
] | I'm using a builder pattern to seperate a bunch of different configuration possibilities. Basically, I have a bunch of classes that are named an ID (something like ID12345). These all inherit from the base builder class. In my script, I need to instantiate an instance for each class (about 50) every time this app runs.... | Not totally sure this is what you want, but it seems like a more Python'y way to instantiate a bunch of classes listed in a string:
```
class idClasses:
class ID12345:pass
class ID01234:pass
# could also be: import idClasses
class ProcessDirector:
def __init__(self):
self.allClasses = []
def ... |
Can anyone provide a more pythonic way of generating the morris sequence? | 553,871 | 5 | 2009-02-16T16:24:53Z | 554,028 | 23 | 2009-02-16T18:07:12Z | [
"python",
"sequences",
"itertools"
] | I'm trying to generate the [morris sequence](http://www.ocf.berkeley.edu/~stoll/answer.html) in python. My current solution is below, but I feel like I just wrote c in python. Can anyone provide a more pythonic solution?
```
def morris(x):
a = ['1', '11']
yield a[0]
yield a[1]
while len(a) <= x:
... | [`itertools.groupby`](http://docs.python.org/library/itertools.html#itertools.groupby) seems to fit perfectly! Just define a `next_morris` function as follows:
```
def next_morris(number):
return ''.join('%s%s' % (len(list(group)), digit)
for digit, group in itertools.groupby(str(number)))
```
... |
How do I prevent Python's urllib(2) from following a redirect | 554,446 | 40 | 2009-02-16T20:29:30Z | 554,475 | 11 | 2009-02-16T20:38:43Z | [
"python",
"urllib2"
] | I am currently trying to log into a site using Python however the site seems to be sending a cookie and a redirect statement on the same page. Python seems to be following that redirect thus preventing me from reading the cookie send by the login page. How do I prevent Python's urllib (or urllib2) urlopen from followin... | `urllib2.urlopen` calls `build_opener()` which uses this list of handler classes:
```
handlers = [ProxyHandler, UnknownHandler, HTTPHandler,
HTTPDefaultErrorHandler, HTTPRedirectHandler,
FTPHandler, FileHandler, HTTPErrorProcessor]
```
You could try calling `urllib2.build_opener(handlers)` yourself with a list that o... |
How do I prevent Python's urllib(2) from following a redirect | 554,446 | 40 | 2009-02-16T20:29:30Z | 554,580 | 33 | 2009-02-16T21:13:43Z | [
"python",
"urllib2"
] | I am currently trying to log into a site using Python however the site seems to be sending a cookie and a redirect statement on the same page. Python seems to be following that redirect thus preventing me from reading the cookie send by the login page. How do I prevent Python's urllib (or urllib2) urlopen from followin... | You could do a couple of things:
1. Build your own HTTPRedirectHandler that intercepts each redirect
2. Create an instance of HTTPCookieProcessor and install that opener so that you have access to the cookiejar.
This is a quick little thing that shows both
```
import urllib2
#redirect_handler = urllib2.HTTPRedirect... |
How do I prevent Python's urllib(2) from following a redirect | 554,446 | 40 | 2009-02-16T20:29:30Z | 11,744,894 | 27 | 2012-07-31T16:33:51Z | [
"python",
"urllib2"
] | I am currently trying to log into a site using Python however the site seems to be sending a cookie and a redirect statement on the same page. Python seems to be following that redirect thus preventing me from reading the cookie send by the login page. How do I prevent Python's urllib (or urllib2) urlopen from followin... | If all you need is stopping redirection, then there is a simple way to do it. For example I only want to get cookies and for a better performance I don't want to be redirected to any other page. Also I hope the code is kept as 3xx. let's use 302 for instance.
```
class MyHTTPErrorProcessor(urllib2.HTTPErrorProcessor):... |
Stackless python network performance degrading over time? | 554,805 | 8 | 2009-02-16T22:16:06Z | 554,914 | 14 | 2009-02-16T22:52:41Z | [
"python",
"performance",
"networking",
"io",
"python-stackless"
] | So i'm toying around with stackless python, writing a *very simple* webserver to teach myself programming with microthreads/tasklets. But now to my problem, when I run something like `ab -n 100000 -c 50 http://192.168.0.192/` (100k requests, 50 concurrency) in apache bench I get something like 6k req/s, the second time... | Two things.
First, please make Class Name start with an Upper Case Letter. It's more conventional and easier to read.
More importantly, in the `stackless_accept` function you accumulate a `list` of `Sock` objects, named `sockets`. This list appears to grow endlessly. Yes, you have a `remove`, but it isn't *always* in... |
Euler problem number #4 | 555,009 | 2 | 2009-02-16T23:21:46Z | 555,020 | 9 | 2009-02-16T23:25:00Z | [
"python",
"palindrome"
] | Using Python, I am trying to solve [problem #4](http://projecteuler.net/index.php?section=problems&id=4) of the [Project Euler](http://projecteuler.net/) problems. Can someone please tell me what I am doing incorrectly? The problem is to **Find the largest palindrome made from the product of two 3-digit numbers**. Here... | Try computing x from the product of z and y rather than checking every number from 1 to a million. Think about it: if you were asked to calculate 500\*240, which is more efficient - multiplying them, or counting up from 1 until you find the right answer? |
Euler problem number #4 | 555,009 | 2 | 2009-02-16T23:21:46Z | 555,107 | 9 | 2009-02-17T00:08:11Z | [
"python",
"palindrome"
] | Using Python, I am trying to solve [problem #4](http://projecteuler.net/index.php?section=problems&id=4) of the [Project Euler](http://projecteuler.net/) problems. Can someone please tell me what I am doing incorrectly? The problem is to **Find the largest palindrome made from the product of two 3-digit numbers**. Here... | Some efficiency issues:
1. start at the top (since we can use this in skipping a lot of calculations)
2. don't double-calculate
> ```
> def is_palindrome(n):
> s = str(n)
> return s == s[::-1]
>
> def biggest():
> big_x, big_y, max_seen = 0,0, 0
> for x in xrange(999,99,-1):
> for y in xrange(... |
Match series of (non-nested) balanced parentheses at end of string | 555,344 | 3 | 2009-02-17T02:29:03Z | 555,404 | 7 | 2009-02-17T03:02:58Z | [
"python",
"regex"
] | How can I match one or more parenthetical expressions appearing at the end of string?
Input:
```
'hello (i) (m:foo)'
```
Desired output:
```
['i', 'm:foo']
```
Intended for a python script. Paren marks cannot appear inside of each other ([no nesting](http://i89.photobucket.com/albums/k220/kipper_308/fran_web.jpg))... | ```
paren_pattern = re.compile(r"\(([^()]*)\)(?=(?:\s*\([^()]*\))*\s*$)")
def getParens(s):
return paren_pattern.findall(s)
```
or even shorter:
```
getParens = re.compile(r"\(([^()]*)\)(?=(?:\s*\([^()]*\))*\s*$)").findall
```
explaination:
```
\( # opening paren
([^()]*) # cont... |
Character Translation using Python (like the tr command) | 555,705 | 28 | 2009-02-17T06:33:06Z | 555,724 | 29 | 2009-02-17T06:40:10Z | [
"python"
] | Is there a way to do character translation (kind of like the tr command) using python | See [`string.translate`](http://docs.python.org/library/stdtypes.html#str.translate)
```
import string
"abc".translate(string.maketrans("abc", "def")) # => "def"
```
Note the doc's comments about subtleties in the translation of unicode strings.
Edit: Since `tr` is a bit more advanced, also consider using `re.sub`. |
Character Translation using Python (like the tr command) | 555,705 | 28 | 2009-02-17T06:33:06Z | 1,385,542 | 14 | 2009-09-06T12:17:56Z | [
"python"
] | Is there a way to do character translation (kind of like the tr command) using python | If you're using python3 translate is less verbose:
```
>>> 'abc'.translate(str.maketrans('ac','xy'))
'xby'
```
Ahh.. and there is also equivalent to `tr -d`:
```
>>> "abc".translate(str.maketrans('','','b'))
'ac'
```
For `tr -d` with python2.x use an additional argument to translate function:
```
>>> "abc".transla... |
ImportError: No module named copy_reg pickle | 556,269 | 13 | 2009-02-17T10:42:58Z | 556,295 | 17 | 2009-02-17T10:52:36Z | [
"python",
"pickle"
] | I'm trying to unpickle an object stored as a blob in a MySQL database. I've manually generated and stored the pickled object in the database, but when I try to unpickle the object, I get the following rather cryptic exception:
ImportError: No module named copy\_reg
Any ideas as to why this happens?
**Method of Repro... | It seems this might be caused by my method of exporting the pickled object.
[This bug report](http://www.archivum.info/python-bugs-list@python.org/2007-04/msg00222.html) seens to suggest that my issue can be resolved by exporting to a file writen in binary mode. I'm going to give this a go now and see if this solves m... |
ImportError: No module named copy_reg pickle | 556,269 | 13 | 2009-02-17T10:42:58Z | 760,499 | 9 | 2009-04-17T13:50:01Z | [
"python",
"pickle"
] | I'm trying to unpickle an object stored as a blob in a MySQL database. I've manually generated and stored the pickled object in the database, but when I try to unpickle the object, I get the following rather cryptic exception:
ImportError: No module named copy\_reg
Any ideas as to why this happens?
**Method of Repro... | Also, simply running dos2unix (under linux) over the (windows-created) pickle file solved the problem for me. (Haven't tried the open mode 'wb' thing.)
Dan |
Python list serialization - fastest method | 556,730 | 11 | 2009-02-17T13:16:25Z | 556,946 | 7 | 2009-02-17T14:07:06Z | [
"python",
"serialization",
"caching"
] | I need to load (de-serialize) a pre-computed list of integers from a file in a Python script (into a Python list). The list is large (upto millions of items), and I can choose the format I store it in, as long as loading is fastest.
Which is the fastest method, and why?
1. Using `import` on a .py file that just conta... | I would guess [cPickle](http://docs.python.org/library/pickle.html#module-cPickle) will be fastest if you really need the thing in a list.
If you can use an [array](http://docs.python.org/library/array.html), which is a built-in sequence type, I timed this at a quarter of a second for 1 million integers:
```
from arr... |
How to get distinct Django apps on same subdomain to share session cookie? | 556,907 | 7 | 2009-02-17T13:58:41Z | 557,020 | 12 | 2009-02-17T14:21:11Z | [
"python",
"django",
"deployment",
"session",
"cookies"
] | We have a couple of Django applications deployed on the same subdomain. A few power users need to jump between these applications. I noticed that each time they bounce between applications their session cookie receives a new session ID from Django.
I don't use the Django session table much except in one complex workfl... | I would instead advise you to set `SESSION_COOKIE_NAME` to *different* values for the two apps. Your users will still have to log in twice initially, but their sessions won't conflict - if they log in to app A, then app B, and return to A, they'll still have their A session.
Sharing sessions between Django instances i... |
How to get distinct Django apps on same subdomain to share session cookie? | 556,907 | 7 | 2009-02-17T13:58:41Z | 659,606 | 8 | 2009-03-18T18:44:25Z | [
"python",
"django",
"deployment",
"session",
"cookies"
] | We have a couple of Django applications deployed on the same subdomain. A few power users need to jump between these applications. I noticed that each time they bounce between applications their session cookie receives a new session ID from Django.
I don't use the Django session table much except in one complex workfl... | I agree that sharing sessions between Django instances is probably not a good idea. If you really wanted to, you could:
* make sure the two django applications share the same SECRET\_KEY
* make sure the two django applications share the same SeSSON\_COOKIE\_NAME
* make sure the SESSION\_COOKIE\_DOMAIN is set to someth... |
How to re-use a reusable app in Django | 557,171 | 17 | 2009-02-17T14:50:22Z | 557,509 | 25 | 2009-02-17T15:59:50Z | [
"python",
"django",
"code-reuse"
] | ## Hello Django experts
I am trying to create my first site in Django and as I'm looking for example apps out there to draw inspiration from, I constantly stumble upon a term called *"reusable apps"*.
I understand the *concept* of an app that is reusable easy enough, but the means of reusing an app in Django are quit... | In general, the only thing required to use a reusable app is to make sure it's on `sys.path`, so that you can import it from Python code. In most cases (if the author follows best practice), the reusable app tarball or bundle will contain a top-level directory with docs, a README, a `setup.py`, and then a subdirectory ... |
Django - having middleware communicate with views/templates | 557,460 | 7 | 2009-02-17T15:47:49Z | 557,538 | 12 | 2009-02-17T16:06:36Z | [
"python",
"django"
] | Alright, this is probably a really silly question but I am new to Python/Django so I can't really wrap my head around its scoping concepts just yet. Right now I am writing a [middleware](http://docs.djangoproject.com/en/dev/topics/http/middleware/#topics-http-middleware) class to handle some stuff, and I want to set 'g... | Here's what we do. We use a context processor like this...
```
def context_myApp_settings(request):
"""Insert some additional information into the template context
from the settings.
Specifically, the LOGOUT_URL, MEDIA_URL and BADGES settings.
"""
from django.conf import settings
additions = {
... |
Django - having middleware communicate with views/templates | 557,460 | 7 | 2009-02-17T15:47:49Z | 557,540 | 19 | 2009-02-17T16:06:49Z | [
"python",
"django"
] | Alright, this is probably a really silly question but I am new to Python/Django so I can't really wrap my head around its scoping concepts just yet. Right now I am writing a [middleware](http://docs.djangoproject.com/en/dev/topics/http/middleware/#topics-http-middleware) class to handle some stuff, and I want to set 'g... | 1. It's not the best way. You could set my\_var on the request rather than on the settings. Settings are global and apply to the whole site. You don't want to modify it for every request. There could be concurrency issues with multiple request updating/reading the variable at the same time.
2. To access request.my\_var... |
How do I use easy_install and buildout when pypi is down? | 557,462 | 13 | 2009-02-17T15:48:23Z | 557,832 | 12 | 2009-02-17T17:22:44Z | [
"python",
"plone",
"easy-install",
"buildout"
] | I am using [buildout](http://pypi.python.org/pypi/zc.buildout) to automatically download and setup the many dependencies of my Plone installation. buildout more or less uses easy\_install to download and install a bunch of Python eggs. This usually works, but it doesn't work if any of the dependencies cannot be downloa... | Here are [instructions on how to setup your own PyPi mirror](http://www.zopyx.de/blog/creating-a-local-pypi-mirror). The homepage of this project is [here](http://www.openplans.org/projects/pypi-mirroring/project-home). There also seems to be a growing number of mirrors out there.
For instructions on how to setup your... |
How do I use easy_install and buildout when pypi is down? | 557,462 | 13 | 2009-02-17T15:48:23Z | 3,292,240 | 8 | 2010-07-20T16:36:12Z | [
"python",
"plone",
"easy-install",
"buildout"
] | I am using [buildout](http://pypi.python.org/pypi/zc.buildout) to automatically download and setup the many dependencies of my Plone installation. buildout more or less uses easy\_install to download and install a bunch of Python eggs. This usually works, but it doesn't work if any of the dependencies cannot be downloa... | You can also use a mirror. Put this in the "[global]" section of "~/.pip/pip.conf":
```
index-url = http://d.pypi.python.org/simple/
```
This is a recent feature as announced [here](http://mail.python.org/pipermail/catalog-sig/2010-July/003132.html). |
Want procmail to run a custom python script, everytime a new mail shows up | 557,906 | 9 | 2009-02-17T17:37:23Z | 557,932 | 11 | 2009-02-17T17:45:04Z | [
"python",
"email",
"procmail"
] | I have a pretty usual requirement with procmail but I am unable to get the results somehow. I have procmailrc file with this content:
```
:0
* ^To.*@myhost
| /usr/bin/python /work/scripts/privilege_emails_forward.py
```
Wherein my custom python script(privilege\_emails\_forward.py) will be scanning through the email ... | That is just fine, just put `fw` after `:0` (`:0 fw`). Your python program will receive the mail on `stdin`. You have to 'echo' the possibly transformed mail on `stdout`.
`fw` means:
* `f` Consider the pipe as a filter.
* `w` Wait for the filter or program to finish and check its exitcode (normally ignored); if the f... |
Debugging web apps | 557,927 | 8 | 2009-02-17T17:43:59Z | 557,938 | 7 | 2009-02-17T17:47:05Z | [
"python",
"eclipse",
"debugging",
"google-app-engine"
] | I've gotten pretty used to step-through debuggers over the years, both in builder, and using the pydev debugger in Eclipse.
Currently, I'm making something in Python and running it on Google App Engine, and I should add that I'm pretty new to developing any real web app; I've never really done much beyond editing HTML... | The dev\_appserver is just a python script, you can simply use the pydev debugger on that script with the proper arguments as far as I know.
Here is a very detailed guide on how to do that:
<http://www.ibm.com/developerworks/opensource/library/os-eclipse-mashup-google-pt1/index.html> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.