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 |
|---|---|---|---|---|---|---|---|---|---|
Estimating aspect ratio of a convex hull | 7,059,841 | 6 | 2011-08-14T21:27:49Z | 7,060,268 | 7 | 2011-08-14T22:50:07Z | [
"python",
"geometry"
] | What would be the best way to approximate the aspect ratio of a convex hull in Python? I have already tried doing this by fitting the vertices of the convex hull with an ellipse and taking the ratio of the semi- and major-axis. The results are not satisfactory though, so I'm now looking into deriving the aspect ratio d... | Typically, you'd find the eigenvectors of the covariance matrix of the point cloud. The aspect ratio is the ratio of the largest to smallest eigenvalues.
As an example for a bunch of random points (you'd just apply the same thing to your convex hull, only using the vertices):
```
import matplotlib.pyplot as plt
impor... |
Itertools for containers | 7,060,229 | 9 | 2011-08-14T22:42:57Z | 7,060,288 | 7 | 2011-08-14T22:52:51Z | [
"iterator",
"python"
] | Considder the following interactive example
```
>>> l=imap(str,xrange(1,4))
>>> list(l)
['1', '2', '3']
>>> list(l)
[]
```
Does anyone know if there is already an implementation somewhere out there with a version of imap (and the other itertools functions) such that the second time list(l) is executed you get the sam... | You do not have to build such an object for each type of container. Basically, you have the following:
```
mkimap = lambda: imap(str,xrange(1,4))
list(mkimap())
list(mkimap())
```
Now you onlky need a nice wrapping object to prevent the "ugly" function calls. This could work this way:
```
class MultiIter(object):
... |
Accessing module level variables, from within a function in the module | 7,060,711 | 19 | 2011-08-15T00:30:29Z | 7,060,755 | 35 | 2011-08-15T00:40:52Z | [
"python"
] | I'd like to be able to do something like this:
```
#mymodule
var = None
def load():
var = something()
```
Other module(s):
```
#secondmodule
import mymodule
mymodule.load()
#thirdmodule
from mymodule import var
print var #Shouldn't be None
```
But I don't know how to reference a modules variable from a functi... | Just change
```
def load():
global var
var = something()
```
Global variables are read-only from sibling methods. More accurately unless a variable is specified as global, Python consider it as local, but a read access to a local variable name will reach module-level scope if the name is not present in local ... |
Accessing module level variables, from within a function in the module | 7,060,711 | 19 | 2011-08-15T00:30:29Z | 7,060,758 | 12 | 2011-08-15T00:41:17Z | [
"python"
] | I'd like to be able to do something like this:
```
#mymodule
var = None
def load():
var = something()
```
Other module(s):
```
#secondmodule
import mymodule
mymodule.load()
#thirdmodule
from mymodule import var
print var #Shouldn't be None
```
But I don't know how to reference a modules variable from a functi... | You seem to mostly have it. You are missing only the fact that "module-level" variables are called global in Python. (They are not truly global, but only global to the module they are declared in, in other words.)
In any function where you *modify* a global variable (you want to make the name refer to a different obje... |
Calculating Time in Python (datetime.timedelta?) | 7,061,479 | 9 | 2011-08-15T03:31:27Z | 7,061,503 | 10 | 2011-08-15T03:37:55Z | [
"python",
"datetime"
] | I am sure this is a nobrainer for a lot of you, but I find myself really confused with the whole datetime.timedelta thing. Essentially I timestamp something when I start `startTime` and then I timestamp the end of the process `endTime` and I am trying to get the difference in HH:MM:SS and am having no luck.
I get this... | Use a `datetime` instead of a `time`. Subtracting one time from another is meaningless without a date; you can't just assume that they're on the same day and the left operand comes first. |
Do any Python environments support edit-and-continue? | 7,061,628 | 14 | 2011-08-15T04:05:51Z | 7,061,755 | 11 | 2011-08-15T04:37:08Z | [
"python",
"debugging"
] | Is it possible in Python to make changes to code that you're currently debugging and continue without having to restart everything? (The way I can in C#, for example.) | You have the full power of the interpreter at your fingertips with `pdb`, use
```
import pdb
pdb.set_trace()
```
From there you can define and create new objects, redefine existing ones, modify and reload modules, etc. Syntax is simalar to `gdb`. If you're using ipython, `ipdb` may be a nicer choice, or you can autom... |
What's the most efficient way to convert a MySQL result set to a NumPy array? | 7,061,824 | 7 | 2011-08-15T05:00:13Z | 7,062,033 | 9 | 2011-08-15T05:49:01Z | [
"python",
"numpy",
"mysql-python",
"etl"
] | I'm using MySQLdb and Python. I have some basic queries such as this:
```
c=db.cursor()
c.execute("SELECT id, rating from video")
results = c.fetchall()
```
I need "results" to be a NumPy array, and I'm looking to be economical with my memory consumption. It seems like copying the data row by row would be incredibly ... | The `fetchall` method actually returns an iterator, and numpy has the [fromiter](http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromiter.html) method to initialize an array from an interator. So, depending on what data is in the table you could combine the two easily, or use an adapter generator. |
What's the most efficient way to convert a MySQL result set to a NumPy array? | 7,061,824 | 7 | 2011-08-15T05:00:13Z | 18,258,173 | 11 | 2013-08-15T17:26:50Z | [
"python",
"numpy",
"mysql-python",
"etl"
] | I'm using MySQLdb and Python. I have some basic queries such as this:
```
c=db.cursor()
c.execute("SELECT id, rating from video")
results = c.fetchall()
```
I need "results" to be a NumPy array, and I'm looking to be economical with my memory consumption. It seems like copying the data row by row would be incredibly ... | This solution uses Kieth's *fromiter* technique, but handles the two dimensional table structure of SQL results more intuitively. Also, it improves on Doug's method by avoiding all the reshaping and flattening in python data types. Using a [structured array](http://docs.scipy.org/doc/numpy/user/basics.rec.html) we can ... |
Given two python lists of same length. How to return the best matches of similar values? | 7,062,340 | 7 | 2011-08-15T06:50:25Z | 7,062,390 | 11 | 2011-08-15T06:58:36Z | [
"python",
"string",
"list",
"mapping"
] | Given are two python lists with strings in them (names of persons):
```
list_1 = ['J. Payne', 'George Bush', 'Billy Idol', 'M Stuart', 'Luc van den Bergen']
list_2 = ['John Payne', 'George W. Bush', 'Billy Idol', 'M. Stuart', 'Luc Bergen']
```
I want a mapping of the names, that are most similar.
```
'J. Payne' ... | Using the function defined here: <http://hetland.org/coding/python/levenshtein.py>
```
>>> for i in list_1:
... print i, '==>', min(list_2, key=lambda j:levenshtein(i,j))
...
```
```
J. Payne ==> John Payne
George Bush ==> George W. Bush
Billy Idol ==> Billy Idol
M Stuart ==> M. Stuart
Luc van den Bergen ==> Luc ... |
Given two python lists of same length. How to return the best matches of similar values? | 7,062,340 | 7 | 2011-08-15T06:50:25Z | 7,062,409 | 10 | 2011-08-15T07:01:24Z | [
"python",
"string",
"list",
"mapping"
] | Given are two python lists with strings in them (names of persons):
```
list_1 = ['J. Payne', 'George Bush', 'Billy Idol', 'M Stuart', 'Luc van den Bergen']
list_2 = ['John Payne', 'George W. Bush', 'Billy Idol', 'M. Stuart', 'Luc Bergen']
```
I want a mapping of the names, that are most similar.
```
'J. Payne' ... | You might try `difflib`:
```
import difflib
list_1 = ['J. Payne', 'George Bush', 'Billy Idol', 'M Stuart', 'Luc van den Bergen']
list_2 = ['John Payne', 'George W. Bush', 'Billy Idol', 'M. Stuart', 'Luc Bergen']
mymap = {}
for elem in list_1:
closest = difflib.get_close_matches(elem, list_2)
if closest:
... |
I want to call a reduce with a list that contains longs an ints in python | 7,062,617 | 2 | 2011-08-15T07:38:27Z | 7,062,659 | 7 | 2011-08-15T07:44:25Z | [
"python",
"int",
"long-integer",
"reduce"
] | I am trying to call a reduce on a list that contains ints and longs. For example,
```
reduce( int.__mul__, [ 231212312412L, 3 ], 1 )
```
but I get an unimplemented error. and when I replace the int's mul method with the long's mul method it complains that it is getting an int. Must I map them all to a long first? lik... | ```
>>> from operator import mul
>>> reduce( mul, map( long, [ 12312412314L, 5 ] ), 1 )
61562061570L
>>> reduce( mul, [ 231212312412L, 3 ], 1 )
693636937236L
>>>
```
operator has:
```
'abs',
'add',
'and_',
'attrgetter',
'concat',
'contains',
'countOf',
'delitem',
'delslice',
'div',
'eq',
'floordiv',
'ge',... |
Last character of a window in python + curses | 7,063,128 | 8 | 2011-08-15T08:50:15Z | 7,063,315 | 8 | 2011-08-15T09:13:40Z | [
"python",
"ncurses"
] | The following program raises an error:
```
import curses
def test(scr):
top = curses.newwin(1, 10, 0, 0)
top.addstr(0, 9, "X")
curses.wrapper(test)
```
It looks like whenever I try to use addstr() to write a character in the last column of the last line of a window (even when it is smaller than the screen), it ... | It looks like simply writing the last character of a window is impossible with curses, for historical reasons.
The only workaround I could find consists in writing the character one place to the left of its final destination, and pushing it with an insert. The following code will push the "X" to position 9:
```
top =... |
Perl Compatible Regular Expression (PCRE) in Python | 7,063,420 | 15 | 2011-08-15T09:26:54Z | 7,066,413 | 46 | 2011-08-15T14:52:05Z | [
"python",
"regex",
"parsing",
"pcre"
] | I have to parse some strings based on PCRE in Python and I've no idea how to do that.
Strings I want to parse looks like :
```
match mysql m/^.\0\0\0\n(4\.[-.\w]+)\0...\0/s p/MySQL/ i/$1/
```
In this example, I have to get this different items :
```
"m/^.\0\0\0\n(4\.[-.\w]+)\0...\0/s" ; "p/MySQL/" ; "i/$1/"
```
Th... | # Be Especially Careful with nonâASCII in Python
There are some really subtle issues with how Python deals with, or fails to deal with, non-ASCII in patterns and strings. Worse, these disparities vary substantially according not just to which version of Python you are using, but also whether you have a âwide build... |
PyPy significantly slower than CPython | 7,063,508 | 6 | 2011-08-15T09:38:33Z | 7,067,001 | 16 | 2011-08-15T15:35:44Z | [
"python",
"optimization",
"jit",
"pypy",
"cprofile"
] | I've been testing a cacheing system of my making. Its purpose is to speed up a Django web application. It stores everything in-memory. According to cProfile most of the time in my tests is spent inside QuerySet.\_clone() which turns out to be terribly inefficient (it's actually not that strange given the implementation... | Brushing aside the fact that PyPy might really be intrinsically slower for your case, there are some factors that could be making it unnecessarily slower:
* Profiling is known to slow PyPy a lot more than CPython.
* Some debugging/logging code can disable optimizations (by, e.g., forcing frames).
* The server you're u... |
Why is my MergeSort so slow in Python? | 7,063,697 | 3 | 2011-08-15T09:59:18Z | 7,063,913 | 9 | 2011-08-15T10:27:55Z | [
"python",
"algorithm",
"sorting",
"mergesort"
] | I'm having some troubles understanding this behaviour.
I'm measuring the execution time with the timeit-module and get the following results for **10000** cycles:
* Merge : **1.22722930395**
* Bubble: 0.810706578175
* Select: 0.469924766812
**This is my code for MergeSort:**
```
def mergeSort(array):
if len(arra... | `list.pop(0)` pops the first element and has to shift all remaining ones, this is an additional O(n) operation which must not happen.
Also, slicing a `list` object creates a copy:
```
left = array[:len(array)/2]
right = array[len(array)/2:]
```
Which means you're also using O(n \* log(n)) memory instead of O(n).
I ... |
Python AppIndicator bindings -> howto check if the menu is open? | 7,063,743 | 15 | 2011-08-15T10:05:13Z | 7,136,238 | 7 | 2011-08-21T03:59:08Z | [
"python",
"pygtk",
"ubuntu-unity",
"appindicator"
] | Here is a minimal example of an AppIndicator:
```
#!/usr/bin/python
import gobject
import gtk
import appindicator
if __name__ == "__main__":
ind = appindicator.Indicator("example-simple-client", "gtk-execute", appindicator.CATEGORY_APPLICATION_STATUS)
ind.set_status (appindicator.STATUS_ACTIVE)
menu = gt... | It looks like the answer is no unfortunately.
```
print gobject.signal_list_names(ind)
('new-icon', 'new-attention-icon', 'new-status', 'new-label', 'x-ayatana-new-label', 'connection-changed', 'new-icon-theme-path')
```
I tried all of them and none of them appear to activate when the indicator is clicked. For what i... |
Django Binary or BLOB model field | 7,064,197 | 6 | 2011-08-15T11:03:14Z | 24,962,446 | 9 | 2014-07-25T18:40:35Z | [
"python",
"mysql",
"django",
"blob",
"django-blob"
] | I have a C# program that inserts a pdf inside a MySQL database. Now I want to retrieve that pdf via django but django's `models.FileField` needs an "Upload To" parameter which means behind the scenes it actually stores the File on the file system rather than in the database. Is there any way I can set up a django model... | Just as an update to this, as of Django 1.6, there's now a BinaryField option that will store files up to 4 GB in size. <https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.BinaryField> |
Use slice notation with collections.deque | 7,064,289 | 21 | 2011-08-15T11:14:26Z | 7,064,775 | 31 | 2011-08-15T12:15:56Z | [
"python",
"slice",
"deque"
] | How would you extract items 3..6 efficiently, elegantly and pythonically from the following `deque` without altering it:
```
from collections import deque
q = deque('',maxlen=10)
for i in range(10,20):
q.append(i)
```
the [slice notation](http://stackoverflow.com/questions/509211/good-primer-for-python-slice-nota... | ```
import itertools
output = list(itertools.islice(q, 3, 7))
```
For example:
```
>>> import collections, itertools
>>> q = collections.deque(xrange(10, 20))
>>> q
deque([10, 11, 12, 13, 14, 15, 16, 17, 18, 19])
>>> list(itertools.islice(q, 3, 7))
[13, 14, 15, 16]
```
This should be more efficient the the other sol... |
How to include external css, image, etc in django template? | 7,064,745 | 2 | 2011-08-15T12:12:37Z | 7,064,884 | 8 | 2011-08-15T12:27:29Z | [
"python",
"django"
] | In django, all urls are parsed from urls.py file. So, there is no directory structure as such.
> So, what if you have to include a css file in your template ?
>
> Is there a way without adding it to url.py file ?
>
> If no, then will you make new entry in urls.py for every resource ? | See the [Django HOWTO on static files](https://docs.djangoproject.com/en/dev/howto/static-files/).
Basically, in your configuration file, you specify a special directory to store static files in. The example in the docs is:
```
STATIC_ROOT = "/home/jacob/projects/mysite.com/sitestatic"
```
You put CSS files, images,... |
how can I get complete header info from urlib2 request? | 7,064,848 | 5 | 2011-08-15T12:23:21Z | 7,064,915 | 7 | 2011-08-15T12:31:10Z | [
"python",
"html",
"urllib2"
] | I am using the python urllib2 library for opening URL, and what I want is to get the complete header info of the request. When I use `response.info` I only get this:
```
Date: Mon, 15 Aug 2011 12:00:42 GMT
Server: Apache/2.2.0 (Unix)
Last-Modified: Tue, 01 May 2001 18:40:33 GMT
ETag: "13ef600-141-897e4a40"
Accept-Rang... | Those *are* all of the headers the server is sending when you do the request with `urllib2`.
Firefox is showing you the headers it's sending to the server as well.
When the server gets those headers from Firefox, some of them may trigger it to send back additional headers, so you end up with more response headers as ... |
Python metaclass and ModGrammar | 7,064,925 | 11 | 2011-08-15T12:32:17Z | 7,064,994 | 14 | 2011-08-15T12:39:19Z | [
"python",
"metaclass"
] | I found (after another question here on StackOverflow) this interesting library written in Python which goal is the grammar parsing.
<http://code.google.com/p/modgrammar/>
And I also found this tutorial regarding it:
<http://packages.python.org/modgrammar/tutorial.html>
So, after reading all the tutorial, I underst... | ```
class Grammar(metaclass=GrammarClass)
```
is using Python3 syntax. The equivalent Python2 syntax would be
```
class Grammar(object):
__metaclass__=GrammarClass
```
but since there may be lots of other Python3-isms, you may have to use Python3 to use `modgrammar`. |
Is there any reason why lVals = [1, 08, 2011] throws an exception? | 7,064,936 | 9 | 2011-08-15T12:33:40Z | 7,064,958 | 14 | 2011-08-15T12:35:43Z | [
"python"
] | I have discovered one thing that makes me crazy. If I specify the following list:
```
lVals = [1, 01, 2011]
```
then no errors will be displayed, and the same will happen if I use `02,03,04,05,06,07`, but in case I use `08` or `09` as the second item in the list, I get the following exception:
```
>>> a = [26, 08, 2... | `08` is attempting to parse `8` as an octal digit. It isn't one. |
Appengine BulkLoader problem using development server | 7,065,121 | 5 | 2011-08-15T12:51:37Z | 7,065,406 | 7 | 2011-08-15T13:20:21Z | [
"python",
"google-app-engine",
"bulkloader"
] | I am doing something that should be simple and getting stuck over and over again. I am getting this error when uploading quite simple csv files to my development server:
```
Error in WorkerThread-0: app "dev~fbdec" cannot access app "fbdec"'s data
```
The exact output being:
```
[INFO ] Logging to bulkloader-log-... | When starting dev\_appserver, pass the `--default_partition=""` parameter. |
How to make an unaware datetime timezone aware in python | 7,065,164 | 200 | 2011-08-15T12:55:44Z | 7,065,242 | 245 | 2011-08-15T13:03:52Z | [
"python",
"datetime",
"timezone"
] | **What I need to do**
I have a timezone-unaware datetime object, to which I need to add a time zone in order to be able to compare it with other timezone-aware datetime objects. I do not want to convert my entire application to timezone unaware for this one legacy case.
**What I've Tried**
First, to demonstrate the ... | In general, to make a naive datetime timezone-aware, use the [localize method](http://pytz.sourceforge.net/#localized-times-and-date-arithmetic):
```
import datetime
import pytz
unaware = datetime.datetime(2011, 8, 15, 8, 15, 12, 0)
aware = datetime.datetime(2011, 8, 15, 8, 15, 12, 0, pytz.UTC)
now_aware = pytz.utc.... |
How to make an unaware datetime timezone aware in python | 7,065,164 | 200 | 2011-08-15T12:55:44Z | 8,220,515 | 29 | 2011-11-22T00:34:32Z | [
"python",
"datetime",
"timezone"
] | **What I need to do**
I have a timezone-unaware datetime object, to which I need to add a time zone in order to be able to compare it with other timezone-aware datetime objects. I do not want to convert my entire application to timezone unaware for this one legacy case.
**What I've Tried**
First, to demonstrate the ... | I had use from dt\_aware to dt\_unware
```
dt_unaware = dt_aware.replace(tzinfo=None)
```
and dt\_unware to dt\_aware
```
from pytz import timezone
localtz = timezone('Europe/Lisbon')
dt_aware = localtz.localize(dt_unware)
```
but answer before is also a good solution. |
How to make an unaware datetime timezone aware in python | 7,065,164 | 200 | 2011-08-15T12:55:44Z | 28,173,891 | 13 | 2015-01-27T15:21:38Z | [
"python",
"datetime",
"timezone"
] | **What I need to do**
I have a timezone-unaware datetime object, to which I need to add a time zone in order to be able to compare it with other timezone-aware datetime objects. I do not want to convert my entire application to timezone unaware for this one legacy case.
**What I've Tried**
First, to demonstrate the ... | I use this statement in Django to convert an unaware time to an aware:
```
from django.utils import timezone
dt_aware = timezone.make_aware(dt_unaware, timezone.get_current_timezone())
``` |
Should I use orbited or gevent for integrating comet functionality into a django app | 7,065,283 | 5 | 2011-08-15T13:08:14Z | 7,065,818 | 7 | 2011-08-15T14:00:11Z | [
"python",
"django",
"postgresql",
"comet",
"gevent"
] | I have been working with Django for some time now and have written several apps on a setup that uses Apache 2 mod\_wsgi and a PostgreSQL database on ubuntu.
I have aa app that uses xsendfile to serve files from Apache via a Django view, and also allow users to upload files via a form as well. All this working great, b... | I'd recommend using WebSockets for bidirectional realtime communication. Keep running Django as is and run a WebSocket server on another port. As far as your database blocking, yes, you'll need to keep that in mind as you write your WebSocket server and either use a non-blocking database driver, or address that in some... |
GCC permission denied when trying to install Python module | 7,065,416 | 3 | 2011-08-15T13:20:49Z | 7,065,522 | 9 | 2011-08-15T13:31:46Z | [
"python",
"gcc",
"cygwin"
] | I'm trying to install this module <http://pypi.python.org/pypi/winrandom/1.1>. So I extract the content of the zip-file and try to install it with the command:
```
python setup.py install
```
And receives this output:
```
running install
running build
running build_ext
building 'winrandom' extension
c:\cygwin\bin\gc... | This problem *may* be caused by the fact that cygwin uses symlinks for gcc and g++, and windows doesn't understand how to handle this. A quick test to see if this is so is as follows:
```
C:\>g++
Access is denied.
C:\>bash
$ ls -l /usr/bin/g++
lrwxrwxrwx 1 nate Domain Users 21 Mar 22 2010 /usr/bin/g++ -> /etc/alter... |
Pyplot, main title, subplot | 7,066,121 | 49 | 2011-08-15T14:28:57Z | 7,066,293 | 74 | 2011-08-15T14:42:59Z | [
"python",
"matplotlib"
] | Simple question: I am using `pyplot`, I have 4 subplots. How to set a single, main title above all the subplots? `title()` sets it above the last subplot. | Use [plt.suptitle](http://matplotlib.sourceforge.net/api/figure_api.html#matplotlib.figure.Figure.suptitle):
```
import matplotlib.pyplot as plt
import numpy as np
fig=plt.figure()
data=np.arange(900).reshape((30,30))
for i in range(1,5):
ax=fig.add_subplot(2,2,i)
ax.imshow(data)
plt.suptitle('Main t... |
Pyplot, main title, subplot | 7,066,121 | 49 | 2011-08-15T14:28:57Z | 28,132,929 | 13 | 2015-01-25T03:31:59Z | [
"python",
"matplotlib"
] | Simple question: I am using `pyplot`, I have 4 subplots. How to set a single, main title above all the subplots? `title()` sets it above the last subplot. | If your subplots also have titles, you may need to adjust the main title size:
```
plt.suptitle("Main Title", size=16)
``` |
Pyplot, main title, subplot | 7,066,121 | 49 | 2011-08-15T14:28:57Z | 35,676,071 | 13 | 2016-02-27T22:11:18Z | [
"python",
"matplotlib"
] | Simple question: I am using `pyplot`, I have 4 subplots. How to set a single, main title above all the subplots? `title()` sets it above the last subplot. | A few points I find useful when applying this to my own plots:
* I prefer the consistency of using `fig.suptitle(title)` rather than `plt.suptitle(title)`
* When using `fig.tight_layout()` the title must be shifted with `fig.subplots_adjust(top=0.88)`
* See answer [below](http://stackoverflow.com/a/28132929/4013571) a... |
Weirdness calling str() to convert integer to string in Python 3? | 7,067,524 | 4 | 2011-08-15T16:13:24Z | 7,067,550 | 7 | 2011-08-15T16:15:42Z | [
"python",
"python-3.x",
"shadowing"
] | Why is this giving me an error?
```
>>> variable = str(21)
Traceback (most recent call last):
File "<pyshell#101>", line 1, in <module>
variable = str(21)
TypeError: 'str' object is not callable
``` | Because you've probably overwritten the `str` function by calling your own variable `str`. |
Weirdness calling str() to convert integer to string in Python 3? | 7,067,524 | 4 | 2011-08-15T16:13:24Z | 7,067,564 | 20 | 2011-08-15T16:16:43Z | [
"python",
"python-3.x",
"shadowing"
] | Why is this giving me an error?
```
>>> variable = str(21)
Traceback (most recent call last):
File "<pyshell#101>", line 1, in <module>
variable = str(21)
TypeError: 'str' object is not callable
``` | That code alone won't give you an error. For example, I just tried this:
```
~ $ python3.2
>>> variable = str(21)
>>> variable
'21'
```
Somewhere in your code you're defining that `str =` something else, masking the builtin definition of `str`. Remove that and your code will work fine. |
How do I read the output of the IPython %prun (profiler) command? | 7,069,733 | 17 | 2011-08-15T19:30:37Z | 7,070,146 | 21 | 2011-08-15T20:06:01Z | [
"python",
"interpreter",
"profiler",
"ipython"
] | I run this:
```
In [303]: %prun my_function()
384707 function calls (378009 primitive calls) in 83.116 CPU seconds
Ordered by: internal time
ncalls tottime percall cumtime percall filename:lineno(function)
37706 41.693 0.001 41.693 0.001 {max}
20039 36.000 0.002 36.000 ... | It's just a convenient wrapper for Python's own profiler, the documentation for which is here:
<http://docs.python.org/library/profile.html#module-pstats>
Quoting:
```
ncalls
for the number of calls,
tottime
for the total time spent in the given function (and excluding time made in calls to sub-functions),
p... |
How can I securely pass an arbitrarily deep path to a webapp (Flask, in this case)? | 7,069,753 | 6 | 2011-08-15T19:31:39Z | 7,091,541 | 7 | 2011-08-17T10:47:24Z | [
"python",
"web-applications",
"flask",
"werkzeug"
] | I have a form that sends a string to my Flask app when the form is posted. The string is a filepath, so I'd like to make sure it doesn't contain anything nasty, like `../../../etc/passwd`. Werkzeug, which Flask uses, has a handy function called `secure_filename` that strips nasty stuff out of filenames. Unfortunately, ... | For situations like this Flask has `safe_join` which raises 404 if a user attempts to leave the path:
```
>>> safe_join('/foo/bar', 'test')
'/foo/bar/test'
>>> safe_join('/foo/bar', 'test/../other_test')
'/foo/bar/other_test'
>>> safe_join('/foo/bar', 'test/../../../etc/htpassw')
Traceback (most recent call last):
F... |
twisted - get OS-chosen listen port | 7,069,948 | 9 | 2011-08-15T19:49:38Z | 7,073,546 | 17 | 2011-08-16T04:08:28Z | [
"python",
"tcp",
"twisted",
"p2p"
] | I am writing a twisted P2P client using the application framework. The listen port for incoming connections will be on a random (OS-determined) port. However, I need a way to determine what that port is after creating it:
```
import twisted... etc.
application = service.Application('vmesh')
peerservice = MyPeerServic... | `listenTCP` returns an [`IListeningPort`](http://twistedmatrix.com/documents/11.0.0/api/twisted.internet.interfaces.IListeningPort.html), which has a `getHost()` method that gives back an object with a `port`. For example:
```
>>> from twisted.internet import reactor
>>> from twisted.internet.protocol import Factory
>... |
python collections.defaultdict() compile error | 7,070,296 | 3 | 2011-08-15T20:17:04Z | 7,070,341 | 12 | 2011-08-15T20:20:21Z | [
"python",
"dictionary",
"defaultdict"
] | The following code, simple and clear enough, produces an error when compiled:
```
import string
import collections
#create dictionary with alphabets as keys, and empty values
list = ['aema', 'airplane', 'amend']
gen_dict = dict.fromkeys(string.ascii_lowercase, '')
gen_dict = collections.defaultdict(list)
for x in ... | you overwrite the internal `list`, being the name of a type, with your `list = ['aema', 'airplane', 'amend']` above. Rename your `list` to e.g. `keys` or `keylist` and all will be fine.
So replace
```
list = ['aema', 'airplane', 'amend']
```
with
```
keys = ['aema', 'airplane', 'amend']
```
and
```
for x in list:... |
Passing options to nose in a Python test script | 7,070,501 | 11 | 2011-08-15T20:33:58Z | 7,070,571 | 7 | 2011-08-15T20:38:59Z | [
"python",
"nose"
] | Rather than running my nose tests from the command line, I'm using a test runner that sets up a few things for all the tests, including a connection to a local test instance of MongoDB. The documentation for nose only seems to indicate how to pass options through the command line or a configuration file located in your... | Like this:
```
import nose
argv = ['fake', '--with-xunit']
nose.main(argv=argv)
```
The "fake" argument must be added to stand in for the executable name, as described in dbw's answer. |
Passing options to nose in a Python test script | 7,070,501 | 11 | 2011-08-15T20:33:58Z | 13,888,865 | 16 | 2012-12-15T02:48:25Z | [
"python",
"nose"
] | Rather than running my nose tests from the command line, I'm using a test runner that sets up a few things for all the tests, including a connection to a local test instance of MongoDB. The documentation for nose only seems to indicate how to pass options through the command line or a configuration file located in your... | Nose does something sneaky with the first argument, so it is not parsed. My nose wrapper does something like this:
```
import nose
import sys
argv = sys.argv[:]
argv.insert(1, "--with-xunit")
nose.main(argv=argv)
```
As a bonus, this allows the clients of your program to use Nose arguments to control its behavior! |
DJANGO_SETTINGS_MODULE not importing my model classes | 7,070,693 | 2 | 2011-08-15T20:50:15Z | 9,635,273 | 7 | 2012-03-09T14:02:41Z | [
"python",
"django"
] | I read from various posts that you can use DJANGO\_SETTINGS\_MODULE = APPNAME.settings to import model classes to run with python scripts on the linux command line. I tried running:
DJANGO\_SETTINGS\_MODULE=dishtank.settings PYTHONPATH=$HOME/pythonDirLocation python pythonScript.py
In my python script I need to impor... | The `setup_environ` solution is [deprecated since version 1.4](https://docs.djangoproject.com/en/dev/releases/1.4/#django-core-management-setup-environ), thus a new solution is to follow the guidelines of the [official doc](http://readthedocs.org/docs/django/en/latest/topics/settings.html).
In essence, you need to ada... |
Print the actual query MySQLdb runs? | 7,071,166 | 38 | 2011-08-15T21:43:37Z | 7,190,914 | 65 | 2011-08-25T13:08:44Z | [
"python",
"mysql",
"mysql-python"
] | I'm looking for a way to debug queries as they are executed and I was wondering if there is a way to have MySQLdb print out the actual query that it runs, after it has finished inserting the parameters and all that? From the documentation, it seems as if there is supposed to be a Cursor.info() call that will give infor... | We found an attribute on the cursor object called `cursor._last_executed` that holds the last query string to run even when an exception occurs. This was easier and better for us in production than using profiling all the time or MySQL query logging as both of those have a performance impact and involve more code or m... |
Print the actual query MySQLdb runs? | 7,071,166 | 38 | 2011-08-15T21:43:37Z | 23,649,936 | 12 | 2014-05-14T08:55:08Z | [
"python",
"mysql",
"mysql-python"
] | I'm looking for a way to debug queries as they are executed and I was wondering if there is a way to have MySQLdb print out the actual query that it runs, after it has finished inserting the parameters and all that? From the documentation, it seems as if there is supposed to be a Cursor.info() call that will give infor... | You can print the last executed query with the cursor attribute `_last_executed`:
```
try:
cursor.execute(sql, (arg1, arg2))
connection.commit()
except:
print(cursor._last_executed)
raise
```
Currently, there is a discussion how to get this as a real feature in pymysql (see [pymysql issue #330: Add mo... |
Testing for 400 errors with paste on a web.py app | 7,071,210 | 11 | 2011-08-15T21:48:33Z | 7,942,966 | 23 | 2011-10-30T02:33:18Z | [
"python",
"functional-testing",
"paste"
] | I'm using paste to do some functional testing on my 'controllers' in my web.py app. In one case I'm trying to test for a 400 response when a malformed post is made to an API endpoint. Here is what my test looks like:
```
def test_api_users_index_post_malformed(self):
r = self.testApp.post('/api/users', params={})
... | I know I'm tardy to the party, but I ran across this searching for the answer to the same issue. To allow the TestApp to pass non 2xx/3xx responses back you need to tell the request to allow "errors".
```
def test_api_users_index_post_malformed(self):
r = self.testApp.post('/api/users', params={}, expect_errors=Tr... |
Create a slice using a tuple | 7,071,264 | 14 | 2011-08-15T21:54:08Z | 7,071,292 | 7 | 2011-08-15T21:57:48Z | [
"python",
"arrays",
"python-3.x",
"tuples",
"slice"
] | Is there any way in python to use a tuple as the indices for a slice?
The following is not valid:
```
>>> a = range(20)
>>> b = (5, 12) # my slice indices
>>> a[b] # not valid
>>> a[slice(b)] # not valid
>>> a[b[0]:b[1]] # is an awkward syntax
[5, 6, 7, 8, 9, 10, 11]
>>> b1, b2 = b
>>> a[b1:b2] # loo... | How about `a[slice(*b)]`?
Is that sufficiently pythonic? |
Create a slice using a tuple | 7,071,264 | 14 | 2011-08-15T21:54:08Z | 7,071,303 | 28 | 2011-08-15T21:58:53Z | [
"python",
"arrays",
"python-3.x",
"tuples",
"slice"
] | Is there any way in python to use a tuple as the indices for a slice?
The following is not valid:
```
>>> a = range(20)
>>> b = (5, 12) # my slice indices
>>> a[b] # not valid
>>> a[slice(b)] # not valid
>>> a[b[0]:b[1]] # is an awkward syntax
[5, 6, 7, 8, 9, 10, 11]
>>> b1, b2 = b
>>> a[b1:b2] # loo... | You can use Python's `*args` syntax for this:
```
>>> a = range(20)
>>> b = (5, 12)
>>> a[slice(*b)]
[5, 6, 7, 8, 9, 10, 11]
```
Basically, you're telling Python to unpack the tuple `b` into individual elements and pass each of those elements to the `slice()` function as individual arguments. |
what's the tornado ioloop, and tornado's workflow? | 7,072,701 | 20 | 2011-08-16T01:37:17Z | 7,078,286 | 26 | 2011-08-16T12:36:58Z | [
"python",
"tornado"
] | i want to know tornado's internal workflow, and have seen [this article](http://golubenco.org/?p=16), it's great, but something i just can't figure out
within the ioloop.py, there is such a function
```
def add_handler(self, fd, handler, events):
"""Registers the given handler to receive the given events for fd."... | I'll see if I can answer your questions in order:
* Here `_impl` is whichever socket polling mechanism is available, `epoll` on Linux, `select` on Windows. So `self._impl.register(fd, events | self.ERROR)` passes the "wait for some event" request to the underlying operating system, also specifically including error ev... |
Preserve space when stripping HTML with Beautiful Soup | 7,072,789 | 2 | 2011-08-16T01:50:46Z | 7,072,808 | 7 | 2011-08-16T01:53:29Z | [
"python",
"html",
"beautifulsoup"
] | ```
from BeautifulSoup import BeautifulSoup
html = "<html><p>Para 1. Words</p><p>Merge. Para 2<blockquote>Quote 1<blockquote>Quote 2</p></html>"
print html
soup = BeautifulSoup(html)
print u''.join(soup.findAll(text=True))
```
The out put of this code is "Para 1 WordsMerge. Para 2Quote 1Quote 2".
I don't want the la... | Just join the pieces with a space:
```
print u' '.join(soup.findAll(text=True))
``` |
Including a formatted iterable as part of a larger formatted string | 7,072,938 | 13 | 2011-08-16T02:17:17Z | 7,073,020 | 8 | 2011-08-16T02:31:06Z | [
"python",
"python-3.x"
] | In writing a class recently, I initially included a `__repr__` method along the following lines:
```
return "{}({!r}, {!r}, {!r})".format(
self.__class__.__name__,
self.arg1,
self.arg2,
self.arg3)
```
Repeating the '{!r}' snippet like that feels wrong an... | My inclination would be, if you don't like the code, hide it in a function:
```
def repr_all(*args):
return ", ".join(repr(a) for a in args)
def __repr__(self):
args = repr_all(self.arg1, self.arg2, self.arg3)
return "{}({})".format(self.__class__.__name__, args)
``` |
Including a formatted iterable as part of a larger formatted string | 7,072,938 | 13 | 2011-08-16T02:17:17Z | 7,073,050 | 8 | 2011-08-16T02:35:04Z | [
"python",
"python-3.x"
] | In writing a class recently, I initially included a `__repr__` method along the following lines:
```
return "{}({!r}, {!r}, {!r})".format(
self.__class__.__name__,
self.arg1,
self.arg2,
self.arg3)
```
Repeating the '{!r}' snippet like that feels wrong an... | If this is a pattern you're going to repeat, I'd probably use:
```
# This is a static method or module-level function
def argrepr(name, *args):
return '{}({})'.format(name, ', '.join(repr(arg) for arg in args))
def __repr__(self):
return argrepr(self.__name__, self.arg1, self.arg2, self.arg3)
```
or
```
# T... |
Remove traceback in Python on Ctrl-C? | 7,073,268 | 9 | 2011-08-16T03:16:40Z | 7,073,293 | 15 | 2011-08-16T03:20:00Z | [
"python",
"traceback",
"keyboardinterrupt"
] | Is there a way to keep tracebacks from coming up when you hit Cntl-c [keyboardInterupt] in a python script? | ```
import sys
try:
# your code
except KeyboardInterrupt:
sys.exit(0) # or 1, or whatever
```
Is the simplest way, assuming you still want to exit when you get a Ctrl-C.
If you want to trap it without a try/except, you can use a [recipe like this](http://stacyprowell.com/blog/2009/03/30/trapping-ctrlc-in-pyth... |
Remove traceback in Python on Ctrl-C? | 7,073,268 | 9 | 2011-08-16T03:16:40Z | 11,762,636 | 14 | 2012-08-01T15:32:49Z | [
"python",
"traceback",
"keyboardinterrupt"
] | Is there a way to keep tracebacks from coming up when you hit Cntl-c [keyboardInterupt] in a python script? | Try this:
```
import signal
signal.signal(signal.SIGINT, lambda x,y: sys.exit(0))
```
This way you don't need to wrap everything in an exception handler. |
How to run Google app engine web server on Windows correct? | 7,073,679 | 5 | 2011-08-16T04:43:09Z | 7,073,791 | 9 | 2011-08-16T05:02:38Z | [
"python",
"google-app-engine",
"python-3.x",
"python-2.x"
] | I tried to run Google App Engine development server using Python 3.2 and Python 2.7, got errors on both:
Python 2.7:
```
D:\nCdy\WA>C:\Python27\python.exe "D:\Program Files\Google\google_appengine\dev_
appserver.py" wa.py
Traceback (most recent call last):
File "D:\Program Files\Google\google_appengine\dev_appserve... | It won't work with Python 3.2.
I've had no trouble with GAE and Python 2.7 on Windows 7. It will soon be the officially supported version.
Right now, the officially supported version is Python 2.5, so you should download that if you have any problems getting other versions to work.
I'd suggest something like [Active... |
How do you use a python decorator on a function whose definition you cannot access? | 7,073,738 | 3 | 2011-08-16T04:52:28Z | 7,073,754 | 7 | 2011-08-16T04:55:30Z | [
"python",
"decorator"
] | Suppose that for administrative reasons I do not have write access to module xxx.
I want to do something like:
```
from xxx import yyy
@myDeco
yyy
```
which of course fails.
I think I can do
```
yyy = myDeco(yyy)
```
but is there a way to use the `@myDeco`" notation ? Or is this only permitted immediately before... | The `@` syntax is only allowed before a `def` or `class`. |
What is the best way to generate all possible three letter strings? | 7,074,051 | 17 | 2011-08-16T05:46:05Z | 7,074,066 | 42 | 2011-08-16T05:48:35Z | [
"python",
"performance"
] | I am generating all possible three letters keywords `e.g. aaa, aab, aac.... zzy, zzz` below is my code:
```
alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
keywords = []
for alpha1 in alphabets:
for alpha2 in alphabets:... | ```
keywords = itertools.product(alphabets, repeat = 3)
```
See the [documentation for `itertools.product`](http://docs.python.org/library/itertools.html#itertools.product). If you need a list of strings, just use
```
keywords = [''.join(i) for i in itertools.product(alphabets, repeat = 3)]
```
`alphabets` also does... |
What is the best way to generate all possible three letter strings? | 7,074,051 | 17 | 2011-08-16T05:46:05Z | 7,074,219 | 9 | 2011-08-16T06:08:18Z | [
"python",
"performance"
] | I am generating all possible three letters keywords `e.g. aaa, aab, aac.... zzy, zzz` below is my code:
```
alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
keywords = []
for alpha1 in alphabets:
for alpha2 in alphabets:... | You could also use map instead of the list comprehension (this is one of the cases where map is still faster than the LC)
```
>>> from itertools import product
>>> from string import ascii_lowercase
>>> keywords = map(''.join, product(ascii_lowercase, repeat=3))
```
This variation of the list comprehension is also fa... |
What is __future__ in Python used for and how/when to use it, and how it works | 7,075,082 | 152 | 2011-08-16T07:52:30Z | 7,075,121 | 87 | 2011-08-16T07:56:46Z | [
"python"
] | People including me know there is something in Python called `__future__` and it appears in quite a few modules I read. And the dull people like me don't know why it's there, and how/when to use it , even after reading [the Python's `__future__` doc](http://docs.python.org/library/__future__.html).
So any explains wit... | With it, you can slowly be accustomed to incompatible changes or to such ones introducing new keywords.
E.g., for using context managers, you had to do `from __future__ import with_statement` in 2.5, as the `with` keyword was new and shouldn't be used as variable names any longer. In order to be able to use a program ... |
What is __future__ in Python used for and how/when to use it, and how it works | 7,075,082 | 152 | 2011-08-16T07:52:30Z | 7,075,152 | 71 | 2011-08-16T08:00:00Z | [
"python"
] | People including me know there is something in Python called `__future__` and it appears in quite a few modules I read. And the dull people like me don't know why it's there, and how/when to use it , even after reading [the Python's `__future__` doc](http://docs.python.org/library/__future__.html).
So any explains wit... | When you do
```
from __future__ import whatever
```
You're not actually using an `import` statement, but a [future statement](http://docs.python.org/reference/simple_stmts.html#future-statements). You're reading the wrong docs, as you're not actually importing that module.
Future statements are special -- they chang... |
What is __future__ in Python used for and how/when to use it, and how it works | 7,075,082 | 152 | 2011-08-16T07:52:30Z | 7,075,177 | 13 | 2011-08-16T08:02:30Z | [
"python"
] | People including me know there is something in Python called `__future__` and it appears in quite a few modules I read. And the dull people like me don't know why it's there, and how/when to use it , even after reading [the Python's `__future__` doc](http://docs.python.org/library/__future__.html).
So any explains wit... | It can be used to use features which will appear in newer versions while having an older release of Python.
For example
```
>>> from __future__ import print_function
```
will allow you to use `print` as a function:
```
>>> print('# of entries', len(dictionary), file=sys.stderr)
``` |
What is __future__ in Python used for and how/when to use it, and how it works | 7,075,082 | 152 | 2011-08-16T07:52:30Z | 14,989,446 | 23 | 2013-02-20T20:38:02Z | [
"python"
] | People including me know there is something in Python called `__future__` and it appears in quite a few modules I read. And the dull people like me don't know why it's there, and how/when to use it , even after reading [the Python's `__future__` doc](http://docs.python.org/library/__future__.html).
So any explains wit... | `__future__` **is a pseudo-module which programmers can use to enable new language features which are not compatible with the current interpreter**. For example, the expression `11/4` currently evaluates to `2`. If the module in which it is executed had enabled true division by executing:
`from __future__ import divis... |
Converting Exception to a string in Python 3 | 7,075,200 | 21 | 2011-08-16T08:04:04Z | 7,075,416 | 20 | 2011-08-16T08:23:01Z | [
"python",
"exception",
"unicode",
"character-encoding"
] | does anyone have an idea, why this Python 3.2 code
```
try:
raise Exception('X')
except Exception as e:
print("Error {0}".format(str(e)))
```
works without problem (apart of unicode encoding in windows shell :/),
but this
```
try:
raise Exception('X')
except Exception as e:
print("Error {0}".... | In Python 3.x, `str(e)` should be able to convert any `Exception` to a string, even if it contains Unicode characters.
So unless your exception actually returns an UTF-8 encoded byte array in its custom `__str__()` method, `str(e, 'utf-8')` will not work as expected (it would try to interpret a 16bit Unicode character... |
Is there a good way to do this type of mining? | 7,076,349 | 13 | 2011-08-16T09:48:47Z | 7,237,972 | 12 | 2011-08-30T02:05:05Z | [
"python",
"algorithm",
"data-mining"
] | I am trying to find points that are closest in space in X and Y directions (sample dataset given at the end) and am looking to see if there are smarter approaches to do this than my trivial (and untested) approach. The plot of these points in space looks something like the following and am trying to find sets of points... | This is a little late, but this problem has been worrying me for some time. I
was sure it could be solved with mixed integer / linear programming techniques
and asked for help in this question: [Identifying column and row clusters with linear programming](http://stackoverflow.com/q/7137334/181772)
However, after getti... |
does Python for windows ever insert '\r\n' when told to insert '\n'? | 7,077,355 | 3 | 2011-08-16T11:17:13Z | 7,077,425 | 9 | 2011-08-16T11:22:52Z | [
"python",
"line-breaks",
"python-2.x",
"pc"
] | I use a PC at home and a Mac at work. I've never had any problems with line breaks in python script or their outputs, but whenever i send something to my boss i get an angry e-mail back about windows line breaks in it.
The most recent was the output of a python script where i'd told it to end every line with '\n', but... | This is because you have files opened in text mode and Python is normalizing the newlines in accordance with the platform you're using (Windows used `\r\n` and Linux just uses `\n`). You need to open files in binary mode like this:
```
f = open("myfile.txt","wb")
```
It does the same thing in reverse when you read in... |
[python]: problem about python string literals | 7,077,419 | 3 | 2011-08-16T11:22:27Z | 7,077,452 | 7 | 2011-08-16T11:25:23Z | [
"python",
"backslash"
] | code goes below:
```
line = r'abc\def\n'
rline = re.sub('\\\\', '+', line) # then rline should be r'abc+def+n'
```
Apparently, I just want to replace the backslashes in line with '+'.
What I thought was that a backslash in line can be expressed as '\', then why should I use '\\' to get the re.sub work right.
I'm con... | It's a good habit to *always* use raw strings when dealing with regex patterns:
```
In [45]: re.sub(r'\\', r'+', line)
Out[45]: 'abc+def+n'
```
To answer your question though, Python interprets `'\\\\'` as two backslash characters:
```
In [44]: list('\\\\')
Out[44]: ['\\', '\\']
```
And the rules of regex interpret... |
python how to memoize a method | 7,077,820 | 3 | 2011-08-16T11:56:26Z | 7,077,892 | 8 | 2011-08-16T12:01:12Z | [
"python",
"performance",
"memoization",
"cprofile"
] | Say I a method to create a dictionary from the given parameters:
```
def newDict(a,b,c,d): # in reality this method is a bit more complex, I've just shortened for the sake of simplicity
return { "x": a,
"y": b,
"z": c,
"t": d }
```
And I have another method that calls newDic... | If by memorizing you mean memoizing, use [`functools.lru_cache`](http://docs.python.org/dev/library/functools.html#functools.lru_cache).
It's a function decorator |
python how to memoize a method | 7,077,820 | 3 | 2011-08-16T11:56:26Z | 7,077,930 | 9 | 2011-08-16T12:04:14Z | [
"python",
"performance",
"memoization",
"cprofile"
] | Say I a method to create a dictionary from the given parameters:
```
def newDict(a,b,c,d): # in reality this method is a bit more complex, I've just shortened for the sake of simplicity
return { "x": a,
"y": b,
"z": c,
"t": d }
```
And I have another method that calls newDic... | 1. You mean `memoize` not `memorize`.
2. If the values are almost always different, memoizing won't help, it will slow things down.
3. Without seeing your full code, and knowing what it's supposed to do, how can we know if 17k calls is a lot or the little? |
Conventions on creating constants in Python | 7,078,731 | 6 | 2011-08-16T13:12:24Z | 7,078,864 | 8 | 2011-08-16T13:22:50Z | [
"coding-style",
"python"
] | I am writing an application which needs to find out the schema of a database, across engines. To that end, I am writing a small database adapter using Python. I decided to first write a base class that outlines the functionality I need, and then implement it using classes that inherit from this base. Along the way, I n... | > what is the standard way of sharing such constants?
Throughout the standard library, the most common way is to define constants as module-level variables using UPPER\_CASE\_WITH\_UNDERSCORES names.
> what is the right way to create constants that can be combined? I am referring to MAP\_FIXED | MAP\_FILE | MAP\_SHAR... |
In python, when you pass internally defined functions into other functions, how does it keep the variables? | 7,078,840 | 8 | 2011-08-16T13:20:49Z | 7,078,948 | 7 | 2011-08-16T13:29:28Z | [
"python",
"function",
"function-pointers"
] | For example, why does this work?
```
def func1(func1var):
def innerfunc(innerfuncvar):
if func1var == 1:
print innerfuncvar
else:
print 5
func2(innerfunc)
def func2(function):
function(9)
```
When `innerfunc` is called in `func2`, how does it know the values of... | You've created a [closure](http://ynniv.com/blog/2007/08/closures-in-python.html). Basically, think of it like this, from the point of view of the inner function:
```
func1var = whatever
def func2(function):
function(9)
def innerfunc(innerfuncvar):
if func1var = 1:
print innerfuncvar
else:
... |
Django static structure | 7,078,930 | 8 | 2011-08-16T13:28:09Z | 9,124,711 | 10 | 2012-02-03T06:43:03Z | [
"python",
"django"
] | I am trying to understand the static structure django 1.3 tries to pursue:
I have a Project with this structure:
```
Project
someapp
static
someapp
css
etcetera
models.py
views.py
urls.py
urls.py
manage.py
settings.py
```
Now I wish to overwrite... | For local development, try this structure
```
Project
Project (project directory with settings.py etc..)
stylesheets
someapp
static
base.css
```
With this in `settings.py`:
```
import os
ROOT_PATH = os.path.dirname(__file__)
STATIC_ROOT = os.path.join(ROOT_PATH, 'static')
STATIC_URL = '/static/'
S... |
Python: get a dict from a list based on something inside the dict | 7,079,241 | 14 | 2011-08-16T13:53:25Z | 7,079,297 | 32 | 2011-08-16T13:57:34Z | [
"python",
"performance",
"list",
"dictionary"
] | I need to be able to find an item in a `list` (an item in this case being a `dict`) based on some value inside that `dict`. The structure of the `list` I need to process looks like this:
```
[
{
'title': 'some value',
'value': 123.4,
'id': 'an id'
},
{
'title': 'another titl... | ```
my_item = next((item for item in my_list if item['id'] == my_unique_id), None)
```
This iterates through the list until it finds the first item matching `my_unique_id`, then stops. It doesn't store any intermediate lists in memory (by using a generator expression) or require an explicit loop. It sets `my_item` to ... |
Python: get a dict from a list based on something inside the dict | 7,079,241 | 14 | 2011-08-16T13:53:25Z | 7,079,326 | 13 | 2011-08-16T13:58:56Z | [
"python",
"performance",
"list",
"dictionary"
] | I need to be able to find an item in a `list` (an item in this case being a `dict`) based on some value inside that `dict`. The structure of the `list` I need to process looks like this:
```
[
{
'title': 'some value',
'value': 123.4,
'id': 'an id'
},
{
'title': 'another titl... | If you have to do this multiple times, you should recreate a dictionnary indexed by id with your list :
```
keys = [item['id'] for item in initial_list]
new_dict = dict(zip(keys, initial_list))
>>>{
'yet another id': {'id': 'yet another id', 'value': 901.20000000000005, 'title': 'last title'},
'an id': {'id... |
sorting large text data | 7,079,473 | 7 | 2011-08-16T14:08:24Z | 7,079,683 | 15 | 2011-08-16T14:20:57Z | [
"python",
"sorting",
"bigdata"
] | I have a large file (100 million lines of tab separated values - about 1.5GB in size). What is the fastest known way to sort this based on one of the fields?
I have tried hive. I would like to see if this can be done faster using python. | Have you considered using the \*nix [`sort`](http://compute.cnr.berkeley.edu/cgi-bin/man-cgi?sort%201) program? in raw terms, it'll probably be faster than most Python scripts.
Use `-t $'\t'` to specify that it's tab-separated, `-k n` to specify the field, where `n` is the field number, and `-o outputfile` if you want... |
sorting large text data | 7,079,473 | 7 | 2011-08-16T14:08:24Z | 7,079,726 | 7 | 2011-08-16T14:23:44Z | [
"python",
"sorting",
"bigdata"
] | I have a large file (100 million lines of tab separated values - about 1.5GB in size). What is the fastest known way to sort this based on one of the fields?
I have tried hive. I would like to see if this can be done faster using python. | you want to build an in-memory index for the file:
1. create an empty list
2. `open` the file
3. read it line by line (using `f.readline()`, and store in the list a tuple consisting of the value on which you want to sort (extracted with `line.split('\t').strip()`) and the offset of the line in the file (which you can ... |
Are there technical reasons a Ruby DSL like RSpec couldn't be rewritten in Python? | 7,079,855 | 20 | 2011-08-16T14:31:03Z | 7,169,569 | 10 | 2011-08-24T01:46:17Z | [
"python",
"ruby",
"rspec",
"dsl"
] | The section below goes into more detail, but basically someone stated that the Ruby-written [DSL](http://en.wikipedia.org/wiki/Domain-specific_language) [RSpec](http://rspec.info/) couldn't be rewritten in Python. Is that true? If so, why?
I'm wanting to better understand the technical differences between Ruby and Pyt... | If I had to point out one great difficulty for creating a Python RSpec, it would be the lack of a good syntax in Python for creating anonymous functions (as in JavaScript) or blocks (as in Ruby). The only option for a Python programmer is to use lambdas, which is not an option at all because lambdas just accept one exp... |
webapp2 + jinja2: How can i get uri_for() working in jinja2-views | 7,081,250 | 18 | 2011-08-16T16:05:45Z | 7,081,653 | 26 | 2011-08-16T16:37:02Z | [
"python",
"google-app-engine",
"jinja2",
"webapp2"
] | How can i add pass Model-Specific urls to the Template.
Let's say, i want to build an edit-link.
I would guess, using the uri\_for() function would be an easy approach.
But the following gives me "UndefinedError: 'webapp2' is undefined"
```
{% webapp2.uri_for("editGreeting", greeting.key().id()) %}
```
Or should i p... | You must set `uri_for` as a global variable. One way to do it is to set an initializer for global variables and filters:
```
import webapp2
from webapp2_extras import jinja2
def jinja2_factory(app):
j = jinja2.Jinja2(app)
j.environment.filters.update({
# Set filters.
# ...
})
j.environ... |
Python max recursion , question about sys.setrecursionlimit() | 7,081,448 | 12 | 2011-08-16T16:20:17Z | 7,081,504 | 12 | 2011-08-16T16:24:28Z | [
"python",
"recursion"
] | I have one question about **sys.setrecursionlimit()**
from the python doc this function :
*Set the maximum depth of the Python interpreter stack to limit. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python.
The highest possible limit is platform-dependent. A user may ne... | It's poorly named. It should say Stack Depth, not Recursion depth. Recursion implies it's the same thread over and over again that it's limiting. In reality, you could have actual code that just has calls 100 deep. I wouldn't recommend it, but you could. They can get away with it because in the practical world, the onl... |
How to set the labels size on a pie chart in python | 7,082,345 | 12 | 2011-08-16T17:27:06Z | 7,082,651 | 12 | 2011-08-16T17:52:08Z | [
"python",
"matplotlib",
"pie-chart",
"labels"
] | I want to have labels with small size on a piechart in python to improve visibility
here is the code
```
import matplotlib.pyplot as plt
frac=[1.40 , 10.86 , 19.31 , 4.02 , 1.43 , 2.66 , 4.70 , 0.70 , 0.13 , 1.48, 32.96 , 1.11 , 13.30 , 5.86]
labels=['HO0900344', 'HO0900331', 'HO0900332', 'HO0900354',
'HO0900358', '... | There are a couple of ways you can change the font size of the labels.
You can [dynamically changet the rc settings](http://matplotlib.sourceforge.net/users/customizing.html#dynamic-rc-settings). Add the following at the top of your script:
```
import matplotlib as mpl
mpl.rcParams['font.size'] = 9.0
```
Or you can ... |
Suppress output from subprocess.Popen | 7,082,623 | 10 | 2011-08-16T17:50:09Z | 7,082,702 | 18 | 2011-08-16T17:56:18Z | [
"python",
"subprocess"
] | How do you stop the output from subprocess.Popen from being output? Printing can sometimes be slow if there is a great deal of it. | If you want to totally throw it away:
```
import subprocess
import os
with open(os.devnull, 'w') as fp:
cmd = subprocess.Popen(("[command]",), stdout=fp)
```
If you are using Python 2.5, you will need `from __future__ import with_statement`, or just don't use `with`. |
Suppress output from subprocess.Popen | 7,082,623 | 10 | 2011-08-16T17:50:09Z | 17,679,894 | 7 | 2013-07-16T14:50:26Z | [
"python",
"subprocess"
] | How do you stop the output from subprocess.Popen from being output? Printing can sometimes be slow if there is a great deal of it. | In Python 3.3+ you could use [`subprocess.DEVNULL`](http://docs.python.org/3/library/subprocess.html#subprocess.DEVNULL), to suppress the output:
```
from subprocess import DEVNULL, STDOUT, check_call
check_call([cmd, arg1, arg2], stdout=DEVNULL, stderr=STDOUT)
```
Remove `stderr=STDOUT` if you don't want to suppres... |
Should I Return None or (None, None)? | 7,082,966 | 52 | 2011-08-16T18:14:16Z | 7,083,004 | 55 | 2011-08-16T18:16:57Z | [
"python",
"python-3.x",
"coding-style"
] | We have a object method that returns a city/state tuple, i.e. `('Boston', 'MA')`. Under some valid circumstances, there is no valid city/state to return. Stylistically, does it make more sense to return `None`, or a two element tuple containing `(None, None)` in that case? | I would return `None`. If there is no result, why return something that *looks* like a result?
It is also easier to test:
```
result = getCity()
if result:
# do something
```
I would only return `(None, None)` if it were possible that only one of the two values is `None` (i.e. `('Boston', None)`). It would be mor... |
Should I Return None or (None, None)? | 7,082,966 | 52 | 2011-08-16T18:14:16Z | 7,083,006 | 10 | 2011-08-16T18:17:06Z | [
"python",
"python-3.x",
"coding-style"
] | We have a object method that returns a city/state tuple, i.e. `('Boston', 'MA')`. Under some valid circumstances, there is no valid city/state to return. Stylistically, does it make more sense to return `None`, or a two element tuple containing `(None, None)` in that case? | `(None, None)` does not evaluate to `False` in Python. In addition, building a tuple requires more work than, well, not building a tuple. So I would prefer `None`. |
Should I Return None or (None, None)? | 7,082,966 | 52 | 2011-08-16T18:14:16Z | 7,083,039 | 43 | 2011-08-16T18:19:34Z | [
"python",
"python-3.x",
"coding-style"
] | We have a object method that returns a city/state tuple, i.e. `('Boston', 'MA')`. Under some valid circumstances, there is no valid city/state to return. Stylistically, does it make more sense to return `None`, or a two element tuple containing `(None, None)` in that case? | By only returning one value in exceptional circumstances, you risk breaking the tuple unpacking idiom. Some of your callers might issue:
```
city, state = getCityStateTuple("something")
```
In that case, returning `None` will break *the caller* with the error:
`TypeError: 'NoneType' object is not iterable`
So, I pe... |
Should I Return None or (None, None)? | 7,082,966 | 52 | 2011-08-16T18:14:16Z | 7,083,346 | 11 | 2011-08-16T18:44:29Z | [
"python",
"python-3.x",
"coding-style"
] | We have a object method that returns a city/state tuple, i.e. `('Boston', 'MA')`. Under some valid circumstances, there is no valid city/state to return. Stylistically, does it make more sense to return `None`, or a two element tuple containing `(None, None)` in that case? | As others have noted, a tuple with items in it does not test as `False`, which is one reason you might want to return `None` rather than `(None, None)`. However, it is possible to write a tuple *subclass* that tests as `False` even when it has items in it by overriding its `__nonzero__()` method.
```
class falsetuple(... |
Python recursive function exceeds recursion limit. How can I convert it to iteration | 7,083,011 | 5 | 2011-08-16T18:17:31Z | 7,086,514 | 14 | 2011-08-16T23:54:38Z | [
"python",
"recursion",
"refactoring",
"iteration",
"sequencing"
] | I have created a function that reads lists of ID pairs (i.e. [("A","B"),("B","C"),("C","D"),...] and sequences the ID's from start to finish including any branches.
Each list of ordered ID's is held in a class called an Alignment and this function uses recursion to handle branches by creating a new alignment starting ... | your code is a disorganised muddle. i can't tell what it is supposed to be doing in detail. if you were more careful (neater, clearer) then you would probably also find it easier to refactor.
anyway, this may do something like what you want:
```
from collections import defaultdict
def expand(line, links, known):
... |
Python get mac clipboard contents | 7,083,313 | 8 | 2011-08-16T18:42:00Z | 8,309,779 | 10 | 2011-11-29T11:13:02Z | [
"python",
"osx",
"clipboard"
] | How can I, using Python (2.7) get the contents of the Mac clipboard. Is there a better way than making a wrapper around pbpaste?
Thanks! | Have you looked at the [xerox](http://pypi.python.org/pypi/xerox) module?
It is supposed to support windows, OS X and Linux
---
Usage is as follows:
> xerox.copy(u'some string')
And to paste:
> >>> xerox.paste()
> u'some string' |
Python get mac clipboard contents | 7,083,313 | 8 | 2011-08-16T18:42:00Z | 8,317,794 | 10 | 2011-11-29T21:11:49Z | [
"python",
"osx",
"clipboard"
] | How can I, using Python (2.7) get the contents of the Mac clipboard. Is there a better way than making a wrapper around pbpaste?
Thanks! | PyObjC is the way to go:
```
#!/usr/bin/python
from AppKit import *
pb = NSPasteboard.generalPasteboard()
pbstring = pb.stringForType_(NSStringPboardType)
print u"Pastboard string: %s".encode("utf-8") % repr(pbstring)
```
This only supports text and will return `None` otherwise. You can extend it to support other d... |
Is itertools thread-safe? | 7,083,348 | 12 | 2011-08-16T18:44:31Z | 7,083,576 | 11 | 2011-08-16T19:02:39Z | [
"python",
"thread-safety",
"itertools"
] | For instance, if I create an iterator using [`chain`](http://docs.python.org/library/itertools.html#itertools.chain), can I call it on multiple threads? Note that thread-safety that relies on the GIL is acceptable, but not preferable.
(Note that this is a bit different from [this question](http://stackoverflow.com/que... | Firstly, nothing in the [official documentation on itertools](http://docs.python.org/library/itertools.html#module-itertools) say that they're thread-safe. So it seems that by specification Python does not guarantee anything about that. This might be different across implementations such as Jython or PyPy, but this mea... |
In PHP classes, what is the equivalent of self from python classes? | 7,084,564 | 2 | 2011-08-16T20:27:33Z | 7,084,614 | 7 | 2011-08-16T20:31:13Z | [
"php",
"python",
"class",
"self"
] | In PHP, how can I achieve something like this from Python?
```
class CrowdProcess():
def __init__(self,variable):
self.variable = variable
def otherfunc(self):
print self.variable
``` | PHP uses `$this` as a reference to the instance:
```
class CrowdProcess
{
public $variable;
public function __construct($variable)
{
$this->variable = $variable;
}
public function otherfunc()
{
echo $this->variable, PHP_EOL;
}
}
```
For more information, see <http://php.n... |
Does it make sense to make a class in python when it would never get instantiated? | 7,085,184 | 4 | 2011-08-16T21:21:31Z | 7,085,216 | 9 | 2011-08-16T21:24:10Z | [
"python",
"encapsulation"
] | I have some methods in a file and all of them are defined in the global scope (a module). I did not bother to make a class because the class would never get instantiated and everything would still have to be accessed statically if I defined a class. Does it make sense to leave it as it is, or is it better design to mak... | Python is not Java, use module-level methods without worry. |
Request and basic profiling information for Flask | 7,085,311 | 11 | 2011-08-16T21:33:39Z | 7,085,646 | 10 | 2011-08-16T22:07:15Z | [
"python",
"performance",
"sqlite",
"logging",
"flask"
] | Most web frameworks let you know the amount of time that it took to process a certain page request. I'm starting to work with Flask framework now and am very much in need of this information but can't find any good way of getting it. Using the werkzeug Midleware profiler is an option, but it is very verbose and provide... | You should have a look at [`flask-debugtoolbar`](https://github.com/mvantellingen/flask-debugtoolbar), it's basically the same as the `django-debug-toolbar` (if you ever used it) ported to `Flask`. |
Flask blueprints proper usage | 7,085,438 | 18 | 2011-08-16T21:45:33Z | 7,091,729 | 18 | 2011-08-17T11:02:00Z | [
"python",
"flask"
] | I have a question regarding blueprints. I have an app which is structured like this
```
app
/run.py
/APP
/__init__.py
/VIEWS
/__init__.py
/general.py
/crud.py
```
this is the code <http://pastebin.com/bsHsTGAP>
**run.py**
```
from overwatch import app
app.... | To access the current application from your blueprint's views, you should use the `flask.current_app` object, it is a proxy to the current application (and it's what's used in flask extensions for example).
Regarding your code, except the unused imports, it's well organised in my opinion, but i can't tell about the `p... |
Check what number a string ends with in Python | 7,085,512 | 5 | 2011-08-16T21:51:37Z | 7,085,523 | 12 | 2011-08-16T21:52:58Z | [
"python",
"string",
"numbers"
] | Such as "example123" would be 123, "ex123ample" would be None, and "123example" would be None. | I'd use a regular expression, something like `/(\d+)$/`. This will match and capture one or more digits, anchored at the end of the string.
Read about [regular expressions in Python](http://docs.python.org/library/re.html). |
Check what number a string ends with in Python | 7,085,512 | 5 | 2011-08-16T21:51:37Z | 7,085,715 | 7 | 2011-08-16T22:13:15Z | [
"python",
"string",
"numbers"
] | Such as "example123" would be 123, "ex123ample" would be None, and "123example" would be None. | You can use regular expressions from the [`re`](http://docs.python.org/library/re.html) module:
```
import re
def get_trailing_number(s):
m = re.search(r'\d+$', s)
return int(m.group()) if m else None
```
The `r'\d+$'` string specifies the expression to be matched and consists of these [special symbols](http:... |
Sending ^C to Python subprocess objects on Windows | 7,085,604 | 16 | 2011-08-16T22:01:40Z | 7,980,368 | 9 | 2011-11-02T12:33:27Z | [
"python",
"windows",
"subprocess"
] | I have a test harness (written in Python) that needs to shut down the program under test (written in C) by sending it `^C`. On Unix,
```
proc.send_signal(signal.SIGINT)
```
works perfectly. On Windows, that throws an error ("signal 2 is not supported" or something like that). I am using Python 2.7 for Windows, so I h... | There is a solution by using a wrapper (as described in the link Vinay provided) which is started in a new console window with the Windows *start* command.
Code of the wrapper:
```
#wrapper.py
import subprocess, time, signal, sys, os
def signal_handler(signal, frame):
time.sleep(1)
print 'Ctrl+C received in wrap... |
how to know if a variable is a tuple, a string or an integer? | 7,086,990 | 7 | 2011-08-17T01:21:37Z | 7,087,005 | 14 | 2011-08-17T01:24:11Z | [
"python"
] | I am trying to figure out a type mismatch while adding a string to another string in a concatenate operation.
Basically the error returned is a type error (cannot concatenate string and tuple); so I would like to figure out where did i assigned a value as tuple instead than string.
All the values that I assign are st... | You just use:
```
type(varname)
```
which will output int, str, float, etc... |
how to know if a variable is a tuple, a string or an integer? | 7,086,990 | 7 | 2011-08-17T01:21:37Z | 7,087,006 | 8 | 2011-08-17T01:24:12Z | [
"python"
] | I am trying to figure out a type mismatch while adding a string to another string in a concatenate operation.
Basically the error returned is a type error (cannot concatenate string and tuple); so I would like to figure out where did i assigned a value as tuple instead than string.
All the values that I assign are st... | make use of isinstance ?
```
if isinstance(var, int):
if isinstance(var, str):
if isinstance(var, tuple):
``` |
how to know if a variable is a tuple, a string or an integer? | 7,086,990 | 7 | 2011-08-17T01:21:37Z | 7,087,040 | 29 | 2011-08-17T01:29:17Z | [
"python"
] | I am trying to figure out a type mismatch while adding a string to another string in a concatenate operation.
Basically the error returned is a type error (cannot concatenate string and tuple); so I would like to figure out where did i assigned a value as tuple instead than string.
All the values that I assign are st... | ```
isinstance(obj, tuple)
isinstance(obj, basestring)
isinstance(obj, int)
``` |
Python: try-except as an Expression? | 7,088,009 | 15 | 2011-08-17T04:36:36Z | 7,088,046 | 11 | 2011-08-17T04:41:56Z | [
"python"
] | I find myself having this sort of pattern over and over:
```
variable = ""
try:
variable = ... do some file loading stuff ...
except:
variable = ""
```
Is there any way to condense this into a single expression? Like with if-else statements you can turn:
```
variable = ""
if something:
variable = somethi... | ```
def try_except(success, failure):
try:
return success()
except:
return failure()
variable = try_except(do_some_file_loading_stuff, lambda: '')
```
I think the code is self explanatory. It returns the value returned by `success` unless there is an error, then it returns the value returned b... |
Python: try-except as an Expression? | 7,088,009 | 15 | 2011-08-17T04:36:36Z | 7,088,133 | 13 | 2011-08-17T04:53:48Z | [
"python"
] | I find myself having this sort of pattern over and over:
```
variable = ""
try:
variable = ... do some file loading stuff ...
except:
variable = ""
```
Is there any way to condense this into a single expression? Like with if-else statements you can turn:
```
variable = ""
if something:
variable = somethi... | Since agf already provided the approach I'd recommend, here's a version of his routine with a couple of minor enhancements:
```
def try_except(success, failure, *exceptions):
try:
return success()
except exceptions or Exception:
return failure() if callable(failure) else failure
```
This versi... |
Python: try-except as an Expression? | 7,088,009 | 15 | 2011-08-17T04:36:36Z | 7,114,074 | 7 | 2011-08-18T20:59:36Z | [
"python"
] | I find myself having this sort of pattern over and over:
```
variable = ""
try:
variable = ... do some file loading stuff ...
except:
variable = ""
```
Is there any way to condense this into a single expression? Like with if-else statements you can turn:
```
variable = ""
if something:
variable = somethi... | Here's a context manager that provides a little bit of a shortcut:
```
from contextlib import contextmanager
@contextmanager
def catch(*exceptions, **kwargs):
try:
yield kwargs.get("default", None)
except exceptions or Exception:
pass
```
Usage:
```
with catch(ZeroDivisionError, default=0) a... |
How to Query model where name contains any word in python list? | 7,088,173 | 22 | 2011-08-17T05:01:19Z | 7,088,199 | 13 | 2011-08-17T05:06:21Z | [
"python",
"django",
"list"
] | Aim to Achieve:
I want all objects where name attribute contains any word from the list.
I have:
```
list = ['word1','word2','word3']
ob_list = data.objects.filter( // What to write here ? )
// or any other way to get the objects where any word in list is contained, in
// the na-me attribute of data.
```
For exam... | ```
ob_list = data.objects.filter(name__in=my_list)
```
And BTW, avoid using the variable name "list" (Or any other python standard keyword), lest you get into some weird bugs later.
**Update:** (I guess your question was updated too, because when I wrote the answer, I didn't see the part where you wrote you need a c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.