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
Single implementation to cover both single and multiple values in Python?
628,162
4
2009-03-09T21:49:37Z
628,186
13
2009-03-09T21:56:19Z
[ "python", "list" ]
Say you have a value like this: n = 5 and a method that returns the factorial of it, like so: Factorial ( 5 ) How do you handle multiple values: nums = [1,2,3,4,5] Factorial ( nums ) so it returns the factorials of all these values as a list. What's the cleanest way to handle this, without writing 2 methods? Do...
``` def Factorial(arg): try: it = iter(arg) except TypeError: pass else: return [Factorial(x) for x in it] return math.factorial(arg) ``` If it's iterable, apply recursivly. Otherwise, proceed normally. Alternatively, you could move the last `return` into the `except` block. I...
Single implementation to cover both single and multiple values in Python?
628,162
4
2009-03-09T21:49:37Z
628,257
7
2009-03-09T22:20:37Z
[ "python", "list" ]
Say you have a value like this: n = 5 and a method that returns the factorial of it, like so: Factorial ( 5 ) How do you handle multiple values: nums = [1,2,3,4,5] Factorial ( nums ) so it returns the factorials of all these values as a list. What's the cleanest way to handle this, without writing 2 methods? Do...
This is done sometimes. ``` def factorial( *args ): def fact( n ): if n == 0: return 1 return n*fact(n-1) return [ fact(a) for a in args ] ``` It gives an almost magical function that works with simple values as well as sequences. ``` >>> factorial(5) [120] >>> factorial( 5, 6, 7 ) [120, 720,...
Python equivalent to java.util.SortedSet?
628,192
19
2009-03-09T21:58:14Z
628,264
12
2009-03-09T22:22:21Z
[ "python", "data-structures" ]
Does anybody know if Python has an equivalent to Java's SortedSet interface? Heres what I'm looking for: lets say I have an object of type `foo`, and I know how to compare two objects of type `foo` to see whether `foo1` is "greater than" or "less than" `foo2`. I want a way of storing many objects of type `foo` in a li...
You can use `insort` from the [`bisect`](http://docs.python.org/library/bisect.html#module-bisect) module to insert new elements efficiently in an already sorted list: ``` from bisect import insort items = [1,5,7,9] insort(items, 3) insort(items, 10) print items # -> [1, 3, 5, 7, 9, 10] ``` Note that this does not ...
Python equivalent to java.util.SortedSet?
628,192
19
2009-03-09T21:58:14Z
628,432
11
2009-03-09T23:33:08Z
[ "python", "data-structures" ]
Does anybody know if Python has an equivalent to Java's SortedSet interface? Heres what I'm looking for: lets say I have an object of type `foo`, and I know how to compare two objects of type `foo` to see whether `foo1` is "greater than" or "less than" `foo2`. I want a way of storing many objects of type `foo` in a li...
Take a look at [BTrees](http://pypi.python.org/pypi?%3Aaction=search&term=btree). It look like you need one of them. As far as I understood you need structure that will support relatively cheap insertion of element into storage structure and cheap sorting operation (or even lack of it). BTrees offers that. I've experi...
Google Data Source JSON not valid?
628,505
5
2009-03-10T00:07:31Z
628,634
8
2009-03-10T01:35:25Z
[ "python", "simplejson" ]
I am implementing a Google Data Source using their [Python Library](http://code.google.com/apis/visualization/documentation/dev/gviz_api_lib.html#tojsonexample). I would like the response from the library to be able to be imported in another Python script using the [simplejson library.](http://simplejson.googlecode.com...
It is considered to be invalid JSON without the string keys. ``` {id:'name',label:'Name',type:'string'} ``` must be: ``` {'id':'name','label':'Name','type':'string'} ``` According to the [Google Data Source](http://code.google.com/apis/visualization/documentation/dev/implementing%5Fdata%5Fsource.html#jsondatatable)...
How to divide a set of overlapping ranges into non-overlapping ranges?
628,837
8
2009-03-10T03:21:07Z
628,859
11
2009-03-10T03:32:48Z
[ "python", "algorithm", "math", "range", "rectangles" ]
Let's say you have a set of ranges: * 0 - 100: 'a' * 0 - 75: 'b' * 95 - 150: 'c' * 120 - 130: 'd' Obviously, these ranges overlap at certain points. How would you dissect these ranges to produce a list of non-overlapping ranges, while retaining information associated with their original range (in this case, the lette...
I had the same question when writing a program to mix (partly overlapping) audio samples. What I did was add an "start event" and "stop event" (for each item) to a list, sort the list by time point, and then process it in order. You could do the same, except using an integer point instead of a time, and instead of mix...
Performance Advantages to Iterators?
628,903
14
2009-03-10T04:05:59Z
629,169
13
2009-03-10T07:07:24Z
[ "python", "performance", "iterator" ]
What (if any) performance advantages are offered by using iterators. It seems like the 'Right Way' to solve many problems, but does it create faster/more memory-conscious code? I'm thinking specifically in Python, but don't restrict answers to just that.
For Python, generators will be faster and have better memory efficiency. Just think of an example of `range(1000)` **vs** `xrange(1000)` (This has been changed in 3.0, range is now an generator). With Range you pre-build your list but XRange just has a generator object and yields the next item when needed instead. The...
Performance Advantages to Iterators?
628,903
14
2009-03-10T04:05:59Z
631,619
15
2009-03-10T18:16:59Z
[ "python", "performance", "iterator" ]
What (if any) performance advantages are offered by using iterators. It seems like the 'Right Way' to solve many problems, but does it create faster/more memory-conscious code? I'm thinking specifically in Python, but don't restrict answers to just that.
There's actually a very good mail on the python mailing list about this: [Iterators vs Lists](http://markmail.org/message/t2a6tp33n5lddzvy). It's a bit dated (from 2003), but as far as I know, it's still valid. Here's the summary: > For small datasets, iterator and list based approaches have similar > performance. > ...
How to query as GROUP BY in django?
629,551
161
2009-03-10T10:10:30Z
629,600
25
2009-03-10T10:30:44Z
[ "python", "django" ]
I query a model, ``` Members.objects.all() ``` and it returns say ``` Eric, Salesman, X-Shop Freddie, Manager, X2-Shop Teddy, Salesman, X2-Shop Sean, Manager, X2-Shop ``` What i want is, to know the best Django way to fire a group\_by query to my db, as like, ``` Members.objects.all().group_by('designation') ``` ...
An easy solution, but not in a proper way is to use RAW-SQL: <http://docs.djangoproject.com/en/dev/topics/db/sql/#topics-db-sql> Another solution is to use the group\_by property: ``` query = Members.objects.all().query query.group_by = ['designation'] results = QuerySet(query=query, model=Members) ``` You can now ...
How to query as GROUP BY in django?
629,551
161
2009-03-10T10:10:30Z
629,691
246
2009-03-10T11:08:28Z
[ "python", "django" ]
I query a model, ``` Members.objects.all() ``` and it returns say ``` Eric, Salesman, X-Shop Freddie, Manager, X2-Shop Teddy, Salesman, X2-Shop Sean, Manager, X2-Shop ``` What i want is, to know the best Django way to fire a group\_by query to my db, as like, ``` Members.objects.all().group_by('designation') ``` ...
If you mean to do aggregation and are using Django 1.1 (currently in alpha 1), you can use the new [aggregation features of the ORM](http://docs.djangoproject.com/en/dev/topics/db/aggregation/#topics-db-aggregation): ``` from django.db.models import Count Members.objects.values('designation').annotate(dcount=Count('de...
Deploying Google Analytics With Django
629,696
23
2009-03-10T11:09:57Z
629,715
34
2009-03-10T11:17:08Z
[ "python", "django", "deployment", "google-analytics" ]
We're about to deploy a new Django website, and we want to use Google Analytics to keep track of traffic on the site. However, we don't want all of the hits on development instances to contribute to the Google Analytics statistics. There are a few ways we could deal with this: * have a configuration option in setting...
First, create a way to have your development and production servers pull settings from different files, say dev.py and prod.py. There are lots of ways to do this. Then, create a setting, `GOOGLE_ANALYTICS_KEY`. In dev.py set it to the empty string. In prod.py, set it to your key, something like "UA-124465-1". Create a...
Deploying Google Analytics With Django
629,696
23
2009-03-10T11:09:57Z
1,559,982
10
2009-10-13T12:45:30Z
[ "python", "django", "deployment", "google-analytics" ]
We're about to deploy a new Django website, and we want to use Google Analytics to keep track of traffic on the site. However, we don't want all of the hits on development instances to contribute to the Google Analytics statistics. There are a few ways we could deal with this: * have a configuration option in setting...
A little late to the party, but there's a reusable Django app called [django-google-analytics](http://github.com/montylounge/django-google-analytics). The easiest way to use it is: 1. Add the `google_analytics` application to your `INSTALLED_APPS` section of your `settings.py`. 2. In your base template, usually a `bas...
Why avoid CGI for Python with LAMP hosting?
629,919
22
2009-03-10T12:32:06Z
629,930
9
2009-03-10T12:35:50Z
[ "php", "python", ".htaccess", "cgi" ]
I have been using PHP for years. Lately I've come across numerous forum posts stating that **PHP is outdated**, that modern programming languages are easier, more secure, etc. etc. So, I decided to **start learning Python**. Since I'm used to using PHP, I just started building pages by uploading an .htaccess file with...
Classic CGI isn't the best way to use anything at all. With classic CGI server has to **spawn a new process for every request**. As for Python, you have few alternatives: * [`mod_wsgi`](http://code.google.com/p/modwsgi/) * [`mod_python`](http://modpython.org/) * [fastcgi](http://pypi.python.org/pypi/python-fastcgi) *...
BeautifulSoup gives me unicode+html symbols, rather than straight up unicode. Is this a bug or misunderstanding?
629,999
5
2009-03-10T12:52:00Z
630,099
8
2009-03-10T13:15:41Z
[ "python", "html", "unicode", "beautifulsoup" ]
I'm using BeautifulSoup to scrape a website. The website's page renders fine in my browser: > Oxfam International’s report entitled “Offside! > <http://www.coopamerica.org/programs/responsibleshopper/company.cfm?id=271> In particular, the single and double quotes look fine. They look html symbols rather than asci...
That's one seriously messed up page, encoding-wise :-) There's nothing really wrong with your approach at all. I would probably tend to do the conversion before passing it to BeautifulSoup, just because I'm persnickity: ``` import urllib html = urllib.urlopen('http://www.coopamerica.org/programs/responsibleshopper/co...
Interruptible thread join in Python
631,441
21
2009-03-10T17:28:16Z
631,605
15
2009-03-10T18:12:29Z
[ "python", "multithreading" ]
**Is there any way to wait for termination of a thread, but still intercept signals?** Consider the following **C** program: ``` #include <signal.h> #include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <pthread.h> #include <stdlib.h> void* server_thread(void* dummy) { sleep(10); printf("Ser...
Threads in Python are somewhat strange beasts given the global interpreter lock. You may not be able to achieve what you want without resorting to a join timeout and isAlive as eliben suggests. There are two spots in the docs that give the reason for this (and possibly more). The first: From <http://docs.python.org/...
Dictionaries in Python
631,463
5
2009-03-10T17:34:43Z
631,474
14
2009-03-10T17:37:22Z
[ "python", "dictionary" ]
I am trying to get to speed on the use of dictionaries. I spent three hours last night searching the web for examples similar to some of the things I am trying to do. For example, suppose I have two dictionaries (actually I have two lists of dictionaries). ``` d1={key1:1, key2:2} d2={key1:1, key2:'A', key4:4} ``` I w...
Try this: ``` import collections merged = collections.defaultdict(list) for k in d1: merged[k].append( d1[k] ) for k in d2: merged[k].append( d2[k] ) ``` This may be what you're looking for. Or possibly this. ``` import collections merged = collections.defaultdict(set) for k in d1: merged[k].add( d1[k] ) f...
base64 png in python on Windows
631,884
11
2009-03-10T19:25:42Z
631,899
26
2009-03-10T19:29:26Z
[ "python", "windows", "base64" ]
How do you encode a png image into base64 using python on Windows? ``` iconfile = open("icon.png") icondata = iconfile.read() icondata = base64.b64encode(icondata) ``` The above works fine in Linux and OSX, but on Windows it will encode the first few characters then cut short. Why is this?
[Open the file in binary mode](http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files): ``` open("icon.png", "rb") ``` I'm not very familiar with Windows, but I'd imagine what's happening is that the file contains a character (0x1A) that [Windows is interpreting as the end of the file](http://www....
base64 png in python on Windows
631,884
11
2009-03-10T19:25:42Z
632,495
9
2009-03-10T22:16:13Z
[ "python", "windows", "base64" ]
How do you encode a png image into base64 using python on Windows? ``` iconfile = open("icon.png") icondata = iconfile.read() icondata = base64.b64encode(icondata) ``` The above works fine in Linux and OSX, but on Windows it will encode the first few characters then cut short. Why is this?
To augment the answer from Miles, the [first eight bytes in a PNG file](http://www.libpng.org/pub/png/spec/1.2/PNG-Rationale.html#R.PNG-file-signature) are specially designed: * 89 - the first byte is a check that bit 8 hasn't been stripped * "PNG" - let someone read that it's a PNG format * 0d 0a - the DOS end-of...
What is the feasibility of porting a legacy C program to Python?
632,730
2
2009-03-10T23:47:15Z
632,738
9
2009-03-10T23:50:47Z
[ "python", "c" ]
I have a program in C that communicates via UDP with another program (in Java) and then does process manipulation (start/stop) based on the UDP pkt exchange. Now this C program has been legacy and I want to convert it to Python - do you think Python will be a good choice for the tasks mentioned?
Yes, I do think that Python would be a good replacement. I understand that the [Twisted](http://twistedmatrix.com/trac/ "Twisted") Python framework is quite popular.
Python, Evaluate a Variable value as a Variable
632,856
4
2009-03-11T00:31:50Z
632,869
11
2009-03-11T00:35:09Z
[ "python" ]
I'd like to do something like below: particularly the 'f.eval(field)' part, such that it evaluates the value of the variable as the field name. How does one accomplish this in Python? ``` def punctuated_object_list(objects, field): field_list = [f.eval(field) for f in objects] if len(field_list) > 0: i...
`getattr(f, field)`, if I understand you correctly (that is, if you might have `field = "foo"`, and want `f.foo`). If not, you might want to clarify. Python has an `eval()`, and I don't know what other languages' `eval()` you want the equivalent of.
detecting fullscreen on mac
633,086
2
2009-03-11T02:11:41Z
633,166
8
2009-03-11T02:48:50Z
[ "python", "objective-c", "cocoa", "osx", "fullscreen" ]
I am writing an IM client for Mac (in python, but an Objective C / Cocoa solution here is fine). I want to detect whether or not the user is currently watching a movie or playing a game in the foreground, or doing anything else that takes up the entire screen. If so, I won't play a sound when a new IM comes in, but if ...
To check for full-screen, call [CGDisplayIsCaptured(screenID)](http://developer.apple.com/DOCUMENTATION/GraphicsImaging/Reference/Quartz%5FServices%5FRef/Reference/reference.html#//apple%5Fref/c/func/CGDisplayIsCaptured) on each screen. But I'm not sure if you're checking the right thing. For one thing, I could have o...
Writing a socket-based server in Python, recommended strategies?
634,107
9
2009-03-11T11:15:27Z
634,237
7
2009-03-11T12:07:05Z
[ "python", "sockets", "asynchronous", "network-programming", "c10k" ]
I was recently reading [this document](http://www.kegel.com/c10k.html) which lists a number of strategies that could be employed to implement a socket server. Namely, they are: 1. Serve many clients with each thread, and use nonblocking I/O and level-triggered readiness notification 2. Serve many clients with each thr...
[`asyncore`](http://docs.python.org/library/asyncore.html) is basically "1" - It uses `select` internally, and you just have one thread handling all requests. According to the docs it can also use `poll`. (EDIT: Removed Twisted reference, I thought it used asyncore, but I was wrong). "2" might be implemented with [pyt...
using wsgiref.simple_server in unittests
634,485
3
2009-03-11T13:22:09Z
634,571
7
2009-03-11T13:44:29Z
[ "python", "unit-testing", "wsgiref" ]
I have some functions like this one: ``` URL = 'http://localhost:8080' def func(): response = urlopen(URL) return process(response) ``` And i want to test it with unittest. I did something like this: ``` from wsgiref.simple_server import make_server def app_200_hello(environ,start_response): stdout = St...
If you are testing a WSGI application, I can strongly recommend [werkzeug.test](http://werkzeug.pocoo.org/documentation/test) which gets around these issues by testing the application itself without a server: ``` from werkzeug.test import Client # then in your test case def test1(self): client = Client(app_200_he...
svg diagrams using python
634,964
20
2009-03-11T15:07:39Z
634,998
7
2009-03-11T15:15:47Z
[ "python", "svg", "diagram" ]
I am looking for a library to generate svg diagrams in python (I fetch data from a sql database). I have found [python-gd](http://newcenturycomputers.net/projects/gdmodule.html), but it has not much documentation and last update was in 2005 so I wonder if there are any other libraries that are good for this purpose. I...
Here's a general purpose SVG library in Python: [pySVG](http://codeboje.de/pysvg/).
svg diagrams using python
634,964
20
2009-03-11T15:07:39Z
635,001
9
2009-03-11T15:16:51Z
[ "python", "svg", "diagram" ]
I am looking for a library to generate svg diagrams in python (I fetch data from a sql database). I have found [python-gd](http://newcenturycomputers.net/projects/gdmodule.html), but it has not much documentation and last update was in 2005 so I wonder if there are any other libraries that are good for this purpose. I...
Try using [matplotlib](http://matplotlib.sourceforge.net/). You can configure it with a SVG [backend](http://matplotlib.sourceforge.net/faq/installing%5Ffaq.html#what-is-a-backend).
svg diagrams using python
634,964
20
2009-03-11T15:07:39Z
635,002
9
2009-03-11T15:16:53Z
[ "python", "svg", "diagram" ]
I am looking for a library to generate svg diagrams in python (I fetch data from a sql database). I have found [python-gd](http://newcenturycomputers.net/projects/gdmodule.html), but it has not much documentation and last update was in 2005 so I wonder if there are any other libraries that are good for this purpose. I...
[PyChart](http://home.gna.org/pychart/) *"is a Python library for creating high quality Encapsulated Postscript, PDF, PNG, or **SVG** charts."*
svg diagrams using python
634,964
20
2009-03-11T15:07:39Z
635,096
8
2009-03-11T15:36:41Z
[ "python", "svg", "diagram" ]
I am looking for a library to generate svg diagrams in python (I fetch data from a sql database). I have found [python-gd](http://newcenturycomputers.net/projects/gdmodule.html), but it has not much documentation and last update was in 2005 so I wonder if there are any other libraries that are good for this purpose. I...
[pyCairo](http://cairographics.org/pycairo/) is an option worth looking at.
svg diagrams using python
634,964
20
2009-03-11T15:07:39Z
635,149
10
2009-03-11T15:50:55Z
[ "python", "svg", "diagram" ]
I am looking for a library to generate svg diagrams in python (I fetch data from a sql database). I have found [python-gd](http://newcenturycomputers.net/projects/gdmodule.html), but it has not much documentation and last update was in 2005 so I wonder if there are any other libraries that are good for this purpose. I...
As you're looking for simple line graphics, probably, [CairoPlot](http://linil.wordpress.com/2008/09/16/cairoplot-11/) will fit your needs as it can generate svg output files out of the box. Take a look at [this](http://linil.files.wordpress.com/2008/06/cairoplot%5Fdotlineplot.png). ![CairoPlot - DotLinePlot](http://l...
Python urllib2, basic HTTP authentication, and tr.im
635,113
62
2009-03-11T15:43:10Z
635,146
16
2009-03-11T15:50:08Z
[ "python", "http", "authentication" ]
I'm playing around, trying to write some code to use the [tr.im](http://www.programmableweb.com/api/tr.im) APIs to shorten a URL. After reading <http://docs.python.org/library/urllib2.html>, I tried: ``` TRIM_API_URL = 'http://api.tr.im/api' auth_handler = urllib2.HTTPBasicAuthHandler() auth_handler.add_pass...
Really cheap solution: ``` urllib.urlopen('http://user:xxxx@api.tr.im/api') ``` (which you may decide is not suitable for a number of reasons, like security of the url) [Github API example](https://developer.github.com/v3/auth/#via-oauth-tokens): ``` >>> import urllib, json >>> result = urllib.urlopen('https://pers...
Python urllib2, basic HTTP authentication, and tr.im
635,113
62
2009-03-11T15:43:10Z
4,188,709
210
2010-11-15T20:52:54Z
[ "python", "http", "authentication" ]
I'm playing around, trying to write some code to use the [tr.im](http://www.programmableweb.com/api/tr.im) APIs to shorten a URL. After reading <http://docs.python.org/library/urllib2.html>, I tried: ``` TRIM_API_URL = 'http://api.tr.im/api' auth_handler = urllib2.HTTPBasicAuthHandler() auth_handler.add_pass...
This seems to work really well (taken from another thread) ``` import urllib2, base64 request = urllib2.Request("http://api.foursquare.com/v1/user") base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '') request.add_header("Authorization", "Basic %s" % base64string) result = urllib2.u...
Python urllib2, basic HTTP authentication, and tr.im
635,113
62
2009-03-11T15:43:10Z
9,698,319
11
2012-03-14T08:35:25Z
[ "python", "http", "authentication" ]
I'm playing around, trying to write some code to use the [tr.im](http://www.programmableweb.com/api/tr.im) APIs to shorten a URL. After reading <http://docs.python.org/library/urllib2.html>, I tried: ``` TRIM_API_URL = 'http://api.tr.im/api' auth_handler = urllib2.HTTPBasicAuthHandler() auth_handler.add_pass...
Take a look at [this SO post answer](http://stackoverflow.com/a/7755057/1020470) and also look at this [basic authentication tutorial](http://www.voidspace.org.uk/python/articles/authentication.shtml) from the [urllib2 missing manual](http://www.voidspace.org.uk/python/articles/urllib2.shtml). In order for urllib2 bas...
code documentation for python
635,419
16
2009-03-11T16:54:41Z
635,428
33
2009-03-11T16:56:58Z
[ "python", "documentation", "documentation-generation" ]
What is out there on conventions and tools for documenting python source code?
Conventions: [PEP 257](http://www.python.org/dev/peps/pep-0257/) and [PEP 8](http://www.python.org/dev/peps/pep-0008/). Note, that docstrings can be written in [reStructuredText](http://docutils.sourceforge.net/rst.html) Tools for generating documentation: for example [Sphinx](http://sphinx.pocoo.org/)
code documentation for python
635,419
16
2009-03-11T16:54:41Z
635,473
8
2009-03-11T17:06:07Z
[ "python", "documentation", "documentation-generation" ]
What is out there on conventions and tools for documenting python source code?
[Epydoc](http://epydoc.sourceforge.net/) is also a good tool for documenting source code, and handles cross-referencing classes, modules, variables, etc, into HTML, PDF, LaTeX. Draws some nice class inheritance diagrams too. It's used by a number of open-source projects, so it's fairly actively developed.
code documentation for python
635,419
16
2009-03-11T16:54:41Z
635,482
14
2009-03-11T17:08:39Z
[ "python", "documentation", "documentation-generation" ]
What is out there on conventions and tools for documenting python source code?
First, put comments in your docstrings using RestructuredText format. Second, get [sphinx](http://sphinx.pocoo.org/). Third, create an index that uses the [autodoc extension](http://sphinx.pocoo.org/ext/autodoc.html). Then, run Sphinx to get really nice documentation.
What is the best way to implement nested dictionaries in Python?
635,483
149
2009-03-11T17:09:21Z
635,498
7
2009-03-11T17:14:19Z
[ "python", "data-structures", "dictionary", "mapping", "autovivification" ]
I have a data structure which essentially amounts to a nested dictionary. Let's say it looks like this: ``` {'new jersey': {'mercer county': {'plumbers': 3, 'programmers': 81}, 'middlesex county': {'programmers': 81, 'salesmen': 62}...
I find `setdefault` quite useful; It checks if a key is present and adds it if not: ``` d = {} d.setdefault('new jersey', {}).setdefault('mercer county', {})['plumbers'] = 3 ``` `setdefault` always returns the relevant key, so you are actually updating the values of '`d`' in place. When it comes to iterating, I'm su...
What is the best way to implement nested dictionaries in Python?
635,483
149
2009-03-11T17:09:21Z
635,557
17
2009-03-11T17:29:12Z
[ "python", "data-structures", "dictionary", "mapping", "autovivification" ]
I have a data structure which essentially amounts to a nested dictionary. Let's say it looks like this: ``` {'new jersey': {'mercer county': {'plumbers': 3, 'programmers': 81}, 'middlesex county': {'programmers': 81, 'salesmen': 62}...
Since you have a star-schema design, you might want to structure it more like a relational table and less like a dictionary. ``` import collections class Jobs( object ): def __init__( self, state, county, title, count ): self.state= state self.count= county self.title= title self.c...
What is the best way to implement nested dictionaries in Python?
635,483
149
2009-03-11T17:09:21Z
636,109
12
2009-03-11T20:02:11Z
[ "python", "data-structures", "dictionary", "mapping", "autovivification" ]
I have a data structure which essentially amounts to a nested dictionary. Let's say it looks like this: ``` {'new jersey': {'mercer county': {'plumbers': 3, 'programmers': 81}, 'middlesex county': {'programmers': 81, 'salesmen': 62}...
If the number of nesting levels is small, I use `collections.defaultdict` for this: ``` from collections import defaultdict def nested_dict_factory(): return defaultdict(int) def nested_dict_factory2(): return defaultdict(nested_dict_factory) db = defaultdict(nested_dict_factory2) db['new jersey']['mercer coun...
What is the best way to implement nested dictionaries in Python?
635,483
149
2009-03-11T17:09:21Z
636,138
21
2009-03-11T20:08:17Z
[ "python", "data-structures", "dictionary", "mapping", "autovivification" ]
I have a data structure which essentially amounts to a nested dictionary. Let's say it looks like this: ``` {'new jersey': {'mercer county': {'plumbers': 3, 'programmers': 81}, 'middlesex county': {'programmers': 81, 'salesmen': 62}...
You could create a YAML file and read it in using [PyYaml](http://pyyaml.org/). Step 1: Create a YAML file, "employment.yml": ``` new jersey: mercer county: pumbers: 3 programmers: 81 middlesex county: salesmen: 62 programmers: 81 new york: queens county: plumbers: 9 salesmen: 36 ``` St...
What is the best way to implement nested dictionaries in Python?
635,483
149
2009-03-11T17:09:21Z
652,284
178
2009-03-16T21:53:36Z
[ "python", "data-structures", "dictionary", "mapping", "autovivification" ]
I have a data structure which essentially amounts to a nested dictionary. Let's say it looks like this: ``` {'new jersey': {'mercer county': {'plumbers': 3, 'programmers': 81}, 'middlesex county': {'programmers': 81, 'salesmen': 62}...
``` class AutoVivification(dict): """Implementation of perl's autovivification feature.""" def __getitem__(self, item): try: return dict.__getitem__(self, item) except KeyError: value = self[item] = type(self)() return value ``` Testing: ``` a = AutoVivifica...
What is the best way to implement nested dictionaries in Python?
635,483
149
2009-03-11T17:09:21Z
7,476,491
25
2011-09-19T19:51:07Z
[ "python", "data-structures", "dictionary", "mapping", "autovivification" ]
I have a data structure which essentially amounts to a nested dictionary. Let's say it looks like this: ``` {'new jersey': {'mercer county': {'plumbers': 3, 'programmers': 81}, 'middlesex county': {'programmers': 81, 'salesmen': 62}...
Just because I haven't seen one this small, here's a dict that gets as nested as you like, no sweat: ``` # yo dawg, i heard you liked dicts def yodict(): return defaultdict(yodict) ```
What is the best way to implement nested dictionaries in Python?
635,483
149
2009-03-11T17:09:21Z
19,829,714
88
2013-11-07T06:53:24Z
[ "python", "data-structures", "dictionary", "mapping", "autovivification" ]
I have a data structure which essentially amounts to a nested dictionary. Let's say it looks like this: ``` {'new jersey': {'mercer county': {'plumbers': 3, 'programmers': 81}, 'middlesex county': {'programmers': 81, 'salesmen': 62}...
> # What is the best way to implement nested dictionaries in Python? Implement `__missing__` on a `dict` subclass to set and return a new instance! Here is a more elegant approach that has been available [(and documented)](http://docs.python.org/2/library/stdtypes.html#dict) since Python 2.5, and (particularly valuab...
What is the best way to implement nested dictionaries in Python?
635,483
149
2009-03-11T17:09:21Z
22,737,965
8
2014-03-29T22:53:36Z
[ "python", "data-structures", "dictionary", "mapping", "autovivification" ]
I have a data structure which essentially amounts to a nested dictionary. Let's say it looks like this: ``` {'new jersey': {'mercer county': {'plumbers': 3, 'programmers': 81}, 'middlesex county': {'programmers': 81, 'salesmen': 62}...
This is a function that returns a nested dictionary of arbitrary depth: ``` from collections import defaultdict def make_dict(): return defaultdict(make_dict) ``` Use it like this: ``` d=defaultdict(make_dict) d["food"]["meat"]="beef" d["food"]["veggie"]="corn" d["food"]["sweets"]="ice cream" d["animal"]["pet"][...
Django: Open uploaded file while still in memory; In the Form Clean method?
635,524
7
2009-03-11T17:20:30Z
635,559
12
2009-03-11T17:29:45Z
[ "python", "django" ]
I need to validate the contents of an uploaded XML file in my Form clean method, but I'm unable to open the file for validation. It seams, in the clean method, the file hasn't yet been moved from memory (or the temporary directory) to the destination directory. For example the following code doesn't work because the f...
I'm assuming that you've bound your form to the files using: ``` my_form = MyFormClass(request.POST, request.FILES) ``` If you have, once the form has been validated, you can access the file content itself using the request.FILES dictionary: ``` if my_form.is_valid(): data = request.FILES['myfile'].read() ``` T...
tell whether a character is a combining diacritic mark
635,643
3
2009-03-11T17:55:57Z
635,716
7
2009-03-11T18:15:22Z
[ "python", "unicode", "diacritics" ]
if you're looping though the chars a unicode string in python (2.x), say: > ak.sɛp.tɑ̃ How can you tell whether the current char is a combining diacritic mark? For instance, the last char in the above string is actually a combining mark: > ak.sɛp.tɑ̃ --> ̃
Use the unicodedata module: ``` import unicodedata if unicodedata.combining(u'a'): print "is combining character" else: print "is not combining" ``` these posts are also relevant <http://stackoverflow.com/questions/446222/how-do-i-reverse-unicode-decomposition-using-python> <http://stackoverflow.com/questio...
What's different between Python and Javascript regular expressions?
636,485
25
2009-03-11T21:36:56Z
636,501
25
2009-03-11T21:42:55Z
[ "javascript", "python", "regex" ]
Are Python and JavaScript regular expression syntax identical? If not, then: 1. What are the important differences between them 2. Is there a python library that "implements" JavaScript regexps?
There is a comparison table here: [Regex Flavor Comparison](http://www.regular-expressions.info/refflavors.html)
SELECT * in sqlalchemy?
636,548
12
2009-03-11T21:56:49Z
636,631
19
2009-03-11T22:27:31Z
[ "python", "sqlalchemy" ]
Is it possible to do `SELECT *` in sqlalchemy? Edit: Specifically, `SELECT * WHERE foo=1`
Is no one feeling the ORM love of SQLALchemy today? The presented answers correctly describe the lower level interface that SQLAlchemy provides. Just for completeness this is the more-likely *(for me)* real-world situation where you have a session instance and a User class that is orm mapped to the users table. ``` fo...
SELECT * in sqlalchemy?
636,548
12
2009-03-11T21:56:49Z
636,709
7
2009-03-11T23:02:32Z
[ "python", "sqlalchemy" ]
Is it possible to do `SELECT *` in sqlalchemy? Edit: Specifically, `SELECT * WHERE foo=1`
Where **Bar** is the class mapped to your table and **session** is your sa session: ``` bars = session.query(Bar).filter(Bar.foo == 1) ```
How can I run an external command asynchronously from Python?
636,561
60
2009-03-11T22:01:42Z
636,570
72
2009-03-11T22:05:32Z
[ "python", "asynchronous", "subprocess", "scheduler" ]
I need to run a shell command asynchronously from a Python script. By this I mean that I want my Python script to continue running while the external command goes off and does whatever it needs to do. I read this post: > <http://stackoverflow.com/questions/89228/how-to-call-external-command-in-python> I then went of...
[subprocess.Popen](http://docs.python.org/library/subprocess.html) does exactly what you want. ``` from subprocess import Popen p = Popen(['watch', 'ls']) # something long running # ... do other stuff while subprocess is running p.terminate() ``` (Edit to complete the answer from comments) The Popen instance can do ...
How can I run an external command asynchronously from Python?
636,561
60
2009-03-11T22:01:42Z
636,601
33
2009-03-11T22:15:50Z
[ "python", "asynchronous", "subprocess", "scheduler" ]
I need to run a shell command asynchronously from a Python script. By this I mean that I want my Python script to continue running while the external command goes off and does whatever it needs to do. I read this post: > <http://stackoverflow.com/questions/89228/how-to-call-external-command-in-python> I then went of...
If you want to run many processes in parallel and then handle them when they yield results, you can use polling like in the following: ``` from subprocess import Popen, PIPE import time running_procs = [ Popen(['/usr/bin/my_cmd', '-i %s' % path], stdout=PIPE, stderr=PIPE) for path in '/tmp/file0 /tmp/file1 /t...
How can I run an external command asynchronously from Python?
636,561
60
2009-03-11T22:01:42Z
636,620
7
2009-03-11T22:24:32Z
[ "python", "asynchronous", "subprocess", "scheduler" ]
I need to run a shell command asynchronously from a Python script. By this I mean that I want my Python script to continue running while the external command goes off and does whatever it needs to do. I read this post: > <http://stackoverflow.com/questions/89228/how-to-call-external-command-in-python> I then went of...
**What I am wondering is if this [os.system()] is the proper way to accomplish such a thing?** No. `os.system()` is not the proper way. That's why everyone says to use `subprocess`. For more information, read <http://docs.python.org/library/os.html#os.system> > The subprocess module provides more > powerful faciliti...
Django form - set label
636,905
42
2009-03-12T00:18:35Z
637,020
86
2009-03-12T01:06:40Z
[ "python", "django", "inheritance", "django-forms" ]
I have a form that inherits from 2 other forms. In my form, I want to change the label of a field that was defined in one of the parent forms. Does anyone know how this can be done? I'm trying to do it in my `__init__`, but it throws an error saying that "'RegistrationFormTOS' object has no attribute 'email'". Does an...
You should use: ``` def __init__(self, *args, **kwargs): super(RegistrationFormTOS, self).__init__(*args, **kwargs) self.fields['email'].label = "New Email Label" ``` Note first you should use the super call.
Django form - set label
636,905
42
2009-03-12T00:18:35Z
28,162,469
10
2015-01-27T02:54:37Z
[ "python", "django", "inheritance", "django-forms" ]
I have a form that inherits from 2 other forms. In my form, I want to change the label of a field that was defined in one of the parent forms. Does anyone know how this can be done? I'm trying to do it in my `__init__`, but it throws an error saying that "'RegistrationFormTOS' object has no attribute 'email'". Does an...
Here's an example taken from [Overriding the default fields](https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/#overriding-the-default-fields): > ``` > from django.utils.translation import ugettext_lazy as _ > > class AuthorForm(ModelForm): > class Meta: > model = Author > fields = ('n...
Are there any pitfalls with using whitespace in Python?
637,295
3
2009-03-12T03:50:34Z
637,309
11
2009-03-12T03:59:08Z
[ "python", "whitespace" ]
At the moment I have never had a problem with whitespace in Python (although I've only used it in two projects and I was the only programmer). What are some potential pitfalls with whitespace and indentation in Python for someone learning the language?
It can be confusing in some editors where one line is indented with spaces and the next is indented with a tab. This is confusing as the indentation looks the same but causes an error. Also when your copying code, if your editor doesn't have a function to indent entire blocks, it could be annoying fixing all the inden...
Are there any pitfalls with using whitespace in Python?
637,295
3
2009-03-12T03:50:34Z
637,423
10
2009-03-12T04:56:58Z
[ "python", "whitespace" ]
At the moment I have never had a problem with whitespace in Python (although I've only used it in two projects and I was the only programmer). What are some potential pitfalls with whitespace and indentation in Python for someone learning the language?
yeah there are some pitfalls, but most of the time, in practice, they turn out to be enemy [windmills of the Quixotic style](http://en.wikipedia.org/wiki/Tilting%5Fat%5Fwindmills), i.e. imaginary, and nothing to worry about in reality. I would estimate that the pitfalls one is *most likely to encounter* are (including...
Django with Passenger
637,565
8
2009-03-12T06:26:51Z
637,747
24
2009-03-12T08:36:12Z
[ "python", "django", "passenger", "dreamhost" ]
I'm trying to get a trivial Django project working with Passenger on Dreamhost, following the instructions [here](http://www.soasi.com/2008/09/django-10-on-dreamhost-with-passenger-mod_rails/) I've set up the directories exactly as in that tutorial, and ensured that django is on my PYTHONPATH (I can run python and ty...
Are those fancy quotation marks also in your code? ``` os.environ['DJANGO_SETTINGS_MODULE'] = ‘myproject.settings’ ^ ^ ``` If so, start by fixing them, as they cause a syntax error.
Showing page count with ReportLab
637,800
12
2009-03-12T09:05:34Z
639,993
11
2009-03-12T18:54:30Z
[ "python", "reportlab" ]
I'm trying to add a simple "page x of y" to a report made with ReportLab.. I found [this old post](http://two.pairlist.net/pipermail/reportlab-users/2002-May/000020.html) about it, but maybe six years later something more straightforward has emerged? ^^; I found [this recipe](http://code.activestate.com/recipes/54651...
I was able to implement the NumberedCanvas approach from ActiveState. It was very easy to do and did not change much of my existing code. All I had to do was add that NumberedCanvas class and add the canvasmaker attribute when building my doc. I also changed the measurements of where the "x of y" was displayed: ``` se...
How do I sum the first value in each tuple in a list of tuples in Python?
638,048
17
2009-03-12T10:37:27Z
638,055
44
2009-03-12T10:39:31Z
[ "python", "list", "tuples" ]
I have a list of tuples (always pairs) like this: ``` [(0, 1), (2, 3), (5, 7), (2, 1)] ``` I'd like to find the sum of the first items in each pair, i.e.: ``` 0 + 2 + 5 + 2 ``` How can I do this in Python? At the moment I'm iterating through the list: ``` sum = 0 for pair in list_of_pairs: sum += pair[0] ``` I...
A version compatible with Python 2.3 is ``` sum([pair[0] for pair in list_of_pairs]) ``` or in recent versions of Python, see [this answer](https://stackoverflow.com/a/638069/56541) or [this one](https://stackoverflow.com/a/10255912/56541).
How do I sum the first value in each tuple in a list of tuples in Python?
638,048
17
2009-03-12T10:37:27Z
638,069
30
2009-03-12T10:43:45Z
[ "python", "list", "tuples" ]
I have a list of tuples (always pairs) like this: ``` [(0, 1), (2, 3), (5, 7), (2, 1)] ``` I'd like to find the sum of the first items in each pair, i.e.: ``` 0 + 2 + 5 + 2 ``` How can I do this in Python? At the moment I'm iterating through the list: ``` sum = 0 for pair in list_of_pairs: sum += pair[0] ``` I...
``` sum(i for i, j in list_of_pairs) ``` will do too.
How do I sum the first value in each tuple in a list of tuples in Python?
638,048
17
2009-03-12T10:37:27Z
10,255,912
10
2012-04-21T03:24:43Z
[ "python", "list", "tuples" ]
I have a list of tuples (always pairs) like this: ``` [(0, 1), (2, 3), (5, 7), (2, 1)] ``` I'd like to find the sum of the first items in each pair, i.e.: ``` 0 + 2 + 5 + 2 ``` How can I do this in Python? At the moment I'm iterating through the list: ``` sum = 0 for pair in list_of_pairs: sum += pair[0] ``` I...
I recommend: ``` sum(i for i, _ in list_of_pairs) ``` *Note*: Using the variable `_`(or `__` to avoid confliction with the alias of `gettext`) instead of `j` has at least two benefits: 1. `_`(which stands for placeholder) has better readability 2. `pylint` won't complain: "Unused variable 'j'"
Ruby on Rails versus Python
638,150
13
2009-03-12T11:06:40Z
638,160
25
2009-03-12T11:09:40Z
[ "python", "ruby" ]
I am in the field of data crunching and very soon might make a move to the world of web programming. Although I am fascinated both by Python and Ruby as both of them seem to be having every similar styles when it comes to writing business logic or data crunching logic. But when I start googling for web development I s...
Ruby and Python are languages. Rails is a framework. So it is not really sensible to compare Ruby on Rails vs Python. There are Python Frameworks out there you should take a look at for a more direct comparison - <http://wiki.python.org/moin/WebFrameworks> (e.g. I know [Django](http://www.djangoproject.com/) gets a ...
Ruby on Rails versus Python
638,150
13
2009-03-12T11:06:40Z
638,800
9
2009-03-12T14:16:09Z
[ "python", "ruby" ]
I am in the field of data crunching and very soon might make a move to the world of web programming. Although I am fascinated both by Python and Ruby as both of them seem to be having every similar styles when it comes to writing business logic or data crunching logic. But when I start googling for web development I s...
If you want Python screencasts, see ShowMeDo.com. I'm a co-founder, it is 3.5 yrs old and has over 400 Python screencasts (most are free) along with 600+ other free open-source topics: <http://showmedo.com/videos/python> In the Python section (linked) you'll see videos for Django, the entire TurboGears v1 DVD (provide...
Ruby on Rails versus Python
638,150
13
2009-03-12T11:06:40Z
639,650
15
2009-03-12T17:28:55Z
[ "python", "ruby" ]
I am in the field of data crunching and very soon might make a move to the world of web programming. Although I am fascinated both by Python and Ruby as both of them seem to be having every similar styles when it comes to writing business logic or data crunching logic. But when I start googling for web development I s...
Ruby gets more attention than Python simply because Ruby has one clear favourite when it comes to web apps while Python has traditionally had a very splintered approach (Zope, Plone, Django, Pylons, Turbogears). The critical mass of having almost all developers using one system as opposed to a variety of individual one...
Python - How to calculate equal parts of two dictionaries?
638,360
4
2009-03-12T12:15:14Z
638,409
7
2009-03-12T12:30:54Z
[ "python", "list", "dictionary", "merge" ]
I have a problem with combining or calculating common/equal part of these two dictionaries. In my dictionaries, values are lists: ``` d1 = {0:['11','18','25','38'], 1:['11','18','25','38'], 2:['11','18','25','38'], 3:['11','18','25','38']} d2 = {0:['05','08','11','13','16','25','34','38','40', '4...
Assuming this is Python, you want: ``` dict((x, set(y) & set(d1.get(x, ()))) for (x, y) in d2.iteritems()) ``` to generate the resulting dictionary "d3". ### Python 3.0+ version ``` >>> d3 = {k: list(set(d1.get(k,[])).intersection(v)) for k, v in d2.items()} {0: ['11', '25', '38'], 1: ['38'], 2: ['11', '18'], 3: ['...
What is the most efficient way in Python to convert a string to all lowercase stripping out all non-ascii alpha characters?
638,893
25
2009-03-12T14:35:42Z
638,917
8
2009-03-12T14:39:28Z
[ "python", "string" ]
I have a simple task I need to perform in Python, which is to convert a string to all lowercase and strip out all non-ascii non-alpha characters. For example: ``` "This is a Test" -> "thisisatest" "A235th@#$&( er Ra{}|?>ndom" -> "atherrandom" ``` I have a simple function to do this: ``` import string import sys de...
I would: * lowercase the string * replace all `[^a-z]` with `""` Like that: ``` def strip_string_to_lowercase(): nonascii = re.compile('[^a-z]') return lambda s: nonascii.sub('', s.lower().strip()) ``` EDIT: It turns out that the original version (below) is really slow, though some performance can be gained by ...
What is the most efficient way in Python to convert a string to all lowercase stripping out all non-ascii alpha characters?
638,893
25
2009-03-12T14:35:42Z
638,920
10
2009-03-12T14:39:48Z
[ "python", "string" ]
I have a simple task I need to perform in Python, which is to convert a string to all lowercase and strip out all non-ascii non-alpha characters. For example: ``` "This is a Test" -> "thisisatest" "A235th@#$&( er Ra{}|?>ndom" -> "atherrandom" ``` I have a simple function to do this: ``` import string import sys de...
Not especially runtime efficient, but certainly nicer on poor, tired coder eyes: ``` def strip_string_and_lowercase(s): return ''.join(c for c in s.lower() if c in string.ascii_lowercase) ```
What is the most efficient way in Python to convert a string to all lowercase stripping out all non-ascii alpha characters?
638,893
25
2009-03-12T14:35:42Z
639,272
17
2009-03-12T15:55:32Z
[ "python", "string" ]
I have a simple task I need to perform in Python, which is to convert a string to all lowercase and strip out all non-ascii non-alpha characters. For example: ``` "This is a Test" -> "thisisatest" "A235th@#$&( er Ra{}|?>ndom" -> "atherrandom" ``` I have a simple function to do this: ``` import string import sys de...
``` >>> filter(str.isalpha, "This is a Test").lower() 'thisisatest' >>> filter(str.isalpha, "A235th@#$&( er Ra{}|?>ndom").lower() 'atherrandom' ```
What is the most efficient way in Python to convert a string to all lowercase stripping out all non-ascii alpha characters?
638,893
25
2009-03-12T14:35:42Z
639,325
22
2009-03-12T16:06:22Z
[ "python", "string" ]
I have a simple task I need to perform in Python, which is to convert a string to all lowercase and strip out all non-ascii non-alpha characters. For example: ``` "This is a Test" -> "thisisatest" "A235th@#$&( er Ra{}|?>ndom" -> "atherrandom" ``` I have a simple function to do this: ``` import string import sys de...
Another solution (not that pythonic, but very fast) is to use string.translate - though note that this will not work for unicode. It's also worth noting that you can speed up [Dana's code](http://stackoverflow.com/questions/638893/what-is-the-most-efficient-way-in-python-to-convert-a-string-to-all-lowercase-str/638920#...
python: determine if a class is nested
639,162
5
2009-03-12T15:26:53Z
639,209
12
2009-03-12T15:34:51Z
[ "python", "introspection", "inner-classes" ]
Suppose you have a python method that gets a type as parameter; is it possible to determine if the given type is a nested class? E.g. in this example: ``` def show_type_info(t): print t.__name__ # print outer class name (if any) ... class SomeClass: pass class OuterClass: class InnerClass: ...
AFAIK, given a class and no other information, you can't tell whether or not it's a nested class. However, [see here](http://mail.python.org/pipermail/python-list/2005-July/330874.html) for how you might use a decorator to determine this. The problem is that a nested class is simply a normal class that's an attribute ...
Running unit tests with Nose inside a Python environment such as Autodesk Maya?
639,744
6
2009-03-12T17:49:21Z
640,472
15
2009-03-12T21:03:01Z
[ "python", "unit-testing", "environment", "nose", "maya" ]
I'd like to start creating unit tests for my Maya scripts. These scripts must be run inside the Maya environment and rely on the `maya.cmds` module namespace. How can I run Nose tests from inside a running environment such as Maya?
Use the mayapy executable included in your maya install instead of the standard python executable. In order for this work you'll need to run nose programmatically. Create a python file called `runtests.py` and put it next to your test files. In it, include the following code: ``` import os os.environ['PYTHONPATH'] = ...
Unzipping directory structure with python
639,962
26
2009-03-12T18:44:45Z
640,078
21
2009-03-12T19:11:36Z
[ "python", "unzip" ]
I have a zip file which contains the following directory structure: ``` dir1\dir2\dir3a dir1\dir2\dir3b ``` I'm trying to unzip it and maintain the directory structure however I get the error: ``` IOError: [Errno 2] No such file or directory: 'C:\\\projects\\\testFolder\\\subdir\\\unzip.exe' ``` where testFolder is...
The extract and extractall methods are great if you're on Python 2.6. I have to use Python 2.5 for now, so I just need to create the directories if they don't exist. You can get a listing of directories with the `namelist()` method. The directories will always end with a forward slash (even on Windows) e.g., ``` impor...
Unzipping directory structure with python
639,962
26
2009-03-12T18:44:45Z
641,100
14
2009-03-13T00:56:12Z
[ "python", "unzip" ]
I have a zip file which contains the following directory structure: ``` dir1\dir2\dir3a dir1\dir2\dir3b ``` I'm trying to unzip it and maintain the directory structure however I get the error: ``` IOError: [Errno 2] No such file or directory: 'C:\\\projects\\\testFolder\\\subdir\\\unzip.exe' ``` where testFolder is...
**Don't** trust extract() or extractall(). These methods blindly extract files to the paths given in their filenames. But ZIP filenames can be anything at all, including dangerous strings like “x/../../../etc/passwd”. Extract such files and you could have just compromised your entire server. Maybe this should be ...
How can I remove text within parentheses with a regex?
640,001
33
2009-03-12T18:56:57Z
640,016
57
2009-03-12T18:59:43Z
[ "python", "regex", "perl" ]
I'm trying to handle a bunch of files, and I need to alter then to remove extraneous information in the filenames; notably, I'm trying to remove text inside parentheses. For example: ``` filename = "Example_file_(extra_descriptor).ext" ``` and I want to regex a whole bunch of files where the parenthetical expression ...
``` s/\([^)]*\)// ``` So in Python, you'd do: ``` re.sub(r'\([^)]*\)', '', filename) ```
How can I remove text within parentheses with a regex?
640,001
33
2009-03-12T18:56:57Z
640,054
15
2009-03-12T19:08:27Z
[ "python", "regex", "perl" ]
I'm trying to handle a bunch of files, and I need to alter then to remove extraneous information in the filenames; notably, I'm trying to remove text inside parentheses. For example: ``` filename = "Example_file_(extra_descriptor).ext" ``` and I want to regex a whole bunch of files where the parenthetical expression ...
I would use: ``` \([^)]*\) ```
What's the nearest equivalent of Beautiful Soup for Ruby?
640,068
11
2009-03-12T19:10:29Z
640,135
8
2009-03-12T19:25:16Z
[ "python", "ruby", "beautifulsoup" ]
I love the Beautiful Soup scraping library in Python. It just works. Is there a close equivalent in Ruby?
[Nokogiri](http://wiki.github.com/tenderlove/nokogiri) is another HTML/XML parser. It's faster than hpricot according to [these benchmarks](http://gist.github.com/18533). Nokogiri uses libxml2 and is a drop in replacement for hpricot. It also has css3 selector support which is pretty nice. Edit: There's a new benchmar...
Python introspection: How to get an 'unsorted' list of object attributes?
640,479
4
2009-03-12T21:04:56Z
640,638
8
2009-03-12T21:51:30Z
[ "python", "introspection", "python-datamodel" ]
The following code ``` import types class A: class D: pass class C: pass for d in dir(A): if type(eval('A.'+d)) is types.ClassType: print d ``` outputs ``` C D ``` How do I get it to output in the order in which these classes were defined in the code? I.e. ``` D C ``` Is there ...
Note that that parsing is already done for you in inspect - take a look at `inspect.findsource`, which searches the module for the class definition and returns the source and line number. Sorting on that line number (you may also need to split out classes defined in separate modules) should give the right order. Howev...
Writing to the serial port in Vista from Python
640,802
5
2009-03-12T22:49:56Z
640,832
9
2009-03-12T23:02:11Z
[ "python", "windows" ]
How do I write to the serial port in Vista from Python? The termios package only seem to support posix.
[pyserial](http://pyserial.wiki.sourceforge.net/pySerial) does the trick, you'll need [python extensions for windows](http://sourceforge.net/projects/pywin32/) for it to work in windows.
Writing to the serial port in Vista from Python
640,802
5
2009-03-12T22:49:56Z
641,193
7
2009-03-13T01:47:42Z
[ "python", "windows" ]
How do I write to the serial port in Vista from Python? The termios package only seem to support posix.
Seems like it wasn't any harder than this using [pyserial](http://pyserial.wiki.sourceforge.net/pySerial): ``` import serial ser = serial.Serial(0) # open first serial port with 9600,8,N,1 print ser.portstr # check which port was really used ser.write('hello') ser.close() ```
Can anyone point out the pros and cons of TG2 over Django?
640,877
8
2009-03-12T23:26:35Z
640,964
14
2009-03-13T00:06:44Z
[ "python", "django", "turbogears", "turbogears2" ]
Django is my favorite python web framework. I've tried out others like pylons, web2py, nevow and others. But I've never looked into TurboGears with much enthusiasm. Now with TG2 out of beta I may give it a try. I'd like to know what are some of the pros and cons compared to Django.
TG2 takes Pylons and changes some defaults - object dispatching instead of Routes, and Genshi instead of Mako. They believe [there's only one way to do it](http://wiki.python.org/moin/TOOWTDI), so apps can rely on the same API for any TurboGears website. ## Similarities * TG2 and Django both distinguish between websi...
Can anyone point out the pros and cons of TG2 over Django?
640,877
8
2009-03-12T23:26:35Z
703,311
15
2009-03-31T22:21:15Z
[ "python", "django", "turbogears", "turbogears2" ]
Django is my favorite python web framework. I've tried out others like pylons, web2py, nevow and others. But I've never looked into TurboGears with much enthusiasm. Now with TG2 out of beta I may give it a try. I'd like to know what are some of the pros and cons compared to Django.
TG2 has several advantages that I think are important: * Multi-database support * sharding/data partitioning support * longstanding support for aggregates, multi-column primary keys * a transaction system that handles multi-database transactions for you * an admin system that works with all of the above * out of the b...
Email integration
640,970
12
2009-03-13T00:09:14Z
641,004
7
2009-03-13T00:20:12Z
[ "python", "django", "email", "email-integration" ]
I was wondering if someone could help me out. In some web application, the app will send out emails, say when a new message has been posted. Then instead of signing into the application to post a reply you can just simply reply to the email and it will automatically update the web app with your response. My question i...
**Generally:** 1) Set up a dedicated email account for the purpose. 2) Have a programm monitor the mailbox (let's say fetchmail, since that's what I do). 3) When an email arrives at the account, fetchmail downloads the email, writes it to disk, and calls script or program you have written with the email file as an a...
How should I log while using multiprocessing in Python?
641,420
123
2009-03-13T04:02:31Z
641,488
40
2009-03-13T04:39:42Z
[ "python", "logging", "multiprocessing" ]
Right now I have a central module in a framework that spawns multiple processes using the Python 2.6 [`multiprocessing` module](http://docs.python.org/library/multiprocessing.html?#module-multiprocessing). Because it uses `multiprocessing`, there is module-level multiprocessing-aware log, `LOG = multiprocessing.get_log...
The only way to deal with this non-intrusively is to: 1. Spawn each worker process such that its log goes to **a different file descriptor** (to disk or to pipe.) Ideally, all log entries should be timestamped. 2. Your controller process can then do *one* of the following: * **If using disk files:** Coalesce the lo...
How should I log while using multiprocessing in Python?
641,420
123
2009-03-13T04:02:31Z
642,221
16
2009-03-13T11:19:29Z
[ "python", "logging", "multiprocessing" ]
Right now I have a central module in a framework that spawns multiple processes using the Python 2.6 [`multiprocessing` module](http://docs.python.org/library/multiprocessing.html?#module-multiprocessing). Because it uses `multiprocessing`, there is module-level multiprocessing-aware log, `LOG = multiprocessing.get_log...
Yet another alternative might be the various non-file-based logging handlers in the [`logging` package](http://docs.python.org/library/logging.html): * `SocketHandler` * `DatagramHandler` * `SyslogHandler` (and others) This way, you could easily have a logging daemon somewhere that you could write to safely and woul...
How should I log while using multiprocessing in Python?
641,420
123
2009-03-13T04:02:31Z
894,284
65
2009-05-21T18:10:33Z
[ "python", "logging", "multiprocessing" ]
Right now I have a central module in a framework that spawns multiple processes using the Python 2.6 [`multiprocessing` module](http://docs.python.org/library/multiprocessing.html?#module-multiprocessing). Because it uses `multiprocessing`, there is module-level multiprocessing-aware log, `LOG = multiprocessing.get_log...
I just now wrote a log handler of my own that just feeds everything to the parent process via a pipe. I've only been testing it for ten minutes but it seems to work pretty well. (**Note:** This is hardcoded to `RotatingFileHandler`, which is my own use case.) --- ## Update: Implementation! This now uses a queue for...
How should I log while using multiprocessing in Python?
641,420
123
2009-03-13T04:02:31Z
3,253,442
11
2010-07-15T07:41:56Z
[ "python", "logging", "multiprocessing" ]
Right now I have a central module in a framework that spawns multiple processes using the Python 2.6 [`multiprocessing` module](http://docs.python.org/library/multiprocessing.html?#module-multiprocessing). Because it uses `multiprocessing`, there is module-level multiprocessing-aware log, `LOG = multiprocessing.get_log...
A variant of the others that keeps the logging and queue thread separate. ``` """sample code for logging in subprocesses using multiprocessing * Little handler magic - The main process uses loggers and handlers as normal. * Only a simple handler is needed in the subprocess that feeds the queue. * Original logger name...
How should I log while using multiprocessing in Python?
641,420
123
2009-03-13T04:02:31Z
19,397,561
9
2013-10-16T07:31:34Z
[ "python", "logging", "multiprocessing" ]
Right now I have a central module in a framework that spawns multiple processes using the Python 2.6 [`multiprocessing` module](http://docs.python.org/library/multiprocessing.html?#module-multiprocessing). Because it uses `multiprocessing`, there is module-level multiprocessing-aware log, `LOG = multiprocessing.get_log...
All current solutions are too coupled to the logging configuration by using a handler. My solution has the following architecture and features: * You can use *any* logging configuration you want * Logging is done in a daemon thread * Safe shutdown of the daemon by using a context manager * Communication to the logging...
"Pythonic" equivalent for handling switch and multiple string compares
641,469
8
2009-03-13T04:31:55Z
641,485
31
2009-03-13T04:37:58Z
[ "conditional", "python" ]
Alright, so my title sucked. An example works better: ``` input = 'check yahoo.com' ``` I want to parse input, using the first word as the "command", and the rest of the string as a parameter. Here's the simple version of how my non-Pythonic mind is coding it: ``` if len(input) > 0: a = input.split(' ') if a...
``` dispatch = { 'check': do_check, 'search': do_search, } cmd, _, arg = input.partition(' ') if cmd in dispatch: dispatch[cmd](arg) else: do_default(cmd, arg) ```
Can 3D OpenGL game written in Python look good and run fast?
641,770
12
2009-03-13T07:48:58Z
641,832
17
2009-03-13T08:31:34Z
[ "python", "opengl" ]
I am planning to write an simple 3d(isometric view) game in Java using jMonkeyEngine - nothing to fancy, I just want to learn something about OpenGL and writing efficient algorithms (random map generating ones). When I was planning what to do, I started wondering about switching to Python. I know that Python didn't co...
If you are worried about 3D performance: Most of the performance-critical parts will be handled by OpenGL (in a C library or even in hardware), so the language you use to drive it should not matter too much. To really find out if performance is a problem, you'd have to try it. But there is no reason why it cannot work...
Can 3D OpenGL game written in Python look good and run fast?
641,770
12
2009-03-13T07:48:58Z
642,096
8
2009-03-13T10:25:30Z
[ "python", "opengl" ]
I am planning to write an simple 3d(isometric view) game in Java using jMonkeyEngine - nothing to fancy, I just want to learn something about OpenGL and writing efficient algorithms (random map generating ones). When I was planning what to do, I started wondering about switching to Python. I know that Python didn't co...
Yes. Eve Online does it. <http://support.eve-online.com/Pages/KB/Article.aspx?id=128>
Rename files, Python/Jython
641,985
5
2009-03-13T09:48:05Z
642,004
13
2009-03-13T09:58:43Z
[ "python", "file", "jython", "rename" ]
I have a directory full of files, some which have an ampersand in their names. I would like to rename all the files with ampersands and replace each ampersand with a plus (+). I am working with around 10k files. What would be the best method to do this?
``` import glob, os for filename in glob.glob(os.path.join(yourPath, "*&*")): os.rename(filename, filename.replace('&','+')) ```
Rename files, Python/Jython
641,985
5
2009-03-13T09:48:05Z
642,295
7
2009-03-13T11:42:25Z
[ "python", "file", "jython", "rename" ]
I have a directory full of files, some which have an ampersand in their names. I would like to rename all the files with ampersands and replace each ampersand with a plus (+). I am working with around 10k files. What would be the best method to do this?
If you have subdirectories: ``` import os for dirpath, dirs, files in os.walk(your_path): for filename in files: if '&' in filename: os.rename( os.path.join(dirpath, filename), os.path.join(dirpath, filename.replace('&', '+')) ) ```
How to convert strings into integers in Python?
642,154
211
2009-03-13T10:53:59Z
642,169
322
2009-03-13T10:58:42Z
[ "python", "string", "integer" ]
I have a tuple of tuples from a MySQL query like this: ``` T1 = (('13', '17', '18', '21', '32'), ('07', '11', '13', '14', '28'), ('01', '05', '06', '08', '15', '16')) ``` I'd like to convert all the string elements into integers and put it back nicely to list of lists this time: ``` T2 = [[13, 17, 18, 21...
[`int()`](https://docs.python.org/2/library/functions.html#int) is the Python standard built-in function to convert a string into an integer value. You call it with a string containing a number as the argument, and it returns the number converted to an actual integer: ``` print int("1") + 1 ``` The above prints `2`. ...
How to convert strings into integers in Python?
642,154
211
2009-03-13T10:53:59Z
642,177
21
2009-03-13T11:02:30Z
[ "python", "string", "integer" ]
I have a tuple of tuples from a MySQL query like this: ``` T1 = (('13', '17', '18', '21', '32'), ('07', '11', '13', '14', '28'), ('01', '05', '06', '08', '15', '16')) ``` I'd like to convert all the string elements into integers and put it back nicely to list of lists this time: ``` T2 = [[13, 17, 18, 21...
You can do this with a list comprehension: ``` T2 = [[int(column) for column in row] for row in T1] ``` The inner list comprehension (`[int(column) for column in row]`) builds a `list` of `int`s from a sequence of `int`-able objects, like decimal strings, in `row`. The outer list comprehension (`[... for row in T1])`...
How to convert strings into integers in Python?
642,154
211
2009-03-13T10:53:59Z
642,872
7
2009-03-13T14:05:10Z
[ "python", "string", "integer" ]
I have a tuple of tuples from a MySQL query like this: ``` T1 = (('13', '17', '18', '21', '32'), ('07', '11', '13', '14', '28'), ('01', '05', '06', '08', '15', '16')) ``` I'd like to convert all the string elements into integers and put it back nicely to list of lists this time: ``` T2 = [[13, 17, 18, 21...
I would agree with everyones answers so far but the problem is is that if you do not have all integers they will crash. If you wanted to exclude non-integers then ``` T1 = (('13', '17', '18', '21', '32'), ('07', '11', '13', '14', '28'), ('01', '05', '06', '08', '15', '16')) new_list = list(list(int(a) for...
How to convert strings into integers in Python?
642,154
211
2009-03-13T10:53:59Z
855,419
12
2009-05-12T23:33:41Z
[ "python", "string", "integer" ]
I have a tuple of tuples from a MySQL query like this: ``` T1 = (('13', '17', '18', '21', '32'), ('07', '11', '13', '14', '28'), ('01', '05', '06', '08', '15', '16')) ``` I'd like to convert all the string elements into integers and put it back nicely to list of lists this time: ``` T2 = [[13, 17, 18, 21...
I would rather prefer using only comprehension lists: ``` [[int(y) for y in x] for x in T1] ```
How to convert strings into integers in Python?
642,154
211
2009-03-13T10:53:59Z
5,426,537
9
2011-03-24T22:53:40Z
[ "python", "string", "integer" ]
I have a tuple of tuples from a MySQL query like this: ``` T1 = (('13', '17', '18', '21', '32'), ('07', '11', '13', '14', '28'), ('01', '05', '06', '08', '15', '16')) ``` I'd like to convert all the string elements into integers and put it back nicely to list of lists this time: ``` T2 = [[13, 17, 18, 21...
``` T3=[] for i in range(0,len(T1)): T3.append([]) for j in range(0,len(T1[i])): b=int(T1[i][j]) T3[i].append(b) print T3 ```
How do I format positional argument help using Python's optparse?
642,648
22
2009-03-13T13:16:56Z
643,797
8
2009-03-13T17:34:22Z
[ "python", "command-line", "formatting", "command-line-arguments", "optparse" ]
As mentioned in [the docs](http://docs.python.org/library/optparse.html?highlight=indentedhelpformatter#creating-the-parser) the `optparse.OptionParser` uses an `IndentedHelpFormatter` to output the formatted option help, for which which I found some [API documentation](http://corebio.googlecode.com/svn/tags/0.5.0/apid...
Try taking a look at [argparse](https://docs.python.org/3/library/argparse.html). Documentation says it supports position arguments and nicer looking help messages.
How do I format positional argument help using Python's optparse?
642,648
22
2009-03-13T13:16:56Z
664,614
19
2009-03-20T00:57:55Z
[ "python", "command-line", "formatting", "command-line-arguments", "optparse" ]
As mentioned in [the docs](http://docs.python.org/library/optparse.html?highlight=indentedhelpformatter#creating-the-parser) the `optparse.OptionParser` uses an `IndentedHelpFormatter` to output the formatted option help, for which which I found some [API documentation](http://corebio.googlecode.com/svn/tags/0.5.0/apid...
The best bet would be to write a patch to the optparse module. In the meantime, you can accomplish this with a slightly modified OptionParser class. This isn't perfect, but it'll get what you want done. ``` #!/usr/bin/env python from optparse import OptionParser, Option, IndentedHelpFormatter class PosOptionParser(Op...
Is it possible to replace a function/method decorator at runtime? [ python ]
642,762
13
2009-03-13T13:42:33Z
642,832
10
2009-03-13T13:55:56Z
[ "python", "runtime", "language-features", "decorator" ]
If I have a function : ``` @aDecorator def myfunc1(): # do something here if __name__ = "__main__": # this will call the function and will use the decorator @aDecorator myfunc1() # now I want the @aDecorator to be replaced with the decorator @otherDecorator # so that when this code executes, the function n...
As Miya mentioned, you can replace the decorator with another function any point before the interpreter gets to that function declaration. However, once the decorator is applied to the function, I don't think there is a way to dynamically replace the decorator with a different one. So for example: ``` @aDecorator def ...
Python - Intersection of two lists
642,763
271
2009-03-13T13:42:44Z
642,895
120
2009-03-13T14:11:13Z
[ "python", "list", "intersection" ]
I know how to get an intersection of two flat lists: ``` b1 = [1,2,3,4,5,9,11,15] b2 = [4,5,6,7,8] b3 = [val for val in b1 if val in b2] ``` or ``` def intersect(a, b): return list(set(a) & set(b)) print intersect(b1, b2) ``` But when I have to find intersection for nested lists then my problems starts: ``` c...
**If you want:** ``` c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63] c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]] c3 = [[13, 32], [7, 13, 28], [1,6]] ``` **Then here is your solution for Python 2:** ``` c3 = [filter(lambda x: x in c1, sublist) for sublist in c2] ``` **In Python 3 `filter` retur...
Python - Intersection of two lists
642,763
271
2009-03-13T13:42:44Z
642,919
549
2009-03-13T14:16:46Z
[ "python", "list", "intersection" ]
I know how to get an intersection of two flat lists: ``` b1 = [1,2,3,4,5,9,11,15] b2 = [4,5,6,7,8] b3 = [val for val in b1 if val in b2] ``` or ``` def intersect(a, b): return list(set(a) & set(b)) print intersect(b1, b2) ``` But when I have to find intersection for nested lists then my problems starts: ``` c...
You don't need to define intersection. It's already a first-class part of set. ``` >>> b1 = [1,2,3,4,5,9,11,15] >>> b2 = [4,5,6,7,8] >>> set(b1).intersection(b2) set([4, 5]) ```