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 |
|---|---|---|---|---|---|---|---|---|---|
Could not import settings 'myproject.settings' (Is it on sys.path?): No module named pinax | 9,353,092 | 5 | 2012-02-19T20:49:19Z | 23,746,895 | 8 | 2014-05-19T20:45:31Z | [
"python",
"django",
"pinax"
] | I'm trying to get pinax working on WebFaction and having so many issues...
```
[Sun Feb 19 20:01:20 2012] [error] [client 127.0.0.1] mod_wsgi (pid=22796): Exception occurred processing WSGI script '/home/pawesome/webapps/qtsocial/myproject.wsgi'.
[Sun Feb 19 20:01:20 2012] [error] [client 127.0.0.1] Traceback (most re... | In your terminal, cd into the directory that contains settings.py, then run
```
python settings.py
```
You may get an import error that is easily fixed (typing error, or syntax error). |
How do I get a list of all windows on my gnome2 desktop using pygtk? | 9,353,114 | 5 | 2012-02-19T20:52:32Z | 9,376,793 | 9 | 2012-02-21T11:30:12Z | [
"python",
"gtk",
"pygtk",
"gnome",
"window-management"
] | I'm a bit confused with some gtk and gnome concepts. I'm trying to get list of non minimized windows on my gnome2 desktop, but after reading the pygtk documentation and inspecting the results, I can't understand the results.
Neither of the two snippets below appears to work.
First I tried this..
```
>>> gtk.gdk.wind... | Your constraint is like saying "I want to build a CD player using only a banana. Please refrain from posting alternative solutions that resort to lasers." GTK can't do that, you're using the wrong tool for the job.
Here's an explanation of what a "window" actually means and why your code doesn't work:
First off, you ... |
Python CSV module - quotes go missing | 9,353,792 | 5 | 2012-02-19T22:13:57Z | 9,354,366 | 7 | 2012-02-19T23:24:38Z | [
"python",
"csv",
"double-quotes"
] | I have a CSV file that has data like this
```
15,"I",2,41301888,"BYRNESS RAW","","BYRNESS VILLAGE","NORTHUMBERLAND","ENG"
11,"I",3,41350101,2,2935,2,2008-01-09,1,8,0,2003-02-01,,2009-12-22,2003-02-11,377016.00,601912.00,377105.00,602354.00,10
```
I am reading this and then writing different rows to different CSV file... | When writing, `quoting=csv.QUOTE_NONNUMERIC` keeps values unquoted as long as they're *numbers*, ie. if their type is `int` or `float` (for example), which means it will write what you expect.
Your problem could be that, when reading, a `csv.reader` will turn every row it reads into a `list` of *strings* (if you read ... |
Connecting postgresql with sqlalchemy | 9,353,822 | 19 | 2012-02-19T22:17:44Z | 9,353,830 | 22 | 2012-02-19T22:19:17Z | [
"python",
"database",
"postgresql",
"orm",
"sqlalchemy"
] | I know this might be really a simple question but I don't know the solution. What is happening here when I try to connect to postgresql? I am self learner in this field of database and programming so please be gentle with me.
When I try following code:
```
import sqlalchemy
db = sqlalchemy.create_engine('postgresql://... | Yes, psycopg2 are basically the Python drivers for PostgreSQL that need to be installed separately.
A list of valid connection strings can be found here, yours is a bit off (you need to the username, the password and hostname as specified in the link below):
<http://docs.sqlalchemy.org/en/latest/core/engines.html#pos... |
How to grab one random item from a database in Django/postgreSQL? | 9,354,127 | 4 | 2012-02-19T22:56:29Z | 9,354,516 | 8 | 2012-02-19T23:46:25Z | [
"python",
"django",
"postgresql"
] | So i got the database.objects.all() and database.objects.get('name') but how would i got about getting one random item from the database. I'm having trouble trying to figure out how to get it ot select one random item. | Selecting a random element from a list of all database objects isn't a goog solution as retrieving all elements of the database can have a big impact on performance, neither is using `order_by('?')` as mentioned in the [django documentation](https://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by).
The be... |
Why is Python giving me "an integer is required" when it shouldn't be? | 9,354,276 | 3 | 2012-02-19T23:13:17Z | 9,354,341 | 8 | 2012-02-19T23:20:31Z | [
"python",
"file",
"load",
"pickle"
] | I have a save function within my Python program which looks like this:
```
def Save(n):
print("S3")
global BF
global WF
global PBList
global PWList
print(n)
File = open("C:\KingsCapture\Saves\\" + n + "\BF.txt", "w")
pickle.dump(BF, File)
File = open("C:\KingsCapture\Saves\\" + n + ... | You probably did a star import from the os module:
```
>>> open("test.dat","w")
<open file 'test.dat', mode 'w' at 0x1004b20c0>
>>> from os import *
>>> open("test.dat","w")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: an integer is required
```
so you're using the wrong open fu... |
psycopg2 cursor.execute() with SQL query parameter causes syntax error | 9,354,392 | 3 | 2012-02-19T23:28:54Z | 9,354,420 | 11 | 2012-02-19T23:34:09Z | [
"python",
"sql",
"postgresql",
"psycopg2"
] | When specifying a parameter to execute() in psycopg2 in Python, like this:
```
cursor.execute('SELECT * FROM %s', ("my_table", ))
```
I'm getting this error:
```
psycopg2.ProgrammingError: syntax error at or near "'my_table'"
LINE 1: SELECT * FROM 'my_table'
```
What am I doing wrong? It looks like psycopg2 is addi... | I believe that parametrized statements like this are meant to be used with *values* and not table names (or SQL keywords, etc.). So you're basically out of luck with this.
However, do not worry, as this mechanism is meant to prevent SQL injection, and you normally know what table you want to access at code-writing tim... |
Any pretty python string formatting for a counter? | 9,354,912 | 3 | 2012-02-20T00:48:28Z | 9,354,950 | 8 | 2012-02-20T00:56:15Z | [
"python",
"logging",
"printing",
"string-formatting"
] | Is there any string formatting for using correct suffix with log messages, for example:
```
for n in itertools.count():
print 'printing for the {:nth} time'.format(n)
```
Expected output:
```
printing for the 0th time
printing for the 1st time
printing for the 2nd time
printing for the 3rd time
printing for the 4t... | What about simply:
```
def stringify(x):
if x // 10 % 10 == 1:
return str(x) + 'th'
else:
return str(x) + { 1:'st', 2:'nd', 3:'rd' }.get(x % 10, 'th')
```
Or if you prefer ugly hacks:
```
return str(x) + { 1:'st', 2:'nd', 3:'rd' }.get(x//10%10 != 1 and x%10, 'th')
```
I felt a bit dirty while writing th... |
Are there any guidelines to follow when choosing number of processes with multiprocessing? | 9,355,472 | 7 | 2012-02-20T02:26:44Z | 9,355,605 | 7 | 2012-02-20T02:47:25Z | [
"python",
"parallel-processing",
"multiprocessing"
] | I'm just getting my feet wet with multiprocessing(and its totally awesome!), but I was wondering if there was any guidelines to selecting number of processes? Is it just based on number of cores on the server? Is it somehow based on the application your running(number of loops, how much cpu it uses,etc)? etc...how do I... | If all of your threads/processes are indeed CPU-bound, you should run as many processes as the CPU reports cores. Due to [HyperThreading](http://en.wikipedia.org/wiki/Hyper-threading), each physical CPU cores may be able to present multiple virtual cores. Call [`multiprocessing.cpu_count`](http://docs.python.org/librar... |
PyQt QTcpServer: How to return data to multiple clients? | 9,355,511 | 4 | 2012-02-20T02:32:50Z | 9,454,412 | 7 | 2012-02-26T15:41:34Z | [
"python",
"pyqt4",
"qtcpsocket",
"qtcpserver"
] | I am looking to create a QTcpServer using PyQt that can simultaneously return data to 2 or more clients. I assume that this will require threading.
Using the threadedfortuneserver.py example as a test case (included with PyQt4, on my system it is found in /usr/share/doc/python-qt4-doc/examples/network), I want to conn... | As was probably exasperatingly obvious to most of you, I didn't fully understand how to deal with threads! Not to worry, I have discovered a way to design a server that can send data to multiple clients with nary a secondary thread to be found.
Quite simple, really, but I'm not the quickest of cats at the best of time... |
How can i print unhandled exception to the Console instead of the Browser in Django? | 9,356,053 | 3 | 2012-02-20T04:07:12Z | 9,356,177 | 10 | 2012-02-20T04:26:43Z | [
"python",
"django"
] | I got 500 errors in Django console but it doesn't print any information to the Console about the error.
How can i print the detail to Console ? | Run the server with `--traceback` option and set `DEBUG=False` in `settings.py`.
You will get the traceback on console. |
Alternatives to Python PasteScript's paster create? | 9,356,190 | 11 | 2012-02-20T04:28:06Z | 18,294,213 | 16 | 2013-08-17T23:18:52Z | [
"python",
"project"
] | It seems like [PasteScript](http://pythonpaste.org/script/)'s `paster create` functionality is just about the only widely used framework for building/generating a project skeleton within python. I'm wondering if there are any alternatives in the python world that folks use?
**Update**
I want to comment on my experien... | I'm rather partial to [cookiecutter](https://github.com/audreyr/cookiecutter). It works for Python 2.7, 3.3, 3.4, and PyPy on Linux, Mac OS X, and Windows. It's fully documented, actively maintained, well tested, and really easy to use. Here is my [blog entry](http://pydanny.com/cookie-project-templates-made-easy.html)... |
internal comparison of string and int in python | 9,357,009 | 2 | 2012-02-20T06:24:27Z | 9,357,034 | 8 | 2012-02-20T06:27:10Z | [
"python"
] | When a string is being compared to python internally is the string and the integer compare to ASCII code and then compared or how is it.I know that str > int but how is that internal comparison takes place.
> > "a" > 1 | In your example, `1 < "a"` because "i" for `int` comes alphabetically before "s" for `string`.
From the [docs](http://docs.python.org/library/stdtypes.html):
> Objects of different types, except different numeric types and
> different string types, never compare equal; such objects are ordered
> consistently but arbi... |
Running django and flask on same apache server | 9,357,296 | 7 | 2012-02-20T06:57:05Z | 9,357,721 | 7 | 2012-02-20T07:45:22Z | [
"python",
"django",
"apache",
"flask"
] | I am trying to run to run django and flask on the same apache server.
```
WSGISocketPrefix /var/www/wsgi
<VirtualHost *:80>
ServerAdmin name@email.com
ServerName domain.com
ServerAlias www.domain.com
DocumentRoot /var/www/
LogLevel warn
WSGIDaemonProcess apache processe... | I'm not sure if this would solve the problem, but have you tried changing the order of your script alias so that `/app1` is found before `/` ?
```
WSGISocketPrefix /var/www/wsgi
<VirtualHost *:80>
ServerAdmin name@email.com
ServerName domain.com
ServerAlias www.domain.com
DocumentRoot ... |
Performance comparison of OpenCV-Python interfaces, cv and cv2 | 9,357,696 | 20 | 2012-02-20T07:43:07Z | 9,357,834 | 34 | 2012-02-20T07:59:25Z | [
"python",
"performance",
"opencv",
"computer-vision"
] | A few days back, I started using new OpenCV-Python interface, `cv2`.
My question is regarding the comparison of `cv` and `cv2` interface.
Regarding the ease of use, new `cv2` interface has improved far greater, and it is really easy and fun to work with `cv2`.
But what about speed?
I made two small code snipplets, ... | The image returned by cv2.imread() is an array object of NumPy. So you can use NumPy's functions to speedup calculation.
The following program shows how to speedup your origin for loop version by using item(), itemset() method of ndarray object.
```
import time
import numpy as np
import cv2
gray = cv2.imread('lena_f... |
How to make a widget in the center of the screen in PySide/PyQt? | 9,357,944 | 12 | 2012-02-20T08:12:40Z | 10,746,864 | 10 | 2012-05-24T23:58:32Z | [
"python",
"qt",
"pyqt",
"pyside"
] | This code works, but I wonder if there is any simpler way:
```
def center(self):
qr = self.frameGeometry()
cp = gui.QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
``` | just add this line to your main windows :
```
self.move(QtGui.QApplication.desktop().screen().rect().center()- self.rect().center())
``` |
python dictionary and default values | 9,358,983 | 79 | 2012-02-20T09:42:06Z | 9,359,011 | 113 | 2012-02-20T09:44:06Z | [
"python",
"dictionary",
"coding-style"
] | Assuming `connectionDetails` is a Python dictionary, what's the best, most elegant, most "pythonic" way of refactoring code like this:
```
if "host" in connectionDetails:
host = connectionDetails["host"]
else:
host = someDefaultValue
``` | Like this:
```
host = connectionDetails.get('host','someDefault')
``` |
python dictionary and default values | 9,358,983 | 79 | 2012-02-20T09:42:06Z | 17,501,506 | 16 | 2013-07-06T09:17:36Z | [
"python",
"dictionary",
"coding-style"
] | Assuming `connectionDetails` is a Python dictionary, what's the best, most elegant, most "pythonic" way of refactoring code like this:
```
if "host" in connectionDetails:
host = connectionDetails["host"]
else:
host = someDefaultValue
``` | While `.get()` is a nice idiom, it's slower than `if/else` (and slower than `try/except` if presence of the key in the dictionary can be expected most of the time):
```
>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}",
... stmt="try:\n a=d[1]\nexcept KeyError:\n a=10")
0.07691968797894333
>>> timeit.timeit(setup... |
python dictionary and default values | 9,358,983 | 79 | 2012-02-20T09:42:06Z | 23,933,745 | 32 | 2014-05-29T12:50:13Z | [
"python",
"dictionary",
"coding-style"
] | Assuming `connectionDetails` is a Python dictionary, what's the best, most elegant, most "pythonic" way of refactoring code like this:
```
if "host" in connectionDetails:
host = connectionDetails["host"]
else:
host = someDefaultValue
``` | You can also use the [`defaultdict`](https://docs.python.org/2/library/collections.html#collections.defaultdict) like so:
```
from collections import defaultdict
a = defaultdict(lambda: "default", key="some_value")
a["blabla"] => "default"
a["key"] => "some_value"
``` |
How to print a numpy array without brackets | 9,360,103 | 14 | 2012-02-20T11:05:28Z | 9,360,197 | 25 | 2012-02-20T11:12:38Z | [
"python"
] | I want to convert `a = [1,2,3,4,5]` into `a_string = "1 2 3 4 5"`. The real numpy array is quite big (50000x200) so I assume using `for loops` is too slow. | You can use the `join` method from string:
```
>>> a = [1,2,3,4,5]
>>> ' '.join(map(str, a))
"1 2 3 4 5"
``` |
creating a simple package that can be install via Pip & virtualenv | 9,360,458 | 7 | 2012-02-20T11:35:09Z | 9,360,775 | 11 | 2012-02-20T12:00:39Z | [
"python",
"virtualenv",
"pip"
] | I would like to create the simplest (hello world package) package that I could install using pip in a virtualenv from a local zip file.
In python i would do
```
>> from myinstallpackage import mymodule
>> mymodule.sayhello()
hello !
```
What would be in the setup.py and in the package folder ?
Thanks | You have to create account on <http://pypi.python.org/>. Then you can upload the module on <http://pypi.python.org/pypi?%3Aaction=submit_form>.
**Doc on this site contains all commands like**
How to create module which can be upload on pipy?
How to download fro pip?
etc...
You will get help on <http://docs.python.... |
pyparsing capturing groups of arbitrary text with given headers as nested lists | 9,361,521 | 6 | 2012-02-20T12:58:21Z | 9,362,759 | 8 | 2012-02-20T14:30:38Z | [
"python",
"pyparsing"
] | I have a text file that looks similar to;
> section header 1:
> some words can be anything
> more words could be anything at all
> etc etc lala
>
> some other header:
> as before could be anything
> hey isnt this fun
I am trying to contruct a grammar with pyparser that would result in the following list str... | Matt -
Welcome to pyparsing! You have fallen into one of the most common pitfalls in working with pyparsing, and that is that people are smarter than computers. When you look at your input text, you can easily see which text can be headers and which text can't be. Unfortunately, pyparsing is not so intuitive, so you h... |
Python: how to extract the content of a column in a table | 9,362,071 | 3 | 2012-02-20T13:38:43Z | 9,362,102 | 9 | 2012-02-20T13:41:11Z | [
"python",
"html",
"parsing"
] | I have this HTML structure:
```
<div>
<table>
<tbody>
<tr>
<td>stuff</td>
</tr>
<tr>
<td>
<div>The content I want</div>
</td>
</tr>
</tbody>
</table>
</div>
```
How do I get "the content I want" and del... | Use [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/), e.g.
```
>>> from BeautifulSoup import BeautifulSoup as bs
>>> text = """<div>
... Â Â <table>
... Â Â Â Â <tbody>
... Â Â Â Â Â <tr>
... Â Â Â Â Â Â <td>stuff</td>
... Â Â Â Â Â </tr>
... Â Â Â Â Â <tr>
... Â Â Â Â Â Â ... |
Parallelise nested for-loop in IPython | 9,363,118 | 6 | 2012-02-20T14:54:50Z | 9,370,371 | 9 | 2012-02-21T00:13:38Z | [
"python",
"parallel-processing",
"ipython"
] | I have a nested for loop in my python code that looks something like this:
```
results = []
for azimuth in azimuths:
for zenith in zeniths:
# Do various bits of stuff
# Eventually get a result
results.append(result)
```
I'd like to parallelise this loop on my 4 core machine to speed it up... | To parallelize every call, you just need to get a list for each argument. You can use `itertools.product` + `zip` to get this:
```
allzeniths, allazimuths = zip(*itertools.product(zeniths, azimuths))
```
Then you can use map:
```
amr = dview.map(f, allzeniths, allazimuths)
```
To go a bit deeper into the steps, her... |
Parallelise nested for-loop in IPython | 9,363,118 | 6 | 2012-02-20T14:54:50Z | 9,585,935 | 8 | 2012-03-06T14:47:36Z | [
"python",
"parallel-processing",
"ipython"
] | I have a nested for loop in my python code that looks something like this:
```
results = []
for azimuth in azimuths:
for zenith in zeniths:
# Do various bits of stuff
# Eventually get a result
results.append(result)
```
I'd like to parallelise this loop on my 4 core machine to speed it up... | I assume you are using IPython 0.11 or later. First of all define a simple function.
```
def foo(azimuth, zenith):
# Do various bits of stuff
# Eventually get a result
return result
```
then use IPython's fine parallel suite to parallelize your problem. first start a controller with 5 engines attached (#C... |
Delete user when deleting UserProfile | 9,363,128 | 5 | 2012-02-20T14:55:18Z | 9,363,397 | 11 | 2012-02-20T15:13:46Z | [
"python",
"django"
] | I created `UserProfile` (extends from User) and written to `settings.py`
```
AUTH_PROFILE_MODULE = 'mainapp.UserProfile'.
```
When I delete `UserProfile` (from admin area) I would delete also `User` item.
I try delete user so `self.user.delete()`, but method delete (in UserProfile) don't call. Why ?
This is my cod... | First, to answer *why "delete()" is not called from the admin*. This statement is:
1. **True in the case of deleting objects from the list view**, ie. /admin/auth/user/ check some boxes then click Actions -> delete), this is because the delete() method of a **queryset** is called,
2. **Wrong in the case of deleting an... |
code visualizer for Racket programs | 9,365,527 | 5 | 2012-02-20T17:25:54Z | 9,366,966 | 7 | 2012-02-20T19:10:42Z | [
"python",
"racket",
"code-visualization"
] | Is there a code visualization website for Racket programs (for novice [WeScheme](http://wescheme.org/) users) similar to what is available at [Online Python Tutor](http://people.csail.mit.edu/pgbovine/python/tutor.html#mode=edit)? Needless to say, it would provide a great self-teaching or learning tool. | DrRacket provides a Stepper--it's one of the buttons in the toolbar--that shows the evaluation of programs written in Beginning and Intermediate student languages as a sequence of steps. Its interface is not as pretty as the page you point to--as the author of the Stepper, I can say this with confidence--but it's a vis... |
Missing values in scikits machine learning | 9,365,982 | 19 | 2012-02-20T17:56:07Z | 9,369,202 | 16 | 2012-02-20T22:11:54Z | [
"python",
"machine-learning",
"scikits",
"scikit-learn"
] | Is it possible to have missing values in scikit-learn ? How should they be represented? I couldn't find any documentation about that. | ~~Missing values are simply not supported in scikit-learn. There has been discussion on the mailing list about this before, but no attempt to actually write code to handle them.~~
~~Whatever you do, *don't* use NaN to encode missing values, since many of the algorithms refuse to handle samples containing NaNs.~~
The ... |
Missing values in scikits machine learning | 9,365,982 | 19 | 2012-02-20T17:56:07Z | 18,020,591 | 7 | 2013-08-02T15:22:28Z | [
"python",
"machine-learning",
"scikits",
"scikit-learn"
] | Is it possible to have missing values in scikit-learn ? How should they be represented? I couldn't find any documentation about that. | I have come across very similar issue, when running the *RandomForestRegressor* on data. The presence of NA values were throwing out "nan" for predictions. From scrolling around several discussions, the Documentation by Breiman recommends two solutions for continuous and categorical data respectively.
1. Calculate the... |
Correct Use Of Global Variables In Python 3 | 9,366,212 | 12 | 2012-02-20T18:13:45Z | 9,366,806 | 17 | 2012-02-20T18:57:48Z | [
"python",
"function",
"variables",
"python-3.x",
"global-variables"
] | Which is the correct use of global variables in Python 3?:
1) Stating `global VAR_NAME` once in the core script (not within a function) and then simply referring to the variable as `VAR_NAME` everywhere else
2) Stating `global VAR_NAME` once within every function that uses the global variable and then simply referrin... | In the first case the global keyword is pointless, so that is not correct. Defining a variable on the module level makes it a global variable, you don't need to global keyword.
The second example is correct usage.
However, the most common usage for global variables are without using the global keyword anywhere. The g... |
Correct Use Of Global Variables In Python 3 | 9,366,212 | 12 | 2012-02-20T18:13:45Z | 9,366,986 | 18 | 2012-02-20T19:12:06Z | [
"python",
"function",
"variables",
"python-3.x",
"global-variables"
] | Which is the correct use of global variables in Python 3?:
1) Stating `global VAR_NAME` once in the core script (not within a function) and then simply referring to the variable as `VAR_NAME` everywhere else
2) Stating `global VAR_NAME` once within every function that uses the global variable and then simply referrin... | You need to use the global keyword in a function if you use the global variable in a way that would otherwise be interpreted as an assignment to a local variable. Without the global keyword, you will create a local variable that hides the global in the scope of the function.
Here are a few examples:
```
global_var = ... |
Python argparse: Lots of choices results in ugly help output | 9,366,369 | 24 | 2012-02-20T18:24:25Z | 14,812,652 | 17 | 2013-02-11T13:09:14Z | [
"python",
"argparse"
] | I have this code which I am generally pleased with:
```
import argparse
servers = [ "ApaServer", "BananServer", "GulServer", "SolServer", "RymdServer",
"SkeppServer", "HavsServer", "PiratServer", "SvartServer", "NattServer", "SovServer" ]
parser = argparse.ArgumentParser(description="A program to update ... | There is no need to subclass anything. Simply pass a `metavar` argument with the string you want to appear in the help message.
See the [argparse documentation](http://docs.python.org/2/library/argparse.html#metavar) for details. |
Python argparse: Lots of choices results in ugly help output | 9,366,369 | 24 | 2012-02-20T18:24:25Z | 16,985,727 | 31 | 2013-06-07T13:48:00Z | [
"python",
"argparse"
] | I have this code which I am generally pleased with:
```
import argparse
servers = [ "ApaServer", "BananServer", "GulServer", "SolServer", "RymdServer",
"SkeppServer", "HavsServer", "PiratServer", "SvartServer", "NattServer", "SovServer" ]
parser = argparse.ArgumentParser(description="A program to update ... | I am basically repeating what Ernest said - to avoid the ugly long list of choices, set metavar='' for the choice-based arguments (though it won't get rid of the whitespace between the argument and comma (e.g. `-o ,` instead of `-o,`). You can then describe available choices in detail in general description (RawDescrip... |
Why is __init__ not called after __new__ SOMETIMES | 9,367,126 | 7 | 2012-02-20T19:22:27Z | 9,367,201 | 7 | 2012-02-20T19:28:16Z | [
"python",
"genshi"
] | Let me start with this is not a repeat of
[Why does \_\_init\_\_ not get called if \_\_new\_\_ called with no args](http://stackoverflow.com/questions/6903355/why-does-init-not-get-called-if-new-called-with-no-args). I have tried to carefully construct some sample code for `__new__` and `__init__` that has no explanati... | From [the documentation](http://docs.python.org/reference/datamodel.html#object.__new__):
> If `__new__()` does not return an instance of *cls*, then the new instanceâs `__init__()` method will not be invoked.
This is to allow `__new__()` to [return a new instance of a *different* class](http://stackoverflow.com/a/... |
Python 'list indices must be integers, not tuple" error | 9,367,813 | 3 | 2012-02-20T20:16:17Z | 9,367,849 | 7 | 2012-02-20T20:18:35Z | [
"python",
"arrays",
"list",
"grid",
"robot"
] | I'm working on moving a robot around a 2d grid room of 8 x 8, and one part is initialising the sensors which consist of the closest 5 tiles around the robot.
```
self.sensors = [0 for x in xrange(5)]
```
here I'm creating an empty of array of 5 elements.
but when I attempt to set the value of sensors like this:
```... | You say `self.room` is a "2d grid" -- I assume it is a list of lists. In this case, you should access its elements as
```
self.room[self.x][self.y-1]
```
instead of indexing the outer list with the pair `self.x, self.y-1`. |
Make a notebook tab anchored so its position cannot be changed | 9,369,614 | 4 | 2012-02-20T22:48:25Z | 9,370,555 | 7 | 2012-02-21T00:39:46Z | [
"python",
"gtk",
"pygtk"
] | I have a GtkNotebook that will contain at the very least, one permanent tab, called "Search". The widget within this page allows for more pages to be created, and these pages have a tab that contains a close button.
How do I make the tabs reorderable, but also keep the "Search" tab anchored at position 0? The current ... | Seems to me like a possible solution would be to connect to the `'page-reordered'` signal like this:
```
import gtk
def on_reorder(notebook, child, number, user_data):
if number == 0:
notebook.reorder_child(user_data, 0)
def main():
mainwin = gtk.Window()
notebook = gtk.Notebook()
main... |
Does Dividing by Zero in Python Crash Windows 98, et al? | 9,369,899 | 5 | 2012-02-20T23:17:59Z | 9,370,270 | 7 | 2012-02-21T00:00:36Z | [
"python",
"windows"
] | I was told by a professor that dividing by zero or taking a negative square root in Python crashes if you do it in Windows 98.
This seems ridiculous since Python is an interpreted language, but I don't have a way to verify this, and Windows is notorious... Can anyone confirm or deny the claim? If so, does it have to d... | ```
Python 2.7.2 (Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Joke)] on win98
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> math.sqrt(-1) / 0
A fatal exception 0E has occurred at 0028:C0011E36 in VXD VMM(01) +
00010E36. The current application will be terminated
* Press any... |
Simulating a POST request in Django | 9,370,090 | 4 | 2012-02-20T23:39:22Z | 9,370,235 | 15 | 2012-02-20T23:55:45Z | [
"python",
"django",
"django-views",
"django-urls"
] | Let's suppose I have the following url: `/valid/django/app/path/?foo=bar&spam=eggs`
I can simulate a request to this URL in Django thusly:
```
from django.shortcuts import render
from django.core.urlresolvers import resolve
def simulate(request, url=None, template_name="not_important.html"):
if url:
dv =... | request.GET/POST are [QueryDict](https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.QueryDict) instances. According to the documentation on [QueryDict](https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.QueryDict), there are indeed "immutable" **unless you clone them**:
> Quer... |
python shuffle algorithm performance | 9,371,079 | 3 | 2012-02-21T01:54:20Z | 9,371,105 | 9 | 2012-02-21T02:00:00Z | [
"python",
"performance",
"time-complexity",
"shuffle"
] | I was wondering about the time complexity of the [`shuffle` function](http://docs.python.org/library/random.html#random.shuffle) in the `random` Python library/module. Is it O(n) or is it less than that?
Is there a website that shows the time complexities of functions that belong to Python libraries? | You cannot shuffle a list in a completely random fashion in less than O(n).
The [implementation of `random.shuffle()`](http://hg.python.org/cpython/file/2e8b28dbc395/Lib/random.py#l276) uses the [Fisher-Yates shuffle algorithm](http://en.wikipedia.org/wiki/Fisher-Yates_shuffle), which is easily seen to be O(n). |
Check if List of Objects contain an object with a certain attribute value | 9,371,114 | 23 | 2012-02-21T02:00:54Z | 9,371,143 | 40 | 2012-02-21T02:04:29Z | [
"python",
"search",
"python-3.x"
] | I want to check if my list of objects contain an object with a certain attribute value.
```
class Test:
def __init__(self, name):
self.name = name
# in main()
l = []
l.append(Test("t1"))
l.append(Test("t2"))
l.append(Test("t2"))
```
I want a way of checking if list contains an object with name t1 for exa... | As you can easily see from the [documentation](http://docs.python.org/library/functions.html#any), the `any()` function short-circuits an returns `True` as soon as a match has been found.
```
any(x.name == "t2" for x in l)
``` |
Why is reading lines from stdin much slower in C++ than Python? | 9,371,238 | 896 | 2012-02-21T02:17:50Z | 9,371,717 | 820 | 2012-02-21T03:24:19Z | [
"c++",
"python",
"benchmarking",
"readline",
"getline"
] | I wanted to compare reading lines of string input from stdin using Python and C++ and was shocked to see my C++ code run an order of magnitude slower than the equivalent Python code. Since my C++ is rusty and I'm not yet an expert Pythonista, please tell me if I'm doing something wrong or if I'm misunderstanding someth... | By default, `cin` is synchronized with stdio, which causes it to avoid any input buffering. If you add this to the top of your main, you should see much better performance:
```
std::ios_base::sync_with_stdio(false);
```
Normally, when an input stream is buffered, instead of reading one character at a time, the stream... |
Why is reading lines from stdin much slower in C++ than Python? | 9,371,238 | 896 | 2012-02-21T02:17:50Z | 9,371,800 | 51 | 2012-02-21T03:33:36Z | [
"c++",
"python",
"benchmarking",
"readline",
"getline"
] | I wanted to compare reading lines of string input from stdin using Python and C++ and was shocked to see my C++ code run an order of magnitude slower than the equivalent Python code. Since my C++ is rusty and I'm not yet an expert Pythonista, please tell me if I'm doing something wrong or if I'm misunderstanding someth... | I reproduced the original result on my computer using g++ on a Mac.
Adding the following statements to the C++ version just before the `while` loop brings it inline with the [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29) version:
```
std::ios_base::sync_with_stdio(false);
char buffer[1048576... |
Why is reading lines from stdin much slower in C++ than Python? | 9,371,238 | 896 | 2012-02-21T02:17:50Z | 9,657,502 | 50 | 2012-03-11T18:10:16Z | [
"c++",
"python",
"benchmarking",
"readline",
"getline"
] | I wanted to compare reading lines of string input from stdin using Python and C++ and was shocked to see my C++ code run an order of magnitude slower than the equivalent Python code. Since my C++ is rusty and I'm not yet an expert Pythonista, please tell me if I'm doing something wrong or if I'm misunderstanding someth... | Just out of curiosity I've taken a look at what happens under the hood, and I've used [dtruss/strace](http://en.wikipedia.org/wiki/Strace) on each test.
C++
```
./a.out < in
Saw 6512403 lines in 8 seconds. Crunch speed: 814050
```
syscalls `sudo dtruss -c ./a.out < in`
```
CALL ... |
How can I create a borderless application in Python (windows)? | 9,371,663 | 6 | 2012-02-21T03:18:42Z | 9,372,031 | 8 | 2012-02-21T04:07:50Z | [
"python",
"borderless"
] | I would like to know how to create an application in Windows that does not have the default border; particularly the title bar with minimize, maximize, and close buttons.
I'm thinking of writing a ticker program that takes up a narrow space at the top or bottom of the screen, but I won't attempt it unless it's possible... | If you're willing to use [Qt/PySide](http://www.pyside.org/docs/pyside/PySide/QtGui/QMainWindow.html), take a look at `QtCore.Qt.FramelessWindowHint` The code below just proves it's possible and doesn't try to be terribly useful. In particular, you will have to force kill the app to get the app to close. In a proper im... |
How to write a list to a csv file? | 9,372,705 | 3 | 2012-02-21T05:35:14Z | 9,372,731 | 7 | 2012-02-21T05:37:49Z | [
"python",
"csv"
] | I have a list that has data as following:
```
[[a,b,1], [c,d,3], [a,c,2], [c,d,1]]
```
How can I write this list of lists to a csv file?
I tried this, but it did not work.
```
with open('output.csv', 'w') as f:
f.write((list))
``` | [`csv`](http://docs.python.org/library/csv.html)
[`csvwriter.writerows()`](http://docs.python.org/library/csv.html#csv.csvwriter.writerows) |
Remove widgets and layout as well | 9,374,063 | 3 | 2012-02-21T08:04:12Z | 9,383,780 | 7 | 2012-02-21T19:22:05Z | [
"python",
"layout",
"pyqt",
"pyqt4"
] | I was trying to find something that would take a qt layout and delete everything from it. Just to imagine what the window looks like - I have:
```
QVBoxLayout
| ------QHboxLayout
|---------QWidget
| ------QHboxLayout
|---------QWidget
.........
```
So I need som... | The safest way to clear a layout is to extract the items with its [takeAt](http://developer.qt.nokia.com/doc/qt-4.8/qlayout.html#takeAt) method, and then explicitly delete any widgets with [deleteLater](http://developer.qt.nokia.com/doc/qt-4.8/qobject.html#deleteLater):
```
def clearLayout(self, layout):
if layout... |
Why has the numpy random.choice() function been discontinued? | 9,374,885 | 8 | 2012-02-21T09:17:15Z | 9,375,030 | 7 | 2012-02-21T09:27:19Z | [
"python",
"numpy",
"scipy"
] | I've been working with numpy and needed the random.choice() function. Sadly, in version 2.0 it's not in the random or the random.mtrand.RandomState modules. Has it been excluded for a particular reason? There's nothing in the discussion or documentation about it!
For info, I'm running Numpy 2.0 on python 2.7 on mac os... | `random.choice` is as far as I can tell part of python itself, not of numpy. Did you `import random`?
Update: numpy 1.7 added a new function, `numpy.random.choice`. Obviously, you need numpy 1.7 for it.
Update2: it seems that in **unreleased** numpy 2.0, this was temporarily called `numpy.random.sample`. It has been ... |
Preformat to currency and two decimal places in python using xlwt for excel | 9,375,637 | 5 | 2012-02-21T10:10:24Z | 9,376,306 | 8 | 2012-02-21T10:55:39Z | [
"python",
"excel",
"xlwt"
] | I have a column heading **Fee**. Using **xlwt** in **python**, I successfully generated the required excel.This column is always blank at the creation of Excel file.
Is it possible to have the **Fee** column preformatted to 'Currency' and 'two decimal places', so that when I write manually in the **Fee** column of the... | I got it working like this:
`currency_style = xlwt.XFStyle()`
`currency_style.num_format_str = "[$$-409]#,##0.00;-[$$-409]#,##0.00"`
`sheet.write(row+2, col, val, style=currency_style)` |
Python del if in dictionary in one line | 9,377,224 | 7 | 2012-02-21T11:59:45Z | 9,377,273 | 17 | 2012-02-21T12:02:47Z | [
"python",
"dictionary",
"del"
] | Is there a one line way of doing the below?
```
myDict = {}
if 'key' in myDic:
del myDic['key']
```
thanks | You can write
```
myDict.pop(key, None)
``` |
How to customize title bar and window | 9,377,914 | 5 | 2012-02-21T12:49:25Z | 10,712,258 | 17 | 2012-05-23T01:16:49Z | [
"python",
"pyqt",
"customization",
"titlebar"
] | I want to customize the title bar and frame window so that it looks like the [nokia ovi gui](http://blog.maps.nokia.com/wp-content/uploads/2010/12/music21-590x343.png). | ```
#########################################################
## customize Title bar
## dotpy.ir
## iraj.jelo@gmail.com
#########################################################
import sys
from PyQt4 import QtGui
from PyQt4 import QtCore
from PyQt4.QtCore import Qt
class TitleBar(QtGui.QDialog):
def __init__(self,... |
Convert one list to set, but if empty use a default one | 9,377,977 | 6 | 2012-02-21T12:54:56Z | 9,378,116 | 11 | 2012-02-21T13:05:18Z | [
"python",
"list",
"set"
] | I'm looking for a nicer way to assign a set with the conent of a list if such list is not empty, otherwise another list should be used.
If it is possible I'd like a nicer way to write this (or an argument to why this is the nicest way):
```
if args.onlyTheseServers:
only = set(args.onlyTheseServers)
else:
onl... | ```
only = set(args.onlyTheseServers or availableServers)
``` |
How to plot cdf in matplotlib in Python? | 9,378,420 | 7 | 2012-02-21T13:25:55Z | 9,379,432 | 13 | 2012-02-21T14:39:25Z | [
"python",
"matplotlib"
] | I have a disordered list named `d` that looks like:
```
[0.0000, 123.9877,0.0000,9870.9876, ...]
```
I just simply want to plot a cdf graph based on this list by using Matplotlib in Python. But don't know if there's any function I can use
```
d = []
d_sorted = []
for line in fd.readlines():
(addr, videoid, usera... | As mentioned, `cumsum` from `numpy` works well. Make sure that your data is a proper PDF (ie. sums to one), otherwise the CDF won't end at unity [as it should](http://en.wikipedia.org/wiki/Cumulative_distribution_function). Here is a minimal working example:
```
import numpy as np
from pylab import *
# Create some te... |
Why is splitting a string slower in C++ than Python? | 9,378,500 | 66 | 2012-02-21T13:32:49Z | 9,379,203 | 45 | 2012-02-21T14:24:37Z | [
"c++",
"python",
"string",
"split",
"benchmarking"
] | I'm trying to convert some code from Python to C++ in an effort to gain a little bit of speed and sharpen my rusty C++ skills. Yesterday I was shocked when a naive implementation of reading lines from stdin was much faster in Python than C++ (see [this](http://stackoverflow.com/questions/9371238/why-is-reading-lines-fr... | As a guess, Python strings are reference counted immutable strings, so that no strings are copied around in the Python code, while C++ `std::string` is a mutable value type, and is copied at the smallest opportunity.
If the goal is fast splitting, then one would use constant time substring operations, which means only... |
Why is splitting a string slower in C++ than Python? | 9,378,500 | 66 | 2012-02-21T13:32:49Z | 9,657,918 | 8 | 2012-03-11T18:58:16Z | [
"c++",
"python",
"string",
"split",
"benchmarking"
] | I'm trying to convert some code from Python to C++ in an effort to gain a little bit of speed and sharpen my rusty C++ skills. Yesterday I was shocked when a naive implementation of reading lines from stdin was much faster in Python than C++ (see [this](http://stackoverflow.com/questions/9371238/why-is-reading-lines-fr... | I'm not providing any better solutions (at least performance-wise), but some additional data that could be interesting.
Using `strtok_r` (reentrant variant of `strtok`):
```
void splitc1(vector<string> &tokens, const string &str,
const string &delimiters = " ") {
char *saveptr;
char *cpy, *token;
... |
How to create Celery Windows Service? | 9,378,932 | 7 | 2012-02-21T14:06:13Z | 9,380,459 | 12 | 2012-02-21T15:43:40Z | [
"python",
"windows",
"windows-services",
"celery"
] | I'm trying to create a Windows Service to launch Celery. I have come across an article that does it using [Task Scheduler](http://www.calazan.com/windows-tip-run-applications-in-the-background-using-task-scheduler/). However it seems to launch numerous celery instances and keeps eating up memory till the machine dies. ... | I got the answer from another website. Celeryd (daemon service for Celery) runs as a paster application, searching for 'Paster Windows Service' lead me [here](http://wiki.pylonshq.com/display/pylonscookbook/How+to+run+Pylons+as+a+Windows+service). It describes how to run a Pylons application as a Windows Service. Being... |
How do I change the widget type of the DELETE field in a django formset | 9,379,512 | 4 | 2012-02-21T14:45:31Z | 9,379,783 | 8 | 2012-02-21T15:02:14Z | [
"python",
"django"
] | I'm using a formset with can\_delete=True. I want to change the widget of the DELETE field to a hidden input. I can't seem to find a good way to do this. What I've tried is:
Change the form's widget to HiddenInput and/or add a hidden field in the form definition:
```
class MyForm(ModelForm):
DELETE = forms.Boolea... | It doesn't change anything if your input is of type=hidden, or if it is of type=checkbox **and** display: none.
IMHO the elegant way in CSS would look like this:
```
td.delete input { display: none; }
```
Or in JavaScript:
```
$('td.delete input[type=checkbox]').hide()
```
Or, in the admin:
```
django.jQuery('td.... |
How do I change the widget type of the DELETE field in a django formset | 9,379,512 | 4 | 2012-02-21T14:45:31Z | 12,798,786 | 13 | 2012-10-09T11:11:51Z | [
"python",
"django"
] | I'm using a formset with can\_delete=True. I want to change the widget of the DELETE field to a hidden input. I can't seem to find a good way to do this. What I've tried is:
Change the form's widget to HiddenInput and/or add a hidden field in the form definition:
```
class MyForm(ModelForm):
DELETE = forms.Boolea... | The shortest code to accomplish what you need is:
```
class MyFormSet(BaseFormSet):
def add_fields(self, form, index):
super(MyFormSet, self).add_fields(form, index)
form.fields[DELETION_FIELD_NAME].widget = forms.HiddenInput()
```
It cannot be considered a hack because it's mentioned in the offic... |
How can an implementation of a language in the same language be faster than the language? | 9,379,560 | 5 | 2012-02-21T14:48:23Z | 9,379,621 | 7 | 2012-02-21T14:52:30Z | [
"python",
"performance",
"jvm",
"pypy",
"language-implementation"
] | If I make a *JVM in Java*, for example, is it possible to make the implementation I made actually *faster* than the original implementation *I used* to build this implementation, even though my implementation is built on top of the original implementation and may even be dependant on that implementation?
( Confusing..... | Absolutely, it is possible. Your JVM implementation could compile Java bytecodes to optimized machine code. If your optimizer was more sophisticated that that in the JVM implementation which you run your Java compiler on, then the end result could be faster.
In that case, you could run your Java compiler *on its own s... |
How can an implementation of a language in the same language be faster than the language? | 9,379,560 | 5 | 2012-02-21T14:48:23Z | 9,379,692 | 10 | 2012-02-21T14:56:45Z | [
"python",
"performance",
"jvm",
"pypy",
"language-implementation"
] | If I make a *JVM in Java*, for example, is it possible to make the implementation I made actually *faster* than the original implementation *I used* to build this implementation, even though my implementation is built on top of the original implementation and may even be dependant on that implementation?
( Confusing..... | You are confused between a *language* and the *execution apparatus* for that language.
One of the reasons why PyPy can be faster than CPython is because PyPy is compiled to a completely separate native executable, and does not depend on, nor execute in, CPython.
Nevertheless, it would be possible for an inefficient i... |
How to call a python method from a java class? | 9,381,906 | 7 | 2012-02-21T17:10:47Z | 9,382,076 | 12 | 2012-02-21T17:21:24Z | [
"java",
"python",
"methods",
"jython"
] | I am using Jython within a Java project.
I have one Java class: `myJavaClass.java` and one Python class: `myPythonClass.py`
```
public class myJavaClass{
public String myMethod() {
PythonInterpreter interpreter = new PythonInterpreter();
//Code to write
}
}
```
The Python file is as follows:... | If I read [the docs](http://www.jython.org/javadoc/org/python/util/PythonInterpreter.html) right, you can just use the [`eval`](http://www.jython.org/javadoc/org/python/util/PythonInterpreter.html#eval%28org.python.core.PyObject%29) function:
```
interpreter.execfile("/path/to/python_file.py");
PyDictionary result = i... |
Send a file through sockets in python | 9,382,045 | 14 | 2012-02-21T17:19:28Z | 9,382,116 | 10 | 2012-02-21T17:23:56Z | [
"python",
"sockets"
] | I'm trying to make a program in python that implements sockets, each client sends a pdf file and the server receives it and the title is changed to "file\_number.pdf"(ie: file\_1.pdf). The problem presented is that only a client can send a file successfully. When a second client tries to send the program does crash. wh... | You must put all the code from `sc, address = s.accept()` upto `sc.close()` into another loop or the server simply terminates after receiving the first file. It doesn't crash, the script is just finished.
**[EDIT]** Here is the revised code:
```
import socket
import sys
s = socket.socket()
s.bind(("localhost",9999))
... |
Multiplying Binary Numbers in Python | 9,382,357 | 3 | 2012-02-21T17:39:26Z | 9,382,376 | 15 | 2012-02-21T17:40:59Z | [
"python",
"binary"
] | Lets say I have the binary number 0b110, which is 6, and I want to multiply the number by 3, to get 18 which is 0b10010. How would I do that in Python, I tried multiplying it normally, but it didn't work... | ```
>>> 0b110 * 0b11
18
>>> bin(0b110 * 0b11)
'0b10010'
``` |
How can I find circular relations in a graph with Python and Networkx? | 9,382,660 | 7 | 2012-02-21T18:00:30Z | 9,382,745 | 9 | 2012-02-21T18:06:52Z | [
"python",
"algorithm",
"graph-theory",
"networkx"
] | Consider I have the following graph:
```
A -> B
B -> C
C -> D
C -> A
```
What is the easiest way to find that A -> B -> C -> A is a circular relation? Is there such a function already built into NetworkX or another easy to use Python library? | [`networkx.simple_cycles`](http://networkx.lanl.gov/reference/generated/networkx.algorithms.cycles.simple_cycles.html#networkx.algorithms.cycles.simple_cycles) does this for you.
```
>>> import networkx as nx
>>> G = nx.DiGraph()
>>> G.add_edge('A', 'B')
>>> G.add_edge('B', 'C')
>>> G.add_edge('C', 'D')
>>> G.add_edge... |
python matplotlib imshow() custom tickmarks | 9,382,664 | 7 | 2012-02-21T18:00:56Z | 9,382,878 | 11 | 2012-02-21T18:17:31Z | [
"python",
"plot",
"matplotlib",
"histogram"
] | I'm trying to set custom tick marks on my imshow() output, but haven't found the right combination.
The script below summarizes my attempts. In this script, I'm trying to make the tickmarks at all even numbers on each axis instead of the default (-10,-5,0,5,10)
```
#!/usr/bin/env python
import matplotlib.pyplot as pl... | <http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.xticks>
```
plt.xticks(ticks)
```
Edit: as Yann mentions in a comment, you may also be interested in [`plt.yticks()`](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.yticks)
Result (using `plt.xticks(ticks, fontsize=9)`)... |
Can't import my own modules in Python | 9,383,014 | 40 | 2012-02-21T18:27:19Z | 9,383,088 | 9 | 2012-02-21T18:31:18Z | [
"python",
"import",
"module",
"package"
] | I'm having a hard time understanding how module importing works in Python (I've never done it in any other language before either).
Let's say I have:
```
myapp/__init__.py
myapp/myapp/myapp.py
myapp/myapp/SomeObject.py
myapp/tests/TestCase.py
```
Now I'm trying to get something like this:
```
myapp.py
=============... | The function `import` looks for files into your PYTHONPATH env. variable and your local directory. So or you can put all your files in the same directory, or export the path typing into a terminal::
```
export PYTHONPATH="$PYTHONPATH:/path_to_myapp/myapp/myapp/"
``` |
Can't import my own modules in Python | 9,383,014 | 40 | 2012-02-21T18:27:19Z | 9,383,295 | 34 | 2012-02-21T18:46:03Z | [
"python",
"import",
"module",
"package"
] | I'm having a hard time understanding how module importing works in Python (I've never done it in any other language before either).
Let's say I have:
```
myapp/__init__.py
myapp/myapp/myapp.py
myapp/myapp/SomeObject.py
myapp/tests/TestCase.py
```
Now I'm trying to get something like this:
```
myapp.py
=============... | In your particular case it looks like you're trying to import `SomeObject` from the myapp.py and TestCase.py scripts. From myapp.py, do
```
import SomeObject
```
since it is in the same folder. For TestCase.py, do
```
from ..myapp import SomeObject
```
*However*, this will work only if you are importing TestCase fr... |
How to find psycopg2 version number | 9,383,073 | 8 | 2012-02-21T18:30:31Z | 9,383,187 | 18 | 2012-02-21T18:39:07Z | [
"python",
"psycopg2"
] | I installed psycopg2 on my Ubuntu Natty machine using apt-get. Now, I would like to know its version number. Can someone tell what the method to find version number for such python packages is. | Since you installed it with the package manager, you can get the version from the command line with this command:
```
dpkg -s psycopg2
```
Alternatively you can get the version from using `pip`, if you have that installed
```
pip freeze | grep psycopg2
```
Or just run a python command to tell you:
```
python -c "i... |
How can I detect Heroku's environment? | 9,383,450 | 27 | 2012-02-21T18:58:07Z | 9,392,576 | 15 | 2012-02-22T09:57:38Z | [
"python",
"django",
"deployment",
"heroku",
"environment"
] | I have a Django webapp, and I'd like to check if it's running on the Heroku stack (for conditional enabling of debugging, etc.) Is there any simple way to do this? An environment variable, perhaps?
I know I can probably also do it the other way around - that is, have it detect if it's running on a developer machine, b... | An ENV var seems to the most obvious way of doing this. Either look for an ENV var that you know exists, or set your own:
```
on_heroku = False
if 'YOUR_ENV_VAR' in os.environ:
on_heroku = True
```
more at: <http://devcenter.heroku.com/articles/config-vars> |
How can I detect Heroku's environment? | 9,383,450 | 27 | 2012-02-21T18:58:07Z | 19,184,024 | 13 | 2013-10-04T14:38:32Z | [
"python",
"django",
"deployment",
"heroku",
"environment"
] | I have a Django webapp, and I'd like to check if it's running on the Heroku stack (for conditional enabling of debugging, etc.) Is there any simple way to do this? An environment variable, perhaps?
I know I can probably also do it the other way around - that is, have it detect if it's running on a developer machine, b... | Similar to what Neil suggested, I would do the following:
```
debug = True
if 'SOME_ENV_VAR' in os.environ:
debug = False
```
I've seen some people use `if 'PORT' in os.environ:` But the unfortunate thing is that the PORT variable is present when you run `foreman start` locally, so there is no way to distinguish ... |
What does Python's eval() do? | 9,383,740 | 77 | 2012-02-21T19:19:16Z | 9,383,764 | 91 | 2012-02-21T19:20:48Z | [
"python",
"eval"
] | In the book that I am reading on Python, it keeps using the code `eval(input('blah'))`
I read the documentation, and I understand it, but I still do not see how it changes the `input()` function.
What does it do? Can someone explain? | The eval function lets a python program run python code within itself.
eval example (interactive shell):
```
>>> x = 1
>>> eval('x + 1')
2
>>> eval('x')
1
``` |
What does Python's eval() do? | 9,383,740 | 77 | 2012-02-21T19:19:16Z | 9,383,771 | 19 | 2012-02-21T19:21:27Z | [
"python",
"eval"
] | In the book that I am reading on Python, it keeps using the code `eval(input('blah'))`
I read the documentation, and I understand it, but I still do not see how it changes the `input()` function.
What does it do? Can someone explain? | In Python 2.x `input(...)` is equivalent to `eval(raw_input(...))`, in Python 3.x `raw_input` was renamed `input`, which I suspect lead to your confusion (you were probably looking at the documentation for `input` in Python 2.x). Additionally, `eval(input(...))` would work fine in Python 3.x, but would raise a `TypeErr... |
What does Python's eval() do? | 9,383,740 | 77 | 2012-02-21T19:19:16Z | 9,384,005 | 57 | 2012-02-21T19:39:26Z | [
"python",
"eval"
] | In the book that I am reading on Python, it keeps using the code `eval(input('blah'))`
I read the documentation, and I understand it, but I still do not see how it changes the `input()` function.
What does it do? Can someone explain? | `eval()` interprets a string as code. The reason why so many people have warned you about using this is because a user can use this as an option to run code on the computer. If you have `eval(input())` and `os` imported, a person could type into `input()` `os.system('rm -R *')` which would delete all your files in your... |
Hover issue in PyQt | 9,384,305 | 3 | 2012-02-21T20:01:27Z | 9,425,039 | 8 | 2012-02-24T03:39:05Z | [
"python",
"hover",
"pyqt",
"pyqt4"
] | I want to do hover. I saw an example and then write a script which will be use as I made program. I am facing one problem that hover only occur if you put mouse on the left corner of button. I want that it will happen for all the button that if i move cursor on button then it should change.
Here is my code:
```
from ... | Is this what you're looking for
```
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import pyqtSignal
import os,sys
class Main(QtGui.QWidget):
def __init__(self, parent=None):
super(Main, self).__init__(parent)
layout = QtGui.QVBoxLayout(self) # layout of main widget
button = HoverB... |
ipython reads wrong python version | 9,386,048 | 51 | 2012-02-21T22:11:32Z | 10,381,987 | 98 | 2012-04-30T10:16:26Z | [
"python",
"ipython"
] | I've been having trouble with Python, iPython and the libraries. The following points show the chain of the problematics. I'm running Python 2.7 on Mac Lion.
1. iPython doesn't read the libraries of scipy, matplotlib, but it does read numpy.
2. To fix this, I tried installing Python's source code version, and it only ... | Okay quick fix:
```
which python
```
gives you `/usr/bin/python`, right? Do
```
which ipython
```
and I bet that'll be `/usr/local/bin/ipython`. Let's look inside:
**Edit 9/7/16 -- The file now looks like this:**
```
cat /usr/local/bin/ipython
#!/usr/bin/python
# -*- coding: utf-8 -*-
import re
import sys
from... |
Sorting in python, and empty strings | 9,386,501 | 3 | 2012-02-21T22:43:44Z | 9,386,564 | 16 | 2012-02-21T22:49:20Z | [
"python",
"string",
"sorted"
] | Hi I'm using the sorted() function in Python to order a bi-dimensionnal array (I want to sort columns just like it can be done in a classic spreadsheet).
In the example below I use itemgetter(0) to sort the grid based on first column's contents.
But sorted returns empty strings before non-empty ones.
```
>>> imp... | Use a different key function. One that would work is:
```
sorted(res, key=lambda x: (x[0] == "", x[0].lower()))
```
The key is then a tuple with either 0 (False) or 1 (True) in the first position, where True indicates that the first item in the record is blank. The second position has the name field from your origina... |
Repetitive Try and Except Clauses | 9,386,592 | 10 | 2012-02-21T22:52:11Z | 9,386,604 | 20 | 2012-02-21T22:53:27Z | [
"python",
"try-catch",
"except"
] | I've created a bunch of functions and I need very similar except clauses in all of them, but I hate having so many lines of try and except clauses and the same code inside of each function. For example:
```
import sys
import random
def foo():
num=random.random()
try:
if num>0.5: print 'OK'
eli... | [Python Decorators](http://stackoverflow.com/questions/739654/understanding-python-decorators) are what you want.
You said the except block is always the same. Make a custom decorator that does what you want. You'll have to apply this to each function/method but it sure does save duplication.
```
def handleError(func... |
Any good use for list/dict assignment during for loop? | 9,387,317 | 6 | 2012-02-22T00:10:57Z | 9,387,398 | 10 | 2012-02-22T00:20:29Z | [
"python"
] | I saw some code yesterday in [this question](http://stackoverflow.com/q/9372824/505154) that I had not seen before, this line in particular:
```
for xyz[num] in possible[num]:
...
```
So as this loop runs, the elements from `possible[num]` are assigned to the list `xyz` at position `num`. I was really confused by... | The reason this is allowed is simplicity. The list of "loop variables" has the same [grammar as any other assignment target](http://docs.python.org/reference/compound_stmts.html#the-for-statement). As an example, tuple unpacking is allowed in assignments, so it is allowed in `for` loops as well, and this is certainly q... |
Does python fabric support dynamic set env.hosts? | 9,387,407 | 18 | 2012-02-22T00:21:51Z | 9,387,644 | 26 | 2012-02-22T00:48:10Z | [
"python",
"fabric"
] | I want to change the env.hosts dynamically because sometimes I want to deploy to one machine first, check if ok then deploy to many machines.
Currently I need to set env.hosts first, how could I set the env.hosts in a method and not in global at script start? | Yes you can set `env.hosts` dynamically. One common pattern we use is:
```
from fabric.api import env
def staging():
env.hosts = ['XXX.XXX.XXX.XXX', ]
def production():
env.hosts = ['YYY.YYY.YYY.YYY', 'ZZZ.ZZZ.ZZZ.ZZZ', ]
def deploy():
# Do something...
```
You would use this to chain the tasks such as ... |
What's the difference between dist-packages and site-packages? | 9,387,928 | 149 | 2012-02-22T01:29:08Z | 9,388,115 | 124 | 2012-02-22T01:52:54Z | [
"python",
"pip",
"easy-install",
"package-managers"
] | I'm a bit miffed by the python package installation process. Specifically, what's the difference between packages installed in the dist-packages directory and the site-packages directory? | dist-packages is a Debian-specific convention that is also present in its derivatives, like Ubuntu. Modules are installed to dist-packages when they come from the Debian package manager into this location:
```
/usr/lib/python2.7/dist-packages
```
Since `easy_install` and `pip` are installed from the package manager, ... |
Suds generates empty elements; how to remove them? | 9,388,180 | 10 | 2012-02-22T02:04:03Z | 9,574,536 | 15 | 2012-03-05T21:48:06Z | [
"python",
"soap",
"suds"
] | [Major Edit based on experience since 1st post two days ago.]
I am building a Python SOAP/XML script using Suds, but am struggling to get the code to generate SOAP/XML that is acceptable to the server. I had thought that the issue was that Suds was not generating prefixes for inner elements, but subsequently it turns ... | You can use a plugin to modify the XML before is sent to the server (my answer is based on Ronald Smith's solution):
```
from suds.plugin import MessagePlugin
from suds.client import Client
import re
class MyPlugin(MessagePlugin):
def sending(self, context):
context.envelope = re.sub('\s+<.*?/>', '', cont... |
Python, Numpy - Trying split an array according to a condition | 9,389,629 | 3 | 2012-02-22T05:39:56Z | 9,390,135 | 7 | 2012-02-22T06:30:44Z | [
"python",
"numpy",
"scipy"
] | I am trying to find clusters (i.e. groups within an array where the difference between [n+1] and [n] is less than a certain value) inside an array. I have a numpy array that is a sequence of time stamps. I can find the difference between time stamps using numpy.diff(), but I have a hard time trying to determine cluster... | ```
import numpy as np
t = np.array([ 147, 5729, 5794, 5806, 6798, 8756, 8772, 8776, 9976])
dt = np.diff(t)
pos = np.where(dt > 100)[0] + 1
print np.split(t, pos)
```
the output is:
```
[array([147]),
array([5729, 5794, 5806]),
array([6798]),
array([8756, 8772, 8776]),
array([9976])]
``` |
Complete Suffix Array | 9,389,681 | 2 | 2012-02-22T05:45:54Z | 9,390,461 | 14 | 2012-02-22T07:04:22Z | [
"python",
"string",
"algorithm",
"suffix-tree",
"suffix-array"
] | A suffix array will index all the suffixes for a given list of strings, but what if you're trying to index all the possible unique substrings? I'm a bit new at this, so here's an example of what I mean:
Given the string
```
abcd
```
A suffix array indexes (at least to my understanding)
```
(abcd,bcd,cd,d)
```
I wo... | The suffix array does what you need already, because every substring is a prefix of one of the suffixes. Specifically, given your suffix array
abcd
bcd
cd
d
and assume you are looking for substring "bc", then you can find that by looking for all suffixes that start with "bc" (there is only one in this case, "bcd"). S... |
How do you even give an (openFST-made) FST input? Where does the output go? | 9,390,536 | 10 | 2012-02-22T07:11:46Z | 9,644,742 | 15 | 2012-03-10T07:30:45Z | [
"python",
"shell",
"fsm"
] | Before I start, note that I'm using the linux shell (via `using subprocess.call()` from Python), and I am using openFST.
I've been sifting through documents and questions about openFST, but I cannot seem to find an answer to this question: how does one actually give input to an openFST-defined, compiled and composed F... | One way is to create your machine that performs the transformation.
A very simple example would be to upper case a string.
M.wfst
```
0 0 a A
0 0 b B
0 0 c C
0
```
The accompanying symbols file contains a line for for each symbols of the alphabet. Note 0 is reserved for null (epsilon) transitions and has special mea... |
Drawing Histogram in OpenCV-Python | 9,390,592 | 12 | 2012-02-22T07:16:40Z | 9,390,772 | 10 | 2012-02-22T07:35:30Z | [
"python",
"opencv",
"numpy",
"computer-vision",
"histogram"
] | I was just trying to draw histogram using new OpenCV Python interface ( cv2 ).
Below is the code i tried:
```
import cv2
import numpy as np
import time
img = cv2.imread('zzz.jpg')
h = np.zeros((300,256,3))
b,g,r = cv2.split(img)
bins = np.arange(256).reshape(256,1)
color = [ (255,0,0),(0,255,0),(0,0,255) ]
for item... | You should copy the array:
```
b,g,r = img[:,:,0].copy(), img[:,:,1].copy(), img[:,:,2].copy()
```
But, since calcHist() can accept channels parameter, you need not to split your img to three array.
```
import cv2
import numpy as np
img = cv2.imread('zzzyj.jpg')
h = np.zeros((300,256,3))
bins = np.arange(256).resh... |
Django: How to get a static file's filepath in a development environment? | 9,391,167 | 4 | 2012-02-22T08:10:48Z | 9,391,228 | 11 | 2012-02-22T08:15:22Z | [
"python",
"django",
"static-files"
] | Some background first. I'm employing the following "trick" to prevent undesired browser caching of static files (CSS, JS, etc.):
```
<script src="{{ STATIC_URL }}js/utils.js?version=1302983029"></script>
```
When the version string changes on a subsequent page load, it makes the browser re-fetch the static file from ... | If using django.contrib.staticfiles, here's an extract of the [findstatic](https://docs.djangoproject.com/en/1.9/ref/contrib/staticfiles/#findstatic) command (django/contrib/staticfiles/management/commands/findstatic.py) that should help. It uses the [finders.find](https://docs.djangoproject.com/en/1.9/ref/contrib/stat... |
Why doesn't Python evaluate constant number arithmetic before compiling to bytecode? | 9,391,845 | 42 | 2012-02-22T09:07:41Z | 9,392,000 | 69 | 2012-02-22T09:18:38Z | [
"python",
"bytecode"
] | In the following code, why doesn't Python compile `f2` to the same bytecode as `f1`?
Is there a reason not to?
```
>>> def f1(x):
x*100
>>> dis.dis(f1)
2 0 LOAD_FAST 0 (x)
3 LOAD_CONST 1 (100)
6 BINARY_MULTIPLY
7 POP_TOP
... | This is because `x` could have a `__mul__` method with side-effects. `x * 10 * 10` calls `__mul__` twice, while `x * 100` only calls it once:
```
>>> class Foo(object):
... def __init__ (self):
... self.val = 5
... def __mul__ (self, other):
... print "Called __mul__: %s" % (other)
... ... |
Why doesn't Python evaluate constant number arithmetic before compiling to bytecode? | 9,391,845 | 42 | 2012-02-22T09:07:41Z | 9,392,189 | 17 | 2012-02-22T09:30:36Z | [
"python",
"bytecode"
] | In the following code, why doesn't Python compile `f2` to the same bytecode as `f1`?
Is there a reason not to?
```
>>> def f1(x):
x*100
>>> dis.dis(f1)
2 0 LOAD_FAST 0 (x)
3 LOAD_CONST 1 (100)
6 BINARY_MULTIPLY
7 POP_TOP
... | Python evaluates expressions from [left to right](http://docs.python.org/release/2.5.2/ref/evalorder.html). For `f2()`, this means it will first evaluate `x*10` and then multiply the result by 10. Try:
Try:
```
def f2(x):
10*10*x
```
This should be optimized. |
Docstrings - one line vs multiple line | 9,392,096 | 6 | 2012-02-22T09:25:29Z | 9,392,661 | 11 | 2012-02-22T10:03:54Z | [
"python",
"documentation",
"docstring"
] | I'm adding some ([epydoc](http://epydoc.sourceforge.net/manual-fields.html)) documentation to a package I've written, and I'm coming across a lot of instances where I'm repeating myself a multitude of times.
```
def script_running(self, script):
"""Return if script is running
@param script: Script to check wh... | The general guideline you are looking for is right in [PEP257](http://www.python.org/dev/peps/pep-0257/) in what you quoted, maybe you just need to see it in action.
Your function is a good candidate for a one-line docstring (*"really obvious cases"*):
```
def script_running(self, script):
"""Check if the script ... |
Error "unknown delivery tag" occurs when i try ack messages to RabbitMQ using pika (python) | 9,392,478 | 7 | 2012-02-22T09:49:15Z | 22,909,383 | 15 | 2014-04-07T10:09:09Z | [
"python",
"message-queue",
"rabbitmq",
"pika"
] | I want process messages in few threads but i'm getting error during execute this code:
```
from __future__ import with_statement
import pika
import sys
from pika.adapters.blocking_connection import BlockingConnection
from pika import connection, credentials
import time
import threading
import random
from pika.adapters... | The problem probably is that you're setting `no_ack=True` like this:
```
consumer_tag = channel.basic_consume(
message_delivery_event,
no_ack=True,
queue=queue,
)
```
And then acknowledging the messages:
```
channel.basic_ack(delivery_tag=args.delivery_tag)
```
You have to chose if you want to acknowled... |
Python - how to execute shell commands with pipe? | 9,393,425 | 13 | 2012-02-22T10:54:24Z | 9,393,536 | 15 | 2012-02-22T11:01:57Z | [
"python",
"subprocess",
"pipe"
] | I have a case to want to execute the following shell command in Python and get the output,
```
echo This_is_a_testing | grep -c test
```
I could use this python code to execute the above shell command in python,
```
>>> import subprocess
>>> subprocess.check_output("echo This_is_a_testing | grep -c test", shell=True... | From the manual:
> to get anything other than None in the result tuple, you need to give
> stdout=PIPE and/or stderr=PIPE
```
p2 = subprocess.Popen(["grep", "-c", "test"], stdin=p1.stdout, stdout=subprocess.PIPE)
``` |
Python - how to execute shell commands with pipe? | 9,393,425 | 13 | 2012-02-22T10:54:24Z | 9,393,539 | 19 | 2012-02-22T11:02:05Z | [
"python",
"subprocess",
"pipe"
] | I have a case to want to execute the following shell command in Python and get the output,
```
echo This_is_a_testing | grep -c test
```
I could use this python code to execute the above shell command in python,
```
>>> import subprocess
>>> subprocess.check_output("echo This_is_a_testing | grep -c test", shell=True... | Please look here:
```
>>> import subprocess
>>> p1 = subprocess.Popen(["echo", "This_is_a_testing"], stdout=subprocess.PIPE)
>>> p2 = subprocess.Popen(["grep", "-c", "test"], stdin=p1.stdout)
>>> 1
p1.stdout.close()
>>> p2.communicate()
(None, None)
>>>
```
here you get 1 as output after you write `p2 = subprocess.Po... |
Python and MySQLdb: substitution of table resulting in syntax error | 9,394,291 | 5 | 2012-02-22T11:56:48Z | 9,394,450 | 10 | 2012-02-22T12:09:34Z | [
"python",
"mysql-python"
] | I need to dynamically change tables and variables from time to time, so I wrote a python method like this:
```
selectQ ="""SELECT * FROM %s WHERE %s = %s;"""
self.db.execute(selectQ,(self.table,self.columnSpecName,idKey,))
return self.db.store_result()
```
However this results in a syntax error exceptio... | Parameter substitution in the DB API is only for values - not tables or fields. You'll need to use normal string substitution for those:
```
selectQ ="""SELECT * FROM %s WHERE %s = %%s;""" % (self.table,self.columnSpecName)
self.db.execute(selectQ,(idKey,))
return self.db.store_result()
```
Note that the value place... |
Python combine two for loops | 9,394,803 | 7 | 2012-02-22T12:32:10Z | 9,394,841 | 15 | 2012-02-22T12:34:36Z | [
"python"
] | Currently I would do:
```
for x in [1,2,3]:
for y in [1,2,3]
print x,y
```
Is there way of doing something like
```
for x,y in ([1,2,3],[1,2,3]):
print x,y
```
Would like to shorten this kind of loop and this throws the "too many to unpack" exception. | Use [itertools.product](http://docs.python.org/library/itertools.html#itertools.product)
```
import itertools
for x, y in itertools.product([1,2,3], [1,2,3]):
print x, y
```
prints all nine pairs:
```
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
```
**UPDATE**: If the two variables `x` and `y` are to be chosen from one ... |
Python combine two for loops | 9,394,803 | 7 | 2012-02-22T12:32:10Z | 9,394,889 | 7 | 2012-02-22T12:37:27Z | [
"python"
] | Currently I would do:
```
for x in [1,2,3]:
for y in [1,2,3]
print x,y
```
Is there way of doing something like
```
for x,y in ([1,2,3],[1,2,3]):
print x,y
```
Would like to shorten this kind of loop and this throws the "too many to unpack" exception. | You could use a generator expression in the for loop:
```
for x, y in ((a,b) for a in [1,2,3] for b in [5,6,7]):
print x, y
``` |
Django IntegerField returning string(!) - how to coerce to int? | 9,395,106 | 3 | 2012-02-22T12:51:37Z | 9,395,868 | 8 | 2012-02-22T13:36:05Z | [
"python",
"django",
"django-models",
"django-orm"
] | I have an IntegerField declared as below on a model:
```
amount = models.IntegerField()
```
When accessing it, it sometimes returns a string. The proximate cause for this is that it has had a string assigned to it. So far, so unmysterious. It also returns a string even after it has been saved.
This strikes me as a l... | As mentioned in my comment, the reason this is happening is that Django performs relevant coercions on fields at save, but doesn't reflect value changes back on the original model because it can't be done without querying the database again.
The quickest fix (and easiest, in the long run) for this kind of problem is t... |
How to get all child components of QWidget in pyside/pyqt/qt? | 9,395,535 | 4 | 2012-02-22T13:15:34Z | 9,404,886 | 11 | 2012-02-22T23:27:10Z | [
"python",
"qt",
"pyside",
"children"
] | I am developing a desktop application using pyside(qt), I want to access(iterate) all line edit components of QWidget. In qt I found two methods *findChild* and *findChildren* but there is no proper example found and My code shows error, *'form' object has no attribute 'findChild'.*
Here 'form' is Qwidget form consist ... | The signatures of `findChild` and `findChildren` are different in PySide/PyQt4 because there is no real equivalent to the C++ cast syntax in Python.
Instead, you have to pass a type (or `tuple` of types) as the first argument, and an optional string as the second argument (for matching the `objectName`).
So your exam... |
How to organize a relatively large Flask application? | 9,395,587 | 65 | 2012-02-22T13:18:18Z | 9,397,345 | 19 | 2012-02-22T15:06:32Z | [
"python",
"flask"
] | I'm building my first Flask app and I can't figure out a good, clean Pythonic way of organizing my application.
I don't want to have everything in a single .py file as in their example.
I would like to have each part of my app in a separate module.
What would be a good way to organize things? | Flask 0.7 implements [Blueprints](http://flask.pocoo.org/docs/blueprints/). They are great for using the `route` decorator without importing the main application object. |
How to organize a relatively large Flask application? | 9,395,587 | 65 | 2012-02-22T13:18:18Z | 9,398,062 | 70 | 2012-02-22T15:45:40Z | [
"python",
"flask"
] | I'm building my first Flask app and I can't figure out a good, clean Pythonic way of organizing my application.
I don't want to have everything in a single .py file as in their example.
I would like to have each part of my app in a separate module.
What would be a good way to organize things? | I have created a Flask boilerplate project called "[Fbone](https://github.com/imwilsonxu/fbone)", please feel free to check it out and fork :)
Fbone (Flask bone) is a Flask (Python microframework) template/bootstrap/boilerplate application.
Overview
* Well designed for big project using blueprint.
* Integrate with h... |
How to organize a relatively large Flask application? | 9,395,587 | 65 | 2012-02-22T13:18:18Z | 17,344,725 | 11 | 2013-06-27T13:37:48Z | [
"python",
"flask"
] | I'm building my first Flask app and I can't figure out a good, clean Pythonic way of organizing my application.
I don't want to have everything in a single .py file as in their example.
I would like to have each part of my app in a separate module.
What would be a good way to organize things? | I'm working on a (by my standards) big Flask project (5000 lines of Python code and it's only half-finished). The customer wants the project to be modular, so I took this apporach:
My folder structure looks like this:
```
âââ __init__.py
âââ modules.yml
âââ config
âââ controllers
â âââ... |
How to organize a relatively large Flask application? | 9,395,587 | 65 | 2012-02-22T13:18:18Z | 18,442,847 | 15 | 2013-08-26T11:17:18Z | [
"python",
"flask"
] | I'm building my first Flask app and I can't figure out a good, clean Pythonic way of organizing my application.
I don't want to have everything in a single .py file as in their example.
I would like to have each part of my app in a separate module.
What would be a good way to organize things? | **Make sure to read** Matt Wright's [***wonderful* post**](http://mattupstate.com/blog/how-i-structure-my-flask-applications/) on the subject.
The post features:
1. A description of a structure for large flask projects
2. [An example application on Github](https://github.com/mattupstate/overholt)
3. **A description o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.