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
Python + Django page redirect
523,356
131
2009-02-07T07:08:03Z
523,366
213
2009-02-07T07:14:37Z
[ "python", "django", "redirect", "location" ]
How do I accomplish a simple redirect (e.g. `cflocation` in ColdFusion, or `header(location:http://)` in Django)?
It's simple: ``` from django.http import HttpResponseRedirect def myview(request): ... return HttpResponseRedirect("/path/") ``` More info in the [official Django docs](https://docs.djangoproject.com/en/1.4/ref/request-response/#django.http.HttpResponseRedirect) **Update: Django 1.0** There is apparently a...
Python + Django page redirect
523,356
131
2009-02-07T07:08:03Z
2,080,377
37
2010-01-17T08:07:32Z
[ "python", "django", "redirect", "location" ]
How do I accomplish a simple redirect (e.g. `cflocation` in ColdFusion, or `header(location:http://)` in Django)?
There's actually a simpler way than having a view for each redirect - you can do it *directly* in `urls.py`: ``` from django.http import HttpResponsePermanentRedirect urlpatterns = patterns( '', # ...normal patterns here... (r'^bad-old-link\.php', lambda request: HttpResponsePermanentRedirect('/nice-...
Python + Django page redirect
523,356
131
2009-02-07T07:08:03Z
3,645,846
22
2010-09-05T11:09:03Z
[ "python", "django", "redirect", "location" ]
How do I accomplish a simple redirect (e.g. `cflocation` in ColdFusion, or `header(location:http://)` in Django)?
Since Django 1.1, you can also use the simpler [redirect](http://docs.djangoproject.com/en/dev/topics/http/shortcuts/#redirect) shortcut: ``` from django.shortcuts import redirect def myview(request): return redirect('/path') ``` It also takes an optional permanent=True keyword argument.
Python + Django page redirect
523,356
131
2009-02-07T07:08:03Z
3,841,632
109
2010-10-01T17:31:30Z
[ "python", "django", "redirect", "location" ]
How do I accomplish a simple redirect (e.g. `cflocation` in ColdFusion, or `header(location:http://)` in Django)?
Depending on what you want (i.e. if you do not want to do any additional pre-processing), it is simpler to just use Django's `redirect_to` generic view: ``` from django.views.generic.simple import redirect_to urlpatterns = patterns('', (r'^one/$', redirect_to, {'url': '/another/'}), #etc... ) ``` See [docum...
Python + Django page redirect
523,356
131
2009-02-07T07:08:03Z
7,416,655
10
2011-09-14T12:55:33Z
[ "python", "django", "redirect", "location" ]
How do I accomplish a simple redirect (e.g. `cflocation` in ColdFusion, or `header(location:http://)` in Django)?
With Django version 1.3, the class based approach is: ``` from django.conf.urls.defaults import patterns, url from django.views.generic import RedirectView urlpatterns = patterns('', url(r'^some-url/$', RedirectView.as_view(url='/redirect-url/'), name='some_redirect'), ) ``` This example lives in in urls.py
Python + Django page redirect
523,356
131
2009-02-07T07:08:03Z
22,300,866
8
2014-03-10T13:02:02Z
[ "python", "django", "redirect", "location" ]
How do I accomplish a simple redirect (e.g. `cflocation` in ColdFusion, or `header(location:http://)` in Django)?
If you want to redirect a whole subfolder, the `url` argument in [RedirectView is actually interpolated](https://docs.djangoproject.com/en/1.8/ref/class-based-views/base/#redirectview), so you can do something like this in `urls.py`: ``` from django.conf.urls.defaults import url from django.views.generic import Redire...
How do I layout a 3 pane window using wxPython?
523,363
5
2009-02-07T07:12:13Z
523,485
7
2009-02-07T09:08:11Z
[ "python", "layout", "wxpython", "elasticlayout" ]
I am trying to find a simple way to layout a 3 pane window using wxPython. I want to have a tree list in the left pane, then have a right pane that is split into two - with an edit component in the top part and a grid component in the bottom part. Something along the lines of: ``` -----------------------------------...
First of all download [wxGlade](http://wxglade.sourceforge.net/) a gui builder for wxPython (alternative [XRCed](http://xrced.sourceforge.net/), i prefere wxGlade). Then you have to decide if you want to use a [GridSizer](http://www.wxpython.org/docs/api/wx.GridSizer-class.html) or a [Splitter](http://www.wxpython.org...
How do I layout a 3 pane window using wxPython?
523,363
5
2009-02-07T07:12:13Z
532,873
7
2009-02-10T15:50:22Z
[ "python", "layout", "wxpython", "elasticlayout" ]
I am trying to find a simple way to layout a 3 pane window using wxPython. I want to have a tree list in the left pane, then have a right pane that is split into two - with an edit component in the top part and a grid component in the bottom part. Something along the lines of: ``` -----------------------------------...
This is a very simple layout using wx.aui and three panels. I guess you can easily adapt it to suit your needs. Orjanp... ``` import wx import wx.aui class MyFrame(wx.Frame): def __init__(self, *args, **kwargs): wx.Frame.__init__(self, *args, **kwargs) self.mgr = wx.aui.AuiManager(self) leftpane...
Is there a Python equivalent of Groovy/Grails for Java
524,147
3
2009-02-07T17:21:41Z
524,172
8
2009-02-07T17:32:47Z
[ "python", "django", "grails", "groovy", "jython" ]
I'm thinking of something like Jython/Jango? Does this exist? Or does Jython allow you to do everything-Python in Java including Django (I'm not sure how Jython differs from Python)?
<http://wiki.python.org/jython/DjangoOnJython>
How to externally populate a Django model?
524,214
8
2009-02-07T17:54:54Z
524,333
10
2009-02-07T18:43:12Z
[ "python", "django", "django-models" ]
What is the best idea to fill up data into a Django model from an external source? E.g. I have a model Run, and runs data in an XML file, which changes weekly. Should I create a view and call that view URL from a curl cronjob (with the advantage that that data can be read anytime, not only when the cronjob runs), or ...
There is excellent way to do some maintenance-like jobs in project environment- write a [custom manage.py command](http://docs.djangoproject.com/en/dev/howto/custom-management-commands/#howto-custom-management-commands). It takes all environment configuration and other stuff allows you to concentrate on concrete task. ...
How to 'zoom' in on a section of the Mandelbrot set?
524,291
5
2009-02-07T18:22:48Z
524,312
14
2009-02-07T18:31:16Z
[ "python", "math", "mandelbrot" ]
I have created a Python file to generate a Mandelbrot set image. The original maths code was not mine, so I do not understand it - I only heavily modified it to make it about 250x faster (Threads rule!). Anyway, I was wondering how I could modify the maths part of the code to make it render one specific bit. Here is t...
The line: ``` box=((-2,1.25),(0.5,-1.25)) ``` is the bit that defines the area of coordinate space that is being rendered, so you just need to change this line. First coordinate pair is the top-left of the area, the second is the bottom right. To get a new coordinate from the image should be quite straightforward. Y...
Regular expression to detect semi-colon terminated C++ for & while loops
524,548
25
2009-02-07T20:43:52Z
524,562
19
2009-02-07T20:50:09Z
[ "c++", "python", "regex", "parsing", "recursion" ]
In my Python application, I need to write a regular expression that matches a C++ `for` or `while` loop that has been terminated with a semi-colon (`;`). For example, it should match this: ``` for (int i = 0; i < 10; i++); ``` ... but not this: ``` for (int i = 0; i < 10; i++) ``` This looks trivial at first glance...
This is the kind of thing you really shouldn't do with a regular expression. Just parse the string one character at a time, keeping track of opening/closing parentheses. If this is all you're looking for, you definitely don't need a full-blown C++ grammar lexer/parser. If you want practice, you can write a little recu...
Regular expression to detect semi-colon terminated C++ for & while loops
524,548
25
2009-02-07T20:43:52Z
524,563
7
2009-02-07T20:51:09Z
[ "c++", "python", "regex", "parsing", "recursion" ]
In my Python application, I need to write a regular expression that matches a C++ `for` or `while` loop that has been terminated with a semi-colon (`;`). For example, it should match this: ``` for (int i = 0; i < 10; i++); ``` ... but not this: ``` for (int i = 0; i < 10; i++) ``` This looks trivial at first glance...
This is a great example of using the wrong tool for the job. Regular expressions do not handle arbitrarily nested sub-matches very well. What you should do instead is use a real lexer and parser (a grammar for C++ should be easy to find) and look for unexpectedly empty loop bodies.
Regular expression to detect semi-colon terminated C++ for & while loops
524,548
25
2009-02-07T20:43:52Z
524,624
77
2009-02-07T21:29:57Z
[ "c++", "python", "regex", "parsing", "recursion" ]
In my Python application, I need to write a regular expression that matches a C++ `for` or `while` loop that has been terminated with a semi-colon (`;`). For example, it should match this: ``` for (int i = 0; i < 10; i++); ``` ... but not this: ``` for (int i = 0; i < 10; i++) ``` This looks trivial at first glance...
You could write a little, very simple routine that does it, without using a regular expression: * Set a position counter `pos` so that is points to just before the opening bracket after your `for` or `while`. * Set an open brackets counter `openBr` to `0`. * Now keep incrementing `pos`, reading the characters at the r...
Does Python have class prototypes (or forward declarations)?
524,714
20
2009-02-07T22:21:50Z
524,722
30
2009-02-07T22:27:33Z
[ "python", "class", "oop", "prototype" ]
I have a series of Python classes in a file. Some classes reference others. My code is something like this: ``` class A(): pass class B(): c = C() class C(): pass ``` Trying to run that, I get `NameError: name 'C' is not defined`. Fair enough, but is there any way to make it work, or do I have to manua...
In Python you don't create a prototype per se, but you do need to understand the difference between "class attributes" and instance-level attributes. In the example you've shown above, you are declaring a class attribute on class B, not an instance-level attribute. This is what you are looking for: ``` class B(): ...
Does Python have class prototypes (or forward declarations)?
524,714
20
2009-02-07T22:21:50Z
2,330,235
36
2010-02-24T22:45:09Z
[ "python", "class", "oop", "prototype" ]
I have a series of Python classes in a file. Some classes reference others. My code is something like this: ``` class A(): pass class B(): c = C() class C(): pass ``` Trying to run that, I get `NameError: name 'C' is not defined`. Fair enough, but is there any way to make it work, or do I have to manua...
Actually, all of the above are great observations about Python, but none of them will solve your problem. Django needs to introspect stuff. The *right* way to do what you want is the following: ``` class Car(models.Model): manufacturer = models.ForeignKey('Manufacturer') # ... class Manufacturer(models.Mode...
Python, SQLite and threading
524,797
7
2009-02-07T23:18:03Z
524,806
7
2009-02-07T23:25:02Z
[ "python", "multithreading", "sqlite" ]
I'm working on an application that will gather data through HTTP from several places, cache the data locally and then serve it through HTTP. So I was looking at the following. My application will first create several threads that will gather data at a specified interval and cache that data locally into a SQLite databa...
Short answer: Don't use Sqlite3 in a threaded application. Sqlite3 databases scale well for size, but rather terribly for concurrency. You will be plagued with "Database is locked" errors. If you do, you will need a connection per thread, and you have to ensure that these connections clean up after themselves. This i...
Python's equivalent of $this->$varName
524,831
3
2009-02-08T00:17:52Z
524,842
16
2009-02-08T00:21:43Z
[ "php", "python" ]
In PHP I can do the following: ``` $myVar = 'name'; print $myClass->$myVar; // Identical to $myClass->name ``` I wish to do this in Python but can't find out how
In python, it's the getattr built-in function. ``` class Something( object ): def __init__( self ): self.a= 2 self.b= 3 x= Something() getattr( x, 'a' ) getattr( x, 'b' ) ```
NumPy, PIL adding an image
524,930
21
2009-02-08T01:15:16Z
525,129
16
2009-02-08T03:58:33Z
[ "python", "image-processing", "numpy", "python-imaging-library" ]
I'm trying to add two images together using NumPy and PIL. The way I would do this in [MATLAB](http://en.wikipedia.org/wiki/MATLAB) would be something like: ``` >> M1 = imread('_1.jpg'); >> M2 = imread('_2.jpg'); >> resM = M1 + M2; >> imwrite(resM, 'res.jpg'); ``` I get something like this: ![alt text](http://www.de...
Using PIL's blend() with an alpha value of 0.5 would be equivalent to (im1arr + im2arr)/2. Blend does not require that the images have alpha layers. Try this: ``` from PIL import Image im1 = Image.open('/Users/rem7/Desktop/_1.jpg') im2 = Image.open('/Users/rem7/Desktop/_2.jpg') Image.blend(im1,im2,0.5).save('/Users/r...
NumPy, PIL adding an image
524,930
21
2009-02-08T01:15:16Z
526,031
27
2009-02-08T17:05:45Z
[ "python", "image-processing", "numpy", "python-imaging-library" ]
I'm trying to add two images together using NumPy and PIL. The way I would do this in [MATLAB](http://en.wikipedia.org/wiki/MATLAB) would be something like: ``` >> M1 = imread('_1.jpg'); >> M2 = imread('_2.jpg'); >> resM = M1 + M2; >> imwrite(resM, 'res.jpg'); ``` I get something like this: ![alt text](http://www.de...
As everyone suggested already, the weird colors you're observing are overflow. And as you point out in the [comment of schnaader's answer](http://stackoverflow.com/questions/524930/numpy-pil-adding-an-image/524943#524943) you **still get overflow** if you add your images like this: ``` addition=(im1arr+im2arr)/2 ``` ...
Django templates: create a "back" link?
524,992
11
2009-02-08T02:02:04Z
525,000
10
2009-02-08T02:08:27Z
[ "python", "django", "request", "referrer" ]
I'm tooling around with [Django](http://www.djangoproject.com/) and I'm wondering if there is a simple way to create a "back" link to the previous page using the template system. I figure that in the worst case I can get this information from the request object in the view function, and pass it along to the template r...
Well you can enable: ``` 'django.core.context_processors.request', ``` in your `settings.TEMPLATE_CONTEXT_PROCESSORS` block and hook out the referrer but that's a bit nauseating and could break all over the place. Most places where you'd want this (eg the edit post page on SO) you have a real object to hook on to (i...
Django templates: create a "back" link?
524,992
11
2009-02-08T02:02:04Z
666,407
16
2009-03-20T14:33:04Z
[ "python", "django", "request", "referrer" ]
I'm tooling around with [Django](http://www.djangoproject.com/) and I'm wondering if there is a simple way to create a "back" link to the previous page using the template system. I figure that in the worst case I can get this information from the request object in the view function, and pass it along to the template r...
actually it's go(-1) < input type=button value="Previous Page" onClick="javascript:history.go(-1);">
Django templates: create a "back" link?
524,992
11
2009-02-08T02:02:04Z
26,867,597
10
2014-11-11T14:49:38Z
[ "python", "django", "request", "referrer" ]
I'm tooling around with [Django](http://www.djangoproject.com/) and I'm wondering if there is a simple way to create a "back" link to the previous page using the template system. I figure that in the worst case I can get this information from the request object in the view function, and pass it along to the template r...
This solution worked out for me: ``` <a href="{{request.META.HTTP_REFERER}}">Go back</a> ``` But that's previously adding `'django.core.context_processors.request',` to `TEMPLATE_CONTEXT_PROCESSORS` in your project's settings.
Python truncate lines as they are read
525,272
7
2009-02-08T06:34:52Z
525,312
13
2009-02-08T07:08:14Z
[ "python", "file-io" ]
I have an application that reads lines from a file and runs its magic on each line as it is read. Once the line is read and properly processed, I would like to delete the line from the file. A backup of the removed line is already being kept. I would like to do something like ``` file = open('myfile.txt', 'rw+') for l...
### Remove all lines after you've done with them: ``` with open('myfile.txt', 'rw+') as file: for line in file: processLine(line) file.truncate(0) ``` ### Remove each line independently: ``` lines = open('myfile.txt').readlines() for i, line in enumerate(lines[:]): processLine(line) del line...
Python truncate lines as they are read
525,272
7
2009-02-08T06:34:52Z
525,454
8
2009-02-08T09:25:03Z
[ "python", "file-io" ]
I have an application that reads lines from a file and runs its magic on each line as it is read. Once the line is read and properly processed, I would like to delete the line from the file. A backup of the removed line is already being kept. I would like to do something like ``` file = open('myfile.txt', 'rw+') for l...
**You can't**. It is just not possible with actual text file implementations on current filesystems. Text files are sequential, because the lines in a text file can be of any length. Deleting a particular line would mean rewriting the entire file from that point on. Suppose you have a file with the following 3 lines;...
Embedding icon in .exe with py2exe, visible in Vista?
525,329
15
2009-02-08T07:26:06Z
525,486
19
2009-02-08T10:06:26Z
[ "python", "windows-vista", "embed", "icons", "py2exe" ]
I've been trying to embed an icon (.ico) into my "compyled" .exe with py2exe. Py2Exe does have a way to embed an icon: ``` windows=[{ 'script':'MyScript.py', 'icon_resources':[(1,'MyIcon.ico')] }] ``` And that's what I am using. The icon shows up fine on Windows XP or lower, but doesn't show at all on Vista....
Vista uses icons of high resolution *256x256* pixels images, they are stored using *PNG-based* compression. The problem is if you simply make the icon and save it in standard XP `ICO` format, the resulting file will be `400Kb` on disk. The solution is to compress the images. The compression scheme used is `PNG` (Portab...
Regular expression: match start or whitespace
525,635
25
2009-02-08T12:38:08Z
525,639
8
2009-02-08T12:42:22Z
[ "python", "regex" ]
**Can a regular expression match whitespace *or* the start of a string?** I'm trying to replace currency the abbreviation GBP with a £ symbol. I could just match anything starting GBP, but I'd like to be a bit more conservative, and look for certain delimiters around it. ``` >>> import re >>> text = u'GBP 5 Off when...
`\b` is word boundary, which can be a white space, the beginning of a line or a non-alphanumeric symbol (`\bGBP\b`).
Regular expression: match start or whitespace
525,635
25
2009-02-08T12:38:08Z
525,650
30
2009-02-08T12:46:54Z
[ "python", "regex" ]
**Can a regular expression match whitespace *or* the start of a string?** I'm trying to replace currency the abbreviation GBP with a £ symbol. I could just match anything starting GBP, but I'd like to be a bit more conservative, and look for certain delimiters around it. ``` >>> import re >>> text = u'GBP 5 Off when...
Use the OR "`|`" operator: ``` >>> re.sub(r'(^|\W)GBP([\W\d])', u'\g<1>£\g<2>', text) u'\xa3 5 Off when you spend \xa375.00' ```
Accept Cookies in Python
525,773
10
2009-02-08T14:09:04Z
526,695
18
2009-02-08T23:49:44Z
[ "python", "cookies" ]
How can I accept cookies in a python script?
Try this: ``` import urllib2 import cookielib jar = cookielib.FileCookieJar("cookies") opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar)) print "Currently have %d cookies" % len(jar) print "Getting page" response = opener.open("http://google.com") print response.headers print "Got page" print "Currentl...
Probability distribution in Python
526,255
17
2009-02-08T19:52:22Z
526,300
25
2009-02-08T20:26:28Z
[ "python", "algorithm", "random", "distribution", "probability" ]
I have a bunch of keys that each have an unlikeliness variable. I want to randomly choose one of these keys, yet I want it to be more unlikely for unlikely (key, values) to be chosen than a less unlikely (a more likely) object. I am wondering if you would have any suggestions, preferably an existing python module that ...
[This activestate recipe](http://code.activestate.com/recipes/117241/) gives an easy-to-follow approach, specifically the version in the comments that doesn't require you to pre-normalize your weights: ``` import random def weighted_choice(items): """items is a list of tuples in the form (item, weight)""" wei...
Django form fails validation on a unique field
526,457
16
2009-02-08T21:36:23Z
526,656
23
2009-02-08T23:33:29Z
[ "python", "django" ]
I have a simple model that is defined as: ``` class Article(models.Model): slug = models.SlugField(max_length=50, unique=True) title = models.CharField(max_length=100, unique=False) ``` and the form: ``` class ArticleForm(ModelForm): class Meta: model = Article ``` The validation here fails whe...
I don't think you are actually updating an existing article, but instead creating a new one, presumably with more or less the same content, especially the slug, and thus you will get an error. It is a bit strange that you don't get better error reporting, but also I do not know what the rest of your view looks like. W...
subprocess.Popen error
526,734
3
2009-02-09T00:10:49Z
526,781
8
2009-02-09T00:40:21Z
[ "python", "subprocess", "popen" ]
I am running an msi installer in silent mode and caching logs in the specific file. The following is the command i need to execute. `C:\Program Files\ My Installer\Setup.exe /s /v "/qn /lv %TEMP%\log_silent.log"` I used: ``` subprocess.Popen(['C:\Program Files\ My Installer\Setup.exe', '/s /v "/qn /lv %TEMP%\log_sil...
The problem is very subtle. You're executing the program directly. It gets: ``` argv[0] = "C:\Program Files\ My Installer\Setup.exe" argv[1] = /s /v "/qn /lv %TEMP%\log_silent.log" ``` Whereas it should be: ``` argv[1] = "/s" argv[2] = "/v" argv[3] = "/qn" argv[4] = "/lv %TEMP%\log_silent.log" ``` In other words, ...
Python or java which language will exposed a self taught programmer to more computer science concept?
527,134
6
2009-02-09T04:48:10Z
527,146
7
2009-02-09T04:54:20Z
[ "java", "python", "programming-languages" ]
Of the two which one would exposed someone just learning to program to more computer science concept/problems?
Neither. Try Scheme. Or Haskell. or C. or a book.
Python or java which language will exposed a self taught programmer to more computer science concept?
527,134
6
2009-02-09T04:48:10Z
527,149
7
2009-02-09T04:55:42Z
[ "java", "python", "programming-languages" ]
Of the two which one would exposed someone just learning to program to more computer science concept/problems?
Neither *language* will expose a student to computer science concepts. That's up to the instructor (or motivated student) – where will they take the learning experience? [I'm assuming here that by "computer science", you mean algorithms and data structures (and related topics); if instead you mean things like pointe...
Python or java which language will exposed a self taught programmer to more computer science concept?
527,134
6
2009-02-09T04:48:10Z
527,152
14
2009-02-09T04:57:32Z
[ "java", "python", "programming-languages" ]
Of the two which one would exposed someone just learning to program to more computer science concept/problems?
It's not about the language, it's about what you do with it. You can learn about virtually any CS concept in either Python or Java (or anything else), although there are definitely some concepts that are much better suited for one or another - for example, functional programming (e.g. the `map` and `reduce` functions) ...
Intercepting stdout of a subprocess while it is running
527,197
21
2009-02-09T05:43:35Z
527,229
14
2009-02-09T06:12:49Z
[ "python", "process", "subprocess", "stdout", "popen" ]
If this is my subprocess: ``` import time, sys for i in range(200): sys.stdout.write( 'reading %i\n'%i ) time.sleep(.02) ``` And this is the script controlling and modifying the output of the subprocess: ``` import subprocess, time, sys print 'starting' proc = subprocess.Popen( 'c:/test_apps/testcr.py'...
As Charles already mentioned, the problem is buffering. I ran in to a similar problem when writing some modules for SNMPd, and solved it by replacing stdout with an auto-flushing version. I used the following code, inspired by some posts on ActiveState: ``` class FlushFile(object): """Write-only flushing wrapper ...
How to deploy a Python application with libraries as source with no further dependencies?
527,510
12
2009-02-09T09:20:17Z
527,531
9
2009-02-09T09:28:04Z
[ "python", "deployment", "layout", "bootstrapping" ]
**Background**: I have a small Python application that makes life for developers releasing software in our company a bit easier. I build an executable for Windows using py2exe. The application as well as the binary are checked into Subversion. Distribution happens by people just checking out the directory from SVN. The...
Just use [virtualenv](http://pypi.python.org/pypi/virtualenv) - it is a tool to create isolated Python environments. You can create a set-up script and distribute the whole bunch if you want.
How to deploy a Python application with libraries as source with no further dependencies?
527,510
12
2009-02-09T09:20:17Z
527,872
8
2009-02-09T12:01:16Z
[ "python", "deployment", "layout", "bootstrapping" ]
**Background**: I have a small Python application that makes life for developers releasing software in our company a bit easier. I build an executable for Windows using py2exe. The application as well as the binary are checked into Subversion. Distribution happens by people just checking out the directory from SVN. The...
"I dislike the fact that developers (or me starting on a clean new machine) have to jump through the distutils hoops of having to install the libraries locally before they can get started" Why? What -- specifically -- is wrong with this? You did it to create the project. Your project is so popular others want to do ...
How to deploy a Python application with libraries as source with no further dependencies?
527,510
12
2009-02-09T09:20:17Z
528,064
8
2009-02-09T13:05:46Z
[ "python", "deployment", "layout", "bootstrapping" ]
**Background**: I have a small Python application that makes life for developers releasing software in our company a bit easier. I build an executable for Windows using py2exe. The application as well as the binary are checked into Subversion. Distribution happens by people just checking out the directory from SVN. The...
I sometimes use the approach I describe below, for the exact same reason that @Boris states: I would prefer that the use of some code is as easy as a) svn checkout/update - b) go. But for the record: * I use virtualenv/easy\_install most of the time. * I agree to a certain extent to the critisisms by @Ali A and @S.Lo...
Python: Pass or Sleep for long running processes?
529,034
19
2009-02-09T17:15:42Z
529,052
38
2009-02-09T17:20:00Z
[ "python" ]
I am writing an queue processing application which uses threads for waiting on and responding to queue messages to be delivered to the app. For the main part of the application, it just needs to stay active. For a code example like: ``` while True: pass ``` or ``` while True: time.sleep(1) ``` Which one will ha...
I would imagine *time.sleep()* will have less overhead on the system. Using *pass* will cause the loop to immediately re-evaluate and peg the CPU, whereas using time.sleep will allow the execution to be temporarily suspended. **EDIT**: just to prove the point, if you launch the python interpreter and run this: ``` >>...
Python: Pass or Sleep for long running processes?
529,034
19
2009-02-09T17:15:42Z
529,321
21
2009-02-09T18:41:46Z
[ "python" ]
I am writing an queue processing application which uses threads for waiting on and responding to queue messages to be delivered to the app. For the main part of the application, it just needs to stay active. For a code example like: ``` while True: pass ``` or ``` while True: time.sleep(1) ``` Which one will ha...
Why sleep? You don't want to sleep, you want to wait for the threads to finish. So ``` # store the threads you start in a your_threads list, then for a_thread in your_threads: a_thread.join() ``` See: [thread.join](http://www.python.org/doc/2.5.2/lib/thread-objects.html#l2h-3460)
Traverse a list in reverse order in Python
529,424
309
2009-02-09T19:04:58Z
529,427
505
2009-02-09T19:05:54Z
[ "python", "loops" ]
So I can start from `len(collection)` and end in `collection[0]`. EDIT: Sorry, I forgot to mention I also want to be able to access the loop index.
Use the `reversed()` built-in function: ``` >>> a = ["foo", "bar", "baz"] >>> for i in reversed(a): ... print i ... baz bar foo ``` To also access the original index: ``` >>> for i, e in reversed(list(enumerate(a))): ... print i, e ... 2 baz 1 bar 0 foo ```
Traverse a list in reverse order in Python
529,424
309
2009-02-09T19:04:58Z
529,443
81
2009-02-09T19:07:38Z
[ "python", "loops" ]
So I can start from `len(collection)` and end in `collection[0]`. EDIT: Sorry, I forgot to mention I also want to be able to access the loop index.
You can do: ``` for item in my_list[::-1]: print item ``` (Or whatever you want to do in the for loop.) The `[::-1]` slice reverses the list in the for loop (but won't actually modify your list "permanently").
Traverse a list in reverse order in Python
529,424
309
2009-02-09T19:04:58Z
529,466
38
2009-02-09T19:14:12Z
[ "python", "loops" ]
So I can start from `len(collection)` and end in `collection[0]`. EDIT: Sorry, I forgot to mention I also want to be able to access the loop index.
If you need the loop index, and don't want to traverse the entire list twice, or use extra memory, I'd write a generator. ``` def reverse_enum(L): for index in reversed(xrange(len(L))): yield index, L[index] L = ['foo', 'bar', 'bas'] for index, item in reverse_enum(L): print index, item ```
Traverse a list in reverse order in Python
529,424
309
2009-02-09T19:04:58Z
530,507
22
2009-02-09T23:18:11Z
[ "python", "loops" ]
So I can start from `len(collection)` and end in `collection[0]`. EDIT: Sorry, I forgot to mention I also want to be able to access the loop index.
It can be done like this: ``` for i in range(len(collection)-1, -1, -1): print collection[i] ``` So your guess was pretty close :) A little awkward but it's basically saying: start with 1 less than `len(collection)`, keep going until you get to just before -1, by steps of -1. Fyi, the `help` function is very use...
Traverse a list in reverse order in Python
529,424
309
2009-02-09T19:04:58Z
7,722,144
11
2011-10-11T06:28:19Z
[ "python", "loops" ]
So I can start from `len(collection)` and end in `collection[0]`. EDIT: Sorry, I forgot to mention I also want to be able to access the loop index.
The `reversed` builtin function is handy: ``` for item in reversed(sequence): ``` The [documentation](http://docs.python.org/library/functions.html?highlight=reversed#reversed) for reversed explains its limitations. For the cases where I have to walk a sequence in reverse along with the index (e.g. for in-place modi...
Easy_install cache downloaded files
529,425
16
2009-02-09T19:05:40Z
538,701
16
2009-02-11T20:47:23Z
[ "python", "easy-install", "egg", "python-wheel" ]
Is there a way to configure easy\_install to avoid having to download the files again when an installation fails?
pip (<http://pypi.python.org/pypi/pip/>) is a drop-in replacement for the easy\_install tool and can do that. Just run `easy_install pip` and set an environment variable `PIP_DOWNLOAD_CACHE` to the path you want pip to store the files. Note that the cache won't work with dependencies that checkout from a source code r...
Easy_install cache downloaded files
529,425
16
2009-02-09T19:05:40Z
18,520,729
11
2013-08-29T20:51:17Z
[ "python", "easy-install", "egg", "python-wheel" ]
Is there a way to configure easy\_install to avoid having to download the files again when an installation fails?
Here is my solution using pip, managing even installation of binary packages and usable on both, linux and Windows. And as requested, it will limit download from PyPi to the mininum, and as extra bonus, on Linux, it allows to speed up repeated installation of packages usually requiring compilation to a fraction of a se...
Django - How to prepopulate admin form fields
529,890
13
2009-02-09T20:52:34Z
532,008
10
2009-02-10T11:53:41Z
[ "python", "django", "django-admin", "django-forms" ]
I know that you can prepopulate admin form fields based on other fields. For example, I have a slug field that is automatically populated based on the title field. However, I would also like to make other automatic prepopulations based on the date. For example, I have an URL field, and I want it to automatically be se...
Django's built-in prepopulated\_fields functionality is hardcoded to slugify, it can't really be used for more general purposes. You'll need to write your own Javascript function to do the prepopulating. The best way to get it included in the admin page is to include it in the [inner Media class](http://docs.djangopro...
Django - How to prepopulate admin form fields
529,890
13
2009-02-09T20:52:34Z
2,973,380
18
2010-06-04T10:47:17Z
[ "python", "django", "django-admin", "django-forms" ]
I know that you can prepopulate admin form fields based on other fields. For example, I have a slug field that is automatically populated based on the title field. However, I would also like to make other automatic prepopulations based on the date. For example, I have an URL field, and I want it to automatically be se...
I know that you can prepopulate some values via GET, it will be something like this ``` http://localhost:8000/admin/app/model/add/?model_field=hello ``` I got some problems with date fields but, maybe this could help you.
Django - How to prepopulate admin form fields
529,890
13
2009-02-09T20:52:34Z
14,322,706
8
2013-01-14T16:41:46Z
[ "python", "django", "django-admin", "django-forms" ]
I know that you can prepopulate admin form fields based on other fields. For example, I have a slug field that is automatically populated based on the title field. However, I would also like to make other automatic prepopulations based on the date. For example, I have an URL field, and I want it to automatically be se...
I recently used Django's [ModelAdmin.get\_form](https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_form) method for this purpose. ``` class MyModelAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): form = super(MyModelAdmin, self).get_form(re...
Accessing POST Data from WSGI
530,526
26
2009-02-09T23:23:20Z
530,818
20
2009-02-10T01:56:52Z
[ "python", "python-3.x", "wsgi" ]
I can't seem to figure out how to access POST data using WSGI. I tried the example on the wsgi.org website and it didn't work. I'm using Python 3.0 right now. Please don't recommend a WSGI framework as that is not what I'm looking for. I would like to figure out how to get it into a fieldstorage object.
``` body= '' # b'' for consistency on Python 3.0 try: length= int(environ.get('CONTENT_LENGTH', '0')) except ValueError: length= 0 if length!=0: body= environ['wsgi.input'].read(length) ``` Note that WSGI is not yet fully-specified for Python 3.0, and much of the popular WSGI infrastructure has not been c...
Accessing POST Data from WSGI
530,526
26
2009-02-09T23:23:20Z
550,157
24
2009-02-15T01:55:35Z
[ "python", "python-3.x", "wsgi" ]
I can't seem to figure out how to access POST data using WSGI. I tried the example on the wsgi.org website and it didn't work. I'm using Python 3.0 right now. Please don't recommend a WSGI framework as that is not what I'm looking for. I would like to figure out how to get it into a fieldstorage object.
Assuming you are trying to get just the POST data into a FieldStorage object: ``` # env is the environment handed to you by the WSGI server. # I am removing the query string from the env before passing it to the # FieldStorage so we only have POST data in there. post_env = env.copy() post_env['QUERY_STRING'] = '' post...
Python 2.x gotcha's and landmines
530,530
56
2009-02-09T23:25:00Z
530,550
9
2009-02-09T23:31:31Z
[ "python" ]
The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things specific, I'm only interested in the CPython interpreter. I'm looking for something similar to what learned from my [PHP landmines](http://stackoverf...
The only gotcha/surprise I've dealt with is with CPython's GIL. If for whatever reason you expect python threads in CPython to run concurrently... well they're not and this is pretty well documented by the Python crowd and even Guido himself. A long but thorough explanation of CPython threading and some of the things ...
Python 2.x gotcha's and landmines
530,530
56
2009-02-09T23:25:00Z
530,577
19
2009-02-09T23:43:40Z
[ "python" ]
The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things specific, I'm only interested in the CPython interpreter. I'm looking for something similar to what learned from my [PHP landmines](http://stackoverf...
Dynamic binding makes typos in your variable names surprisingly hard to find. It's easy to spend half an hour fixing a trivial bug. EDIT: an example... ``` for item in some_list: ... # lots of code ... # more code for tiem in some_other_list: process(item) # oops! ```
Python 2.x gotcha's and landmines
530,530
56
2009-02-09T23:25:00Z
530,768
81
2009-02-10T01:27:06Z
[ "python" ]
The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things specific, I'm only interested in the CPython interpreter. I'm looking for something similar to what learned from my [PHP landmines](http://stackoverf...
**Expressions in default arguments are calculated when the function is defined, *not* when it’s called.** **Example:** consider defaulting an argument to the current time: ``` >>>import time >>> def report(when=time.time()): ... print when ... >>> report() 1210294387.19 >>> time.sleep(5) >>> report() 1210294387...
Python 2.x gotcha's and landmines
530,530
56
2009-02-09T23:25:00Z
531,327
56
2009-02-10T07:12:07Z
[ "python" ]
The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things specific, I'm only interested in the CPython interpreter. I'm looking for something similar to what learned from my [PHP landmines](http://stackoverf...
You should be aware of how class variables are handled in Python. Consider the following class hierarchy: ``` class AAA(object): x = 1 class BBB(AAA): pass class CCC(AAA): pass ``` Now, check the output of the following code: ``` >>> print AAA.x, BBB.x, CCC.x 1 1 1 >>> BBB.x = 2 >>> print AAA.x, BBB.x,...
Python 2.x gotcha's and landmines
530,530
56
2009-02-09T23:25:00Z
531,376
37
2009-02-10T07:39:02Z
[ "python" ]
The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things specific, I'm only interested in the CPython interpreter. I'm looking for something similar to what learned from my [PHP landmines](http://stackoverf...
Loops and lambdas (or any closure, really): variables are bound by *name* ``` funcs = [] for x in range(5): funcs.append(lambda: x) [f() for f in funcs] # output: # 4 4 4 4 4 ``` A work around is either creating a separate function or passing the args by name: ``` funcs = [] for x in range(5): funcs.append(lamb...
Python 2.x gotcha's and landmines
530,530
56
2009-02-09T23:25:00Z
532,256
12
2009-02-10T13:10:19Z
[ "python" ]
The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things specific, I'm only interested in the CPython interpreter. I'm looking for something similar to what learned from my [PHP landmines](http://stackoverf...
There was a lot of discussion on hidden language features a while back: [hidden-features-of-python](http://stackoverflow.com/questions/101268/hidden-features-of-python). Where some pitfalls were mentioned (and some of the good stuff too). Also you might want to check out [Python Warts](http://wiki.python.org/moin/Pyth...
Python 2.x gotcha's and landmines
530,530
56
2009-02-09T23:25:00Z
535,589
9
2009-02-11T06:02:08Z
[ "python" ]
The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things specific, I'm only interested in the CPython interpreter. I'm looking for something similar to what learned from my [PHP landmines](http://stackoverf...
[James Dumay eloquently reminded me](http://twitter.com/i386/status/1194993686) of another Python gotcha: **Not all of Python's “included batteries” are wonderful**. James’ specific example was the HTTP libraries: `httplib`, `urllib`, `urllib2`, `urlparse`, `mimetools`, and `ftplib`. Some of the functionality i...
Python 2.x gotcha's and landmines
530,530
56
2009-02-09T23:25:00Z
890,789
7
2009-05-20T23:49:21Z
[ "python" ]
The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things specific, I'm only interested in the CPython interpreter. I'm looking for something similar to what learned from my [PHP landmines](http://stackoverf...
Floats are not printed at full precision by default (without `repr`): ``` x = 1.0 / 3 y = 0.333333333333 print x #: 0.333333333333 print y #: 0.333333333333 print x == y #: False ``` `repr` prints too many digits: ``` print repr(x) #: 0.33333333333333331 print repr(y) #: 0.33333333333300003 print x == 0.3333333...
Python 2.x gotcha's and landmines
530,530
56
2009-02-09T23:25:00Z
890,823
10
2009-05-20T23:58:14Z
[ "python" ]
The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things specific, I'm only interested in the CPython interpreter. I'm looking for something similar to what learned from my [PHP landmines](http://stackoverf...
Not including an `__init__`.py in your packages. That one still gets me sometimes.
Python 2.x gotcha's and landmines
530,530
56
2009-02-09T23:25:00Z
1,150,758
7
2009-07-19T20:12:13Z
[ "python" ]
The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things specific, I'm only interested in the CPython interpreter. I'm looking for something similar to what learned from my [PHP landmines](http://stackoverf...
Unintentionally **mixing oldstyle and newstyle classes** can cause seemingly mysterious errors. Say you have a simple class hierarchy consisting of superclass A and subclass B. When B is instantiated, A's constructor must be called first. The code below correctly does this: ``` class A(object): def __init__(self)...
Python 2.x gotcha's and landmines
530,530
56
2009-02-09T23:25:00Z
4,285,882
16
2010-11-26T14:00:22Z
[ "python" ]
The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things specific, I'm only interested in the CPython interpreter. I'm looking for something similar to what learned from my [PHP landmines](http://stackoverf...
One of the biggest surprises I ever had with Python is this one: ``` a = ([42],) a[0] += [43, 44] ``` This works as one might expect, except for raising a TypeError after updating the first entry of the tuple! So `a` will be `([42, 43, 44],)` after executing the `+=` statement, but there will be an exception anyway. ...
Python 2.x gotcha's and landmines
530,530
56
2009-02-09T23:25:00Z
4,403,680
14
2010-12-09T22:13:35Z
[ "python" ]
The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things specific, I'm only interested in the CPython interpreter. I'm looking for something similar to what learned from my [PHP landmines](http://stackoverf...
``` try: int("z") except IndexError, ValueError: pass ``` reason this doesn't work is because IndexError is the type of exception you're catching, and ValueError is the name of the variable you're assigning the exception to. Correct code to catch multiple exceptions is: ``` try: int("z") except (IndexErr...
Python 2.x gotcha's and landmines
530,530
56
2009-02-09T23:25:00Z
5,988,660
11
2011-05-13T07:28:52Z
[ "python" ]
The purpose of my question is to strengthen my knowledge base with Python and get a better picture of it, which includes knowing its faults and surprises. To keep things specific, I'm only interested in the CPython interpreter. I'm looking for something similar to what learned from my [PHP landmines](http://stackoverf...
**List slicing** has caused me a lot of grief. I actually consider the following behavior a bug. Define a list x ``` >>> x = [10, 20, 30, 40, 50] ``` Access index 2: ``` >>> x[2] 30 ``` As you expect. Slice the list from index 2 and to the end of the list: ``` >>> x[2:] [30, 40, 50] ``` As you expect. Access i...
Parsing datetime strings with microseconds
531,157
13
2009-02-10T05:35:08Z
531,220
21
2009-02-10T06:16:21Z
[ "python", "datetime", "parsing" ]
I have a text file with a lot of datetime strings in isoformat. The strings are similar to this: '2009-02-10 16:06:52.598800' These strings were generated using `str(datetime_object)`. The problem is that, for some reason, `str(datetime_object)` generates a different format when the datetime object has microseconds s...
Alternatively: ``` from datetime import datetime def str2datetime(s): parts = s.split('.') dt = datetime.strptime(parts[0], "%Y-%m-%d %H:%M:%S") return dt.replace(microsecond=int(parts[1])) ``` Using `strptime` itself to parse the date/time string (so no need to think up corner cases for a regex).
Parsing datetime strings with microseconds
531,157
13
2009-02-10T05:35:08Z
531,234
9
2009-02-10T06:23:30Z
[ "python", "datetime", "parsing" ]
I have a text file with a lot of datetime strings in isoformat. The strings are similar to this: '2009-02-10 16:06:52.598800' These strings were generated using `str(datetime_object)`. The problem is that, for some reason, `str(datetime_object)` generates a different format when the datetime object has microseconds s...
Use the dateutil module. It supports a much wider range of date and time formats than the built in Python ones. You'll need to **easy\_install dateutil** for the following code to work: ``` from dateutil.parser import parser p = parser() datetime_with_microseconds = p.parse('2009-02-10 16:06:52.598800') print dateti...
Adding a shebang causes No such file or directory error when running my python script
531,382
19
2009-02-10T07:43:51Z
531,387
40
2009-02-10T07:47:12Z
[ "python", "shell" ]
I'm trying to run a python script. It works fine when I run it: ``` python2.5 myscript.py inpt0 ``` The problem starts when I add a shebang: ``` #!/usr/bin/env python2.5 ``` Result in: ``` $ myscript.py inpt0 : No such file or directory ``` Try 2: ``` #!/usr/local/bin/python2.5 ``` Result in: ``` $ myscript.py...
I had similar problems and it turned out to be problem with line-endings. You use windows/linux/mac line endings? Edit: forgot the script name, but as OP says, it's `dos2unix <filename>`
Python file indexing and searching
532,312
9
2009-02-10T13:27:29Z
533,638
8
2009-02-10T18:51:31Z
[ "python", "search", "indexing", "lucene" ]
I have a large set off files (hdf) that I need to enable search for. For Java I would use Lucene for this, as it's a file and document indexing engine. I don't know what the python equivalent would be though. Can anyone recommend which library I should use for indexing a large collection of files for fast search? Or i...
Lupy [has been retired](http://divmod.org/trac/wiki/WhitherLupy) and the developers recommend PyLucene instead. As for PyLucene, its mailing list activity may be low, but it is definitely supported. In fact, it just recently became an [official apache subproject](http://lucene.apache.org/pylucene/#news20090108). You m...
Lightweight pickle for basic types in python?
532,934
6
2009-02-10T16:03:57Z
533,045
12
2009-02-10T16:28:58Z
[ "python", "serialization", "pickle" ]
All I want to do is serialize and unserialize tuples of strings or ints. I looked at pickle.dumps() but the byte overhead is significant. Basically it looks like it takes up about 4x as much space as it needs to. Besides, all I need is basic types and have no need to serialize objects. marshal is a little better in t...
Take a look at [json](http://docs.python.org/library/json.html), at least the generated `dumps` are readable with many other languages. > JSON (JavaScript Object Notation) <http://json.org> is a subset of JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data interchange format.
Lightweight pickle for basic types in python?
532,934
6
2009-02-10T16:03:57Z
533,150
8
2009-02-10T16:47:10Z
[ "python", "serialization", "pickle" ]
All I want to do is serialize and unserialize tuples of strings or ints. I looked at pickle.dumps() but the byte overhead is significant. Basically it looks like it takes up about 4x as much space as it needs to. Besides, all I need is basic types and have no need to serialize objects. marshal is a little better in t...
personally i would use [yaml](http://pyyaml.org/wiki/PyYAML). it's on par with json for encoding size, but it can represent some more complex things (e.g. classes, recursive structures) when necessary. ``` In [1]: import yaml In [2]: x = [1, 2, 3, 'pants'] In [3]: print(yaml.dump(x)) [1, 2, 3, pants] In [4]: y = yaml...
Lightweight pickle for basic types in python?
532,934
6
2009-02-10T16:03:57Z
533,381
8
2009-02-10T17:39:57Z
[ "python", "serialization", "pickle" ]
All I want to do is serialize and unserialize tuples of strings or ints. I looked at pickle.dumps() but the byte overhead is significant. Basically it looks like it takes up about 4x as much space as it needs to. Besides, all I need is basic types and have no need to serialize objects. marshal is a little better in t...
Maybe you're not using the right protocol: ``` >>> import pickle >>> a = range(1, 100) >>> len(pickle.dumps(a)) 492 >>> len(pickle.dumps(a, pickle.HIGHEST_PROTOCOL)) 206 ``` See the documentation for [pickle data formats](http://docs.python.org/library/pickle.html#data-stream-format).
Extend standard python logging, to include the line number where a log method was invoked
533,048
41
2009-02-10T16:29:23Z
533,077
71
2009-02-10T16:33:26Z
[ "python", "logging" ]
Is it possible to somehow decorate/extend the python standard logging system, so that when a logging method is invoked it also logs the file and the line number where it was invoked or maybe the method that invoked it.
Sure, check [formatters](http://docs.python.org/library/logging.html#formatter-objects) in logging docs. Specifically the lineno and pathname variables. > **%(pathname)s** Full pathname of the source file where the logging call was issued(if available). > > **%(filename)s** Filename portion of pathname. > > **%(module...
What does 'self' refer to in a @classmethod?
533,300
15
2009-02-10T17:18:53Z
533,315
32
2009-02-10T17:22:58Z
[ "python", "self", "class-method" ]
I thought I was starting to get a grip on "the Python way" of programming. Methods of a class accept self as the first parameter to refer to the instance of the class whose context the method is being called in. The @classmethod decorator refers to a method whose functionality is associated with the class, but which do...
[class itself](http://docs.python.org/library/functions.html#classmethod): > A class method receives the class as implicit first argument, just like an instance method receives the instance. ``` class C: @classmethod def f(cls): print(cls.__name__, type(cls)) >>> C.f() C <class 'type'> ``` and it's ...
What does 'self' refer to in a @classmethod?
533,300
15
2009-02-10T17:18:53Z
533,331
12
2009-02-10T17:28:00Z
[ "python", "self", "class-method" ]
I thought I was starting to get a grip on "the Python way" of programming. Methods of a class accept self as the first parameter to refer to the instance of the class whose context the method is being called in. The @classmethod decorator refers to a method whose functionality is associated with the class, but which do...
The first parameter of a classmethod is named `cls` by convention and refers to the the class object *on which the method it was invoked*. ``` >>> class A(object): ... @classmethod ... def m(cls): ... print cls is A ... print issubclass(cls, A) >>> class B(A): pass >>> a = A() >>> a.m() True T...
Dynamic/runtime method creation (code generation) in Python
533,382
32
2009-02-10T17:40:05Z
533,583
9
2009-02-10T18:38:47Z
[ "python", "metaprogramming", "exec" ]
I need to generate code for a method at runtime. It's important to be able to run arbitrary code and have a docstring. I came up with a solution combining `exec` and `setattr`, here's a dummy example: ``` class Viking(object): def __init__(self): code = ''' def dynamo(self, arg): ...
Function docstrings and names are mutable properties. You can do anything you want in the inner function, or even have multiple versions of the inner function that makedynamo() chooses between. No need to build any code out of strings. Here's a snippet out of the interpreter: ``` >>> def makedynamo(i): ... def in...
Dynamic/runtime method creation (code generation) in Python
533,382
32
2009-02-10T17:40:05Z
534,597
54
2009-02-10T22:46:31Z
[ "python", "metaprogramming", "exec" ]
I need to generate code for a method at runtime. It's important to be able to run arbitrary code and have a docstring. I came up with a solution combining `exec` and `setattr`, here's a dummy example: ``` class Viking(object): def __init__(self): code = ''' def dynamo(self, arg): ...
Based on Theran's code, but extending it to methods on classes: ``` class Dynamo(object): pass def add_dynamo(cls,i): def innerdynamo(self): print "in dynamo %d" % i innerdynamo.__doc__ = "docstring for dynamo%d" % i innerdynamo.__name__ = "dynamo%d" % i setattr(cls,innerdynamo.__name__,in...
In python 2.4, how can I execute external commands with csh instead of bash?
533,398
2
2009-02-10T17:44:23Z
533,435
10
2009-02-10T17:53:19Z
[ "python", "shell", "csh", "tcsh" ]
Without using the new 2.6 subprocess module, how can I get either os.popen or os.system to execute my commands using the tcsh instead of bash? I need to source some scripts which are written in tcsh before executing some other commands and I need to do this within python2.4. EDIT Thanks for answers using 'tcsh -c', bu...
Just prefix the shell as part of your command. I don't have tcsh installed but with zsh: ``` >>> os.system ("zsh -c 'echo $0'") zsh 0 ```
What is a mixin, and why are they useful?
533,631
540
2009-02-10T18:50:42Z
533,675
152
2009-02-10T19:00:51Z
[ "python", "oop", "multiple-inheritance", "mixins" ]
In "[Programming Python](http://rads.stackoverflow.com/amzn/click/0596009259)", Mark Lutz mentions "mixins". I'm from a C/C++/C# background and I have not heard the term before. What is a mixin? Reading between the lines of [this example](http://books.google.com/books?id=5zYVUIl7F0QC&pg=RA1-PA584&lpg=RA1-PA584&dq=prog...
First, you should note that mixins only exist in multiple-inheritance languages. You can't do a mixin in Java or C#. Basically, a mixin is a stand-alone base type that provides limited functionality and polymorphic resonance for a child class. If you're thinking in C#, think of an interface that you don't have to actu...
What is a mixin, and why are they useful?
533,631
540
2009-02-10T18:50:42Z
533,768
9
2009-02-10T19:21:19Z
[ "python", "oop", "multiple-inheritance", "mixins" ]
In "[Programming Python](http://rads.stackoverflow.com/amzn/click/0596009259)", Mark Lutz mentions "mixins". I'm from a C/C++/C# background and I have not heard the term before. What is a mixin? Reading between the lines of [this example](http://books.google.com/books?id=5zYVUIl7F0QC&pg=RA1-PA584&lpg=RA1-PA584&dq=prog...
I'd advise against mix-ins in new Python code, if you can find any other way around it (such as composition-instead-of-inheritance, or just monkey-patching methods into your own classes) that isn't much more effort. In old-style classes you could use mix-ins as a way of grabbing a few methods from another class. But i...
What is a mixin, and why are they useful?
533,631
540
2009-02-10T18:50:42Z
547,714
386
2009-02-13T21:15:17Z
[ "python", "oop", "multiple-inheritance", "mixins" ]
In "[Programming Python](http://rads.stackoverflow.com/amzn/click/0596009259)", Mark Lutz mentions "mixins". I'm from a C/C++/C# background and I have not heard the term before. What is a mixin? Reading between the lines of [this example](http://books.google.com/books?id=5zYVUIl7F0QC&pg=RA1-PA584&lpg=RA1-PA584&dq=prog...
A mixin is a special kind of multiple inheritance. There are two main situations where mixins are used: 1. You want to provide a lot of optional features for a class. 2. You want to use one particular feature in a lot of different classes. For an example of number one, consider [werkzeug's request and response system...
What is a mixin, and why are they useful?
533,631
540
2009-02-10T18:50:42Z
11,008,499
12
2012-06-13T05:06:32Z
[ "python", "oop", "multiple-inheritance", "mixins" ]
In "[Programming Python](http://rads.stackoverflow.com/amzn/click/0596009259)", Mark Lutz mentions "mixins". I'm from a C/C++/C# background and I have not heard the term before. What is a mixin? Reading between the lines of [this example](http://books.google.com/books?id=5zYVUIl7F0QC&pg=RA1-PA584&lpg=RA1-PA584&dq=prog...
Mixins is a concept in Programming in which the class provides functionalities but it is not meant to be used for instantiation. Main purpose of Mixins is to provide functionalities which are standalone and it would be best if the mixins itself do not have inheritance with other mixins and also avoid state. In language...
What is a mixin, and why are they useful?
533,631
540
2009-02-10T18:50:42Z
17,491,186
17
2013-07-05T14:26:37Z
[ "python", "oop", "multiple-inheritance", "mixins" ]
In "[Programming Python](http://rads.stackoverflow.com/amzn/click/0596009259)", Mark Lutz mentions "mixins". I'm from a C/C++/C# background and I have not heard the term before. What is a mixin? Reading between the lines of [this example](http://books.google.com/books?id=5zYVUIl7F0QC&pg=RA1-PA584&lpg=RA1-PA584&dq=prog...
I think of them as a disciplined way of using multiple inheritance - because ultimately a mixin is just another python class that (might) follow the conventions about classes that are called mixins. My understanding of the conventions that govern something you would call a Mixin are that a Mixin: * adds methods but n...
What is a mixin, and why are they useful?
533,631
540
2009-02-10T18:50:42Z
20,022,860
77
2013-11-16T19:36:03Z
[ "python", "oop", "multiple-inheritance", "mixins" ]
In "[Programming Python](http://rads.stackoverflow.com/amzn/click/0596009259)", Mark Lutz mentions "mixins". I'm from a C/C++/C# background and I have not heard the term before. What is a mixin? Reading between the lines of [this example](http://books.google.com/books?id=5zYVUIl7F0QC&pg=RA1-PA584&lpg=RA1-PA584&dq=prog...
This answer aims to explain mixins **with examples** that are: * **self-contained**: short, with no need to know any libraries to understand the example. * **in Python**, not in other languages. It is understandable that there were examples from other languages such as Ruby since the term is much more common in tho...
How do I use the the Django ORM to query this many-to-many example?
533,726
5
2009-02-10T19:12:06Z
533,770
14
2009-02-10T19:21:36Z
[ "python", "django", "django-orm" ]
I have the following models: ``` class Author(models.Model): author_name = models.CharField() class Book(models.Model): book_name = models.CharField() class AuthorBook(models.Model): author_id = models.ForeignKeyField(Author) book_id = models.ForeignKeyField(Book) ``` With that being said, I'm trying to emu...
You should be able to do: ``` books = Book.objects.filter(authorbook__author_id=1) ``` to get a QuerySet of Book objects matching your author\_id restriction. The nice thing about Django is you can cook this up and play around with it in the shell. You may also find <http://docs.djangoproject.com/en/dev/topics/db/qu...
How do I use the the Django ORM to query this many-to-many example?
533,726
5
2009-02-10T19:12:06Z
533,799
14
2009-02-10T19:28:58Z
[ "python", "django", "django-orm" ]
I have the following models: ``` class Author(models.Model): author_name = models.CharField() class Book(models.Model): book_name = models.CharField() class AuthorBook(models.Model): author_id = models.ForeignKeyField(Author) book_id = models.ForeignKeyField(Book) ``` With that being said, I'm trying to emu...
"AuthorBook" seems not correctly modeled. You should use a `ManyToManyField`: ``` class Book(models.Model): name = models.CharField() authors = models.ManyToManyField(Author) ``` Then you can do: ``` books = Book.objects.filter(authors__id=1) ```
Get the cartesian product of a series of lists in Python
533,905
131
2009-02-10T19:54:17Z
533,917
159
2009-02-10T19:58:01Z
[ "python", "list" ]
How can I get the Cartesian product (every possible combination of values) from a group of lists? Input: ``` somelists = [ [1, 2, 3], ['a', 'b'], [4, 5] ] ``` Desired output: ``` [(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4), (2, 'a', 5) ...] ```
In Python 2.6+ ``` import itertools for element in itertools.product(*somelists): print element ``` Documentation: [Python 2 - itertools.product](https://docs.python.org/2/library/itertools.html#itertools.product)
Get the cartesian product of a series of lists in Python
533,905
131
2009-02-10T19:54:17Z
533,919
42
2009-02-10T19:58:31Z
[ "python", "list" ]
How can I get the Cartesian product (every possible combination of values) from a group of lists? Input: ``` somelists = [ [1, 2, 3], ['a', 'b'], [4, 5] ] ``` Desired output: ``` [(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4), (2, 'a', 5) ...] ```
``` import itertools >>> for i in itertools.product([1,2,3],['a','b'],[4,5]): ... print i ... (1, 'a', 4) (1, 'a', 5) (1, 'b', 4) (1, 'b', 5) (2, 'a', 4) (2, 'a', 5) (2, 'b', 4) (2, 'b', 5) (3, 'a', 4) (3, 'a', 5) (3, 'b', 4) (3, 'b', 5) >>> ```
Get the cartesian product of a series of lists in Python
533,905
131
2009-02-10T19:54:17Z
533,928
7
2009-02-10T20:01:26Z
[ "python", "list" ]
How can I get the Cartesian product (every possible combination of values) from a group of lists? Input: ``` somelists = [ [1, 2, 3], ['a', 'b'], [4, 5] ] ``` Desired output: ``` [(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4), (2, 'a', 5) ...] ```
with [itertools.product](http://docs.python.org/library/itertools.html#itertools.permutations): ``` import itertools result = list(itertools.product(*somelists)) ```
Get the cartesian product of a series of lists in Python
533,905
131
2009-02-10T19:54:17Z
533,934
9
2009-02-10T20:02:47Z
[ "python", "list" ]
How can I get the Cartesian product (every possible combination of values) from a group of lists? Input: ``` somelists = [ [1, 2, 3], ['a', 'b'], [4, 5] ] ``` Desired output: ``` [(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4), (2, 'a', 5) ...] ```
In Python 2.6 and above you can use 'itertools.product`. In older versions of Python you can use the following (almost -- see documentation) equivalent [code from the documentation](http://docs.python.org/library/itertools.html#itertools.product): ``` def product(*args, **kwds): # product('ABCD', 'xy') --> Ax Ay B...
Get the cartesian product of a series of lists in Python
533,905
131
2009-02-10T19:54:17Z
534,085
24
2009-02-10T20:38:16Z
[ "python", "list" ]
How can I get the Cartesian product (every possible combination of values) from a group of lists? Input: ``` somelists = [ [1, 2, 3], ['a', 'b'], [4, 5] ] ``` Desired output: ``` [(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4), (2, 'a', 5) ...] ```
For Python 2.5 and older: ``` >>> [(a, b, c) for a in [1,2,3] for b in ['a','b'] for c in [4,5]] [(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4), (2, 'a', 5), (2, 'b', 4), (2, 'b', 5), (3, 'a', 4), (3, 'a', 5), (3, 'b', 4), (3, 'b', 5)] ``` Here's a recursive version of `product()` (just an illus...
Python Golf: what's the most concise way of turning this list of lists into a dictionary:
534,608
3
2009-02-10T22:49:02Z
534,615
14
2009-02-10T22:51:09Z
[ "python", "code-golf" ]
I have a list of lists that looks like this: ``` [['Tom', 'Dick'], ['Harry', 'John', 'Mike'], ['Bob']] ``` and I want to turn it into a dictionary where each key is a name and each value is a number corresponding to the position of its sublist in the list: ``` {'Tom': 0, 'Dick': 0, 'Harry': 1, 'John': 1, 'Mike': 1, ...
``` names_dict = dict((name,index) for index,lst in enumerate(names) for name in lst) ``` Example: ``` >>> names = [['Tom', 'Dick'], ['Harry', 'John', 'Mike'], ['Bob']] >>> names_dict = dict((name,index) ... for index,lst in enumerate(names) ... ...
Python Golf: what's the most concise way of turning this list of lists into a dictionary:
534,608
3
2009-02-10T22:49:02Z
534,686
19
2009-02-10T23:09:25Z
[ "python", "code-golf" ]
I have a list of lists that looks like this: ``` [['Tom', 'Dick'], ['Harry', 'John', 'Mike'], ['Bob']] ``` and I want to turn it into a dictionary where each key is a name and each value is a number corresponding to the position of its sublist in the list: ``` {'Tom': 0, 'Dick': 0, 'Harry': 1, 'John': 1, 'Mike': 1, ...
Same idea as MizardX, but slightly smaller and prettier in Python 3.0 using [dict comprehensions:](http://www.python.org/dev/peps/pep-0274/) ``` >>> names = [['Tom', 'Dick'], ['Harry', 'John', 'Mike'], ['Bob']] >>> names_dict = {name:index for index, lst in enumerate(names) for name in lst} >>> names_dict {'Tom': 0, '...
How to create a GUID/UUID in Python
534,839
245
2009-02-10T23:51:21Z
534,847
169
2009-02-10T23:54:26Z
[ "python", "guid", "uuid" ]
How do I create a GUID in Python that is platform independent? I hear there is a method using ActivePython on Windows but it's Windows only because it uses COM. Is there a method using plain Python?
"The uuid module, in Python 2.5 and up, provides RFC compliant UUID generation. See the module docs and the RFC for details." Docs: * Python 2: <http://docs.python.org/2/library/uuid.html> * Python 3: <https://docs.python.org/3/library/uuid.html> <http://code.activestate.com/lists/python-list/72693/>
How to create a GUID/UUID in Python
534,839
245
2009-02-10T23:51:21Z
534,851
242
2009-02-10T23:55:52Z
[ "python", "guid", "uuid" ]
How do I create a GUID in Python that is platform independent? I hear there is a method using ActivePython on Windows but it's Windows only because it uses COM. Is there a method using plain Python?
If you're using Python 2.5 or later, the [**uuid module**](https://docs.python.org/2/library/uuid.html#module-uuid) is already included with the Python standard distribution. Ex: ``` >>> import uuid >>> uuid.uuid4() UUID('5361a11b-615c-42bf-9bdb-e2c3790ada14') ```
How to create a GUID/UUID in Python
534,839
245
2009-02-10T23:51:21Z
10,984,286
19
2012-06-11T16:47:53Z
[ "python", "guid", "uuid" ]
How do I create a GUID in Python that is platform independent? I hear there is a method using ActivePython on Windows but it's Windows only because it uses COM. Is there a method using plain Python?
I use GUIDs as random keys for database type operations. The hexadecimal form, with the dashes and extra characters seem unnecessarily long to me. But I also like that strings representing hexadecimal numbers are very safe in that they do not contain characters that can cause problems in some situations such as '+','=...
How to create a GUID/UUID in Python
534,839
245
2009-02-10T23:51:21Z
27,302,466
43
2014-12-04T19:34:05Z
[ "python", "guid", "uuid" ]
How do I create a GUID in Python that is platform independent? I hear there is a method using ActivePython on Windows but it's Windows only because it uses COM. Is there a method using plain Python?
Copied from : <https://docs.python.org/2/library/uuid.html> (Since the links posted were not active and they keep updating) ``` >>> import uuid >>> # make a UUID based on the host ID and current time >>> uuid.uuid1() UUID('a8098c1a-f86e-11da-bd1a-00112444be1e') >>> # make a UUID using an MD5 hash of a namespace UUID...
Subtracting 2 lists in Python
534,855
33
2009-02-10T23:57:22Z
534,866
77
2009-02-11T00:00:52Z
[ "python", "list", "tuples", "vector" ]
Right now I have vector3 values represented as lists. is there a way to subtract 2 of these like vector3 values, like ``` [2,2,2] - [1,1,1] = [1,1,1] ``` Should I use tuples? If none of them defines these operands on these types, can I define it instead? If not, should I create a new vector3 class?
If this is something you end up doing frequently, and with different operations, you should probably create a class to handle cases like this, or better use some library like [Numpy](http://numpy.scipy.org/). Otherwise, look for [list comprehensions](http://docs.python.org/tutorial/datastructures.html#list-comprehensi...
Subtracting 2 lists in Python
534,855
33
2009-02-10T23:57:22Z
534,872
7
2009-02-11T00:01:51Z
[ "python", "list", "tuples", "vector" ]
Right now I have vector3 values represented as lists. is there a way to subtract 2 of these like vector3 values, like ``` [2,2,2] - [1,1,1] = [1,1,1] ``` Should I use tuples? If none of them defines these operands on these types, can I define it instead? If not, should I create a new vector3 class?
Check out the [NumPy](http://numpy.scipy.org/) package for python.