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 |
|---|---|---|---|---|---|---|---|---|---|
Beautifulsoup - nextSibling | 5,999,747 | 11 | 2011-05-14T04:09:35Z | 5,999,786 | 32 | 2011-05-14T04:23:14Z | [
"python",
"beautifulsoup"
] | I'm trying to get the content "My home address" using the following but got the AttributeError:
```
address = soup.find(text="Address:")
print address.nextSibling
<td><b>Address:</b></td>
<td>My home address</td>
```
What is a good way to navigate down td tag and pull the content? | The problem is that you have found a `NavigableString`, not the `<td>`. Also `nextSibling` will find the next `NavigableString` *or* `Tag` so even if you had the `<td>` it wouldn't work the way you expect.
This is what you want:
```
address = soup.find(text="Address:")
b_tag = address.parent
td_tag = b_tag.parent
nex... |
How to get an app name using python in django | 6,000,205 | 10 | 2011-05-14T06:32:07Z | 6,000,221 | 13 | 2011-05-14T06:36:01Z | [
"python",
"django",
"django-views"
] | If you are in the view and want to retrieve the app name using Python ( the app name will be used for further logic ), how would you do it ? | You could do:
```
from django.core.urlresolvers import resolve
....
resolve(request.path).app_name
```
See [How to get current application in Django](http://stackoverflow.com/questions/4256295/how-to-get-current-application-in-django) and [resolve()](http://docs.djangoproject.com/en/dev/topics/http/urls/#resolve)
... |
`return None` in python not recommended. How to bypass? | 6,000,413 | 9 | 2011-05-14T07:25:50Z | 6,000,438 | 30 | 2011-05-14T07:32:03Z | [
"python",
"return-value",
"handle"
] | I have a function which connects to a url by `httplib` using `lxml`. It checks by `xpath`for a certain pattern and if the check is positive it returns a string. But if the check was negative it returns nothing.
Now the situation is, that my function returns `None`. I call the function, check if its return value is `no... | There is nothing wrong with returning `None`.
In most cases, you don't need to explicitly return `None`. Python will do it for you. This is an altered version of your `foobar` which behaves identically without explicitly returning `None`:
```
def foobar(arg):
if check:
return result
# If not check, then None wi... |
Does the MySQLdb module in python returns utf8 encoding or unicode in this case? | 6,001,104 | 4 | 2011-05-14T10:04:06Z | 6,001,250 | 9 | 2011-05-14T10:34:59Z | [
"python",
"unicode",
"encoding",
"utf-8",
"mysql-python"
] | Using MySQLdb I connect to a database where everything is stored in the utf8 encoding.
If I do
```
cursor.execute("SET NAMES utf8")
```
and fetch some data from the database by another statement. Does that mean, that the strings in
```
cursor.execute("SELECT ...")
cursor.fetchall()
```
will be in unicode? Or do I ... | From [the docs](http://mysql-python.sourceforge.net/MySQLdb.html):
> connect(parameters...)
> ...
>
> > `use_unicode`
> >
> > > If True, CHAR and VARCHAR and TEXT columns are returned as Unicode strings, using the configured character set. It is best to set the default encoding in the server configuration, or client... |
Usage of for and if in Python | 6,001,209 | 2 | 2011-05-14T10:26:29Z | 6,001,223 | 8 | 2011-05-14T10:29:27Z | [
"python",
"for-loop",
"if-statement",
"colon"
] | Could you please look at the code below:
```
def search(self, filter):
return [note for note in self.notes if note.match(filter)]
```
I thought `for` and `if` statements require a colon. Above, there is no colon after `for` and `if`. And this kind of if and for usage does not look like what I read in text boo... | That's not a mere loop/if, but a [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions)
In particular this piece of code:
```
return [note for note in self.notes if note.match(filter)]
```
for each note in `self.notes` returns only those notes matching the filter condition.
Th... |
Dynamic choices field in Django Models | 6,001,986 | 12 | 2011-05-14T13:03:27Z | 12,005,426 | 12 | 2012-08-17T12:02:45Z | [
"python",
"django",
"django-models",
"django-forms"
] | My models.py:
```
SHOP1_CHOICES = (
('Food Court', 'Food Court'),
('KFC', 'KFC'),
)
SHOP2_CHOICES = (
('Sports Arena', 'Sports Arena'),
('Disco D', 'Disco D'),
)
SHOP3_CHOICES = (
('Bowling Arena', 'Bowling Arena'),
('Cinemax', 'Cinemax'),
)
class Feed(models.Model):
gender = models.Cha... | This is my approach:
I use lazy for lazy load:
```
from django.utils.functional import lazy
```
Here, a helper to chose options:
```
def help_SHOP_CHOICES():
SHOP1_CHOICES = [
('Food Court', 'Food Court'),
('KFC', 'KFC'),
]
SHOP3_CHOICES = [
('Bowling Arena', 'Bowling Arena'),
... |
Is there a recommended way for interaction between python and MySQL? | 6,002,147 | 3 | 2011-05-14T13:32:46Z | 6,002,160 | 8 | 2011-05-14T13:35:38Z | [
"python",
"mysql",
"interaction"
] | What is the recommonded way to interact between python and MySQL? Currently I am using MySQLdb and I heared from Oursql. But I asked myself, if there is a more appropriate way to manage this. | MySQLdb is what most people use at the lower level, but oursql is interesting too. You can use higher level mechanisms such as
* [sqlalchemy](http://www.sqlalchemy.org/)
* [Django](https://docs.djangoproject.com/en/dev/topics/db/) - note it comes with a whole web framework :)
* I'm sure you can find others, look for '... |
Scala: Implementing Java's AspectJ around advice or Python decorators | 6,002,418 | 7 | 2011-05-14T14:23:14Z | 6,002,595 | 8 | 2011-05-14T14:55:47Z | [
"java",
"python",
"scala",
"aop",
"aspectj"
] | I have been using Java + AspectJ extensively for my startup. I would love to switch to Scala but I have a common design pattern that I am not sure entirely the best way to implement in Scala.
A tremendous amount of our application uses AspectJ pointcuts using annotations as the marker.
This is very similar to Python's... | The scala way would be
```
def transaction(f: =>Unit) = {
println("start transaction")
f
println("end transaction")
}
transaction {
println("inside transaction")
}
```
This prints
```
start transaction
inside transaction
end transaction
``` |
Scala: Implementing Java's AspectJ around advice or Python decorators | 6,002,418 | 7 | 2011-05-14T14:23:14Z | 6,004,154 | 12 | 2011-05-14T19:02:42Z | [
"java",
"python",
"scala",
"aop",
"aspectj"
] | I have been using Java + AspectJ extensively for my startup. I would love to switch to Scala but I have a common design pattern that I am not sure entirely the best way to implement in Scala.
A tremendous amount of our application uses AspectJ pointcuts using annotations as the marker.
This is very similar to Python's... | Incidentally, I am giving a talk at [Scala Days 2011 on the same topic](http://days2011.scala-lang.org/node/252). The core idea is the same as Kim's and Dean's example. However, when it comes to the full spectrum of crosscutting concerns, similarity and differences become more nuanced.
**On one end of the spectrum**, ... |
How can I create directories recursively? | 6,004,073 | 45 | 2011-05-14T18:46:37Z | 6,004,084 | 95 | 2011-05-14T18:48:32Z | [
"python"
] | Is there a Python method to create directories recursively? I have this path:
```
/home/dail/
```
I would like to create
```
/home/dail/first/second/third
```
Can I do it recursively or I have to create one directory after the other?
The same thing for:
**chmod** and **chown** can I do it recursively without assi... | [`os.makedirs`](http://docs.python.org/2/library/os.html#os.makedirs) is what you need. For `chmod` or `chown` you'll have to use `os.walk` and use it on every file/dir yourself. |
Trouble with Python Inheritance | 6,005,316 | 4 | 2011-05-14T23:01:05Z | 6,005,325 | 9 | 2011-05-14T23:03:36Z | [
"python",
"class",
"inheritance",
"object"
] | The code that I'm acttualy having the problem with is very long, so I made an example that displays my problem.
I have two classes that inherit from a base-class (**BaseClass**). Both of these classes add some elements to **self.Dict**. However, they seem to cross contaminate elements. I was expecting **c0.Dict** to r... | You hit a python gotcha : mutable default arguments.
<http://blog.objectmentor.com/articles/2008/05/22/pythons-mutable-default-problem>
```
class BaseClass :
def __init__ (self, _dict=None) :
self.Dict = _dict or {}
``` |
Replace first occurrence only of a string? | 6,005,891 | 14 | 2011-05-15T01:23:52Z | 6,005,896 | 39 | 2011-05-15T01:26:15Z | [
"python"
] | I have something like this:
```
text = 'This text is very very long.'
replace_words = ['very','word']
for word in replace_words:
text = text.replace('very','not very')
```
I would like to only replace the first 'very' or choose which 'very' gets overwritten. I'm doing this on much larger amounts of text so I wan... | ```
text = text.replace("very", "not very", 1)
```
```
>>> help(str.replace)
Help on method_descriptor:
replace(...)
S.replace (old, new[, count]) -> string
Return a copy of string S with all occurrences of substring
old replaced by new. If the optional argument count is
given, only the first count ... |
module object has no attribute 'Screen' | 6,006,871 | 3 | 2011-05-15T06:29:15Z | 6,006,878 | 9 | 2011-05-15T06:31:09Z | [
"python",
"python-3.x"
] | I am teaching myself python from [this site](http://openbookproject.net/thinkcs/python/english3e/). On [Chapter 3](http://openbookproject.net/thinkcs/python/english3e/ch03.html), when I typed the code in the given example, I got the following error--
```
Python 3.2 (r32:88445, Mar 25 2011, 19:28:28)
[GCC 4.5.2] on li... | Rename `turtle.py`. It is clashing with the imported module of the same name.
I tested that the code from that site works in Python 2.6 (without installing any external packages).
From <http://docs.python.org/tutorial/modules.html#the-module-search-path>
> When a module named `spam` is imported, the interpreter sear... |
module object has no attribute 'Screen' | 6,006,871 | 3 | 2011-05-15T06:29:15Z | 6,006,976 | 11 | 2011-05-15T06:58:06Z | [
"python",
"python-3.x"
] | I am teaching myself python from [this site](http://openbookproject.net/thinkcs/python/english3e/). On [Chapter 3](http://openbookproject.net/thinkcs/python/english3e/ch03.html), when I typed the code in the given example, I got the following error--
```
Python 3.2 (r32:88445, Mar 25 2011, 19:28:28)
[GCC 4.5.2] on li... | [Adam Bernier's answer](http://stackoverflow.com/questions/6006871/module-object-has-no-attribute-screen/6006878#6006878) is probably correct. It looks like you have a file called `turtle.py` that Python is picking up before the one that came with your Python installation.
To track down these problems:
```
% python
P... |
When and why to use Django development server? | 6,007,660 | 2 | 2011-05-15T09:49:25Z | 6,007,802 | 8 | 2011-05-15T10:23:02Z | [
"python",
"django"
] | I understand that it's simple and doesn't require any installation whatsoever, but are there any other reasons to use it for long-term development instead of Apache with mod\_wsgi? As a Django newbie, I just find deployment from development to live (Apache) environment quite cumbersome and annoying, so the question tha... | You sometimes *need* the production setup locally when you're developing. I've needed it when I was messing with some subdomain related code that tied into the application and needed to mimic my real server locally.
However, for most things, the dev server is a big win. Here are a few points.
1. Like rebus mentioned,... |
What makes a python tuple? | 6,007,728 | 4 | 2011-05-15T10:06:57Z | 6,007,757 | 9 | 2011-05-15T10:13:54Z | [
"python",
"tuples"
] | The following code does not print what I would expect:
```
#!/usr/bin/env python
print type(1,)
a = 1,
print type(a)
```
Here is the output:
```
<type 'int'>
<type 'tuple'>
```
I understand that the comma makes a into a tuple. But if that is the case how come the original print is not printing a tuple type but an ... | Because the tuple syntax inside a function call is also the way parameters are passed:
```
>>> print type(1,2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: type() takes 1 or 3 arguments
>>> print type((1,))
<type 'tuple'>
>>> a = 1,
>>> type(a)
<type 'tuple'>
```
It is a synta... |
Sum() in python | 6,007,808 | 2 | 2011-05-15T10:24:23Z | 6,007,819 | 11 | 2011-05-15T10:26:51Z | [
"python",
"sum"
] | I have been trying to be comfortable with the sum() in python, I did understand the basic function of sum but as a mathematica backgroud,I was just inquistive to know can we use sum in python in the same way like we do in mathematica for example consider this mathematica module:
```
Sq[a_, b_] := Module[{m, n}, m = Ma... | ```
sum((m - r + 1) * (n - r + 1) for r in xrange(1,n+1))
```
1. There's no implicit multiplication between integers, so you need the `*`.
2. `f(x) for x in xes` is the general format of a list comprehension, where you want `x` to iterate through every element of `xes`, and give back the value `f(x)`. |
What does the [0]*x syntax do in Python? | 6,007,881 | 3 | 2011-05-15T10:41:16Z | 6,007,900 | 11 | 2011-05-15T10:45:36Z | [
"python",
"math",
"programming-languages"
] | A flash question, I'm looking at the following code
```
from __future__ import division
import math
import time
def dft(x, inverse = False, verbose = False) :
t = time.clock()
N = len(x)
inv = -1 if not inverse else 1
X =[0] * N
for k in xrange(N) :
for n in xrange(N) :
X[k] +=... | The `[0] * x` creates a list with `x` elements. So,
```
>>> [ 0 ] * 5
[0, 0, 0, 0, 0]
>>>
```
Be warned that they all point to the same object. This is cool for immutables like integers but a pain for things like lists.
```
>>> t = [[]] * 5
>>> t
[[], [], [], [], []]
>>> t[0].append(5)
>>> t
[[5], [5], [5], [5], [5]... |
Is it possible to stop Django from creating .pyc files, whilst in development? | 6,008,683 | 9 | 2011-05-15T13:31:00Z | 6,008,699 | 9 | 2011-05-15T13:36:01Z | [
"python",
"django",
"linux"
] | Is it possible to stop Django from creating the .pyc files? I know it's Python that creates them when modules are imported, but is there some way of turning them off?
Totally understand why they're created, etc, and will want them when I go live, but currently they just clutter up the directory and it bothers me - so ... | You can try setting the **PYTHONDONTWRITEBYTECODE** environment variable:
* [Python Command line and environment](http://docs.python.org/using/cmdline.html#miscellaneous-options)
> PYTHONDONTWRITEBYTECODE
>
> If this is set, Python wonât try to write .pyc or .pyo files on the import of source modules.
>
> New in ve... |
Is it possible to stop Django from creating .pyc files, whilst in development? | 6,008,683 | 9 | 2011-05-15T13:31:00Z | 6,008,801 | 8 | 2011-05-15T13:55:22Z | [
"python",
"django",
"linux"
] | Is it possible to stop Django from creating the .pyc files? I know it's Python that creates them when modules are imported, but is there some way of turning them off?
Totally understand why they're created, etc, and will want them when I go live, but currently they just clutter up the directory and it bothers me - so ... | You can use this, where applicable:
```
import sys
sys.dont_write_bytecode = True
``` |
Unable to install Python and GDAL (DLL load failed) | 6,009,506 | 14 | 2011-05-15T15:58:08Z | 8,890,144 | 17 | 2012-01-17T05:33:13Z | [
"python",
"gdal"
] | I am trying to install GDAL and Python on my Windows 7 workstation.
* Python-version: 2.6.6
* Gdal 1.8
* (Visual Visual C++ Studio 2010 Express)
I followed the instructions at <http://ucsb.pbworks.com/w/page/1936549/Using-GDAL-with-Python> and added PYTHONPATH and the GDAL\_DATA to my systems environment variables. F... | To successfully load GDAL from python in Windows 7, I follow these steps, which should be quite generic:
1. Install python of your choosing, I used v2.7.2 x64 downloaded from the official website
2. Run python from command line to determine the compiler version used to build python (mine shows this message: `Python 2.... |
Unable to install Python and GDAL (DLL load failed) | 6,009,506 | 14 | 2011-05-15T15:58:08Z | 10,010,835 | 8 | 2012-04-04T12:12:10Z | [
"python",
"gdal"
] | I am trying to install GDAL and Python on my Windows 7 workstation.
* Python-version: 2.6.6
* Gdal 1.8
* (Visual Visual C++ Studio 2010 Express)
I followed the instructions at <http://ucsb.pbworks.com/w/page/1936549/Using-GDAL-with-Python> and added PYTHONPATH and the GDAL\_DATA to my systems environment variables. F... | The step by step procedure is great. But I had the same issue.
This was caused because my `PATH` variable has other paths where a same named `dll` was used. If you put the `c:\program files\gdal` before the other paths in `PATH`, it works fine! |
How to test if every item in a list of type 'int'? | 6,009,589 | 7 | 2011-05-15T16:11:46Z | 6,009,630 | 27 | 2011-05-15T16:17:33Z | [
"python",
"list",
"int"
] | Say I have a list of numbers. How would I do to check that every item in the list is an int?
I have searched around, but haven't been able to find anything on this.
```
for i in myList:
result=isinstance(i, int)
if result == False:
break
```
would work, but looks very ugly and unpythonic in my opinion.
Is... | ```
>>> my_list = [1, 2, 3.25]
>>> all(isinstance(item, int) for item in my_list)
False
>>> other_list = range(3)
>>> all(isinstance(item, int) for item in other_list)
True
>>>
``` |
How is this called and how can be done ( `function_name.decorator` )? | 6,010,102 | 3 | 2011-05-15T17:43:35Z | 6,010,148 | 7 | 2011-05-15T17:52:00Z | [
"python",
"python-3.x",
"decorator"
] | Really sorry for the extremely stupid title, but if I know what it is, I wouldn't write here (:
```
def some_decorator( func ):
# ..
class A:
@some_decorator
def func():
pass
@func.some_decorator # this one here - func.some_decorator ?
def func():
pass
```
`some_decorator` deco... | Remember that the function definition with decorator is equivalent to this:
```
def func():
pass
func = some_decorator(func)
```
So in the following lines, `func` doesn't refer to the function you defined but to what the decorator turned it into. Also note that decorators can return *any* object, not just functio... |
.doc to pdf using python | 6,011,115 | 11 | 2011-05-15T20:42:43Z | 6,018,039 | 24 | 2011-05-16T13:19:36Z | [
"python",
"pdf",
"automation",
"ms-word",
"win32com"
] | I'am tasked with converting tons of .doc files to .pdf. And the only way my supervisor wants me to do this is through MSWord 2010. I know I should be able to automate this with python COM automation. Only problem is I dont know how and where to start. I tried searching for some tutorials but was not able to find any (M... | A simple example using [comtypes](http://pypi.python.org/pypi/comtypes), converting a single file, input and output filenames given as commandline arguments:
```
import sys
import os
import comtypes.client
wdFormatPDF = 17
in_file = os.path.abspath(sys.argv[1])
out_file = os.path.abspath(sys.argv[2])
word = comtype... |
Run a program from python, and have it continue to run after the script is killed | 6,011,235 | 21 | 2011-05-15T21:03:31Z | 6,011,298 | 19 | 2011-05-15T21:14:44Z | [
"python",
"subprocess",
"nohup"
] | I've tried running things like this:
```
subprocess.Popen(['nohup', 'my_command'],
stdout=open('/dev/null', 'w'),
stderr=open('logfile.log', 'a'))
```
This works if the parent script exits gracefully, but if I kill the script (Ctrl-C), all my child processes are killed too. Is there ... | The usual way to do this on Unix systems is to fork and exit if you're the parent. Have a look at `os.fork()` . You could have a look [here](http://onlamp.com/python/pythoncook2/solution.csp?day=1) for more information.
Here's a function that does the job:
```
def spawnDaemon(func):
# do the UNIX double-fork magi... |
Run a program from python, and have it continue to run after the script is killed | 6,011,235 | 21 | 2011-05-15T21:03:31Z | 16,928,558 | 20 | 2013-06-04T22:26:57Z | [
"python",
"subprocess",
"nohup"
] | I've tried running things like this:
```
subprocess.Popen(['nohup', 'my_command'],
stdout=open('/dev/null', 'w'),
stderr=open('logfile.log', 'a'))
```
This works if the parent script exits gracefully, but if I kill the script (Ctrl-C), all my child processes are killed too. Is there ... | The child process receives the same SIGINT as your parent process because it's in the same process group. You can put the child in its own process group by calling os.setpgrp() in the child process. Popen's preexec\_fn argument is useful here:
```
subprocess.Popen(['nohup', 'my_command'],
stdout=open(... |
Working with multiple code files and folders in Python | 6,011,322 | 10 | 2011-05-15T21:18:56Z | 6,011,502 | 12 | 2011-05-15T21:49:07Z | [
"python",
"import"
] | I am new to Python and I haven't figured out a simple way of separating code in multiple code files and folders.
What I do today is: for each folder I create an `__init__.py` file. Sometimes it's empty. I don't know why I do it, but it seems necessary. That's the first difference from working with C#.
The second diff... | You should read up on modules: <http://docs.python.org/tutorial/modules.html>
Basically, I think you aren't organizing your code right. With python, directories and files have a meaning; it's not just what you write into the files. With every new directory (with `__init__.py`) and every new file you create a new "name... |
Python: How can I use variable from main file in module? | 6,011,371 | 7 | 2011-05-15T21:27:36Z | 6,011,389 | 9 | 2011-05-15T21:30:25Z | [
"python",
"global-variables"
] | I have 2 files main.py and irc.py.
main.py
```
import irc
var = 1
func()
```
irc.py
```
def func():
print var
```
When I try to run main.py I'm getting this error
> NameError: global name 'var' is not defined
How to make it work?
@Edit
I thought there is a better solution but unfortunately the only one i... | Don't. Pass it in. Try and keep your code as decoupled as possible: one module should not rely on the inner workings of the other. Instead, try and expose as little as possible. In this way, you'll protect yourself from having to change the world every time you want to make things behave a little different.
**main.py*... |
Python select() behavior is strange | 6,011,481 | 6 | 2011-05-15T21:45:45Z | 6,011,688 | 9 | 2011-05-15T22:28:38Z | [
"python",
"linux",
"unix",
"io"
] | I'm having some trouble understanding the behavior of select.select. Please consider the following Python program:
```
def str_to_hex(s):
def dig(n):
if n > 9:
return chr(65-10+n)
else:
return chr(48+n)
r = ''
while len(s) > 0:
c = s[0]
s = s[1:]
... | The `read` method of `sys.stdin` works at a higher level of abstraction than `select`. When you do `ans[0].read(1)`, python actually reads a larger number of bytes from the operating system and buffers them internally. `select` is not aware of this extra buffering; It only sees that everything has been read, and so wil... |
[float(i) for i in lst] | 6,011,759 | 2 | 2011-05-15T22:48:03Z | 6,011,776 | 7 | 2011-05-15T22:52:08Z | [
"python",
"python-3.x"
] | prorgamming newbie--I was looking for answers to an exercise I was doing and got my answers from [here](http://stackoverflow.com/q/1614236/731819). My question is this--from that thread, the one chosen as best answer, was this code
```
[float(i) for i in lst]
```
The code did what it was supposed to do, but when I tr... | You have to assign `[float(i) for i in xs]` to something:
```
>>> new_list = [float(i) for i in xs]
>>> new_list
[12.0, 10.0, 32.0, 3.0, 66.0, 17.0, 42.0, 99.0, 20.0]
>>> new_list[0]
12.0
>>> new_list[5]
17.0
``` |
Validate dicts in Python | 6,011,881 | 14 | 2011-05-15T23:10:38Z | 6,012,023 | 25 | 2011-05-15T23:43:38Z | [
"python"
] | i looking for tool, or examples to/how to validate dictionaries in python.
For example, i have dict:
```
test = {'foo' : 'bar', 'nested' : {'foo1' : 'bar1', 'foo2' : 'bar2'} }
```
And now i must validate it. Lets say, value for key `foo` must be boolean **False** or non-empty string. Next, if key `foo1` have value ... | Voluptous is a nice tool that does this
<http://pypi.python.org/pypi/voluptuous> |
Python -- Limits On Number of Imports? | 6,012,022 | 8 | 2011-05-15T23:43:11Z | 6,012,053 | 9 | 2011-05-15T23:50:30Z | [
"python"
] | I have 1000s of custom (compiled to '.so') modules that I'd like to use in `python` at the same time. Each such module is of size (`100 [KB]`) on average.
My question is, is there any limit on the number of imports in `python`? what are the consequences of many `imports`? (for example, will this require a lot of memor... | There's **no Python limit on number of imports** in a module. If there's a limit in any particular implementation, it's probably because of resource limits outside the Python interpreter. |
Python -- Limits On Number of Imports? | 6,012,022 | 8 | 2011-05-15T23:43:11Z | 6,012,129 | 7 | 2011-05-16T00:06:50Z | [
"python"
] | I have 1000s of custom (compiled to '.so') modules that I'd like to use in `python` at the same time. Each such module is of size (`100 [KB]`) on average.
My question is, is there any limit on the number of imports in `python`? what are the consequences of many `imports`? (for example, will this require a lot of memor... | The amount of memory consumed by a single imported module is going to be at *least* as big as the size of the module on disk. The overhead is determined by both the OS itself (for loading a dynamic module) and Python's overhead in importing a module.
So if your module are on average 100kB in size, then importing 10000... |
Why is Python easy_install not working on my Mac? | 6,012,246 | 55 | 2011-05-16T00:32:22Z | 6,012,347 | 25 | 2011-05-16T01:00:16Z | [
"python",
"osx",
"easy-install"
] | I have a Mac running Python 2.6. When I try to use `easy_install` I get this message:
```
/usr/bin/easy_install-2.6:7: UserWarning: Module pkg_resources was already imported from /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/pkg_resources.pyc, but /Library/Python/2.6/site-packages is being... | I suspect the easiest way you can get `easy_install` working again is to install [`distribute`](http://pypi.python.org/pypi/distribute), which is an improved version of [`distutils`](http://docs.python.org/distutils/index.html) that bundles it's own version of `easy_install`. Installation is simple:
```
curl -O http:/... |
Why is Python easy_install not working on my Mac? | 6,012,246 | 55 | 2011-05-16T00:32:22Z | 6,803,614 | 9 | 2011-07-23T22:07:08Z | [
"python",
"osx",
"easy-install"
] | I have a Mac running Python 2.6. When I try to use `easy_install` I get this message:
```
/usr/bin/easy_install-2.6:7: UserWarning: Module pkg_resources was already imported from /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/pkg_resources.pyc, but /Library/Python/2.6/site-packages is being... | I had the same problem just after installing the new Operating System (Lion OSX).
After install python and execute it
```
sudo easy_install ipython
ipython
```
I got the following error:
```
Traceback (most recent call last):
File "/usr/local/bin/ipython", line 8, in <module>
load_entry_point('ipython==0.10.2'... |
Why is Python easy_install not working on my Mac? | 6,012,246 | 55 | 2011-05-16T00:32:22Z | 12,574,436 | 143 | 2012-09-24T23:42:07Z | [
"python",
"osx",
"easy-install"
] | I have a Mac running Python 2.6. When I try to use `easy_install` I get this message:
```
/usr/bin/easy_install-2.6:7: UserWarning: Module pkg_resources was already imported from /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/pkg_resources.pyc, but /Library/Python/2.6/site-packages is being... | 1. Check your /usr/bin and /usr/local/bin for easy\_install installations and remove any old script:
```
sudo rm -f /usr/bin/easy_install*
sudo rm -f /usr/local/bin/easy_install*
```
2. Download and run distribute:
```
curl -O https://svn.apache.org/repos/asf/oodt/tools/oodtsite.publisher/trunk/dist... |
Tuple Unpacking Similar to Python, but in Common Lisp | 6,012,688 | 12 | 2011-05-16T02:29:29Z | 6,012,830 | 8 | 2011-05-16T03:07:21Z | [
"python",
"list",
"lisp",
"common-lisp",
"iterable-unpacking"
] | Is there a way to assign the values of a list to a list of symbols in Common Lisp similar to the way that you can assign the values of tuple to variables in Python?
```
x, y, z = (1, 2, 3)
```
Something like
```
(setq '(n p) '(1 2))
```
Where `n` and `p` are now equal to `1` and `2`, respectively. The above was jus... | Sounds like [destructuring-bind](http://www.gigamonkeys.com/book/beyond-lists-other-uses-for-cons-cells.html) (it's way at the bottom) may do what you want.
Also, the [HyperSpec](http://www.ai.mit.edu/projects/iiip/doc/CommonLISP/HyperSpec/Body/mac_destructuring-bind.html) description, but I think the other link demon... |
Tuple Unpacking Similar to Python, but in Common Lisp | 6,012,688 | 12 | 2011-05-16T02:29:29Z | 6,013,242 | 12 | 2011-05-16T04:44:47Z | [
"python",
"list",
"lisp",
"common-lisp",
"iterable-unpacking"
] | Is there a way to assign the values of a list to a list of symbols in Common Lisp similar to the way that you can assign the values of tuple to variables in Python?
```
x, y, z = (1, 2, 3)
```
Something like
```
(setq '(n p) '(1 2))
```
Where `n` and `p` are now equal to `1` and `2`, respectively. The above was jus... | Use [DESTRUCTURING-BIND](http://www.lispworks.com/documentation/HyperSpec/Body/m_destru.htm), which can do a whole heck of a lot more than tuple unpacking. Like assignment by keywords, and optional parameters, etc. Really, anything you can do with a function's parameter list.
But if you don't actually have a list to d... |
How to Emulate Assignment Operator Overloading in Python? | 6,012,763 | 2 | 2011-05-16T02:51:29Z | 6,012,925 | 11 | 2011-05-16T03:28:50Z | [
"python",
"operator-overloading"
] | How can you emulate assignment operator overloading in Python? For example...
```
class Example(object):
name = String()
age = Integer()
def __init__(self,myname,myage):
self.name.value = myname
self.age.value = myage
```
Rather than doing self.name.value = name, how can you emulate over... | In this very special case, in attribute assignment, you can use a [`descriptor`](http://docs.python.org/reference/datamodel.html#implementing-descriptors). In fact, I suspect that in the example you are using, `Integer` and `String` are actually descriptors.
Aside from using premade descriptors, the easiest way to use... |
Python unbound method | 6,012,799 | 11 | 2011-05-16T03:00:17Z | 6,019,246 | 33 | 2011-05-16T14:57:35Z | [
"python",
"methods",
"tkinter"
] | I have two classes, the relevant code is shown below. The method `get_pos` is supposed to grab what the user inputs in the entry. When run `get_pos` in app, it returns with:
`TypeError: unbound method get_pos() must be called with app instance as first argument (got nothing instead)`
```
class app(object):
def __... | You reported this error:
`TypeError: unbound method get_pos() must be called with app instance as first argument (got nothing instead)`
What that means in laymans terms is, you're doing something like this:
```
class app(object):
def get_pos(self):
...
...
app.get_pos()
```
What you need to do instead i... |
Python unbound method | 6,012,799 | 11 | 2011-05-16T03:00:17Z | 14,592,418 | 12 | 2013-01-29T21:14:17Z | [
"python",
"methods",
"tkinter"
] | I have two classes, the relevant code is shown below. The method `get_pos` is supposed to grab what the user inputs in the entry. When run `get_pos` in app, it returns with:
`TypeError: unbound method get_pos() must be called with app instance as first argument (got nothing instead)`
```
class app(object):
def __... | I've run into this error when forgetting to add parentheses to the class name when constructing an instance of the class:
from my.package import MyClass
```
# wrong
instance = MyClass
instance.someMethod() # tries to call MyClass.someMethod()
# right
instance = MyClass()
instance.someMethod()
``` |
Pyramid project structure | 6,012,991 | 16 | 2011-05-16T03:46:34Z | 6,014,197 | 27 | 2011-05-16T07:18:18Z | [
"python",
"pyramid"
] | I am developing a rather big project in pyramid. I used django before. I really like the way it structures the project and encapsulate functionality into apps. I would like to achieve same structure with pyramid. I know pyramid is very flexible to get this, but I need some help to achieve same structure with loose coup... | Since Pyramid makes no assumptions about your package structure in the first place, any way you divide your app ends up being fairly similar in configuration. However, if you're breaking your app into some distinct packages, you can (optionally) take advantage of the `config.include()` directive to include each package... |
Python __init__ syntax | 6,013,844 | 3 | 2011-05-16T06:24:55Z | 6,013,865 | 7 | 2011-05-16T06:27:58Z | [
"python",
"class",
"constructor"
] | While learning Python I'm having some confusion over the syntax of the initialization of classes using inheritance. In various examples I've seen something like the following:
```
class Foo(Bar):
def __init__(self, arg, parent = None):
Bar.__init__(self, parent)
self.Baz = arg
etc.
```
Whi... | Generally passing `parent` is not something that's required, only when the parent class's constructor explicitly needs such an argument. This is used in some hierarchies, such as PyQt.
And a good idiom of parent class initialization is to use `super`:
```
class Child(Father):
def __init__(self):
super(Child, se... |
Is there a function for Python which like getimagesize in PHP? | 6,013,996 | 5 | 2011-05-16T06:46:25Z | 6,014,074 | 9 | 2011-05-16T06:59:08Z | [
"python",
"image",
"url",
"dimension"
] | I have search for a while, and there is a function call get\_image\_dimensions(), however, as to my understanding, it works for the images which are downloaded or say local. So, any functions or solution like getimagesize in PHP, that we can just get the dimension of an image via URL, instead of path to local? | Using the python image library (PIL)
```
from PIL import Image
im = Image.open("fileName.jpg")
im.size
```
If you have an url, open it via urlopen and pass the file object to Image.open
```
import urllib2 as urllib
fd = urllib.urlopen("http://a/b/c")
im = Image.open(fd)
im.size
``` |
Copying a stream in Python | 6,014,520 | 16 | 2011-05-16T07:54:56Z | 6,014,540 | 19 | 2011-05-16T07:56:29Z | [
"python",
"io"
] | How do I transfer the contents of a stream to another in Python?
The trivial solution would be
```
output.write(input.read())
```
but that fails if the input file is larger than the available memory (or even infinitely large); and it doesn't work well when a partial copy is useful as well. Basically I'm looking for ... | `shutil.copyfile` and `shutil.copyfileobj` for the rescue. See <http://docs.python.org/library/shutil.html#module-shutil> |
Getting a specific parent folder with Python | 6,015,721 | 2 | 2011-05-16T10:00:06Z | 6,015,847 | 7 | 2011-05-16T10:11:07Z | [
"python",
"path",
"directory",
"folders"
] | I already have this piece of functioning code, but after writing it I did feel the urge to scream "It's alive, it's alive!".
What I want to do is get the folder which has the folder "modules" as its parent folder, e.g. from /home/user/puppet/modules/impuls-test/templates/apache22/ I want /home/user/puppet/modules/impu... | ```
path = "/home/user/puppet/modules/impuls-test/templates"
components = path.split(os.sep)
print str.join(os.sep, components[:components.index("modules")+2])
```
prints
```
/home/user/puppet/modules/impuls-test
``` |
NaN in python and validity checking | 6,016,744 | 4 | 2011-05-16T11:33:47Z | 6,017,693 | 15 | 2011-05-16T12:52:31Z | [
"python",
"numpy",
null
] | I'm doing a program where I optimize some values. Due to the equations, from time to time my values are NaN
My problem, some of the entries are NaN.
I would like to know if there is a test to check their logical validity so I can skip those values and retry.
So far I have tried checking for
```
a==np.nan, a==nan, b... | Using numpy,
```
import numpy as np
np.isnan(np.nan) # returns True
``` |
How to get formatted date time in python | 6,017,570 | 2 | 2011-05-16T12:44:42Z | 6,017,620 | 15 | 2011-05-16T12:48:41Z | [
"python",
"linux"
] | I want my Linux Filename like this
```
May-01-0340AM-2011.tar
```
How can i get the date variable formatted like above in Python
IN bash i write
```
date1=$(date +"%b-%d-%I%M%p-%G")
``` | You can use the same formatting string in `strftime` on a [datetime object](http://docs.python.org/library/datetime.html#datetime-datetime):
```
>>> import datetime
>>> datetime.datetime.now().strftime('%b-%d-%I%M%p-%G')
'May-16-0245PM-2011'
```
Incidentally, I'd just like to put a word in for the joy of [ISO-8601 da... |
Python: Pick other value | 6,018,173 | 4 | 2011-05-16T13:30:20Z | 6,018,242 | 10 | 2011-05-16T13:35:43Z | [
"python",
"list"
] | Please excuse (or improve the title) but I have a silly little problem that's making me very unsure.
I have a list that can contain one to two values, never more, never less and only these two options:
```
options = ['option one', 'option two']
```
As I say, sometimes there may only be one of those values in the lis... | ```
options.remove(current_option)
options.append(False)
return options[0]
```
**Edit**: If you don't want to modify `options`, you can also use the somewhat less readable
```
return (options + [False])[current_option == options[0]]
``` |
How to insert current_timestamp into Postgres via python | 6,018,214 | 18 | 2011-05-16T13:34:02Z | 6,019,262 | 34 | 2011-05-16T14:58:43Z | [
"python",
"postgresql",
"datetime"
] | I need to insert rows into PG one of the fields is date and time with time stamp, this is the time of incident, so I can not use --> current\_timestamp function of Postgres at the time of insertion, so how can I then insert the time and date which I collected before into pg row in the same format as it would have been ... | A timestamp does not have "a format".
The recommended way to deal with timestamps is to use a PreparedStatement where you just pass a placeholder in the SQL and pass a "real" object through the API of your programming language. As I don't know Python, I don't know if it supports PreparedStatements and how the syntax f... |
Capturing group with findall? | 6,018,340 | 25 | 2011-05-16T13:43:40Z | 6,018,450 | 23 | 2011-05-16T13:51:50Z | [
"python",
"regex"
] | How can I access captured groups if I do `findall(r'regex(with)capturing.goes.here')` ?
I know I can do it through `finditer`, but I don't want to iterate. | `findall` just returns the captured groups:
```
>>> re.findall('abc(de)fg(123)', 'abcdefg123 and again abcdefg123')
[('de', '123'), ('de', '123')]
```
Relevant doc excerpt:
> Return all non-overlapping matches of
> pattern in string, as a list of
> strings. The string is scanned
> left-to-right, and matches are
> re... |
Python - How to specify an optional argument for class based decorators? | 6,018,403 | 4 | 2011-05-16T13:49:25Z | 6,018,467 | 7 | 2011-05-16T13:53:01Z | [
"python",
"decorator",
"memoization"
] | How would I write a decorator like this. I want to be able to specify the value for max\_hits when I call the decorator (or optionally leave it out).
E.g., the desired use would be
```
@memoize(max_hits=7)
def a(val):
print val
```
or
```
@memoize
def a(val):
print val
```
(Using the first example gives an... | You have to make `memoize` a *function* that takes an optional argument `max_hits` and returns a decorator (i.e. another callable object that will take the function as the first argument); in this case, you can use the following two syntaxes:
```
@memoize()
def func(x):
[...]
@memoize(max_hits=7)
def func(x):
... |
Find max length of each column in a list of lists | 6,018,916 | 4 | 2011-05-16T14:31:06Z | 6,018,930 | 8 | 2011-05-16T14:32:43Z | [
"python"
] | I'm using Python 2.6 along with the xlwt and pyodbc modules to create excel reports from a view on an MS SQL Sever (2008). In order to programatically set the correct width of each field in excel, I would like to retrieve the maximum length of the values in each column.
For example
```
foo=[[1, 'This is a test',12039... | ```
[max(len(str(x)) for x in line) for line in zip(*foo)]
``` |
Memory profiler for numpy | 6,018,986 | 18 | 2011-05-16T14:37:24Z | 6,019,085 | 10 | 2011-05-16T14:45:26Z | [
"python",
"memory",
"numpy",
"memory-profiling"
] | I have a `numpy` script that -- according to `top` -- is using about 5GB of RAM:
```
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
16994 aix 25 0 5813m 5.2g 5.1g S 0.0 22.1 52:19.66 ipython
```
Is there a memory profiler that would enable me to get some idea about the objects that are takin... | Numpy (and its library bindings, more on that in a minute) use C malloc to allocate space, which is why memory used by big numpy allocations doesn't show up in the profiling of things like heapy and never gets cleaned up by the garbage collector.
The usual suspects for big leaks are actually scipy or numpy library bin... |
Python 'self' keyword | 6,019,627 | 42 | 2011-05-16T15:25:53Z | 6,019,656 | 93 | 2011-05-16T15:27:58Z | [
"python"
] | I am new to Python (usually work on C#), started using it over the last couple of days.
Within a class, do you need to prefix any call to that classes data members and methods? So if I am calling a method or obtaining a value from that class, from within that class, I need to use self.method(), or self.intvalue, for e... | There is no less verbose way. Always use `self.x` to access the instance attribute `x`. Note that unlike `this` in C++, `self` is not a keyword, though. You *could* give the first parameter of your method any name you want, but you are strongly advised to stick to the convention of calling it `self`. |
Python 'self' keyword | 6,019,627 | 42 | 2011-05-16T15:25:53Z | 6,019,984 | 48 | 2011-05-16T15:54:49Z | [
"python"
] | I am new to Python (usually work on C#), started using it over the last couple of days.
Within a class, do you need to prefix any call to that classes data members and methods? So if I am calling a method or obtaining a value from that class, from within that class, I need to use self.method(), or self.intvalue, for e... | I'll supplement Sven's (accurate) response with an answer to the natural follow-up question (i.e. *Why* is `self` explicit rather than implicit?).
Python works this way as it operates on the idea of lexical scoping: bare name references will always refer to a local variable within the current function definition, a lo... |
matplotlib figures disappearing between show() and savefig() | 6,019,776 | 8 | 2011-05-16T15:38:39Z | 6,020,293 | 7 | 2011-05-16T16:22:10Z | [
"python",
"matplotlib"
] | I've kept a set of references to figures in a dictionary so that I could save them later if desired. I am troubled that the saved figures are blank if invoke a `show()` command and look at them first. Since the `show()` command blocks and I am not using a spyder-like interpreter, I have to close the figures before I ge... | Generally speaking, in cases like this don't use the interactive matlab-ish state machine interface to matplotlib. It's meant for interactive use.
You're trying to make a figure "active", and creating a new figure instead. It doesn't matter which figure is active, if you just retain the returned figure and/or axis obj... |
Are Python inner functions compiled? | 6,020,532 | 26 | 2011-05-16T16:39:56Z | 6,020,630 | 7 | 2011-05-16T16:47:58Z | [
"python"
] | So AFAIK in CPython, function definitions are compiled into function objects when executed at parse time. But what about inner functions? Do they get compiled into function objects at parse time or do they get compiled (or interpreted) every single time the function is called? Do inner functions incur any performance p... | ```
>>> import dis
>>> def foo():
... def bar():
... print "stuff"
... return bar
...
>>> b = foo()
>>> dis.dis(foo)
2 0 LOAD_CONST 1 (<code object bar at 0x20bf738, file "<stdin>", line 2>)
3 MAKE_FUNCTION 0
6 STORE_FAST ... |
Are Python inner functions compiled? | 6,020,532 | 26 | 2011-05-16T16:39:56Z | 6,020,750 | 7 | 2011-05-16T16:59:47Z | [
"python"
] | So AFAIK in CPython, function definitions are compiled into function objects when executed at parse time. But what about inner functions? Do they get compiled into function objects at parse time or do they get compiled (or interpreted) every single time the function is called? Do inner functions incur any performance p... | Easy test: the default arguments to a function are called once, at define time.
```
>>> def foo():
... def bar(arg=count()):
... pass
... pass
...
>>> def count():
... print "defined"
...
>>> foo()
defined
>>> foo()
defined
```
So yes: this is a minor (very very! minor) performance hit. |
Are Python inner functions compiled? | 6,020,532 | 26 | 2011-05-16T16:39:56Z | 6,020,909 | 29 | 2011-05-16T17:15:04Z | [
"python"
] | So AFAIK in CPython, function definitions are compiled into function objects when executed at parse time. But what about inner functions? Do they get compiled into function objects at parse time or do they get compiled (or interpreted) every single time the function is called? Do inner functions incur any performance p... | To give a general explaination - assuming you have the following code in a module:
```
def outer(x=1):
def inner(y=2):
return x+y
```
When the file is parsed by python via `compile()`, the above text is turned into bytecode for how to execute the *module*. In the module bytecode, there are two "code objec... |
how to get POST data in django 1.3 | 6,020,928 | 9 | 2011-05-16T17:17:40Z | 6,020,978 | 9 | 2011-05-16T17:21:46Z | [
"python",
"django",
"http-post",
"django-1.3"
] | Hey, I am following this tutorial to learn to make a wiki page with Django. However, it is made in django 0.96 and I use Django 1.3 so there are some things that are different. Some I already fixed myself, however this one I can't seem to make it work.
I made a form that submits data to a view.
This is the form:
```
... | You've got to include `{% csrf_token %}` in your form's template between your `<form>` tags.
```
<form method="post" action"/wikicamp/{{page_name}}/save/">
{% csrf_token %}
<textarea name="content" rows="20" cols="60">{{content}}</textarea><br>
<input type="submit" value="Save Page"/>
</form>
```
If the `... |
how to get POST data in django 1.3 | 6,020,928 | 9 | 2011-05-16T17:17:40Z | 6,021,123 | 8 | 2011-05-16T17:35:10Z | [
"python",
"django",
"http-post",
"django-1.3"
] | Hey, I am following this tutorial to learn to make a wiki page with Django. However, it is made in django 0.96 and I use Django 1.3 so there are some things that are different. Some I already fixed myself, however this one I can't seem to make it work.
I made a form that submits data to a view.
This is the form:
```
... | You will need the {% csrf\_token %} template tag in between your tags as well as including
```
django.middleware.csrf.CsrfViewMiddleware
django.middleware.csrf.CsrfResponseMiddleware
```
in your MIDDLEWARE\_CLASSES in the applications settings.py
Adding some example post data handling:
This is an example of o... |
API design Python | 6,022,074 | 11 | 2011-05-16T19:04:32Z | 6,022,243 | 15 | 2011-05-16T19:17:57Z | [
"python",
"api",
"design"
] | I have found a very nice talk by Joshua Bloch:
<http://www.youtube.com/watch?v=aAb7hSCtvGw>
<http://lcsd05.cs.tamu.edu/slides/keynote.pdf>
While it is fairly general, some comments are only valid to statically typed languages. I am looking for something equivalent for Python.
([This](http://ep2011.europython.eu/conf... | Perhaps one of these (or both).
* [PyCon 2011: API Design: Lessons Learned by Hettinger](http://pyvideo.org/video/366/pycon-2011--api-design--lessons-learned)
* [PyCon 2011: API Design anti-patterns by Alex Martelli](http://pyvideo.org/video/445/pycon-2011--api-design-anti-patterns) |
how to edit model data using django forms | 6,023,421 | 12 | 2011-05-16T21:05:03Z | 6,023,563 | 38 | 2011-05-16T21:17:51Z | [
"python",
"django",
"django-forms"
] | hello
i'm new to django so i'm sorry for my newbie question
i have a model and i need to let user edit data inside it using django forms or any other way.

look at the image above , i want to show this form ready populated with the data and let u... | Assuming you are using a `ModelForm`, use the `instance` keyword argument, and pass the model you are updating.
So, if you have `MyModel` and `MyModelForm` (the latter of which must extend `django.forms.ModelForm`), then your code snippet might look like:
```
my_record = MyModel.objects.get(id=XXX)
form = MyModelForm... |
Why doesn't zeromq work on localhost? | 6,024,003 | 39 | 2011-05-16T22:07:46Z | 6,024,019 | 23 | 2011-05-16T22:10:31Z | [
"python",
"localhost",
"zeromq"
] | This code works great:
```
import zmq, json, time
def main():
context = zmq.Context()
subscriber = context.socket(zmq.SUB)
subscriber.bind("ipc://test")
subscriber.setsockopt(zmq.SUBSCRIBE, '')
while True:
print subscriber.recv()
def main():
context = zmq.Context()
publisher = con... | The problem is at line:
```
subscriber.bind("tcp://localhost:5555")
```
try to change to:
```
subscriber.bind("tcp://127.0.0.1:5555")
``` |
Why doesn't zeromq work on localhost? | 6,024,003 | 39 | 2011-05-16T22:07:46Z | 8,958,414 | 101 | 2012-01-22T02:11:56Z | [
"python",
"localhost",
"zeromq"
] | This code works great:
```
import zmq, json, time
def main():
context = zmq.Context()
subscriber = context.socket(zmq.SUB)
subscriber.bind("ipc://test")
subscriber.setsockopt(zmq.SUBSCRIBE, '')
while True:
print subscriber.recv()
def main():
context = zmq.Context()
publisher = con... | As @fdb points out:
The problem is at line:
```
subscriber.bind("tcp://localhost:5555")
```
try to change to:
```
subscriber.bind("tcp://127.0.0.1:5555")
```
However this deserves more explanation to understand why.
The documentation for [zmq\_bind](http://api.zeromq.org/2-1%3azmq-bind) explains (bold emphasis mi... |
How to print file contents with filename before each line? | 6,024,116 | 5 | 2011-05-16T22:21:31Z | 6,024,322 | 8 | 2011-05-16T22:54:42Z | [
"python",
"perl",
"bash",
"scripting",
"sed"
] | I have several files, say, a,b,c, I would like to something like
```
> cat a b c
```
but with "a," in the beginning lines of a. "b," in the beginning of the lines of b and "c," in the beginning of the lines of c.
I can do this using python:
```
#!/bin/env python
files = 'a b c'
all_lines = []
for f in files.split... | ```
perl -pe 'print "$ARGV,"' a b c
```
will do it. |
Pipe text to Python script or prompt | 6,024,149 | 10 | 2011-05-16T22:25:55Z | 6,024,166 | 17 | 2011-05-16T22:28:50Z | [
"python",
"bash"
] | I'm trying to write a very simple email script in python. It's basically a poor man's mutt. At work, we send a lot of data from servers around, and it would be much easier to send it directly from the server.
The part that I'm stuck on is dealing with the message. I want users to to be able to do the following:
```
$... | You can use `sys.stdin.isatty` to check if the script is being run interactively. Example:
```
if sys.stdin.isatty():
message = raw_input('Enter your message ')
else:
message = sys.stdin.read()
``` |
Start background process/daemon from CGI script | 6,024,472 | 14 | 2011-05-16T23:15:25Z | 6,091,159 | 10 | 2011-05-22T22:13:43Z | [
"python",
"apache",
"cgi",
"fork"
] | I'm trying to launch a background process from a CGI scripts. Basically, when a form is submitted the CGI script will indicate to the user that his or her request is being processed, while the background script does the actual processing (because the processing tends to take a long time.) The problem I'm facing is that... | ## Don't fork - run batch separately
This double-forking approach is some kind of hack, which to me is indication it shouldn't be done :). For CGI anyway. Under the general principle that if something is too hard to accomplish, you are probably approaching it the wrong way.
Luckily you give the background info on wha... |
South ignores change in field default value in Python / Django | 6,024,724 | 12 | 2011-05-16T23:50:29Z | 6,024,816 | 11 | 2011-05-17T00:04:58Z | [
"python",
"django",
"django-south"
] | Why does South not recognize changes in default field values in Python models? For example, take this existing model that is migrated with south:
```
class MyFamily(models.Model):
family_size = models.IntegerField(verbose_name="What is your family size?", default=2)
```
Now, I'd like to change the default value f... | South won't update the default value for existing columns, because it matters for him only when adding a new column to a non empty table. The `django orm` will handle writing the new default value to new rows before hitting the database.
If you will work on the database from outside `django orm`, you have to update it... |
Readline functionality on windows with python 2.7 | 6,024,952 | 16 | 2011-05-17T00:27:24Z | 6,024,996 | 25 | 2011-05-17T00:34:15Z | [
"python",
"windows",
"readline",
"python-2.7"
] | I need to import the readline functionality in a program written in python. I am currently using version 2.7 and the 3rd party packages I have seen only work up to version 2.6. Does anyone know of a 3rd party readline package for Windows with Python 2.7? | I believe pyreadline was designed just for this.
`easy_install pyreadline`
or:
`pip install pyreadline`
<http://pypi.python.org/pypi/pyreadline>
Also, use the following for forward/reverse compatibility:
```
try:
import readline
except ImportError:
import pyreadline as readline
``` |
Issues trying to SSH into a fresh EC2 instance with Paramiko | 6,025,546 | 8 | 2011-05-17T02:17:12Z | 6,026,190 | 9 | 2011-05-17T04:17:47Z | [
"python",
"amazon-ec2",
"paramiko",
"boto"
] | I'm working on a script that spins up a fresh EC2 instance with boto and uses the Paramiko SSH client to execute remote commands on the instance. For whatever reason, the Paramiko client is unabled to connect, I get the error:
```
Traceback (most recent call last):
File "scripts/sconfigure.py", line 29, in <module>
... | I seem to have figured this out by trial and error. Even though the instance status is "running" according to boto, there is a delay for when it will actually allow an SSH connection. Adding a "time.sleep(30)" before the "ssh.connect(...)" seems to do the trick for me, though this may vary. |
Tools for static type checking in Python | 6,025,714 | 33 | 2011-05-17T02:48:17Z | 6,025,725 | 10 | 2011-05-17T02:50:27Z | [
"python",
"static-typing"
] | I'm working with a large existing Python codebase and would like to start adding in type annotations so I can get some level of static checking. I'm imagining something like [Erlang](http://www.erlang.org/doc/reference_manual/typespec.html), [Strongtalk](http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.51.4406), ... | You might want to check out some of the projects mentioned in this [related StackOverflow post on static analysis for Python](http://stackoverflow.com/questions/35470/are-there-any-static-analysis-tools-for-python).
In summary:
* [pylint](http://www.logilab.org/project/pylint)
* [PyFlakes](http://pypi.python.org/pypi... |
Tools for static type checking in Python | 6,025,714 | 33 | 2011-05-17T02:48:17Z | 25,714,986 | 9 | 2014-09-07T21:35:06Z | [
"python",
"static-typing"
] | I'm working with a large existing Python codebase and would like to start adding in type annotations so I can get some level of static checking. I'm imagining something like [Erlang](http://www.erlang.org/doc/reference_manual/typespec.html), [Strongtalk](http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.51.4406), ... | You may find [mypy](http://www.mypy-lang.org/) interesting. It has been [proposed for inclusion in Python 3.5 by Guido](https://mail.python.org/pipermail/python-ideas/2014-August/028618.html). |
What's the pythonic way to set class variables? | 6,025,758 | 3 | 2011-05-17T02:56:13Z | 6,025,807 | 9 | 2011-05-17T03:04:49Z | [
"python"
] | perhaps I'm asking the wrong question. I have code like this:
```
class ExpressionGrammar(Grammar):
def __init__(self, nonterminals, terminals, macros, rules, precedence, nonterminal_name = '_expr'):
self.nonterminals = nonterminals
self.terminals = terminals
self.rules = rules
self.macros = macros
... | You can avoid doing that with something like:
```
class C(object):
def __init__(self, x, y, z, etc):
self.__dict__.update(locals())
```
then all these arguments become members (including the self argument). So you may remove it with: `self.__dict__.pop('self')`
I don't know how pythonic this approach is,... |
Python MySql Insert not working | 6,027,271 | 34 | 2011-05-17T06:52:34Z | 6,027,346 | 79 | 2011-05-17T07:00:37Z | [
"python",
"mysql"
] | I am using python MySQL API to connect to Mysql database from python program. I am facing a problem from few days. I am unable to insert records into the database and dont know whats the reason. Here is the way i connect and insert records into the database.
```
db = MySQLdb.connect("localhost","root","padmaramulu","p... | Before closing the connection, you should add `db.commit()`. |
Flatten nested Python dictionaries, compressing keys | 6,027,558 | 51 | 2011-05-17T07:23:01Z | 6,027,615 | 72 | 2011-05-17T07:30:17Z | [
"python",
"dictionary"
] | Suppose you have a dictionary like:
```
{'a': 1,
'c': {'a': 2,
'b': {'x': 5,
'y' : 10}},
'd': [1, 2, 3]}
```
How would you go about flattening that into something like:
```
{'a': 1,
'c_a': 2,
'c_b_x': 5,
'c_b_y': 10,
'd': [1, 2, 3]}
``` | Basically the same way you would flatten a nested list, you just have to do the extra work for iterating the dict by key/value, creating new keys for your new dictionary and creating the dictionary at final step.
```
import collections
def flatten(d, parent_key='', sep='_'):
items = []
for k, v in d.items():
... |
Flatten nested Python dictionaries, compressing keys | 6,027,558 | 51 | 2011-05-17T07:23:01Z | 6,043,835 | 42 | 2011-05-18T11:19:28Z | [
"python",
"dictionary"
] | Suppose you have a dictionary like:
```
{'a': 1,
'c': {'a': 2,
'b': {'x': 5,
'y' : 10}},
'd': [1, 2, 3]}
```
How would you go about flattening that into something like:
```
{'a': 1,
'c_a': 2,
'c_b_x': 5,
'c_b_y': 10,
'd': [1, 2, 3]}
``` | There are two big considerations that the original poster needs to consider:
1. Are there keyspace clobbering issues? For example, `{'a_b':{'c':1}, 'a':{'b_c':2}}` would result in `{'a_b_c':???}`. The below solution evades the problem by returning an iterable of pairs.
2. If performance is an issue, does the key-reduc... |
Flatten nested Python dictionaries, compressing keys | 6,027,558 | 51 | 2011-05-17T07:23:01Z | 19,647,596 | 11 | 2013-10-29T00:32:25Z | [
"python",
"dictionary"
] | Suppose you have a dictionary like:
```
{'a': 1,
'c': {'a': 2,
'b': {'x': 5,
'y' : 10}},
'd': [1, 2, 3]}
```
How would you go about flattening that into something like:
```
{'a': 1,
'c_a': 2,
'c_b_x': 5,
'c_b_y': 10,
'd': [1, 2, 3]}
``` | Here is a kind of a "functional", "one-liner" implementation. It is recursive, and based on a conditional expression and a dict comprehension.
```
def flatten_dict(dd, separator='_', prefix=''):
return { prefix + separator + k if prefix else k : v
for kk, vv in dd.items()
for k, v in flat... |
Python: How to read a (static) file from inside a package? | 6,028,000 | 15 | 2011-05-17T08:09:45Z | 20,885,799 | 43 | 2014-01-02T15:07:18Z | [
"python",
"file",
"package"
] | Could you tell me how can I read a file that is inside my python package?
I have a following situation:
a package that I load has a number of templates (text files used as strings) that I want to load from within the program. But how do I specify the path to such file?
Imagine I want to read a file from: package\templ... | Assuming your template is located inside your module's package at this path:
```
<your_package>/templates/temp_file
```
the correct way to read your template is to use [`pkg_resources`](http://pythonhosted.org/setuptools/pkg_resources.html#basic-resource-access) package from *setuptools* distribution:
```
import pkg... |
setting color range in matplotlib patchcollection | 6,028,675 | 5 | 2011-05-17T09:14:16Z | 6,032,083 | 15 | 2011-05-17T14:10:41Z | [
"python",
"matplotlib",
"patch"
] | I am plotting a [`PatchCollection`](http://matplotlib.org/api/collections_api.html#matplotlib.collections.PatchCollection) in matplotlib with coords and patch color values read in from a file.
The problem is that matplotlib seems to automatically scale the color range to the min/max of the data values. How can I manua... | Use `p.set_clim([5, 50])` to set the color scaling minimums and maximums in the case of your example. Anything in matplotlib that has a colormap has the `get_clim` and [`set_clim`](http://matplotlib.sourceforge.net/api/cm_api.html#matplotlib.cm.ScalarMappable.set_clim) methods.
As a full example:
```
import matplotli... |
https for localhost:8080 | 6,029,473 | 16 | 2011-05-17T10:26:28Z | 6,032,305 | 17 | 2011-05-17T14:25:14Z | [
"python",
"facebook",
"google-app-engine"
] | I am trying to develop a facebook app written in Python running on Google App Engine, so i need to make my <http://localhost:8080> to <https://localhost:8080> since facebook is asking for a Secure Canvas URL
how can i make https in localhost:8080 ? | From [the docs](http://code.google.com/appengine/docs/python/config/appconfig.html#Secure_URLs):
> The development web server does not
> support HTTPS connections. It ignores
> the secure parameter, so paths
> intended for use with HTTPS can be
> tested using regular HTTP connections
> to the development web server.
... |
https for localhost:8080 | 6,029,473 | 16 | 2011-05-17T10:26:28Z | 9,870,303 | 7 | 2012-03-26T10:13:44Z | [
"python",
"facebook",
"google-app-engine"
] | I am trying to develop a facebook app written in Python running on Google App Engine, so i need to make my <http://localhost:8080> to <https://localhost:8080> since facebook is asking for a Secure Canvas URL
how can i make https in localhost:8080 ? | I use [stunnel](http://www.stunnel.org/) to proxy my https request on localserver. I run my localserver on
127.0.0.1:8000 and have configured stunnel with
```
[https]
accept = 8001
connect = 8000
```
so it responds to https on 127.0.0.1:8001.
I have configured the FB app with the above 2 ips. Works nicely.
For windo... |
Most efficient way to remove non-numeric list entries | 6,030,082 | 5 | 2011-05-17T11:26:36Z | 6,030,118 | 11 | 2011-05-17T11:29:53Z | [
"python"
] | I'm looking to 'clean' a list by excluding any items which contain characters other than 0-9, and wondering if there's a more efficient way than e.g.
```
import re
invalid = re.compile('[^0-9]')
ls = ['1a', 'b3', '1']
cleaned = [i for i in ls if not invalid.search(i)]
print cleaned
>> ['1']
```
As I'm going to be... | Anything wrong with the string method `isdigit` ?
```
>>> ls = ['1a', 'b3', '1']
>>> cleaned = [ x for x in ls if x.isdigit() ]
>>> cleaned
['1']
>>>
``` |
play MIDI files in python? | 6,030,087 | 10 | 2011-05-17T11:26:51Z | 6,030,218 | 12 | 2011-05-17T11:39:15Z | [
"python",
"midi"
] | I'm looking for a method to play midi files in python.
It seems python does not support MIDI in its standard library.
After I searched, I found some python midi librarys such as [pythonmidi](http://www.mxm.dk/products/public/pythonmidi/).
However, most of them can only create and read MIDI file without playing function... | The pygame module can be used to play midi files.
<http://www.pygame.org/docs/ref/music.html>
See the example here:
<http://www.daniweb.com/software-development/python/code/216979>
a whole bunch of options available at:
<http://wiki.python.org/moin/PythonInMusic>
and also here which you can modify to suit your pu... |
How to display a 3D plot of a 3D array isosurface in matplotlib mplot3D or similar? | 6,030,098 | 32 | 2011-05-17T11:27:37Z | 6,031,871 | 31 | 2011-05-17T13:55:46Z | [
"python",
"matplotlib",
"scipy",
"visualization",
"volume"
] | I have a 3-dimensional numpy array. I'd like to display (in matplotlib) a nice 3D plot of an isosurface of this array (or more strictly, display an isosurface of the 3D scalar field defined by interpolating between the sample points).
matplotlib's mplot3D part provides nice 3D plot support, but (so far as I can see) i... | Just to elaborate on my comment above, matplotlib's 3D plotting really isn't intended for something as complex as isosurfaces. It's meant to produce nice, publication-quality vector output for really simple 3D plots. It can't handle complex 3D polygons, so even if implemented marching cubes yourself to create the isosu... |
How to display a 3D plot of a 3D array isosurface in matplotlib mplot3D or similar? | 6,030,098 | 32 | 2011-05-17T11:27:37Z | 26,143,329 | 7 | 2014-10-01T14:06:31Z | [
"python",
"matplotlib",
"scipy",
"visualization",
"volume"
] | I have a 3-dimensional numpy array. I'd like to display (in matplotlib) a nice 3D plot of an isosurface of this array (or more strictly, display an isosurface of the 3D scalar field defined by interpolating between the sample points).
matplotlib's mplot3D part provides nice 3D plot support, but (so far as I can see) i... | If you want to keep your plots in matplotlib (much easier to produce publication-quality images than mayavi in my opinion), then you can use the [marching\_cubes function implemented in skimage](http://scikit-image.org/docs/dev/auto_examples/plot_marching_cubes.html) and then plot the results in matplotlib using
```
m... |
How to display a 3D plot of a 3D array isosurface in matplotlib mplot3D or similar? | 6,030,098 | 32 | 2011-05-17T11:27:37Z | 35,472,146 | 11 | 2016-02-18T03:14:43Z | [
"python",
"matplotlib",
"scipy",
"visualization",
"volume"
] | I have a 3-dimensional numpy array. I'd like to display (in matplotlib) a nice 3D plot of an isosurface of this array (or more strictly, display an isosurface of the 3D scalar field defined by interpolating between the sample points).
matplotlib's mplot3D part provides nice 3D plot support, but (so far as I can see) i... | Complementing the answer of @DanHickstein, you can also use `trisurf` to visualize the polygons obtained in the marching cubes phase.
```
import numpy as np
from numpy import sin, cos, pi
from skimage import measure
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def fun(x, y, z):
return ... |
How to run a code in an Amazone's EC2 instance? | 6,030,115 | 23 | 2011-05-17T11:29:48Z | 6,031,114 | 13 | 2011-05-17T13:00:12Z | [
"python",
"amazon-ec2"
] | I understand nearly nothing to the functioning of EC2. I created an Amazon Web Service (AWS) account. Then I launched an EC2 instance.
And now I would like to execute a Python code in this instance, and I don't know how to proceed. Is it necessary to load the code somewhere in the instance? Or in Amazon's S3 and to li... | You have a variety of options. You can browse through a large library of AMIs [here](http://aws.amazon.com/amis).
You can import a vm, instructions are [here](http://aws.amazon.com/ec2/vmimport/).
This is a general article about [AWS and python](http://aws.amazon.com/articles/3998).
And in this article, the author t... |
Why would a websocket created with pywebsocket be closed automatically? | 6,030,436 | 4 | 2011-05-17T11:58:58Z | 6,030,605 | 7 | 2011-05-17T12:14:34Z | [
"python",
"apache",
"websocket",
"mod-pywebsocket"
] | I want to test websocket with [pywebsocket](http://code.google.com/p/pywebsocket/), after some configurations following some instructions I found on the Internet, I finally got it run.
Then I want to try the echo example: <http://code.google.com/p/pywebsocket/source/browse/trunk/src/example/console.html>
the websoc... | I've found the solution by myself, modify `/etc/apache2/mods-enabled/reqtimeout.conf` to change the timeout time to 60 seconds. |
Plone 4.0.5 unified installer failing on Ubuntu 11.04 (natty) with zip/zlib error | 6,030,876 | 5 | 2011-05-17T12:39:19Z | 6,031,134 | 9 | 2011-05-17T13:01:36Z | [
"python",
"ubuntu",
"plone",
"zlib"
] | I am a Plone newbie and am trying to install Plone 4.0.5 on Ubuntu 11.04 Natty using the Unified Installer.
I unpack the installer and run the `./install.sh zeo` as root and I get the following error:
```
ZEO Cluster Install selected
Detailed installation log being written to /tmp/Plone-4.0.5-UnifiedInstaller/instal... | Its an issue with the Python disutils and the new multilib setup of natty. I ran into the same issue trying to get sqlite support in Python built from source.
You can hack around it in the detect modules section of the setup.py
<http://bugs.python.org/issue9762>
**Edit:**
To work around it, change `lib_dirs` in the... |
Merging a list of numpy arrays into one array (fast) | 6,030,906 | 17 | 2011-05-17T12:42:16Z | 6,031,096 | 14 | 2011-05-17T12:59:01Z | [
"python",
"arrays",
"numpy"
] | what would be the fastest way to merge a list of numpy arrays into one array if one knows the length of the list and the size of the arrays, which is the same for all?
I tried two approaches:
* `merged_array = array(list_of_arrays)` from [Pythonic way to create a numpy array from a list of numpy arrays](http://stacko... | You have 80 arrays 320x320? So you probably want to use `dstack`:
```
first3 = numpy.dstack(firstmatrices)
```
This returns one 80x320x320 array just like `numpy.array(firstmatrices)` does:
```
timeit numpy.dstack(firstmatrices)
10 loops, best of 3: 47.1 ms per loop
timeit numpy.array(firstmatrices)
1 loops, best ... |
Importing from builtin library when module with same name exists | 6,031,584 | 60 | 2011-05-17T13:34:31Z | 6,031,918 | 13 | 2011-05-17T13:58:56Z | [
"python",
"import"
] | Situation:
- There is a module in my project\_folder called calendar
- I would like to use the built-in Calendar class from the Python libraries
- When I use from calendar import Calendar it complains because it's trying to load from my module.
I've done a few searches and I can't seem to find a solution to my problem... | The only way to solve this problem is to hijack the internal import machinery yourself. This is not easy, and fraught with peril. You should avoid the grail shaped beacon at all costs because the peril is too perilous.
Rename your module instead.
If you want to learn how to hijack the internal import machinery, here ... |
Importing from builtin library when module with same name exists | 6,031,584 | 60 | 2011-05-17T13:34:31Z | 6,032,023 | 28 | 2011-05-17T14:06:32Z | [
"python",
"import"
] | Situation:
- There is a module in my project\_folder called calendar
- I would like to use the built-in Calendar class from the Python libraries
- When I use from calendar import Calendar it complains because it's trying to load from my module.
I've done a few searches and I can't seem to find a solution to my problem... | Actually, solving this is rather easy, but the implementation will always be a bit fragile, because it depends python import mechanism's internals and they are subject to change in future versions.
(the following code shows how to load both local and non-local modules and how they may coexist)
```
def import_non_loca... |
Importing from builtin library when module with same name exists | 6,031,584 | 60 | 2011-05-17T13:34:31Z | 8,280,677 | 74 | 2011-11-26T18:40:52Z | [
"python",
"import"
] | Situation:
- There is a module in my project\_folder called calendar
- I would like to use the built-in Calendar class from the Python libraries
- When I use from calendar import Calendar it complains because it's trying to load from my module.
I've done a few searches and I can't seem to find a solution to my problem... | Changing the name of your module is not necessary. Rather, you can use absolute\_import to change the importing behavior. For example with [stem/socket.py](https://gitweb.torproject.org/stem.git/blob/HEAD:/stem/socket.py) I import the socket module as follows:
```
from __future__ import absolute_import
import socket
`... |
Python logging: Why is __init__ called twice? | 6,032,053 | 10 | 2011-05-17T14:08:55Z | 6,032,273 | 9 | 2011-05-17T14:23:23Z | [
"python",
"logging",
"handler",
"config",
"init"
] | I am trying to use python logging with a config file and an own handler. This works to some degree. What really puzzle me is `__init__` being called twice and `__del__` being called once. When I remove the whole config file stuff and create the handler directly within the code `__init__` is called once and `__del__` is... | > 1. Why is init called twice?
If you follow the code of the `logging` module, you'll see that when you're loading the logging configuration file, it instantiates all the handlers (First instantiation).
In your code, you declare your handler like `test1.Test1TimedRotatingFileHandler`, so when it try to import your ha... |
python+numpy: why does numpy.log throw an attribute error if its operand is too big? | 6,032,781 | 16 | 2011-05-17T14:58:23Z | 6,038,571 | 21 | 2011-05-18T00:11:51Z | [
"python",
"numpy"
] | Running
```
np.log(math.factorial(21))
```
throws an `AttributeError: log`. Why is that? I could imagine a `ValueError`, or some sort of `UseYourHighSchoolMathsError`, but why the attribute error? | The result of `math.factorial(21)` is a Python long. numpy cannot convert it to one of its numeric types, so it leaves it as `dtype=object`. The way that unary ufuncs work for object arrays is that they simply try to call a method of the same name on the object. E.g.
```
np.log(np.array([x], dtype=object)) <-> np.arra... |
OSError 38 [Errno 38] with multiprocessing | 6,033,599 | 9 | 2011-05-17T15:52:16Z | 10,808,102 | 13 | 2012-05-29T23:27:21Z | [
"python",
"linux",
"multiprocessing"
] | I'm having the following error:
```
$ sudo chmod a+rwxt /dev/shm/
$ ls -ld /dev/shm/
drwxrwxrwt 2 root root 4096 Feb 4 06:56 /dev/shm/
$ python
Python 2.6.6 (r266:84292, Dec 26 2010, 22:31:48)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import multiprocessing
>>> ... | For anyone else coming here from Google, the answer is at [Django Celery Implementation - OSError errno 38 - Function not implemented](http://stackoverflow.com/questions/3314031/django-celery-implementation-oserror-errno-38-function-not-implemented#comment7543003_3699231):
> Got it working by adding `none /dev/shm tmp... |
one-to-many inline select with django admin | 6,034,047 | 27 | 2011-05-17T16:26:40Z | 6,034,062 | 20 | 2011-05-17T16:28:27Z | [
"python",
"django",
"django-models",
"django-admin"
] | I have a standard many-to-one relationship set up. There are a bunch of fields, but for our purposes here, the relevant model is:
```
class Class(models.Model):
name = models.CharField(max_length=128)
class Student(models.Model):
class = models.ForeignKey(Class)
name = models.CharField(max_length=128)
... | There is! You want `InlineModelAdmin` [(see InlineModelAdmin documentation here)](https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#inlinemodeladmin-objects)
Sample code in brief:
```
class StudentAdminInline(admin.TabularInline):
model = Student
class ClassAdmin(admin.ModelAdmin):
inlines = (StudentA... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.