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 When I catch an exception, how do I get the type, file, and line number?
1,278,705
115
2009-08-14T16:02:14Z
16,046,900
22
2013-04-16T20:55:32Z
[ "python", "exception", "exception-handling", "stack-trace" ]
Catching an exception that would print like this: ``` Traceback (most recent call last): File "c:/tmp.py", line 1, in <module> 4 / 0 ZeroDivisionError: integer division or modulo by zero ``` I want to format it into: ``` ZeroDivisonError, tmp.py, 1 ```
[Source](http://jserv.sayya.org/misc/use_source_luke.png) (Py v2.7.3) for [traceback.format\_exception()](http://hg.python.org/cpython/file/8dffb76faacc/Lib/traceback.py#l130) and called/related functions helps greatly. Embarrassingly, I always forget to [Read the Source](http://catb.org/jargon/html/U/UTSL.html). I onl...
How do I detect missing fields in a CSV file in a Pythonic way?
1,278,749
7
2009-08-14T16:10:36Z
1,278,792
13
2009-08-14T16:17:55Z
[ "python", "error-handling", "csv" ]
I'm trying to parse a CSV file using Python's `csv` module (specifically, the `DictReader` class). Is there a Pythonic way to detect empty or missing fields and throw an error? Here's a sample file using the following headers: NAME, LABEL, VALUE ``` foo,bar,baz yes,no x,y,z ``` When parsing, I'd like the second line...
``` if any(row[key] in (None, "") for key in row): # raise error ``` **Edit**: Even better: ``` if any(val in (None, "") for val in row.itervalues()): # raise error ```
Controlling Django ModelForm output
1,279,221
6
2009-08-14T17:49:06Z
1,279,291
9
2009-08-14T18:04:31Z
[ "python", "django", "django-templates", "django-forms" ]
I've got a Model in Django, example code below (not my actual code): ``` class Department(models.Model): name = models.CharField(max_length=100) abbreviation = models.CharField(max_length=4) ``` Let's say I do the following in the Django shell: ``` >>> Department(name='Computer Science',abbreviation='C S ')....
> How can I change the way these items are sorted in the ModelForm code, or in the Model code, rather than in the template? One thing you can do is add an [`ordering`](http://docs.djangoproject.com/en/dev/ref/models/options/#ordering) [meta option](http://docs.djangoproject.com/en/dev/ref/models/options/#ref-models-op...
Default route doesn't work
1,279,403
4
2009-08-14T18:27:52Z
1,280,099
9
2009-08-14T20:40:39Z
[ "python", "routes", "pylons" ]
I'm using the standard routing module with pylons to try and setup a default route for the home page of my website. I've followed the instructions in the docs and here <http://routes.groovie.org/recipes.html> but when I try `http://127.0.0.1:5000/` I just get the 'Welcome to Pylons' default page. My config/routing.py...
You have to delete the static page (myapp/public/index.html). Static files take priority due to the Cascade configuration at the end of middleware.py.
What is an ORM and where can I learn more about it?
1,279,613
64
2009-08-14T19:03:59Z
1,279,638
8
2009-08-14T19:08:40Z
[ "python", "orm" ]
Someone suggested I use an ORM for a project I'm designing but I'm having trouble finding information on what it is or how it works. Can anyone give me a brief explanation or a link as to where I can learn more about it?
An ORM (Object Relational Mapper) is a piece/layer of software that helps map your code Objects to your database. Some handle more aspects than others...but the purpose is to take some of the weight of the Data Layer off of the developer's shoulders. Here's a brief clip from Martin Fowler (Data Mapper): [Patterns of...
What is an ORM and where can I learn more about it?
1,279,613
64
2009-08-14T19:03:59Z
1,279,678
166
2009-08-14T19:17:15Z
[ "python", "orm" ]
Someone suggested I use an ORM for a project I'm designing but I'm having trouble finding information on what it is or how it works. Can anyone give me a brief explanation or a link as to where I can learn more about it?
## Introduction [Object-Relational Mapping](http://en.wikipedia.org/wiki/Object-relational_mapping) (ORM) is a technique that lets you query and manipulate data from a database using an object-oriented paradigm. When talking about ORM, most people are referring to a *library* that implements the Object-Relational Mapp...
What is an ORM and where can I learn more about it?
1,279,613
64
2009-08-14T19:03:59Z
1,280,345
17
2009-08-14T21:34:45Z
[ "python", "orm" ]
Someone suggested I use an ORM for a project I'm designing but I'm having trouble finding information on what it is or how it works. Can anyone give me a brief explanation or a link as to where I can learn more about it?
> *Can anyone give me a brief explanation...* Sure. ORM stands for "Object to Relational Mapping" where * The **Object** part is the one you use with your programming language ( python in this case ) * The **Relational** part is a Relational Database Manager System ( A database that is ) there are other types of dat...
remove duplicates from nested dictionaries in list
1,279,805
4
2009-08-14T19:41:26Z
1,280,217
7
2009-08-14T21:03:26Z
[ "python", "dictionary" ]
quick and very basic newbie question. If i have list of dictionaries looking like this: ``` L = [] L.append({"value1": value1, "value2": value2, "value3": value3, "value4": value4}) ``` Let's say there exists multiple entries where value3 and value4 are identical to other nested dictionaries. How can i quick and eas...
Here's one way: ``` keyfunc = lambda d: (d['value3'], d['value4']) from itertools import groupby giter = groupby(sorted(L, key=keyfunc), keyfunc) L2 = [g[1].next() for g in giter] print L2 ```
wxPython: Items in BoxSizer don't expand horizontally, only vertically
1,280,600
9
2009-08-14T23:02:25Z
1,281,041
23
2009-08-15T03:12:03Z
[ "python", "wxpython", "wxwidgets" ]
I have several buttons in various sizers and they expand in the way that I want them to. However, when I add the parent to a new wx.BoxSizer that is used to add a border around all the elements in the frame, the sizer that has been added functions correctly vertically, but not horizontally. The following code demonstr...
First of all, you're passing some flags incorrectly. BoxSizer takes wx.HORIZONTAL or wx.VERTICAL, not wx.EXPAND. sizer.Add does not take wx.HORIZONTAL. If you have a VERTICAL BoxSizer, wx.EXPAND will make the control fill horizontally, while a proportion of 1 or more (second argument to Add) will make the control fill...
In python is there an easier way to write 6 nested for loops?
1,280,667
30
2009-08-14T23:31:40Z
1,280,677
7
2009-08-14T23:36:03Z
[ "python", "for-loop", "nested-loops" ]
This problem has been getting at me for a while now. Is there an easier way to write nested `for` loops in python? For example if my code went something like this: ``` for y in range(3): for x in range(3): do_something() for y1 in range(3): for x1 in range(3): do_something_else() ``...
When faced with that sort of program logic, I would probably break up the sequence of loops into two or more separate functions. Another technique in Python is to use [list comprehensions](http://docs.python.org/tutorial/datastructures.html#list-comprehensions) where possible, instead of a loop.
In python is there an easier way to write 6 nested for loops?
1,280,667
30
2009-08-14T23:31:40Z
1,280,724
49
2009-08-14T23:51:35Z
[ "python", "for-loop", "nested-loops" ]
This problem has been getting at me for a while now. Is there an easier way to write nested `for` loops in python? For example if my code went something like this: ``` for y in range(3): for x in range(3): do_something() for y1 in range(3): for x1 in range(3): do_something_else() ``...
If you're frequently iterating over a Cartesian product like in your example, you might want to investigate [Python 2.6's itertools.product](http://docs.python.org/library/itertools.html#itertools.product) -- or write your own if you're in an earlier Python. ``` from itertools import product for y, x in product(range(...
In python is there an easier way to write 6 nested for loops?
1,280,667
30
2009-08-14T23:31:40Z
1,280,730
10
2009-08-14T23:53:34Z
[ "python", "for-loop", "nested-loops" ]
This problem has been getting at me for a while now. Is there an easier way to write nested `for` loops in python? For example if my code went something like this: ``` for y in range(3): for x in range(3): do_something() for y1 in range(3): for x1 in range(3): do_something_else() ``...
This is fairly common when looping over multidimensional spaces. My solution is: ``` xy_grid = [(x, y) for x in range(3) for y in range(3)] for x, y in xy_grid: # do something for x1, y1 in xy_grid: # do something else ```
How can I list the methods in a Python 2.5 module?
1,280,787
19
2009-08-15T00:13:02Z
1,280,800
43
2009-08-15T00:17:51Z
[ "python", "introspection", "python-2.5" ]
I'm trying to use a Python library written in C that has no documentation of any kind. I want to use introspection to at least see what methods and classes are in the modules. Does somebody have a function or library I can use to list the functions (with argument lists) and classes (with methods and member variables) w...
Here are some things you can do at least: ``` import module print dir(module) # Find functions of interest. # For each function of interest: help(module.interesting_function) print module.interesting_function.func_defaults ```
How can I list the methods in a Python 2.5 module?
1,280,787
19
2009-08-15T00:13:02Z
1,280,846
12
2009-08-15T00:44:24Z
[ "python", "introspection", "python-2.5" ]
I'm trying to use a Python library written in C that has no documentation of any kind. I want to use introspection to at least see what methods and classes are in the modules. Does somebody have a function or library I can use to list the functions (with argument lists) and classes (with methods and member variables) w...
Mark Pilgrim's [chapter 4](http://diveintopython.net/power_of_introspection/index.html), which you mention, does actually apply just fine to Python 2.5 (and any other recent `2.*` version, thanks to backwards compatibility). Mark doesn't mention `help`, but I see other answers do. One key bit that nobody (including Ma...
What's the Ruby equivalent of Python's os.walk?
1,281,090
20
2009-08-15T03:40:16Z
1,281,103
20
2009-08-15T03:51:30Z
[ "python", "ruby" ]
Does anyone know if there's an existing module/function inside Ruby to traverse file system directories and files? I'm looking for something similar to Python's `os.walk`. The closest module I've found is `Find` but requires some extra work to do the traversal. The Python code looks like the following: ``` for root, ...
The following will print all files recursively. Then you can use File.directory? to see if the it is a directory or a file. ``` Dir['**/*'].each { |f| print f } ```
What's the Ruby equivalent of Python's os.walk?
1,281,090
20
2009-08-15T03:40:16Z
1,281,222
8
2009-08-15T05:17:15Z
[ "python", "ruby" ]
Does anyone know if there's an existing module/function inside Ruby to traverse file system directories and files? I'm looking for something similar to Python's `os.walk`. The closest module I've found is `Find` but requires some extra work to do the traversal. The Python code looks like the following: ``` for root, ...
[Find](http://www.ruby-doc.org/stdlib-2.0/libdoc/find/rdoc/Find.html) seems pretty simple to me: ``` require "find" Find.find('mydir'){|f| puts f} ```
Why can't I set a global variable in Python?
1,281,184
17
2009-08-15T04:49:48Z
1,281,186
43
2009-08-15T04:50:57Z
[ "python", "global-variables" ]
How do global variables work in Python? I know global variables are evil, I'm just experimenting. This does not work in python: ``` G = None def foo(): if G is None: G = 1 foo() ``` I get an error: ``` UnboundLocalError: local variable 'G' referenced before assignment ``` What am I doing wrong?
You need the [`global`](http://www.python.org/doc/ref/global.html) statement: ``` def foo(): global G if G is None: G = 1 ``` In Python, variables *that you assign to* become local variables by default. You need to use `global` to declare them as global variables. On the other hand, variables that you...
How to get the desktop resolution in Mac via Python?
1,281,397
5
2009-08-15T07:35:13Z
1,281,659
10
2009-08-15T11:07:52Z
[ "python", "osx" ]
Trying to write a python application that downloads images from an RSS feed, and makes a composite background. How do I get the current desktop resolution on Mac OS X (leopard?)
With Pyobjc something like this should work. Pyobjc comes with Leopard. ``` from AppKit import NSScreen print NSScreen.mainScreen().frame() ``` With that, you can also grab the width and height. ``` NSScreen.mainScreen().frame().width NSScreen.mainScreen().frame().height ```
Accessing elements with offsets in Python's for .. in loops
1,281,752
7
2009-08-15T12:00:36Z
1,281,758
13
2009-08-15T12:03:33Z
[ "python", "loops" ]
I've been mucking around a bit with Python, and I've gathered that it's usually better (or 'pythonic') to use ``` for x in SomeArray: ``` rather than the more C-style ``` for i in range(0, len(SomeArray)): ``` I do see the benefits in this, mainly cleaner code, and the ability to use the nice `map()` and related fu...
The way to do this in Python is: ``` for i, x in enumerate(SomeArray): print i, x ``` The [`enumerate`](http://docs.python.org/library/functions.html#enumerate) generator produces a sequence of 2-tuples, each containing the array index and the element.
Making sure that psycopg2 database connection alive
1,281,875
7
2009-08-15T13:17:09Z
1,282,019
8
2009-08-15T14:36:08Z
[ "python", "database", "connection", "psycopg2" ]
I have a python application that opens a database connection that can hang online for an hours, but sometimes the database server reboots and while python still have the connection it won't work with `OperationalError` exception. So I'm looking for any reliable method to "ping" the database and know that connection is...
`pg_connection_status` is implemented using PQstatus. psycopg doesn't expose that API, so the check is not available. The only two places psycopg calls PQstatus itself is when a new connection is made, and at the beginning of execute. So yes, you will need to issue a simple SQL statement to find out whether the connect...
Making sure that psycopg2 database connection alive
1,281,875
7
2009-08-15T13:17:09Z
18,708,605
13
2013-09-09T23:29:24Z
[ "python", "database", "connection", "psycopg2" ]
I have a python application that opens a database connection that can hang online for an hours, but sometimes the database server reboots and while python still have the connection it won't work with `OperationalError` exception. So I'm looking for any reliable method to "ping" the database and know that connection is...
This question is really old, but still pops up on Google searches so I think it's valuable to know that the `psycopg2.connection` instance now has a [`closed` attribute](http://initd.org/psycopg/docs/connection.html#connection.closed) that will be `0` when the connection is open, and greater than zero when the connecti...
Python integer division yields float
1,282,945
101
2009-08-15T21:48:39Z
1,282,948
32
2009-08-15T21:50:14Z
[ "python", "integer", "python-3.x", "division" ]
``` Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> 2/2 1.0 ``` Is this intended? I strongly remember earlier versions returning `int/int=int`? What should I do, is there a new division operator or must I alwa...
Oops, immediately found `2//2`.
Python integer division yields float
1,282,945
101
2009-08-15T21:48:39Z
1,282,954
142
2009-08-15T21:51:44Z
[ "python", "integer", "python-3.x", "division" ]
``` Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> 2/2 1.0 ``` Is this intended? I strongly remember earlier versions returning `int/int=int`? What should I do, is there a new division operator or must I alwa...
Take a look at [PEP-238](http://www.python.org/dev/peps/pep-0238/): Changing the Division Operator > The // operator will be available to request floor division unambiguously.
Programmatically change font color of text in PDF
1,283,065
7
2009-08-15T22:52:13Z
1,283,166
11
2009-08-16T00:07:21Z
[ "python", "pdf", "fonts" ]
I'm not familiar with the PDF specification at all. I was wondering if it's possible to directly manipulate a PDF file so that certain blocks of text that I've identified as important are highlighted in colors of my choice. Language of choice would be python.
It's possible, but not necessarily easy, because the PDF format is so rich. You can find a document describing it in detail [here](http://www.adobe.com/devnet/acrobat/pdfs/PDF32000%5F2008.pdf). The first elementary example it gives about how PDFs display text is: ``` BT /F13 12 Tf 288 720 Td (ABC) Tj ET ``` BT and ET...
A python based PowerShell?
1,283,198
9
2009-08-16T00:35:10Z
1,283,300
10
2009-08-16T01:48:06Z
[ "python", "bash", "powershell" ]
I just took a brief look at PowerShell (I knew it as Monad shell). My ignorant eyes see it more or less like a hybrid between regular bash and python. I would consider such integration between the two environments very cool on linux and osx, so I was wondering if it already exists (ipython is not really the same), and ...
I've only dabbled in Powershell, but what distinguishes it for me is the ability to pipe actual objects in the shell. In that respect, the closest I've found is actually using the IPython shell with `ipipe`: * [Using ipipe](http://wiki.ipython.org/Using_ipipe) * [Adding support for ipipe](http://wiki.ipython.org/Cookb...
Python get wrong value for os.environ["ProgramFiles"] on 64bit vista
1,283,664
3
2009-08-16T07:11:16Z
1,283,667
11
2009-08-16T07:14:12Z
[ "python", "windows", "64bit" ]
Python 2.4.3 on a Vista64 machine. The following 2 variables are in the environment: ``` ProgramFiles=C:\Program Files ProgramFiles(x86)=C:\Program Files (x86) ``` But when I run the following ``` import os print os.environ["ProgramFiles"] print os.environ["ProgramFiles(x86)"] ``` I get: ``` C:\Program Files (x86...
From the [Wikipedia page](http://en.wikipedia.org/wiki/Environment%5Fvariable#Examples%5Ffrom%5FMicrosoft%5FWindows): > %ProgramFiles% > > This variable points to Program Files directory, which stores all the installed program of Windows and others. The default on English-language systems is C:\Program Files. In 64-bi...
Python - Use a Regex to Filter Data
1,284,789
4
2009-08-16T17:08:16Z
1,284,802
13
2009-08-16T17:13:31Z
[ "python", "regex" ]
Is there a simple way to remove all characters from a given string that match a given regular expression? I know in Ruby I can use `gsub`: ``` >> key = "cd baz ; ls -l" => "cd baz ; ls -l" >> newkey = key.gsub(/[^\w\d]/, "") => "cdbazlsl" ``` What would the equivalent function be in Python?
``` import re re.sub(pattern, '', s) ``` [Docs](http://docs.python.org/library/re.html#re.sub)
How can I check to see if a Python script was started interactively?
1,285,024
2
2009-08-16T18:48:54Z
1,285,045
7
2009-08-16T18:53:11Z
[ "python", "interactive" ]
I'd like for a script of mine to have 2 behaviours, one when started as a scheduled task, and another if started manually. How could I test for interactiveness? EDIT: this could either be a cron job, or started by a windows batch file, through the scheduled tasks.
If you want to know if you're reading from a terminal (not clear if that is enough of a distinction, please clarify) you can use ``` sys.stdin.isatty() ```
How can I check to see if a Python script was started interactively?
1,285,024
2
2009-08-16T18:48:54Z
1,285,056
11
2009-08-16T18:55:54Z
[ "python", "interactive" ]
I'd like for a script of mine to have 2 behaviours, one when started as a scheduled task, and another if started manually. How could I test for interactiveness? EDIT: this could either be a cron job, or started by a windows batch file, through the scheduled tasks.
You should simply add a command-line switch in the scheduled task, and check for it in your script, modifying the behavior as appropriate. Explicit is better than implicit. One benefit to this design: you'll be able to test both behaviors, regardless of how you actually invoked the script.
Implement Comet / Server push in Google App Engine in Python
1,285,150
25
2009-08-16T19:34:16Z
2,870,191
69
2010-05-19T23:43:54Z
[ "python", "google-app-engine", "comet", "server-push", "channel-api" ]
How can I implement Comet / Server push in Google App Engine in Python?
We just announced the Channel API to do comet push with App Engine apps: <http://googleappengine.blogspot.com/2010/05/app-engine-at-google-io-2010.html> If you're at Google IO, I'll be talking about this at 1pm tomorrow (on the APIs track): <http://code.google.com/events/io/2010/sessions/building-real-time-apps-app-en...
How does one make logging color in Django/Google App Engine?
1,285,372
11
2009-08-16T21:20:08Z
16,349,987
13
2013-05-03T00:53:38Z
[ "python", "django", "google-app-engine", "logging", "colors" ]
If one iswriting a Django/ Google App Engine application and would like to have logs that are conveniently conspicuous based on color (i.e. errors in red), how does one set that up? I've copied the helpful solution from [this question](http://stackoverflow.com/questions/384076/how-can-i-make-the-python-logging-output-...
We use [colorlog](https://pypi.python.org/pypi/colorlog) and it does exactly what you expect. For posterity, the formatter config we use is: ``` 'color': { '()': 'colorlog.ColoredFormatter', 'format': '%(log_color)s%(levelname)-8s %(message)s', 'log_colors': { 'DEBUG': 'bold_black', 'IN...
Python filter a list to only leave objects that occur once
1,285,468
5
2009-08-16T22:13:05Z
1,285,475
12
2009-08-16T22:16:56Z
[ "python", "list", "filter" ]
I would like to filter this list, l = [0,1,1,2,2] to only leave, [0]. I'm struggling to do it in a 'pythonic' way :o) Is it possible without nested loops?
You'll need two loops (or equivalently a loop and a listcomp, like below), but not nested ones: ``` import collections d = collections.defaultdict(int) for x in L: d[x] += 1 L[:] = [x for x in L if d[x] == 1] ``` This solution assumes that the list items are *hashable*, that is, that they're usable as indices into di...
Python filter a list to only leave objects that occur once
1,285,468
5
2009-08-16T22:13:05Z
1,285,482
8
2009-08-16T22:18:33Z
[ "python", "list", "filter" ]
I would like to filter this list, l = [0,1,1,2,2] to only leave, [0]. I'm struggling to do it in a 'pythonic' way :o) Is it possible without nested loops?
``` [x for x in the_list if the_list.count(x)==1] ``` Though that's still a nested loop behind the scenes.
Using Python Mechanize like "Tamper Data"
1,285,895
3
2009-08-17T02:05:02Z
1,286,047
7
2009-08-17T03:33:46Z
[ "python", "forms", "mechanize", "tampering" ]
I'm writing a web testing script with python (2.6) and mechanize (0.1.11). The page I'm working with has an html form with a select field like this: ``` <select name="field1" size="1"> <option value="A" selected>A</option> <option value="B">B</option> <option value="C">C</option> <option value="D">D</o...
After poking around with the guts of ClientForm, it looks like you can trick it into adding another item. For a select field, something like this seems to work: ``` xitem = ClientForm.Item(browser.form.find_control(name="field1"), {'contents':'E', 'value':'E', 'label':'E'}) ``` Similarly, for a radio button...
python: How do I check that multiple keys are in a dict in one go?
1,285,911
101
2009-08-17T02:12:35Z
1,285,919
8
2009-08-17T02:17:41Z
[ "python", "dictionary" ]
I want to do something like: ``` foo = {'foo':1,'zip':2,'zam':3,'bar':4} if ("foo","bar") in foo: #do stuff ``` I'm not sure if its possible but would like to know. :-)
How about this: ``` if all(key in foo for key in ["foo","bar"]): # do stuff pass ```
python: How do I check that multiple keys are in a dict in one go?
1,285,911
101
2009-08-17T02:12:35Z
1,285,920
174
2009-08-17T02:18:15Z
[ "python", "dictionary" ]
I want to do something like: ``` foo = {'foo':1,'zip':2,'zam':3,'bar':4} if ("foo","bar") in foo: #do stuff ``` I'm not sure if its possible but would like to know. :-)
Well, you could do this: ``` >>> if all (k in foo for k in ("foo","bar")): ... print "They're there!" ... They're there! ```
python: How do I check that multiple keys are in a dict in one go?
1,285,911
101
2009-08-17T02:12:35Z
1,285,926
67
2009-08-17T02:22:13Z
[ "python", "dictionary" ]
I want to do something like: ``` foo = {'foo':1,'zip':2,'zam':3,'bar':4} if ("foo","bar") in foo: #do stuff ``` I'm not sure if its possible but would like to know. :-)
``` if set(("foo", "bar")) <= set(myDict): ... ```
python: How do I check that multiple keys are in a dict in one go?
1,285,911
101
2009-08-17T02:12:35Z
1,285,930
17
2009-08-17T02:25:15Z
[ "python", "dictionary" ]
I want to do something like: ``` foo = {'foo':1,'zip':2,'zam':3,'bar':4} if ("foo","bar") in foo: #do stuff ``` I'm not sure if its possible but would like to know. :-)
Using **[sets](http://docs.python.org/library/stdtypes.html#set-types-set-frozenset)**: ``` if set(("foo", "bar")).issubset(foo): #do stuff ``` Alternatively: ``` if set(("foo", "bar")) <= set(foo): #do stuff ```
python: How do I check that multiple keys are in a dict in one go?
1,285,911
101
2009-08-17T02:12:35Z
1,552,005
23
2009-10-11T22:51:48Z
[ "python", "dictionary" ]
I want to do something like: ``` foo = {'foo':1,'zip':2,'zam':3,'bar':4} if ("foo","bar") in foo: #do stuff ``` I'm not sure if its possible but would like to know. :-)
## Simple benchmarking rig for 3 of the alternatives. Put in your own values for D and Q ``` >>> from timeit import Timer >>> setup='''from random import randint as R;d=dict((str(R(0,1000000)),R(0,1000000)) for i in range(D));q=dict((str(R(0,1000000)),R(0,1000000)) for i in range(Q));print("looking for %s items in %s...
python: How do I check that multiple keys are in a dict in one go?
1,285,911
101
2009-08-17T02:12:35Z
25,458,648
10
2014-08-23T05:06:54Z
[ "python", "dictionary" ]
I want to do something like: ``` foo = {'foo':1,'zip':2,'zam':3,'bar':4} if ("foo","bar") in foo: #do stuff ``` I'm not sure if its possible but would like to know. :-)
You don't have to wrap the left side in a set. You can just do this: ``` if {'foo', 'bar'} <= set(some_dict): pass ``` This also performs better than the `all(k in d...)` solution.
Is the order of results coming from a list comprehension guaranteed?
1,286,167
14
2009-08-17T04:33:24Z
1,286,180
20
2009-08-17T04:40:01Z
[ "python", "list-comprehension" ]
When using a list comprehension, is the order of the new list guaranteed in any way? As a contrived example, is the following behavior guaranteed by the definition of a list comprehension: ``` >> a = [x for x in [1,2,3]] >> a [1, 2, 3] ``` Equally, is the following equality guaranteed: ``` >> lroot = [1, 2, 3] >> la...
Yes, the list comprehension preserves the order of the original iterable (if there is one). If the original iterable is ordered (list, tuple, file, etc.), that's the order you'll get in the result. If your iterable is unordered (set, dict, etc.), there are no guarantees about the order of the items.
Where can i get technical information on how the internals of Django works?
1,286,176
6
2009-08-17T04:38:12Z
1,286,186
8
2009-08-17T04:42:23Z
[ "python", "django" ]
Where can i get the technical manuals/details of how django internals work, i.e. i would like to know when a request comes in from a client; * which django function receives it? * what middleware get called? * how is the request object created? and what class/function creates it? * What function maps the request to th...
"Use the source, Luke." The beauty of open source software is that you can view (and modify) the code yourself.
Where can i get technical information on how the internals of Django works?
1,286,176
6
2009-08-17T04:38:12Z
1,286,241
10
2009-08-17T05:09:40Z
[ "python", "django" ]
Where can i get the technical manuals/details of how django internals work, i.e. i would like to know when a request comes in from a client; * which django function receives it? * what middleware get called? * how is the request object created? and what class/function creates it? * What function maps the request to th...
Besides reading the source, here's a few articles I've tagged and bookmarked from a little while ago: * [How Django processes a request](http://www.b-list.org/weblog/2006/jun/13/how-django-processes-request/) * [Django Request Response processing](http://uswaretech.com/blog/2009/06/django-request-response-processing/)...
Where can i get technical information on how the internals of Django works?
1,286,176
6
2009-08-17T04:38:12Z
1,287,116
8
2009-08-17T09:57:49Z
[ "python", "django" ]
Where can i get the technical manuals/details of how django internals work, i.e. i would like to know when a request comes in from a client; * which django function receives it? * what middleware get called? * how is the request object created? and what class/function creates it? * What function maps the request to th...
Easiest way to understand the internals of django, is by reading a book specifically written for that. Read [Pro Django](http://rads.stackoverflow.com/amzn/click/1430210478). It provides you a good in depth understanding of the meta programming first and demonstrates how it is used in django models, to create them dyn...
Using the Python NLTK (2.0b5) on the Google App Engine
1,286,301
17
2009-08-17T05:36:55Z
1,287,150
8
2009-08-17T10:08:31Z
[ "python", "google-app-engine", "nlp", "nltk" ]
I have been trying to make the NLTK (Natural Language Toolkit) work on the Google App Engine. The steps I followed are: 1. Download the installer and run it (a .dmg file, as I am using a Mac). 2. copy the nltk folder out of the python site-packages directory and place it as a sub-folder in my project folder. 3. Create...
[oakmad](http://groups.google.com/group/nltk-users/browse%5Fthread/thread/95db3032ccca7ab8/) has managed to successfully work through deploying **SEVERAL** NLTK modules to GAE. Hope this helps. But , but be honest, I still don't think it's true even after read the post.
Django - String to Date - Date to UNIX Timestamp
1,286,619
4
2009-08-17T07:42:58Z
1,286,817
12
2009-08-17T08:40:40Z
[ "python", "django" ]
I need to convert a date from a string (entered into a url) in the form of 12/09/2008-12:40:49. Obviously, I'll need a UNIX Timestamp at the end of it, but before I get that I need the Date object first. How do I do this? I can't find any resources that show the date in that format? Thank you.
You need the `strptime` method. If you're on Python 2.5 or higher, this is a method on `datetime`, otherwise you have to use a combination of the `time` and `datetime` modules to achieve this. Python 2.5 up: ``` from datetime import datetime dt = datetime.strptime(s, "%d/%m/%Y-%H:%M:%S") ``` below 2.5: ``` from dat...
how fast is python's slice
1,286,757
8
2009-08-17T08:24:06Z
1,286,777
7
2009-08-17T08:29:08Z
[ "python", "optimization" ]
In order to save space and the complexity of having to maintain the consistency of data between different sources, I'm considering storing start/end indices for some substrings instead of storing the substrings themselves. The trick is that if I do so, it's possible I'll be creating slices ALL the time. Is this somethi...
1. Fast enough as opposed to what? How do you do it right now? What exactly are you storing, what exactly are you retrieving? The answer probably highly depends on this. Which brings us to ... 2. Measure! Don't discuss and analyze theoretically; try and measure what is the more performant way. Then decide whether the p...
Python SIP library
1,286,875
19
2009-08-17T08:55:21Z
1,286,973
10
2009-08-17T09:22:48Z
[ "python", "voip", "sip", "trixbox" ]
I need to write python application connect to trixbox that run as SIP server. But I not found any library that implement in python. I found SIP SKD at <http://www.vaxvoip.com/> but it not support python. Can anyone suggest me an alternative to VaxVoip? Thank you.
There are [Python bindings](http://trac.pjsip.org/repos/wiki/Python_SIP_Tutorial) for the PJSUA API.
Python SIP library
1,286,875
19
2009-08-17T08:55:21Z
1,380,887
12
2009-09-04T18:41:55Z
[ "python", "voip", "sip", "trixbox" ]
I need to write python application connect to trixbox that run as SIP server. But I not found any library that implement in python. I found SIP SKD at <http://www.vaxvoip.com/> but it not support python. Can anyone suggest me an alternative to VaxVoip? Thank you.
[Twisted](http://twistedmatrix.com/trac/) supports SIP. That's really cool
Python SIP library
1,286,875
19
2009-08-17T08:55:21Z
1,761,507
8
2009-11-19T07:27:55Z
[ "python", "voip", "sip", "trixbox" ]
I need to write python application connect to trixbox that run as SIP server. But I not found any library that implement in python. I found SIP SKD at <http://www.vaxvoip.com/> but it not support python. Can anyone suggest me an alternative to VaxVoip? Thank you.
You might want to have a look at [Sippy](http://www.b2bua.org/). It's a B2BUA with a complete SIP stack implementation underneath (you could use just that). It's written entirely in Python, so it's pretty hackable. Sippy is implemented with Twisted but uses none of its SIP functionality.
'datetime.time' has no 'mktime'
1,287,598
6
2009-08-17T12:08:48Z
1,287,629
18
2009-08-17T12:17:10Z
[ "python", "datetime" ]
I'm trying to convert a datetime object to a UNIX timestamp (preferably in milliseconds, though I wouldn't mind with and without). Mktime seems to be the method that usually gets it, however I keep getting the error: AttributeError: type object 'datetime.time' has no attribute 'mktime'. Can anyone tell me what I'm d...
I think you have done ``` from datetime import datetime, time ``` instead of ``` import time from datetime import datetime ``` so that the object called `time` is actually coming from the datetime module, not the time module.
Using the same decorator (with arguments) with functions and methods
1,288,498
11
2009-08-17T15:08:12Z
1,288,936
9
2009-08-17T16:15:33Z
[ "python", "function", "methods", "arguments", "decorator" ]
I have been trying to create a decorator that can be used with both functions and methods in python. This on it's own is not that hard, but when creating a decorator that takes arguments, it seems to be. ``` class methods(object): def __init__(self, *_methods): self.methods = _methods def __call__(sel...
To expand on the `__get__` approach. This can be generalized into a decorator decorator. ``` class _MethodDecoratorAdaptor(object): def __init__(self, decorator, func): self.decorator = decorator self.func = func def __call__(self, *args, **kwargs): return self.decorator(self.func)(*arg...
python multiprocessing vs threading for cpu bound work on windows and linux
1,289,813
25
2009-08-17T19:04:58Z
1,289,849
12
2009-08-17T19:13:25Z
[ "python", "multiprocessing" ]
So I knocked up some test code to see how the multiprocessing module would scale on cpu bound work compared to threading. On linux I get the performance increase that I'd expect: ``` linux (dual quad core xeon): serialrun took 1192.319 ms parallelrun took 346.727 ms threadedrun took 2108.172 ms ``` My dual core macbo...
Processes are much more lightweight under UNIX variants. Windows processes are heavy and take much more time to start up. Threads are the recommended way of doing multiprocessing on windows.
python multiprocessing vs threading for cpu bound work on windows and linux
1,289,813
25
2009-08-17T19:04:58Z
1,289,875
23
2009-08-17T19:20:24Z
[ "python", "multiprocessing" ]
So I knocked up some test code to see how the multiprocessing module would scale on cpu bound work compared to threading. On linux I get the performance increase that I'd expect: ``` linux (dual quad core xeon): serialrun took 1192.319 ms parallelrun took 346.727 ms threadedrun took 2108.172 ms ``` My dual core macbo...
The [python documentation for multiprocessing](http://docs.python.org/library/multiprocessing.html) blames the lack of os.fork() for the problems in Windows. It may be applicable here. See what happens when you import psyco. First, easy\_install it: ``` C:\Users\hughdbrown>\Python26\scripts\easy_install.exe psyco Sea...
How do I mock an open used in a with statement (using the Mock framework in Python)?
1,289,894
80
2009-08-17T19:26:50Z
3,268,310
27
2010-07-16T19:42:53Z
[ "python", "mocking", "with-statement" ]
How do I test the following code with mocks (using mocks, the patch decorator and sentinels provided by [Michael Foord's Mock framework](http://www.voidspace.org.uk/python/mock/)): ``` def testme(filepath): with open(filepath, 'r') as f: return f.read() ```
Updated Daryl's answer to fix changes to Mock class. ``` @patch('__builtin__.open') def test_testme(self, open_mock): # # setup # context_manager_mock = Mock() open_mock.return_value = context_manager_mock file_mock = Mock() file_mock.read.return_value = sentinel.file_contents enter_moc...
How do I mock an open used in a with statement (using the Mock framework in Python)?
1,289,894
80
2009-08-17T19:26:50Z
6,112,456
89
2011-05-24T14:56:44Z
[ "python", "mocking", "with-statement" ]
How do I test the following code with mocks (using mocks, the patch decorator and sentinels provided by [Michael Foord's Mock framework](http://www.voidspace.org.uk/python/mock/)): ``` def testme(filepath): with open(filepath, 'r') as f: return f.read() ```
The way to do this has changed in mock 0.7.0 which finally supports mocking the python protocol methods (magic methods), particularly using the MagicMock: <http://www.voidspace.org.uk/python/mock/magicmock.html> An example of mocking open as a context manager (from the examples page in the mock documentation): ``` >...
How do I mock an open used in a with statement (using the Mock framework in Python)?
1,289,894
80
2009-08-17T19:26:50Z
19,146,253
45
2013-10-02T20:28:51Z
[ "python", "mocking", "with-statement" ]
How do I test the following code with mocks (using mocks, the patch decorator and sentinels provided by [Michael Foord's Mock framework](http://www.voidspace.org.uk/python/mock/)): ``` def testme(filepath): with open(filepath, 'r') as f: return f.read() ```
With the latest versions of mock, you can use the really useful [mock\_open](http://www.voidspace.org.uk/python/mock/helpers.html#mock-open) helper: > **mock\_open(mock=None, read\_data=None)** > > A helper function to create a > mock to replace the use of open. It works for open called directly or > used as a context...
How do I mock an open used in a with statement (using the Mock framework in Python)?
1,289,894
80
2009-08-17T19:26:50Z
27,429,755
7
2014-12-11T18:19:22Z
[ "python", "mocking", "with-statement" ]
How do I test the following code with mocks (using mocks, the patch decorator and sentinels provided by [Michael Foord's Mock framework](http://www.voidspace.org.uk/python/mock/)): ``` def testme(filepath): with open(filepath, 'r') as f: return f.read() ```
To use [mock\_open](https://docs.python.org/3.3/library/unittest.mock.html#mock-open) for a simple file `read()` (the original mock\_open snippet [already given on this page](http://stackoverflow.com/a/19146253/552793) is geared more for write): ``` my_text = "some text to return when read() is called on the file obje...
How do I mock an open used in a with statement (using the Mock framework in Python)?
1,289,894
80
2009-08-17T19:26:50Z
34,677,735
19
2016-01-08T13:00:13Z
[ "python", "mocking", "with-statement" ]
How do I test the following code with mocks (using mocks, the patch decorator and sentinels provided by [Michael Foord's Mock framework](http://www.voidspace.org.uk/python/mock/)): ``` def testme(filepath): with open(filepath, 'r') as f: return f.read() ```
There is lot of noise in these answers, almost all are correct but outdated and not neat. [`mock_open`](https://docs.python.org/3/library/unittest.mock.html#mock-open) is part of [`mock`](https://docs.python.org/3/library/unittest.mock.html#module-unittest.mock) framework and is very simple to use. [`patch`](https://do...
Web Application Frameworks: C++ vs Python
1,289,941
8
2009-08-17T19:33:40Z
1,289,978
7
2009-08-17T19:40:27Z
[ "c++", "python", "wt" ]
I am familiar with both Python and C++ as a programmer. I was thinking of writing my own simple web application and I wanted to know which language would be more appropriate for server-side web development. Some things I'm looking for: * It has to be intuitive. I recognize that Wt exists and it follows the model of Q...
If you'd like to avoid writing HTML, you could try [GWT](http://code.google.com/webtoolkit/). However, in my experience, using an intermediate framework to generate HTML and ECMAScript never works anywhere near as well as hand-writing the pages. [edit] nikow mentions in the comments that [Pyjamas](http://pyjs.org/) is...
Web Application Frameworks: C++ vs Python
1,289,941
8
2009-08-17T19:33:40Z
1,290,058
7
2009-08-17T19:54:21Z
[ "c++", "python", "wt" ]
I am familiar with both Python and C++ as a programmer. I was thinking of writing my own simple web application and I wanted to know which language would be more appropriate for server-side web development. Some things I'm looking for: * It has to be intuitive. I recognize that Wt exists and it follows the model of Q...
* Django is good point to start web development it is great framework * If you look for C++ take a look on [CppCMS](http://cppcms.sourceforge.net/), it is much more close to Django, it is not like Wt that mimics Qt. In any case, it is really depends on your needs. C++ can be used for embedded or high performance web a...
Web Application Frameworks: C++ vs Python
1,289,941
8
2009-08-17T19:33:40Z
11,300,548
10
2012-07-02T20:14:47Z
[ "c++", "python", "wt" ]
I am familiar with both Python and C++ as a programmer. I was thinking of writing my own simple web application and I wanted to know which language would be more appropriate for server-side web development. Some things I'm looking for: * It has to be intuitive. I recognize that Wt exists and it follows the model of Q...
I would go with Wt because: * You already know C++ * It has a nice [layout system](http://www.webtoolkit.eu/widgets/style-and-layout/wboxlayout), so you don't need to know lots of HTML * It is very well written and a pleasure to code in * Your deployed apps will handle 50 times the load of the python app on less hardw...
python: Overhead to using classes instead of dictionaries?
1,290,030
5
2009-08-17T19:47:44Z
1,290,060
8
2009-08-17T19:54:33Z
[ "python", "design", "class", "dictionary" ]
First, I'd like to point out that I know OOP concepts and understand the differences between dictionaries and classes. My question is about what makes sense design wise in this case: I am designing a webapp in python and I have to represent something like a book object. Books have chapters and chapters have titles and...
A few thoughts: 1. If you start with a dictionary, you can always switch to a custom class later that implements the mapping protocol (or subclasses dict). So it's probably a good starting point. 2. You can define custom Python objects to use `__slots__`, which will be faster and more memory efficient if you have a la...
python: Overhead to using classes instead of dictionaries?
1,290,030
5
2009-08-17T19:47:44Z
1,290,132
9
2009-08-17T20:07:31Z
[ "python", "design", "class", "dictionary" ]
First, I'd like to point out that I know OOP concepts and understand the differences between dictionaries and classes. My question is about what makes sense design wise in this case: I am designing a webapp in python and I have to represent something like a book object. Books have chapters and chapters have titles and...
This is *highly* unlikely to be the bottleneck in your application, so worrying about the performance is probably a waste of time. However, if this is the bottleneck or you just have some time on your hands, look into using a [`namedtuple`](http://docs.python.org/dev/library/collections.html#namedtuple-factory-function...
Django MVC pattern for non database driven models?
1,290,891
20
2009-08-17T22:40:35Z
1,290,978
31
2009-08-17T23:07:15Z
[ "python", "django", "model-view-controller", "models" ]
I'm just working my way through Django, and really liking it so far, but I have an issue and I'm not sure what the typical way to solve it. Suppose I have a View which is supposed to be updated when some complex Python object is updated, but this object is not driven by the database, say it is driven by AJAX calls or ...
Your `models.py` can be (and sometimes is) empty. You are not obligated to have a model which maps to a database. You should still have a `models.py` file, to make Django's admin happy. The `models.py` file name is important, and it's easier to have an empty file than to try and change the file expected by various adm...
Confused by Django's claim to MVC, what is it exactly?
1,291,213
6
2009-08-18T00:30:28Z
1,291,223
14
2009-08-18T00:33:51Z
[ "python", "django", "model-view-controller", "design-patterns" ]
So what exactly is Django implementing? Seems like there are ``` Models Views Templates ``` > Models = Database mappings > > Views = Grab relevant data from the > models and formats it via templates > > Templates = Display HTML depending on data given by Views EDIT: S. Lott cleared a lot up with this in an edit to ...
Django's developers have a slightly non-traditional view on the MVC paradigm. They actually address this question in their FAQs, which you can read [here](http://docs.djangoproject.com/en/dev/faq/general/#django-appears-to-be-a-mvc-framework-but-you-call-the-controller-the-view-and-the-view-the-template-how-come-you-do...
How can I tell whether my Django application is running on development server or not?
1,291,755
36
2009-08-18T04:10:26Z
1,291,858
16
2009-08-18T04:49:39Z
[ "python", "django", "wsgi" ]
How can I be certain that my application is running on development server or not? I suppose I could check value of `settings.DEBUG` and assume if `DEBUG` is `True` then it's running on development server, but I'd prefer to know for sure than relying on convention.
``` server = request.META.get('wsgi.file_wrapper', None) if server is not None and server.__module__ == 'django.core.servers.basehttp': print('inside dev') ``` Of course, `wsgi.file_wrapper` might be set on META, and have a class from a module named `django.core.servers.basehttp` by extreme coincidence on another ...
How can I tell whether my Django application is running on development server or not?
1,291,755
36
2009-08-18T04:10:26Z
1,291,864
9
2009-08-18T04:54:41Z
[ "python", "django", "wsgi" ]
How can I be certain that my application is running on development server or not? I suppose I could check value of `settings.DEBUG` and assume if `DEBUG` is `True` then it's running on development server, but I'd prefer to know for sure than relying on convention.
Typically I set an variable called `environment` and set it to "DEVELOPMENT", "STAGING" or "PRODUCTION". Within the settings file I can then add basic logic to change which settings are being used, based on environment. **EDIT:** Additionally, you can simply use this logic to include different `settings.py` files that...
How can I tell whether my Django application is running on development server or not?
1,291,755
36
2009-08-18T04:10:26Z
4,277,798
22
2010-11-25T13:54:22Z
[ "python", "django", "wsgi" ]
How can I be certain that my application is running on development server or not? I suppose I could check value of `settings.DEBUG` and assume if `DEBUG` is `True` then it's running on development server, but I'd prefer to know for sure than relying on convention.
I put the following in my settings.py to distinguish between the standard dev server and production: ``` import sys RUNNING_DEVSERVER = (len(sys.argv) > 1 and sys.argv[1] == 'runserver') ``` This also relies on convention, however. (Amended per Daniel Magnusson's comment)
How does Python for loop work?
1,292,189
4
2009-08-18T06:44:12Z
1,292,214
20
2009-08-18T06:53:46Z
[ "python", "for-loop" ]
I am used to the C++ way of for loops, but the Python loops have left me confused. ``` for party in feed.entry: print party.location.address.text ``` Here `party` in `feed.entry`. What does it signify and how does it actually work?
feed.entry is property of feed and it's value is (if it's not, this code will fail) object implementing iteration protocol (array, for example) and has **iter** method, which returns iterator object Iterator has next() method, returning next element or raising exception, so python for loop is actually: ``` iterator =...
How to automate browsing using python?
1,292,817
17
2009-08-18T09:23:10Z
1,292,892
13
2009-08-18T09:43:36Z
[ "python", "browser-automation" ]
suppose, I need to perform a set of procedure on a particular website say, fill some forms, click submit button, send the data back to server, receive the response, again do something based on the response and send the data back to the server of the website. I know there is a webbrowser module in python, but I want to ...
You can also take a look at [mechanize](http://wwwsearch.sourceforge.net/mechanize/). Its meant to handle *"stateful programmatic web browsing"* (as per their site).
How to automate browsing using python?
1,292,817
17
2009-08-18T09:23:10Z
3,486,971
14
2010-08-15T10:19:57Z
[ "python", "browser-automation" ]
suppose, I need to perform a set of procedure on a particular website say, fill some forms, click submit button, send the data back to server, receive the response, again do something based on the response and send the data back to the server of the website. I know there is a webbrowser module in python, but I want to ...
selenium will do exactly what you want and it handles javascript
How to automate browsing using python?
1,292,817
17
2009-08-18T09:23:10Z
19,256,265
7
2013-10-08T19:11:27Z
[ "python", "browser-automation" ]
suppose, I need to perform a set of procedure on a particular website say, fill some forms, click submit button, send the data back to server, receive the response, again do something based on the response and send the data back to the server of the website. I know there is a webbrowser module in python, but I want to ...
All answers are old, I recommend and I am a big fan of [requests](http://docs.python-requests.org/en/latest/) From homepage: > Python’s standard urllib2 module provides most of the HTTP > capabilities you need, but the API is thoroughly broken. It was built > for a different time — and a different web. It require...
How to convince my boss to use Django?
1,293,361
18
2009-08-18T11:47:10Z
1,293,401
7
2009-08-18T11:57:46Z
[ "php", "python", "django" ]
I have an unusual problem: I have to convince my superiors to use Django for our new project. Alternative is some PHP framework. I've programmed in PHP for 2 years and then switched to Python and have about 3 years of experience in it. However I'm not too good in business speech. I know all the technical pros and cons...
People like to see tangible results. *On your own time* implement a small portion of the project using Django that can demonstrate what you believe to be some of the advantages of switching the project to Django. Besides demonstrating technical advantages, it will demonstrate your commitment to the idea. From your bos...
How to convince my boss to use Django?
1,293,361
18
2009-08-18T11:47:10Z
1,293,405
13
2009-08-18T11:58:26Z
[ "php", "python", "django" ]
I have an unusual problem: I have to convince my superiors to use Django for our new project. Alternative is some PHP framework. I've programmed in PHP for 2 years and then switched to Python and have about 3 years of experience in it. However I'm not too good in business speech. I know all the technical pros and cons...
Why do you *have* to convince your boss to use Django? Your boss should understand that it's in his best interest to work in what the people he'll be employing know best. But, how can you tell that Django is really the best suit all things considered? For example: * Are the servers in-house? do the sysadmins know h...
Best way to obtain indexed access to a Python queue, thread-safe
1,293,966
8
2009-08-18T13:45:32Z
1,294,330
9
2009-08-18T14:39:19Z
[ "python", "multithreading", "queue", "deque" ]
I have a queue (from the `Queue` module), and I want to get indexed access into it. (i.e., being able to ask for item number four in the queue, without removing it from the queue.) I saw that a queue uses a deque internally, and deque has indexed access. The question is, how can I use the deque without (1) messing up ...
``` import Queue class IndexableQueue(Queue): def __getitem__(self, index): with self.mutex: return self.queue[index] ``` It's of course crucial to release the mutex whether the indexing succeeds or raises an IndexError, and I'm using a `with` statement for that. In older Python versions, `try`/`finally` ...
How do I install PyGTK / PyGobject on Windows with Python 2.6?
1,294,272
10
2009-08-18T14:31:08Z
1,294,354
10
2009-08-18T14:44:11Z
[ "python", "pygtk", "mingw", "pygobject" ]
I have an application which depends on PyGTK, PyGobject, and PyCairo that I built to work on Linux. I want to port it over to windows, but when I execute `import gobject` I get this: ``` Traceback (most recent call last): import gobject File "C:\Python26\lib\site-packages\gtk-2.0\gobject\__init__.py", line 30, i...
I have it working fine, and it didn't give me much trouble, so we know it can be done... Keep in mind you will probably need all of the following installed on your Windows machine: * PyCairo ( <http://ftp.gnome.org/pub/GNOME/binaries/win32/pycairo/> ) * PyGobject ( <http://ftp.gnome.org/pub/GNOME/binaries/win32/pygob...
What is a global interpreter lock (GIL)?
1,294,382
87
2009-08-18T14:50:06Z
1,294,398
28
2009-08-18T14:53:04Z
[ "python", "gil" ]
What is a global interpreter lock and why is that an issue? A lot noise has been made around removing the GIL from Python, and I'd like to understand why that is so important. I have never written a compiler nor an interpreter myself, so don't be frugal with details, I'll probably need them to understand.
Suppose you have multiple threads which don't *really* touch each other's data. Those should execute as independently as possible. If you have a "global lock" which you need to acquire in order to (say) call a function, that can end up as a bottleneck. You can wind up not getting much benefit from having multiple threa...
What is a global interpreter lock (GIL)?
1,294,382
87
2009-08-18T14:50:06Z
1,294,402
90
2009-08-18T14:53:17Z
[ "python", "gil" ]
What is a global interpreter lock and why is that an issue? A lot noise has been made around removing the GIL from Python, and I'd like to understand why that is so important. I have never written a compiler nor an interpreter myself, so don't be frugal with details, I'll probably need them to understand.
Python's GIL is intended to serialize access to interpreter internals from different threads. On multi-core systems, it means that multiple threads can't effectively make use of multiple cores. (If the GIL didn't lead to this problem, most people wouldn't care about the GIL - it's only being raised as an issue because ...
What is a global interpreter lock (GIL)?
1,294,382
87
2009-08-18T14:50:06Z
1,294,430
10
2009-08-18T14:57:06Z
[ "python", "gil" ]
What is a global interpreter lock and why is that an issue? A lot noise has been made around removing the GIL from Python, and I'd like to understand why that is so important. I have never written a compiler nor an interpreter myself, so don't be frugal with details, I'll probably need them to understand.
Whenever two threads have access to the same variable you have a problem. In C++ for instance, the way to avoid the problem is to define some mutex lock to prevent two thread to, let's say, enter the setter of an object at the same time. Multithreading is possible in python, but two threads cannot be executed at the s...
What is a global interpreter lock (GIL)?
1,294,382
87
2009-08-18T14:50:06Z
1,294,553
7
2009-08-18T15:16:02Z
[ "python", "gil" ]
What is a global interpreter lock and why is that an issue? A lot noise has been made around removing the GIL from Python, and I'd like to understand why that is so important. I have never written a compiler nor an interpreter myself, so don't be frugal with details, I'll probably need them to understand.
[Watch David Beazley](http://blip.tv/pycon-us-videos-2009-2010-2011/pycon-2010-understanding-the-python-gil-82-3273690) tell you everything you ever wanted to know about the GIL.
How to insert / retrieve a file stored as a BLOB in a MySQL db using python
1,294,385
10
2009-08-18T14:50:58Z
1,294,496
12
2009-08-18T15:09:15Z
[ "python", "mysql", "file-io", "blob" ]
I want to write a python script that populates a database with some information. One of the columns in my table is a BLOB that I would like to save a file to for each entry. How can I read the file (binary) and insert it into the DB using python? Likewise, how can I retrieve it and write that file back to some arbitra...
``` thedata = open('thefile', 'rb').read() sql = "INSERT INTO sometable (theblobcolumn) VALUES (%s)" cursor.execute(sql, (thedata,)) ``` That code of course works as written only if your table has just the BLOB column and what you want to do is INSERT, but of course you could easily tweak it to add more columns, use U...
how to register more than 10 apps in Google App Engine
1,294,618
13
2009-08-18T15:25:56Z
1,295,100
12
2009-08-18T16:43:19Z
[ "python", "google-app-engine", "registration" ]
Anyone knows any "legal" way to surpass the 10-app-limit Google imposes? I wouldn't mind to pay, or anything, but I wasn't able to find a way to have more than 10 apps and can't either remove one.
This post in the Google App Engine group "solves" the problem: [link](http://groups.google.com/group/google-appengine/browse%5Fthread/thread/815d0e29076da2b1/ecc21212ed9362ab#ecc21212ed9362ab)
Python WWW macro
1,294,862
6
2009-08-18T16:05:29Z
1,295,028
7
2009-08-18T16:31:31Z
[ "python", "screen-scraping" ]
i need something like iMacros for Python. It would be great to have something like that: ``` browse_to('www.google.com') type_in_input('search', 'query') click_button('search') list = get_all('<p>') ``` Do you know something like that? Thanks in advance, Etam.
Almost a direct fulfillment of the wishes in the question - [twill](http://twill.idyll.org/). > twill is a simple language that allows users to browse the Web from a command-line interface. With twill, you can navigate through Web sites that use forms, cookies, and most standard Web features. > > twill supports automa...
Numpy: Is there an array size limit?
1,295,994
3
2009-08-18T19:33:20Z
1,296,017
9
2009-08-18T19:38:08Z
[ "python", "numpy" ]
I'm learning to use Numpy and I wanted to see the speed difference in the summation of a list of numbers so I made this code: ``` np_array = numpy.arange(1000000) start = time.time() sum_ = np_array.sum() print time.time() - start, sum_ >>> 0.0 1783293664 python_list = range(1000000) start = time.time() sum_ = sum(p...
The standard list switched over to doing arithmetic with the long type when numbers got larger than a 32-bit int. The numpy array did not switch to long, and suffered from integer overflow. The price for speed is smaller range of values allowed. ``` >>> 499999500000 % 2**32 1783293664L ```
Numpy: Is there an array size limit?
1,295,994
3
2009-08-18T19:33:20Z
1,296,028
9
2009-08-18T19:40:03Z
[ "python", "numpy" ]
I'm learning to use Numpy and I wanted to see the speed difference in the summation of a list of numbers so I made this code: ``` np_array = numpy.arange(1000000) start = time.time() sum_ = np_array.sum() print time.time() - start, sum_ >>> 0.0 1783293664 python_list = range(1000000) start = time.time() sum_ = sum(p...
Numpy is creating an array of 32-bit unsigned ints. When it sums them, it sums them into a 32-bit value. ``` if 499999500000L % (2**32) == 1783293664L: print "Overflowed a 32-bit integer" ``` You can explicitly choose the data type at array creation time: ``` a = numpy.arange(1000000, dtype=numpy.uint64) a.sum()...
Tuple list from dict in Python
1,296,042
23
2009-08-18T19:41:26Z
1,296,049
40
2009-08-18T19:42:48Z
[ "python", "list", "dictionary", "key-value" ]
How can I obtain a list of key-value tuples from a [dict](http://docs.python.org/2/library/stdtypes.html#dict) in Python?
For Python 2.x only (thanks Alex): ``` yourdict = {} # ... items = yourdict.items() ``` See <http://docs.python.org/library/stdtypes.html#dict.items> for details. For Python 3.x only (taken from [Alex's answer](http://stackoverflow.com/questions/1296042/tuple-list-from-dict-in-python/1296074#1296074)): ``` yourdict...
How can I read a python pickle database/file from C?
1,296,162
8
2009-08-18T20:02:51Z
4,166,900
14
2010-11-12T16:37:26Z
[ "python", "c" ]
I am working on integrating with several music players. At the moment my favorite is exaile. In the new version they are migrating the database format from SQLite3 to an internal Pickle format. I wanted to know if there is a way to access pickle format files without having to reverse engineer the format by hand. I kn...
<http://www.picklingtools.com/> There is a library called the PicklingTools which I help maintain which might be useful: it allows you to form data structures in C++ that you can then pickle/unpickle ... it is C++, not C, but that shouldn't be a problem these days (assuming you are using the gcc/g++ suite). The libra...
Bruce Eckel's code snippet from Design Pattern: I'm confused on how it works
1,296,311
3
2009-08-18T20:28:46Z
1,297,577
9
2009-08-19T02:37:39Z
[ "python" ]
I've been reading [Thinking in python](http://www.mindview.net/Books/TIPython) by Bruce Eckel. Currently, I'm reading the *Pattern Concept* chapter. In this chapter, Eckel shows the different implementations of Singletons in python. But I have an unclear understanding of Alex Martelli's code of Singleton (utilizing inh...
Good answers so far, but let me also answer directly... `self.__dict__` holds the attributes (i.e., the state) of instance `self` (unless its class does peculiar things such as defining `__slots__`;-). So by ensuring that all instances have the same `__dict__` we're ensuring they all have the same attributes, i.e., exa...
Parse Gmail with Python and mark all older than date as "read"
1,296,446
4
2009-08-18T20:52:28Z
1,296,613
8
2009-08-18T21:25:53Z
[ "python", "email", "gmail", "imap", "pop3" ]
Long story short, I created a new gmail account, and linked several other accounts to it (each with 1000s of messages), which I am importing. All imported messages arrive as unread, but I need them to appear as read. I have a little experience with python, but I've only used mail and imaplib modules for sending mail, ...
``` typ, data = M.search(None, '(BEFORE 01-Jan-2009)') for num in data[0].split(): M.store(num, '+FLAGS', '\\Seen') ``` This is a slight modification of the code in the [imaplib doc page](http://docs.python.org/library/imaplib.html) for the store method. I found the search criteria to use from [RFC 3501](http://too...
Python - Find Path to File Being Run
1,296,501
23
2009-08-18T21:02:54Z
1,296,522
12
2009-08-18T21:08:20Z
[ "python" ]
How can I find the full path to the currently running python script? That is to say, what do I have to put to achieve this: ``` Nirvana@bahamut:/tmp$ python baz.py running from /tmp file is baz.py ```
This will print the directory in which the script lives (as opposed to the working directory): ``` import os dirname, filename = os.path.split(os.path.abspath(__file__)) print "running from", dirname print "file is", filename ``` Here's how it behaves, when I put it in `c:\src`: ``` > cd c:\src > python so-where.py ...
Python - Find Path to File Being Run
1,296,501
23
2009-08-18T21:02:54Z
1,297,407
43
2009-08-19T01:29:19Z
[ "python" ]
How can I find the full path to the currently running python script? That is to say, what do I have to put to achieve this: ``` Nirvana@bahamut:/tmp$ python baz.py running from /tmp file is baz.py ```
**`__file__` is NOT what you are looking for.** Don't use accidental side-effects `sys.argv[0]` is **always** the path to the script (if in fact a script has been invoked) -- see <http://docs.python.org/library/sys.html#sys.argv> `__file__` is the path of the *currently executing* file (script or module). This is **a...
Efficiency of using a Python list as a queue
1,296,511
34
2009-08-18T21:05:58Z
1,296,527
23
2009-08-18T21:09:05Z
[ "python", "list", "memory-leaks" ]
A coworker recently wrote a program in which he used a Python list as a queue. In other words, he used `.append(x)` when needing to insert items and `.pop(0)` when needing to remove items. I know that Python has [`collections.deque`](http://docs.python.org/library/collections.html#collections.deque) and I'm trying to ...
You won't run out of memory using the `list` implementation, but performance will be poor. From [the docs](http://docs.python.org/library/collections.html): > Though `list` objects support similar > operations, they are optimized for > fast fixed-length operations and incur > O(n) memory movement costs for > `pop(0)` ...
Efficiency of using a Python list as a queue
1,296,511
34
2009-08-18T21:05:58Z
1,297,464
60
2009-08-19T02:00:10Z
[ "python", "list", "memory-leaks" ]
A coworker recently wrote a program in which he used a Python list as a queue. In other words, he used `.append(x)` when needing to insert items and `.pop(0)` when needing to remove items. I know that Python has [`collections.deque`](http://docs.python.org/library/collections.html#collections.deque) and I'm trying to ...
Some answers claimed a "10x" speed advantage for deque vs list-used-as-FIFO when both have 1000 entries, but that's a bit of an overbid: ``` $ python -mtimeit -s'q=range(1000)' 'q.append(23); q.pop(0)' 1000000 loops, best of 3: 1.24 usec per loop $ python -mtimeit -s'import collections; q=collections.deque(range(1000)...
Efficiency of using a Python list as a queue
1,296,511
34
2009-08-18T21:05:58Z
1,297,467
14
2009-08-19T02:00:18Z
[ "python", "list", "memory-leaks" ]
A coworker recently wrote a program in which he used a Python list as a queue. In other words, he used `.append(x)` when needing to insert items and `.pop(0)` when needing to remove items. I know that Python has [`collections.deque`](http://docs.python.org/library/collections.html#collections.deque) and I'm trying to ...
From Beazley's [*Python Essential Reference, Fourth Edition*](http://rads.stackoverflow.com/amzn/click/0672329786), p. 194: > Some library modules provide new types > that outperform the built-ins at > certain tasks. For instance, > collections.deque type provides > similar functionality to a list but > has been highl...
Does IronPython implement python standard library?
1,296,640
6
2009-08-18T21:32:14Z
1,296,770
9
2009-08-18T21:55:21Z
[ "python", "ironpython" ]
I tried IronPython some time ago and it seemed that it implements only python language, and uses .NET for libraries. Is this still the case? Can one use python modules from IronPython?
The [IronPython installer](http://ironpython.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=22981) includes the Python standard library. Otherwise, you can use the standard library from a compatible Python install (IPy 2.0 -> CPy 2.5, IPy 2.6 -> CPy 2.6). Either copy the Python Lib directory to the IronPython fold...
Getting system status in python
1,296,703
8
2009-08-18T21:42:51Z
1,296,816
8
2009-08-18T22:03:23Z
[ "python", "operating-system" ]
Is there any way to get system status in python, for example the amount of memory free, processes that are running, cpu load and so on. I know on linux I can get this from the /proc directory, but I would like to do this on unix and windows as well.
I don't know of any such library/ package that currently supports both Linux and Windows. There's [libstatgrab](http://www.i-scream.org/libstatgrab/) which doesn't seem to be very actively developed (it already supports a decent variety of Unix platforms though) and the very active [PSI (Python System Information)](htt...
Python class method - Is there a way to make the calls shorter?
1,297,583
4
2009-08-19T02:39:34Z
1,297,590
13
2009-08-19T02:40:27Z
[ "python", "class-method" ]
I am playing around with Python, and I've created a class in a different package from the one calling it. In this class, I've added a class method which is being called from my main function. Again, they are in separate packages. The line to call the class method is much longer than I thought it would be from the examp...
``` from config.TestClass import TestClass TestClass.add_key( "mykey", "newvalue" ) ```
Why there is a difference in "import" vs. "import *"?
1,297,766
6
2009-08-19T04:08:36Z
1,297,784
21
2009-08-19T04:18:00Z
[ "python", "import" ]
``` """module a.py""" test = "I am test" _test = "I am _test" __test = "I am __test" ``` ============= ``` ~ $ python Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39) [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from a import * >>>...
Variables with a leading "\_" (underbar) are not *public names* and will not be imported when `from x import *` is used. Here, `_test` and `__test` are not *public* names. From the [import](http://docs.python.org/reference/simple_stmts.html#the-import-statement) statement description: > If the list of identifiers is...
How do I write a single-file Django application?
1,297,873
11
2009-08-19T04:58:30Z
1,297,911
8
2009-08-19T05:14:57Z
[ "python", "django", "web-applications" ]
I want to write a very small Django application in a single file, requiring all the appropriate modules and stuff, and then be able to run that as a normal Python script, like this: ``` $ python myapp.py ``` You can assume I won't render HTML, so I don't need templates (I'll return [JSON](http://en.wikipedia.org/wiki...
This is a simple CMS implemented in Django, as a single file. It was written by [Paul Bissex](http://news.e-scribe.com/395). Some of it has been "golfed" and could do with a bit of expansion, but it's still relatively easy to read. The source has vanished from his pastebin, but I saved it: ``` #!/usr/bin/env python "...