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 |
|---|---|---|---|---|---|---|---|---|---|
How do I extend Python with C? | 6,961,204 | 4 | 2011-08-05T18:49:12Z | 6,961,313 | 9 | 2011-08-05T18:58:28Z | [
"python",
"c"
] | I have been doing a lot of reading on this subject and am having a lot of trouble wrapping my brain around how this needs to happen.
What I want to do is have a function:
```
int Add(int a, int b) { return a + b; }
```
And be able to call it from my Python scripts. How do I do this? | The easiest way by far is using the [ctypes](http://docs.python.org/library/ctypes.html) module, which will allow you to call functions in C libraries directly from Python. Once you have your C function compiled as a library, you can write something to the effect of:
```
# Load ctypes, and your library
from ctypes imp... |
How do I extend Python with C? | 6,961,204 | 4 | 2011-08-05T18:49:12Z | 6,961,347 | 7 | 2011-08-05T19:02:01Z | [
"python",
"c"
] | I have been doing a lot of reading on this subject and am having a lot of trouble wrapping my brain around how this needs to happen.
What I want to do is have a function:
```
int Add(int a, int b) { return a + b; }
```
And be able to call it from my Python scripts. How do I do this? | The proper way is to [write an extension module](http://docs.python.org/extending/extending.html). But if you're doing simple stuff (such as adding two integers) than can be done independently of Python, you can just write a regular shared library in C (which would be a DLL on Windows), and load it using the [ctypes mo... |
Locating the line number where an exception occurs in python code | 6,961,750 | 9 | 2011-08-05T19:40:58Z | 6,961,780 | 19 | 2011-08-05T19:43:52Z | [
"python",
"exception"
] | I have a code similar to this:
```
try:
if x:
statement1
statement2
statement3
elif y:
statement4
statement5
statement6
else:
raise
except:
statement7
```
Here, I am sure that the exception occurs in `If x:` block, but I would like to know in which statement of `... | what about this:
```
try:
if x:
print 'before statement 1'
statement1
print 'before statement 2' #ecc. ecc.
statement2
statement3
elif y:
statement4
statement5
statement6
else:
raise
except:
statement7
```
this is the straightforward workaround but I ... |
Locating the line number where an exception occurs in python code | 6,961,750 | 9 | 2011-08-05T19:40:58Z | 6,961,861 | 10 | 2011-08-05T19:52:56Z | [
"python",
"exception"
] | I have a code similar to this:
```
try:
if x:
statement1
statement2
statement3
elif y:
statement4
statement5
statement6
else:
raise
except:
statement7
```
Here, I am sure that the exception occurs in `If x:` block, but I would like to know in which statement of `... | I believe the several answers here recommending you manage your `try/except` blocks more tightly are the answer you're looking for. That's a style thing, not a library thing.
However, at times we find ourselves in a situation where it's not a style thing, and you really *do* need the line number to do some other progr... |
Python string search efficiency | 6,963,236 | 5 | 2011-08-05T22:23:30Z | 6,963,259 | 12 | 2011-08-05T22:26:52Z | [
"python",
"performance"
] | For very large strings (spanning multiple lines) is it faster to use Python's built-in string search or to split the large string (perhaps on `\n`) and iteratively search the smaller strings?
E.g., for very large strings:
```
for l in get_mother_of_all_strings().split('\n'):
if 'target' in l:
return True
return F... | ~~Probably~~ Certainly the second, I don't see any difference in doing a search in a big string or many in small strings. You may skip some chars thanks to the shorter lines, but the split operation has its costs too (searching for `\n`, creating n different strings, creating the list) and the loop is done in python.
... |
Speed comparison with Project Euler: C vs Python vs Erlang vs Haskell | 6,964,392 | 476 | 2011-08-06T02:34:14Z | 6,964,514 | 48 | 2011-08-06T03:12:55Z | [
"python",
"c",
"performance",
"haskell",
"erlang"
] | I have taken [Problem #12](http://projecteuler.net/index.php?section=problems&id=12) from [Project Euler](http://projecteuler.net/) as a programming exercise and to compare my (surely not optimal) implementations in C, Python, Erlang and Haskell. In order to get some higher execution times, I search for the first trian... | Take a look at [this blog](http://scrollingtext.org/). Over the past year or so he's done a few of the Project Euler problems in Haskell and Python, and he's generally found *Haskell* to be much faster. I think that between those languages it has more to do with your fluency and coding style.
When it comes to Python s... |
Speed comparison with Project Euler: C vs Python vs Erlang vs Haskell | 6,964,392 | 476 | 2011-08-06T02:34:14Z | 6,964,658 | 13 | 2011-08-06T03:59:44Z | [
"python",
"c",
"performance",
"haskell",
"erlang"
] | I have taken [Problem #12](http://projecteuler.net/index.php?section=problems&id=12) from [Project Euler](http://projecteuler.net/) as a programming exercise and to compare my (surely not optimal) implementations in C, Python, Erlang and Haskell. In order to get some higher execution times, I search for the first trian... | > Question 1: Do erlang, python and haskell loose speed due to using arbitrary length integers or don't they as long as the values are less than MAXINT?
This is unlikely. I cannot say much about Erlang and Haskell (well, maybe a bit about Haskell below) but I can point a lot of other bottlenecks in Python. Every time ... |
Speed comparison with Project Euler: C vs Python vs Erlang vs Haskell | 6,964,392 | 476 | 2011-08-06T02:34:14Z | 6,964,760 | 585 | 2011-08-06T04:25:46Z | [
"python",
"c",
"performance",
"haskell",
"erlang"
] | I have taken [Problem #12](http://projecteuler.net/index.php?section=problems&id=12) from [Project Euler](http://projecteuler.net/) as a programming exercise and to compare my (surely not optimal) implementations in C, Python, Erlang and Haskell. In order to get some higher execution times, I search for the first trian... | Using `GHC 7.0.3`, `gcc 4.4.6`, `Linux 2.6.29` on an x86\_64 Core2 Duo (2.5GHz) machine, compiling using `ghc -O2 -fllvm -fforce-recomp` for Haskell and `gcc -O3 -lm` for C.
* Your C routine runs in 8.4 seconds (faster than your run probably because of `-O3`)
* The Haskell solution runs in 36 seconds (due to the `-O2`... |
Speed comparison with Project Euler: C vs Python vs Erlang vs Haskell | 6,964,392 | 476 | 2011-08-06T02:34:14Z | 6,967,420 | 181 | 2011-08-06T14:20:16Z | [
"python",
"c",
"performance",
"haskell",
"erlang"
] | I have taken [Problem #12](http://projecteuler.net/index.php?section=problems&id=12) from [Project Euler](http://projecteuler.net/) as a programming exercise and to compare my (surely not optimal) implementations in C, Python, Erlang and Haskell. In order to get some higher execution times, I search for the first trian... | There are some problems with the Erlang implementation. As baseline for the following, my measured execution time for your unmodified Erlang program was 47.6 seconds, compared to 12.7 seconds for the C code.
The first thing you should do if you want to run computationally intensive Erlang code is to use native code. C... |
Speed comparison with Project Euler: C vs Python vs Erlang vs Haskell | 6,964,392 | 476 | 2011-08-06T02:34:14Z | 6,968,223 | 8 | 2011-08-06T16:44:13Z | [
"python",
"c",
"performance",
"haskell",
"erlang"
] | I have taken [Problem #12](http://projecteuler.net/index.php?section=problems&id=12) from [Project Euler](http://projecteuler.net/) as a programming exercise and to compare my (surely not optimal) implementations in C, Python, Erlang and Haskell. In order to get some higher execution times, I search for the first trian... | Looking at your Erlang implementation. The timing has included the start up of the entire virtual machine, running your program and halting the virtual machine. Am pretty sure that setting up and halting the erlang vm takes some time.
If the timing was done within the erlang virtual machine itself, results would be di... |
Speed comparison with Project Euler: C vs Python vs Erlang vs Haskell | 6,964,392 | 476 | 2011-08-06T02:34:14Z | 6,975,434 | 138 | 2011-08-07T20:04:18Z | [
"python",
"c",
"performance",
"haskell",
"erlang"
] | I have taken [Problem #12](http://projecteuler.net/index.php?section=problems&id=12) from [Project Euler](http://projecteuler.net/) as a programming exercise and to compare my (surely not optimal) implementations in C, Python, Erlang and Haskell. In order to get some higher execution times, I search for the first trian... | In regards to Python optimization, in addition to using PyPy (for pretty impressive speed-ups with zero change to your code), you could use PyPy's [translation toolchain](http://doc.pypy.org/en/release-1.9/translation.html) to compile an RPython-compliant version, or [Cython](http://docs.cython.org/src/quickstart/overv... |
Speed comparison with Project Euler: C vs Python vs Erlang vs Haskell | 6,964,392 | 476 | 2011-08-06T02:34:14Z | 7,037,750 | 57 | 2011-08-12T08:53:23Z | [
"python",
"c",
"performance",
"haskell",
"erlang"
] | I have taken [Problem #12](http://projecteuler.net/index.php?section=problems&id=12) from [Project Euler](http://projecteuler.net/) as a programming exercise and to compare my (surely not optimal) implementations in C, Python, Erlang and Haskell. In order to get some higher execution times, I search for the first trian... | > **Question 3:** Can you offer me some hints how to optimize these implementations
> without changing the way I determine the factors? Optimization in any
> way: nicer, faster, more "native" to the language.
The C implementation is suboptimal (as hinted at by Thomas M. DuBuisson), the version uses 64-bit integers (i.... |
Speed comparison with Project Euler: C vs Python vs Erlang vs Haskell | 6,964,392 | 476 | 2011-08-06T02:34:14Z | 14,973,230 | 11 | 2013-02-20T05:58:15Z | [
"python",
"c",
"performance",
"haskell",
"erlang"
] | I have taken [Problem #12](http://projecteuler.net/index.php?section=problems&id=12) from [Project Euler](http://projecteuler.net/) as a programming exercise and to compare my (surely not optimal) implementations in C, Python, Erlang and Haskell. In order to get some higher execution times, I search for the first trian... | With Haskell, you really don't need to think in recursions explicitly.
```
factorCount number = foldr factorCount' 0 [1..isquare] -
(fromEnum $ square == fromIntegral isquare)
where
square = sqrt $ fromIntegral number
isquare = floor square
factorCount' candidate
| nu... |
Speed comparison with Project Euler: C vs Python vs Erlang vs Haskell | 6,964,392 | 476 | 2011-08-06T02:34:14Z | 19,330,617 | 22 | 2013-10-12T04:43:43Z | [
"python",
"c",
"performance",
"haskell",
"erlang"
] | I have taken [Problem #12](http://projecteuler.net/index.php?section=problems&id=12) from [Project Euler](http://projecteuler.net/) as a programming exercise and to compare my (surely not optimal) implementations in C, Python, Erlang and Haskell. In order to get some higher execution times, I search for the first trian... | Your Haskell implementation could be greatly sped up by using some functions from Haskell packages.
In this case I used primes, which is just installed with 'cabal install primes' ;)
```
import Data.Numbers.Primes
import Data.List
triangleNumbers = scanl1 (+) [1..]
nDivisors n = product $ map ((+1) . length) (group (... |
Speed comparison with Project Euler: C vs Python vs Erlang vs Haskell | 6,964,392 | 476 | 2011-08-06T02:34:14Z | 19,378,806 | 7 | 2013-10-15T10:23:44Z | [
"python",
"c",
"performance",
"haskell",
"erlang"
] | I have taken [Problem #12](http://projecteuler.net/index.php?section=problems&id=12) from [Project Euler](http://projecteuler.net/) as a programming exercise and to compare my (surely not optimal) implementations in C, Python, Erlang and Haskell. In order to get some higher execution times, I search for the first trian... | > Question 1: Do Erlang, Python and Haskell lose speed due to using
> arbitrary length integers or don't they as long as the values are less
> than MAXINT?
Question one can be answered in the negative for Erlang. The last question is answered by using Erlang appropriately, as in:
<http://bredsaal.dk/learning-erlang-u... |
Speed comparison with Project Euler: C vs Python vs Erlang vs Haskell | 6,964,392 | 476 | 2011-08-06T02:34:14Z | 22,258,455 | 17 | 2014-03-07T18:58:04Z | [
"python",
"c",
"performance",
"haskell",
"erlang"
] | I have taken [Problem #12](http://projecteuler.net/index.php?section=problems&id=12) from [Project Euler](http://projecteuler.net/) as a programming exercise and to compare my (surely not optimal) implementations in C, Python, Erlang and Haskell. In order to get some higher execution times, I search for the first trian... | Just for fun. The following is a more 'native' Haskell implementation:
```
import Control.Applicative
import Control.Monad
import Data.Either
import Math.NumberTheory.Powers.Squares
isInt :: RealFrac c => c -> Bool
isInt = (==) <$> id <*> fromInteger . round
intSqrt :: (Integral a) => a -> Int
--intSqrt = fromIntegr... |
Installing SciPy on Mac OS Lion in Virtualenv | 6,964,881 | 5 | 2011-08-06T04:57:03Z | 7,368,064 | 8 | 2011-09-09T22:21:58Z | [
"python",
"osx",
"install",
"scipy"
] | I am trying to install scipy in my vertualenv on mac.
Python using in virtualenv:
```
(Django)miki725mac:Django miki725$ python
Python 2.7.2 (default, Aug 3 2011, 00:58:00)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more inform... | Personally, I found the easiest and reliable way to install scipy/numpy on Mac OS Lion was through the scipy superpack shell-script maintained at [stronginference weblog](http://stronginference.com/scipy-superpack/). As Steve Jobs says - it just works. Nothing more to do.
**Steps to install scipy in a virtual env:**
... |
How to add builtin functions | 6,965,090 | 8 | 2011-08-06T05:55:58Z | 6,965,111 | 13 | 2011-08-06T06:02:30Z | [
"python",
"user-defined-functions",
"keyword",
"built-in"
] | I am new to python programming. How can I add new built-in functions and keywords to python interpreter using C or C++? | In short, it is *technically* possible to add things to Python's builtinsâ, but it is almost never necessary (and generally considered a very bad idea).
In longer, it's obviously possible to modify Python's source and add new builtins, keywords, etc⦠But the process for doing that is a bit out of the scope of the q... |
Do Python generator objects become "unusable" after being traversed? | 6,965,704 | 7 | 2011-08-06T08:40:15Z | 6,965,730 | 9 | 2011-08-06T08:46:11Z | [
"python",
"flask"
] | I was working on a Flask project, getting some data from an API wrapper. The wrapper returned a generator object, so I `print` the values (`for obj in gen_object: print obj`) before passing it to Flask's `render_template()`.
When requesting the page while `print`ing the objects, the page is empty. But removing the `fo... | Yes, generators are ment to be consumed once. Each time we iterate a generator we ask it to give us another value, and if there's no more values to give the StopIteration exception is thrown which would stop the iteration. There's no way for the generator to know that we want to iterate it again without cloning it.
As... |
Reading a line from standard input in Python | 6,966,194 | 21 | 2011-08-06T10:32:39Z | 6,966,222 | 7 | 2011-08-06T10:37:13Z | [
"python",
"input",
"language-features"
] | What (if any) are the differences between the following two methods of reading a line from standard input: `raw_input()` and `sys.stdin.readline()` ? And in which cases one of these methods is preferable over the other ? | "However, from the point of view of many Python beginners and educators, the use of sys.stdin.readline() presents the following problems:
1. Compared to the name "raw\_input", the name "sys.stdin.readline()" is clunky and inelegant.
2. The names "sys" and "stdin" have no meaning for most beginners, who are mainly inte... |
Reading a line from standard input in Python | 6,966,194 | 21 | 2011-08-06T10:32:39Z | 6,966,228 | 25 | 2011-08-06T10:38:03Z | [
"python",
"input",
"language-features"
] | What (if any) are the differences between the following two methods of reading a line from standard input: `raw_input()` and `sys.stdin.readline()` ? And in which cases one of these methods is preferable over the other ? | [raw\_input()](http://docs.python.org/library/functions.html#raw_input) takes an optional `prompt` argument. It also strips the trailing newline character from the string it returns, and supports history features if the [readline](http://docs.python.org/library/readline.html#module-readline) module is loaded.
[readlin... |
python: convert base64 encoded png image to jpg | 6,966,205 | 7 | 2011-08-06T10:34:03Z | 6,966,225 | 14 | 2011-08-06T10:37:35Z | [
"python",
"image",
"png",
"jpeg"
] | I want to convert some base64 encoded png images to jpg using python. I know how to decode from base64 back to raw:
```
import base64
pngraw = base64.decodestring(png_b64text)
```
but how can I convert this now to jpg? Just writing pngraw to a file obviously only gives me a png file. **I know I can use PIL, but HOW ... | You can use [PIL](http://www.pythonware.com/products/pil/):
```
data = b'''iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAAAXNSR0IArs4c6QAAAIBJRE
FUOMvN08ENgCAMheG/TGniEo7iEiZuqTeiUkoLHORK++Ul8ODPZ92XS2ZiADITmwI+sWHwi
w2BGtYN1jCAZF1GMYDkGfJix3ZK8g57sJywteTFClBbjmAq+ESiGIBEX9nCqgl7sfyxIykt
... |
Using the __call__ method of a metaclass instead of __new__? | 6,966,772 | 11 | 2011-08-06T12:28:37Z | 6,966,909 | 8 | 2011-08-06T12:54:53Z | [
"python",
"metaclass"
] | When discussing metaclasses, [the docs](http://docs.python.org/reference/datamodel.html) state:
> You can of course also override other class methods (or add new
> methods); for example defining a custom `__call__()` method in the
> metaclass allows custom behavior when the class is called, e.g. not
> always creating ... | One difference is that by defining a metaclass `__call__` method you are demanding that it gets called before any of the class's or subclasses's `__new__` methods get an opportunity to be called.
```
class MetaFoo(type):
def __call__(cls,*args,**kwargs):
print('MetaFoo: {c},{a},{k}'.format(c=cls,a=args,k=k... |
Using the __call__ method of a metaclass instead of __new__? | 6,966,772 | 11 | 2011-08-06T12:28:37Z | 6,966,942 | 10 | 2011-08-06T13:01:48Z | [
"python",
"metaclass"
] | When discussing metaclasses, [the docs](http://docs.python.org/reference/datamodel.html) state:
> You can of course also override other class methods (or add new
> methods); for example defining a custom `__call__()` method in the
> metaclass allows custom behavior when the class is called, e.g. not
> always creating ... | The direct answer to your question is: when you want to do **more** than just customize instance creation, or when you want to separate what the class **does** from how it's created.
See my answer to [Creating a singleton in python](http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python) and the ass... |
How do I install a script to run anywhere from the command line? | 6,967,331 | 13 | 2011-08-06T14:05:13Z | 6,967,354 | 16 | 2011-08-06T14:09:42Z | [
"python",
"linux",
"command-line",
"install"
] | If I have a basic Python script, with it's hashbang and what-not in place, so that from the terminal on Linux I can run
```
/path/to/file/MyScript [args]
```
without executing through the interpreter or any file extensions, and it will execute the program.
So would I install this script so that I can type simply
``... | The best place to put things like this is `/usr/local/bin`.
This is the normal place to put custom installed binaries, and should be early in your `PATH`.
Simply copy the script there (probably using `sudo`), and it should work for any user. |
Iterating over a numpy array | 6,967,463 | 78 | 2011-08-06T14:27:03Z | 6,967,491 | 114 | 2011-08-06T14:31:51Z | [
"python",
"numpy"
] | Is there a less verbose alternative to this:
```
for x in xrange(array.shape[0]):
for y in xrange(array.shape[1]):
do_stuff(x, y)
```
I came up with this:
```
for x, y in itertools.product(map(xrange, array.shape)):
do_stuff(x, y)
```
Which saves one indentation, but is still pretty ugly.
I'm hopin... | I think you're looking for the [ndenumerate](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndenumerate.html#numpy.ndenumerate).
```
>>> a =numpy.array([[1,2],[3,4],[5,6]])
>>> for (x,y), value in numpy.ndenumerate(a):
... print x,y
...
0 0
0 1
1 0
1 1
2 0
2 1
```
Regarding the performance. It is a bit s... |
Iterating over a numpy array | 6,967,463 | 78 | 2011-08-06T14:27:03Z | 6,967,525 | 27 | 2011-08-06T14:38:58Z | [
"python",
"numpy"
] | Is there a less verbose alternative to this:
```
for x in xrange(array.shape[0]):
for y in xrange(array.shape[1]):
do_stuff(x, y)
```
I came up with this:
```
for x, y in itertools.product(map(xrange, array.shape)):
do_stuff(x, y)
```
Which saves one indentation, but is still pretty ugly.
I'm hopin... | If you only need the indices, you could try [`numpy.ndindex`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndindex.html#numpy.ndindex):
```
>>> a = numpy.arange(9).reshape(3, 3)
>>> [(x, y) for x, y in numpy.ndindex(a.shape)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
``` |
Unpacking, Extended unpacking, and nested extended unpacking | 6,967,632 | 31 | 2011-08-06T14:59:56Z | 6,968,451 | 38 | 2011-08-06T17:30:57Z | [
"python-3.x",
"python"
] | Consider these expressions... Please be patient... this is a LONG list...
(Note: some expression are repeated -- this is just to present a "context")
```
a, b = 1, 2 # simple sequence assignment
a, b = ['green', 'blue'] # list asqignment
a, b = 'XY' # stri... | My apologies for the length of this post, but I decided to opt for completeness.
Once you know a few basic rules, it's not hard to generalize them. I'll do my best to explain with a few examples. Since you're talking about evaluating these "by hand," I'll suggest some simple substitution rules. Basically, you might fi... |
Getting a python virtual env error after installing Lion | 6,968,914 | 24 | 2011-08-06T18:52:47Z | 7,812,638 | 40 | 2011-10-18T19:35:42Z | [
"python",
"virtualenv",
"osx-lion"
] | I haven't touched python and virtualenv in a while, and I believe I setup my MBP with virtualenv and pip, but have totally forgotten how this stuff works.
After installing lion, I'm getting this error when I open up a new terminal window:
```
Traceback (most recent call last):
File "<string>", line 1, in <module>
I... | I am a complete Python/Virtualenv novice. However, I had the exact same problem and found a solution that worked for me. I believe that this will vary greatly depending upon the way you originally setup Python & Virtualenv.
In my case, the Lion upgrade completely wiped out all contents of my `/Library/Python/2.*/site-... |
Getting a python virtual env error after installing Lion | 6,968,914 | 24 | 2011-08-06T18:52:47Z | 24,037,000 | 13 | 2014-06-04T12:05:50Z | [
"python",
"virtualenv",
"osx-lion"
] | I haven't touched python and virtualenv in a while, and I believe I setup my MBP with virtualenv and pip, but have totally forgotten how this stuff works.
After installing lion, I'm getting this error when I open up a new terminal window:
```
Traceback (most recent call last):
File "<string>", line 1, in <module>
I... | My solution on Ubuntu 14.04 where I had installed python3.4 was to add this to the ~/.bashrc file so that the tail of it looked liked this:
```
#Setup virtual envwrapper for python in case default doesn't work
VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3.4
export VIRTUALENVWRAPPER_PYTHON
# needed for virtualenvwrapper
e... |
Web scraping using Python | 6,969,567 | 2 | 2011-08-06T23:02:39Z | 6,969,603 | 9 | 2011-08-06T23:10:59Z | [
"python",
"urllib2",
"web-scraping"
] | I am trying to scrape the website <http://www.nseindia.com> using urllib2 and BeautifulSoup. Unfortunately, I keep getting 403 Forbidden when I try to access the page through Python. I thought it was a user agent issue, but changing that did not help. Then I thought it may have something to do with cookies, but apparen... | <http://www.nseindia.com/> seems to require an `Accept` header, for whatever reason. This should work:
```
import urllib2
r = urllib2.Request('http://www.nseindia.com/')
r.add_header('Accept', '*/*')
r.add_header('User-Agent', 'My scraping program <author@example.com>')
opener = urllib2.build_opener()
content = opener... |
How do I insert a list into another list in python? | 6,970,579 | 5 | 2011-08-07T03:38:39Z | 6,971,826 | 12 | 2011-08-07T09:16:30Z | [
"python"
] | I have two lists:
```
A = [1,2,3]
B = [4,5,6]
```
Is there an elegant way to insert B into A at an arbitrary postion?
Hypothetical output:
```
[1,4,5,6,2,3]
```
Obviously I could iterate through B and insert them one at a time, but I figured there was a better way. | ```
A[1:1]=B
```
`A` will be `[1, 4, 5, 6, 2, 3]` |
Python find audio frequency and amplitude over time | 6,970,943 | 6 | 2011-08-07T05:35:23Z | 6,971,274 | 7 | 2011-08-07T07:03:00Z | [
"python",
"frequency",
"audio-processing"
] | Here is what I would like to do. I would like to find the audio frequency and amplitude of a .wav file at every say 1ms of that .wav file and save it into a file. I have graphed frequency vs amplitude and have graphed amplitude over time but I cannot figure out frequency overtime. My end goal is to be able to read the ... | Use a STFT with overlapping windows to estimate the spectrogram. To save yourself the trouble of rolling your own, you can use the [specgram method](http://matplotlib.sourceforge.net/api/mlab_api.html#matplotlib.mlab.specgram) of Matplotlib's mlab. It's important to use a small enough window for which the audio is appr... |
import error in python | 6,971,085 | 11 | 2011-08-07T06:12:57Z | 6,971,099 | 61 | 2011-08-07T06:15:47Z | [
"python",
"python-import"
] | I get the following error
```
Traceback (most recent call last):
File "myemail.py", line 1, in <module>
import smtplib
File "/usr/lib/python2.6/smtplib.py", line 46, in <module>
import email.utils
File "/home/nikhil/Desktop/bujji/email.py", line 2, in <module>
ImportError: No module named MIMEMultipart
```
when i... | You've stomped on the `email` package in the stdlib by naming a script `email.py`. Rename it. |
import error in python | 6,971,085 | 11 | 2011-08-07T06:12:57Z | 18,221,030 | 9 | 2013-08-13T23:40:50Z | [
"python",
"python-import"
] | I get the following error
```
Traceback (most recent call last):
File "myemail.py", line 1, in <module>
import smtplib
File "/usr/lib/python2.6/smtplib.py", line 46, in <module>
import email.utils
File "/home/nikhil/Desktop/bujji/email.py", line 2, in <module>
ImportError: No module named MIMEMultipart
```
when i... | Don't have enough reputation to comment on Ignacio Vazquez-Abrams's answer but make sure that not only do you remove email.py put also things like email.py~ and email.pyc |
Python Find distance between two coordinates | 6,971,705 | 2 | 2011-08-07T08:51:12Z | 6,971,724 | 10 | 2011-08-07T08:55:47Z | [
"python"
] | I'm working with a range of 0 to 255.
My data would be a set of numbers within this range.
Except I need the difference between
```
255 & 0 = 1
254 & 5 = 7
```
So in a sense this range is a circular set, and 255 and 0 are the pole.
Is there some function / easy way to do this? Or do I need to take the second half ... | ```
def diff256(a, b):
return min((a - b) % 256, (b - a) % 256)
``` |
Flask user authentication | 6,972,999 | 46 | 2011-08-07T13:00:19Z | 6,973,165 | 11 | 2011-08-07T13:43:51Z | [
"python",
"authentication",
"mongodb",
"flask"
] | I have an application that will use flask and mongodb; I will probably host it on rackspace.
I need to understand how flask authenticating works. I have not found much information on the subject. Is there a complete tutorial on how to roll your own solution? If not, I certainly would like to hear some thoughts on how ... | I don't think that flask has any authentication built-in, only support for tracking sessions.
Here are [some snippets](http://flask.pocoo.org/snippets/category/authentication/) for basic HTTP authentication and authentication with some third-party providers. Otherwise you will need to roll your own or use a framework ... |
Flask user authentication | 6,972,999 | 46 | 2011-08-07T13:00:19Z | 6,973,887 | 49 | 2011-08-07T16:00:48Z | [
"python",
"authentication",
"mongodb",
"flask"
] | I have an application that will use flask and mongodb; I will probably host it on rackspace.
I need to understand how flask authenticating works. I have not found much information on the subject. Is there a complete tutorial on how to roll your own solution? If not, I certainly would like to hear some thoughts on how ... | I would suggest using the [`flask-login`](http://pypi.python.org/pypi/Flask-Login) extension, it makes session management really easy to add to your `flask` application, and provides a nice [documentation](https://flask-login.readthedocs.org/en/latest/) which covers in details every aspect of the extension. |
Changing PyScripter to work with different Python Versions | 6,974,354 | 8 | 2011-08-07T17:13:18Z | 6,974,377 | 18 | 2011-08-07T17:15:55Z | [
"python",
"pyscripter"
] | I'm using [PyScripter](http://code.google.com/p/pyscripter/) for writing python programs and I can't figure out how to make it work with Python26 on my computer. When I installed ArcGIS, by default it installs Python26. I then installed PyScripter which found that installation and it worked fine. Later, I installed Pyt... | If you go to the pyScripter folder in the start menu, it will have a version of pyScripter for Python 2.4 to 3.2. Just run the one corresponding to your Python version. |
Django : get_or_create Raises duplicate entry with together_unique | 6,974,463 | 23 | 2011-08-07T17:29:13Z | 6,976,846 | 15 | 2011-08-08T00:43:49Z | [
"python",
"django",
"django-models"
] | model example
```
class Example(Stat):
numeric = models.IntegerField(...)
date = models.DateField( auto_now_add=True,...) #auto_now_add=True was the problem
class Meta:
unique_together = ('numeric','date')
```
)
If 72 and '2011-08-07' is already stored
```
Example.object.get_or_create(numeric=7... | It appears your problem is with there being more columns you're not including in your `get_or_create`, see i.e. [this thread](http://www.mail-archive.com/django-updates@googlegroups.com/msg19447.html) on a Django mailing list.
You need to use the `defaults` parameter of `get_or_create` as described in the [docs](https... |
iterate through unicode strings and compare with unicode in python dictionary | 6,974,510 | 9 | 2011-08-07T17:36:55Z | 6,974,799 | 11 | 2011-08-07T18:26:25Z | [
"python",
"unicode"
] | I have two python dictionaries containing information about japanese words and characters:
1. vocabDic : contains vocabulary, key: word, value: dictionary with information about it
2. kanjiDic : contains kanji ( single japanese character ), key: kanji, value: dictionary with information about it
Now I would like t... | From your description of the problem, it sounds like `vocab` is an encoded `str` object, not a `unicode` object.
For concreteness, suppose `vocab` equals `u'åµåã®å¤©äº'` encoded in `utf-8`:
```
In [42]: v=u'åµåã®å¤©äº'
In [43]: vocab=v.encode('utf-8') # val['text']
Out[43]: '\xe5\x82\xb5\xe5\x8b\x99\xe3\x... |
Python Process Pool non-daemonic? | 6,974,695 | 27 | 2011-08-07T18:08:04Z | 8,963,618 | 47 | 2012-01-22T18:46:24Z | [
"python",
"multiprocessing",
"pool"
] | Would it be possible to create a python Pool that is non-daemonic? I want a pool to be able to call a function that has another pool inside. Thanks. | The `multiprocessing.pool.Pool` class creates the worker processes in its `__init__` method, makes them daemonic and starts them, and it is not possible to re-set their `daemon` attribute to `False` before they are started (and afterwards it's not allowed anymore). But you can create your own sub-class of `multiprocesi... |
Plot with non-numerical data on x axis (for ex., dates) | 6,974,847 | 10 | 2011-08-07T18:33:07Z | 6,974,871 | 9 | 2011-08-07T18:37:06Z | [
"python",
"matplotlib"
] | I'd like to plot numerical data against non numerical data, say something like this:
```
import matplotlib.pyplot as pl
x=['a','b','c','d']
y=[1,2,3,4]
pl.plot(x,y)
```
However, with matplotlib plot packages you get a warning that the data is not float (ValueError: invalid literal for float(): a).
In their ['How-to'... | ```
import matplotlib.pyplot as plt
x = ['a','b','c','d']
y = [1,2,3,4]
plt.plot(y)
plt.xticks(range(len(x)), x)
plt.show()
```

On a side note, dates are numerical in this sense (i.e. they have an inherent order and spacing).
Matplotlib handles plot... |
Plot with non-numerical data on x axis (for ex., dates) | 6,974,847 | 10 | 2011-08-07T18:33:07Z | 6,974,911 | 8 | 2011-08-07T18:44:11Z | [
"python",
"matplotlib"
] | I'd like to plot numerical data against non numerical data, say something like this:
```
import matplotlib.pyplot as pl
x=['a','b','c','d']
y=[1,2,3,4]
pl.plot(x,y)
```
However, with matplotlib plot packages you get a warning that the data is not float (ValueError: invalid literal for float(): a).
In their ['How-to'... | Use the [xticks](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.xticks) function.
```
import matplotlib.pyplot as pl
xticks=['a','b','c','d']
x=[1,2,3,4]
y=[1,2,3,4]
pl.plot(x,y)
pl.xticks(x,xticks)
pl.show()
``` |
Mulitprocess Pools with different functions | 6,976,372 | 6 | 2011-08-07T22:58:23Z | 6,976,507 | 10 | 2011-08-07T23:27:11Z | [
"python",
"multiprocessing",
"pool"
] | Most examples of the Multiprocess Worker Pools execute a single function in different processes, f.e.
```
def foo(args):
pass
if __name__ == '__main__':
pool = multiprocessing.Pool(processes=30)
res=pool.map_async(foo,args)
```
Is there a way to handle two different and independent functions within the pool... | To pass different functions, you can simply call `map_async` multiple times.
Here is an example to illustrate that,
```
from multiprocessing import Pool
from time import sleep
def square(x):
return x * x
def cube(y):
return y * y * y
pool = Pool(processes=20)
result_squares = pool.map_async(f, range(10))
... |
Most pythonic way of assigning keyword arguments using a variable as keyword? | 6,976,658 | 6 | 2011-08-08T00:01:05Z | 6,976,666 | 19 | 2011-08-08T00:03:32Z | [
"python",
"keyword-argument"
] | What is **the most pythonic way** to get around the following problem? From the interactive shell:
```
>>> def f(a=False):
... if a:
... return 'a was True'
... return 'a was False'
...
>>> f(a=True)
'a was True'
>>> kw = 'a'
>>> val = True
>>> f(kw=val)
Traceback (most recent call last):
File "<std... | Use [keyword argument unpacking](http://docs.python.org/tutorial/controlflow.html#keyword-arguments):
```
>>> kw = {'a': True}
>>> f(**kw)
<<< 'a was True'
``` |
Where should I put Py_INCREF and Py_DECREF on this block in Python C Extension? | 6,977,161 | 7 | 2011-08-08T02:05:47Z | 6,978,933 | 9 | 2011-08-08T07:25:37Z | [
"python",
"c",
"reference-counting"
] | Whenever I called my function, memory usage is increased around +10M per call, so I think there is some memory leak here.
```
....
PyObject *pair = PyTuple_New(2), *item = PyList_New(0);
PyTuple_SetItem(pair, 0, PyInt_FromLong(v[j]));
if(v[j] != DISTANCE_MAX && (p[j] || d[0][j])){
jp=j;
while(jp!=istart) {
P... | The objects you create with PyInt\_FromLong() and you add to the list should be kept in a local variable.
The reason are the [ownership rules](http://docs.python.org/extending/extending.html#ownership-rules): PyInt\_FromLong() generates a reference that you own. In the call to PyTuple\_SetItem(), you lose this ownersh... |
SQLAlchemy: selecting which columns of an object in a query | 6,977,658 | 12 | 2011-08-08T04:09:25Z | 6,977,901 | 13 | 2011-08-08T04:54:47Z | [
"python",
"orm",
"sqlalchemy"
] | Is it possible to control which columns are queried in the query method of SQLAlchemy, while still returning instances of the object you are querying (albeit partially populated)?
Or is it necessary for SQLAlchemy to perform a `SELECT *` to map to an object?
(I do know that querying individual columns is available, b... | you can query for individual columns, which returns named tuples that do in fact act pretty much like your mapped object if you're just passing off to a template or something:
<http://www.sqlalchemy.org/docs/orm/tutorial.html#querying>
or you can establish various columns on the mapped class as "deferred", either con... |
simple instantiations of python classes | 6,978,123 | 4 | 2011-08-08T05:37:24Z | 6,978,134 | 8 | 2011-08-08T05:38:48Z | [
"python"
] | Can you please explain why 'hello world' isn't returned below? What do I need to modify for it to be expressed properly when called? Thanks.
```
>>> class MyClass:
... i=12345
... def f(self):
... return 'hello world'
...
>>> x=MyClass()
>>> x.i
12345
>>> x.f
<bound method MyClass.f of <__main__.M... | `f` is a method, so you need to call it. i.e. `x.f()`
It's no different than if you define a function without the class:
```
def f():
return 'something'
```
If you just refer to `f`, you'll get the function itself
```
print f
```
yields `<function f at 0xdcc2a8>`, while
```
print f()
```
yields `"something"`... |
How to load a javascript or css file into a BottlePy template? | 6,978,603 | 8 | 2011-08-08T06:43:32Z | 6,980,653 | 24 | 2011-08-08T10:15:03Z | [
"javascript",
"python",
"templates",
"bottle",
"url-for"
] | I am trying to return a html template with BottlePy. And this works fine. But if I insert a javascript file like this in my tpl-file:
```
<script type="text/javascript" src="js/main.js" charset="utf-8"></script>
```
I get an 404 error.
*(Failed to load resource: the server responded with a status of 404 (Not Found))*... | Well, first, you need your dev server to actually serve `main.js`, otherwise it won't be available for the browser.
It's customary to put all `.js` and `.css` files under the `static` directory in small web apps, so your layout should look like this:
```
app.py
- static/
main.js
- views/
index.tpl
```
By n... |
Python function argument of predicate type a=b | 6,978,903 | 3 | 2011-08-08T07:21:14Z | 6,978,917 | 7 | 2011-08-08T07:23:51Z | [
"python",
"keyword-argument"
] | Pardon my Python skill or the lack of it. I saw some methods calls of the form
```
auth_req = urllib2.Request(auth_uri, data=authreq_data)
```
If I put in just `authreq_data` I get an error. What is the correct technical definition for this type of method argument? Is it a boolean/predicate type? | They're called [keyword arguments](http://docs.python.org/tutorial/controlflow.html#keyword-arguments).
You can use them without specifying the keyword, so long as you also pass all the arguments before them.
The signature of [urrlib2.Request](http://docs.python.org/library/urllib2.html#urllib2.Request) is
```
urlli... |
Rendering HTML in web.py | 6,979,819 | 12 | 2011-08-08T09:03:13Z | 6,980,241 | 11 | 2011-08-08T09:41:13Z | [
"python",
"html",
"templates",
"web.py"
] | I am handling with a Wikipedia-like project. I can convert the text file to html code using the markdown. My problem is, I want to render this html code in a html file. Here is my code,
```
class articles:
def GET(self):
form_name=web.input()
article_name=form_name.page
article_file_path=os... | HTML escaping is on by default in web.py templates. To turn it off, prepend the variable name with a colon:
```
<form name="form" method="GET">
$:content
</form>
```
Make sure there is no way for a potentially malicious user to feed arbitrary HTML into your unescaped templates. |
Weird django import errors | 6,979,922 | 2 | 2011-08-08T09:13:06Z | 6,979,986 | 7 | 2011-08-08T09:18:53Z | [
"python",
"django",
"django-models",
"django-errors"
] | What I was trying to do was to override the save method of one of my models called `Shastra`
```
class Shastra(models.Model):
something = models.IntegerField()
def save(self, *args, **kwargs):
post_content(app='shastra', content=self)
super(Shastra, self).save(*args, **kwargs)
# The function... | Circular import. Either resolve it, or use string as FK argument (`models.ForeignKey('app.Shastra')`). |
How can I find a process by name and kill using ctypes? | 6,980,246 | 3 | 2011-08-08T09:41:32Z | 6,984,331 | 9 | 2011-08-08T15:14:16Z | [
"python",
"windows",
"ctypes"
] | On Windows, I want to find a process by the name of 'exename.exe', and then kill it.
How can I do it by ctypes not any other 3rd-party module? | This may be cheating, but it works without even getting ctypes involved.
```
import subprocess
subprocess.call("taskkill /IM exename.exe")
```
`taskkill` is a Windows command; this is just invoking it through Python. |
Simpler way to put PDB breakpoints in Python code? | 6,980,749 | 45 | 2011-08-08T10:24:14Z | 6,980,836 | 67 | 2011-08-08T10:31:08Z | [
"python",
"pdb"
] | Just a convenience question. I've been a bit spoiled with debuggers in IDEs like Visual Studio and XCode. I find it a bit clumsy to have to type `import pdb; pdb.set_trace()` to set a breakpoint (I'd rather not import pdb at the top of the file as I might forget and leave it in).
Is there a simpler way of setting a br... | You can run your program into `pdb` from the command line by running
> python -m pdb your\_script.py
It will break on the 1st line, then you'll be able to add a breakpoint wherever you want in your code using the `break` command, its syntax is:
> b(reak) [[filename:]lineno | function[, condition]]
It is enough flex... |
Simpler way to put PDB breakpoints in Python code? | 6,980,749 | 45 | 2011-08-08T10:24:14Z | 19,634,104 | 18 | 2013-10-28T11:51:40Z | [
"python",
"pdb"
] | Just a convenience question. I've been a bit spoiled with debuggers in IDEs like Visual Studio and XCode. I find it a bit clumsy to have to type `import pdb; pdb.set_trace()` to set a breakpoint (I'd rather not import pdb at the top of the file as I might forget and leave it in).
Is there a simpler way of setting a br... | In vim, I have a macro set up for this (in my .vimrc file):
```
map <silent> <leader>b oimport pdb; pdb.set_trace()<esc>
map <silent> <leader>B Oimport pdb; pdb.set_trace()<esc>
```
so I can just press \b (when not in Insert Mode) and it adds in a breakpoint after the current line, or \B (note the capital) and it put... |
Simpler way to put PDB breakpoints in Python code? | 6,980,749 | 45 | 2011-08-08T10:24:14Z | 28,697,682 | 15 | 2015-02-24T13:56:53Z | [
"python",
"pdb"
] | Just a convenience question. I've been a bit spoiled with debuggers in IDEs like Visual Studio and XCode. I find it a bit clumsy to have to type `import pdb; pdb.set_trace()` to set a breakpoint (I'd rather not import pdb at the top of the file as I might forget and leave it in).
Is there a simpler way of setting a br... | You can use:
```
from pdb import set_trace as bp
code
code
bp()
code
code
``` |
django - get field which name is dynamic | 6,980,877 | 5 | 2011-08-08T10:35:09Z | 6,980,935 | 11 | 2011-08-08T10:41:25Z | [
"python",
"django"
] | What I need:
I want to get object details from DB. I use get() function. The problem I have is, that I make in in a function, and one of the arguments is field name as string:
```
def delete_file_if_changed(id, change, form, model, field_name='image'):
if change:
if field_name in form.changed_data:
... | You know, I thought this was your answer at first -- it lets you search by a dynamic property: Could the `**` operator work?
```
kw = {field_name:change} # you're not explicit as to which is the field_name
# value you would like to search for.
old_image = model.objects.get(**kw)
```
But, if y... |
Safeguarding MySQL password when developing in Python? | 6,981,064 | 7 | 2011-08-08T10:52:56Z | 6,981,725 | 11 | 2011-08-08T11:56:49Z | [
"python",
"mysql"
] | I'm writing a Python script which uses a MySQL database, which is locally hosted. The program will be delivered as source code. As a result, the MySQL password will be visible to bare eyes. Is there a good way to protect this?
The idea is to prevent some naughty people from looking at the source code, gaining direct a... | ## Some things first...
The question here should not be how to hide the password, but how to secure the database. Remember that passwords only are often a very weak protection and should not be considered the sole mechanism of protecting the DB. Are you using SSL? No? Well, then even *if* you manage to hide the passwo... |
How can I concatenate a string and a number in Python? | 6,981,495 | 20 | 2011-08-08T11:35:26Z | 6,981,521 | 7 | 2011-08-08T11:37:26Z | [
"python"
] | I was trying to concatenate a string and a number in Python. It gave me an error when I tried this:
```
"abc" + 9
```
The error is:
```
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
"abc" + 9
TypeError: cannot concatenate 'str' and 'int' objects
```
Why I am not able to do this?
... | Since [Python is a strongly typed](http://wiki.python.org/moin/Why%20is%20Python%20a%20dynamic%20language%20and%20also%20a%20strongly%20typed%20language) language, concatenating a string and an integer as you may do in Perl makes no sense, *because there's no defined way to "add" strings and numbers to each other.*
> ... |
How can I concatenate a string and a number in Python? | 6,981,495 | 20 | 2011-08-08T11:35:26Z | 6,981,532 | 45 | 2011-08-08T11:37:48Z | [
"python"
] | I was trying to concatenate a string and a number in Python. It gave me an error when I tried this:
```
"abc" + 9
```
The error is:
```
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
"abc" + 9
TypeError: cannot concatenate 'str' and 'int' objects
```
Why I am not able to do this?
... | Python is [strongly typed](http://en.wikipedia.org/wiki/Strong_typing). There are no implicit type conversions.
You have to do one of these:
```
"asd%d" % 9
"asd" + str(9)
``` |
How can I concatenate a string and a number in Python? | 6,981,495 | 20 | 2011-08-08T11:35:26Z | 6,981,536 | 21 | 2011-08-08T11:38:14Z | [
"python"
] | I was trying to concatenate a string and a number in Python. It gave me an error when I tried this:
```
"abc" + 9
```
The error is:
```
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
"abc" + 9
TypeError: cannot concatenate 'str' and 'int' objects
```
Why I am not able to do this?
... | If it worked the way you expected it to (resulting in `"abc9"`), what would `"9" + 9` deliver? `18` or `"99"`?
To remove this ambiguity, you are required to make explicit what you want to convert in this case:
```
"abc" + str(9)
``` |
sys.argv as bytes in Python 3k | 6,981,594 | 6 | 2011-08-08T11:43:50Z | 7,077,803 | 8 | 2011-08-16T11:54:51Z | [
"python",
"string",
"unicode",
"python-3.x"
] | As Python 3k introduces strict distinction between strings and bytes, command line arguments in the array sys.argv are presented as strings. Sometimes it is necessary to treat the arguments as bytes, e.g. when passing a path that needn't to be in any particular character encoding in Unix.
Let's see an example. A brief... | Note that the error is a `UnicodeEncodeError` rather than a `UnicodeDecodeError`. Python is preserving the exact bytes passed on the command line (via the PEP 383 `surrogateescape` error handler), but those bytes are not valid UTF-8 and hence can't be encoded as such for writing to the console.
The best way to deal wi... |
Pythonic way to combine FOR loop and IF statement | 6,981,717 | 101 | 2011-08-08T11:56:16Z | 6,981,771 | 104 | 2011-08-08T12:01:43Z | [
"python",
"loops",
"if-statement",
"for-loop"
] | I know how to use both for loops and if statements on separate lines, such as:
```
>>> a = [2,3,4,5,6,7,8,9,0]
... xyz = [0,12,4,6,242,7,9]
... for x in xyz:
... if x in a:
... print(x)
0,4,6,7,9
```
And I know I can use a list comprehension to combine these when the statements are simple, such as:
```
p... | You can use [generator expressions](http://www.python.org/dev/peps/pep-0289/) like this:
```
gen = (x for x in xyz if x not in a)
for x in gen:
print x
``` |
Pythonic way to combine FOR loop and IF statement | 6,981,717 | 101 | 2011-08-08T11:56:16Z | 6,981,790 | 18 | 2011-08-08T12:03:48Z | [
"python",
"loops",
"if-statement",
"for-loop"
] | I know how to use both for loops and if statements on separate lines, such as:
```
>>> a = [2,3,4,5,6,7,8,9,0]
... xyz = [0,12,4,6,242,7,9]
... for x in xyz:
... if x in a:
... print(x)
0,4,6,7,9
```
And I know I can use a list comprehension to combine these when the statements are simple, such as:
```
p... | As per [The Zen of Python](http://www.python.org/dev/peps/pep-0020/) (if you are wondering whether your code is "Pythonic", that's the place to go):
* Beautiful is better than ugly.
* Explicit is better than implicit.
* Simple is better than complex.
* Flat is better than nested.
* Readability counts.
The Pythonic wa... |
Cython won't compile on Windows 7 x64 | 6,982,009 | 7 | 2011-08-08T12:20:28Z | 6,983,481 | 9 | 2011-08-08T14:16:33Z | [
"python",
"windows-7",
"mingw",
"64bit",
"cython"
] | I'm struggling with installing Cython on Windows 7 x64.
I downloaded and installed the `automated MinGW installer`. The created a distutils.cfg to the distutils folder with the following content:
```
[build]
compiler = mingw32
```
After adding `C:\MinGW\bin` to the environment variables, I called `easy_install Cython... | There are pre-compiled Cython packages [on this site](http://www.lfd.uci.edu/~gohlke/pythonlibs/#cython). I'd suggest you to switch to x86 Python, you gain no real advantage by using the x64 version. If you want to stick with x64, you can't use MingW and you have to use MS SDK C++ compiler ([more on this](http://wiki.c... |
Output formatting in Python: replacing several %s with the same variable | 6,982,949 | 13 | 2011-08-08T13:36:50Z | 6,982,974 | 39 | 2011-08-08T13:39:03Z | [
"string-formatting",
"python"
] | I'm trying to maintain/update/rewrite/fix a bit of Python that looks a bit like this:
```
variable = """My name is %s and it has been %s since I was born.
My parents decided to call me %s because they thought %s was a nice name.
%s is the same as %s.""" % (name, name, name, name, name, name... | Use a dictionary instead.
```
var = '%(foo)s %(foo)s %(foo)s' % { 'foo': 'look_at_me_three_times' }
```
Or `format` with explicit numbering.
```
var = '{0} {0} {0}'.format('look_at_meeee')
```
Well, or `format` with named parameters.
```
var = '{foo} {foo} {foo}'.format(foo = 'python you so crazy')
``` |
Why is it useful to have a MetaData object which is not bind to an engine in SQLAlchemy? | 6,983,515 | 4 | 2011-08-08T14:18:48Z | 6,984,382 | 10 | 2011-08-08T15:18:54Z | [
"python",
"sqlalchemy",
"metadata"
] | I am trying to understand the behavior of MySQL regarding the `MetaData` object and the `engine` object. [This SO-Answer](http://stackoverflow.com/questions/2317304/what-exactly-is-metadata-in-sqlalchemy/2317401#2317401) describes `MetaData` as
> a collection of table definitions
and `engine` as
> the dialect and co... | SQLAlchemy 0.1 didn't have a "metadata" object - the `Engine` was bound directly to each `Table`. That idea got old very quick, partially because folks wanted to declare their Table object before they connected, and "bound metadata" came along. Then, a long period of mass confusion occurred. People were in the super ha... |
A super strange bug of os.path.abspath | 6,984,450 | 28 | 2011-08-08T15:22:58Z | 6,984,500 | 45 | 2011-08-08T15:26:24Z | [
"python",
"windows",
"filesystems"
] | On My Python 2.6 ( 64bit, win7, ActivePython ),
when i call:
`os.path.abspath('D:/PROJECTS/SuiShouBei/www/ssb/static/voices/en/mp3/con.mp3')`
It returns:
`'\\\\.\\con'`
I have no problem with other paths so far.
Anyone has the same issue?
Can someone please tell me why? | I can reproduce this in Python 2.6, 2.7, 3.1 and 3.2.
The reason for this behavior is the fact that `CON` is an [illegal filename](http://msdn.microsoft.com/en-us/library/aa365247%28v=vs.85%29.aspx) in Windows (try `os.path.abspath('D:/PROJECTS/SuiShouBei/www/ssb/static/voices/en/mp3/cont.mp3')` and see that everythin... |
How to compile .c code from Cython with gcc | 6,985,109 | 17 | 2011-08-08T16:14:48Z | 6,987,419 | 16 | 2011-08-08T19:22:22Z | [
"python",
"c",
"gcc",
"compilation",
"cython"
] | Now that I've successfully installed Cython on Windows 7, I try to compile some Cython code using Cython, but gcc makes my life hard.
```
cdef void say_hello(name):
print "Hello %s" % name
```
Using gcc to compile the code throws dozens of **undefined reference to** -erros, and I'm pretty sure the `libpython.a` i... | Try:
```
gcc -c -IC:\Python27\include -o ctest.o ctest.c
gcc -shared -LC:\Python27\libs -o ctest.pyd ctest.o -lpython27
```
`-shared` creates a shared library. `-lpython27` links with the import library C:\Python27\libs\libpython27.a. |
Python/django root logger level | 6,985,251 | 9 | 2011-08-08T16:27:06Z | 7,018,776 | 12 | 2011-08-10T22:36:46Z | [
"python",
"django",
"logging"
] | In my django project I have following LOGGING config:
```
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'verbose': {
'format': '%(name)s %(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
},
'simple': {
'for... | The South developers shouldn't really be setting its top level logger level to DEBUG. In fact if they don't set it at all, it would inherit the root logger's level, which is normally defined by the application developer (which I guess is you, in this case).
I would suggest you report this as a bug on the relevant Sout... |
Get 2 isolated instances of a python module | 6,985,617 | 14 | 2011-08-08T16:53:19Z | 6,985,648 | 13 | 2011-08-08T16:56:23Z | [
"python"
] | I am interacting with a crusty python 2.x API written in a non-OO way (fools!), it uses module-global scope for some internal state driven stuff.
Short of using subprocess runs of separate interpreters, is there any way I could box off the modules and interact with multiple instances of the module (thus treating it as... | Just remove the module from [`sys.modules`](http://docs.python.org/library/sys.html#sys.modules):
```
>>> import sys
>>> import mod as m1
>>> m1.x = 1
>>> del sys.modules['mod']
>>> import mod as m2
>>> m2.x = 2
>>> m1.x
1
``` |
Use Python to remove lines in a files that start with an octothorpe? | 6,985,783 | 7 | 2011-08-08T17:07:16Z | 6,985,814 | 12 | 2011-08-08T17:09:38Z | [
"python",
"startswith"
] | This seems like a straight-forward question but I can't seem to pinpoint my problem. I am trying to delete all lines in a file that start with an octothorpe (#) except the first line. Here is the loop I am working with:
```
for i, line in enumerate(input_file):
if i > 1:
if not line.startswith('#'):
... | You aren't writing out the first line:
```
for i, line in enumerate(input_file):
if i == 0:
output.write(line)
else:
if not line.startswith('#'):
output.write(line)
```
Keep in mind also that `enumerate` (like most things) starts at zero.
A little more concisely (and not repeating... |
timestamp from 3months ago | 6,986,067 | 6 | 2011-08-08T17:29:53Z | 6,986,216 | 14 | 2011-08-08T17:42:17Z | [
"python",
"timestamp"
] | I've a small script where I'm getting data from the last few months, based on the timestamp. Right now I'm using current day and a set date (currently May). Here's how I'm defining it:
```
today_time = int(time.mktime(date.today().timetuple())*1000000)
earlier_time = int(time.mktime(datetime.date(2011,05,01).timetuple... | ```
import datetime
now = datetime.datetime.now()
then = now - datetime.timedelta(days=90)
``` |
Bin size in Matplotlib (Histogram) | 6,986,986 | 51 | 2011-08-08T18:46:04Z | 12,176,344 | 102 | 2012-08-29T10:55:20Z | [
"python",
"matplotlib",
"histogram"
] | I'm using matplotlib to make a histogram.
Basically, I'm wondering if there is any way to manually set the size of the bins as opposed to the number of bins.
Anyone with any ideas is greatly appreciated.
Thanks | Actually, it's quite easy: instead of the number of bins you can give a list with the bin boundaries. They can be unequally distributed, too:
```
plt.hist(data, bins=[0, 10, 20, 30, 40, 50, 100])
```
If you just want them equally distributed, you can simply use range:
```
plt.hist(data, bins=range(min(data), max(dat... |
Bin size in Matplotlib (Histogram) | 6,986,986 | 51 | 2011-08-08T18:46:04Z | 13,364,261 | 9 | 2012-11-13T16:07:57Z | [
"python",
"matplotlib",
"histogram"
] | I'm using matplotlib to make a histogram.
Basically, I'm wondering if there is any way to manually set the size of the bins as opposed to the number of bins.
Anyone with any ideas is greatly appreciated.
Thanks | For N bins, the bin edges are specified by list of N+1 values where the first N give the lower bin edges and the +1 gives the upper edge of the last bin.
Code:
```
from numpy import np; from pylab import *
bin_size = 0.1; min_edge = 0; max_edge = 2.5
N = (max_edge-min_edge)/bin_size; Nplus1 = N + 1
bin_list = np.lin... |
search in wildcard folders recursively in python | 6,987,123 | 4 | 2011-08-08T18:55:45Z | 6,987,427 | 8 | 2011-08-08T19:23:05Z | [
"python"
] | hello im trying to do something like
```
// 1. for x in glob.glob('/../../nodes/*/views/assets/js/*.js'):
// 2 .for x in glob.glob('/../../nodes/*/views/assets/js/*/*.js'):
print x
```
**is there anything can i do to search it recuresively ?**
i already looked into [Use a Glob() to find files recursively in Pyth... | **Caveat:** This will also select any files matching the pattern anywhere beneath the root folder which is nodes/.
```
import os, fnmatch
def locate(pattern, root_path):
for path, dirs, files in os.walk(os.path.abspath(root_path)):
for filename in fnmatch.filter(files, pattern):
yield os.path.... |
Python - find the item with maximum occurrences | 6,987,285 | 16 | 2011-08-08T19:10:18Z | 6,987,358 | 37 | 2011-08-08T19:16:58Z | [
"python",
"list",
"max",
"counting"
] | In Python, I have a list
```
L = [1, 2, 45, 55, 5, 4, 4, 4, 4, 4, 4, 5456, 56, 6, 7, 67]
```
I want to figure out the number which occurred the maximum number of times. I am able to solve it but I need the fastest way to do so. I know there is a nice Pythonic answer to this. | ```
from collections import Counter
most_common,num_most_common = Counter(L).most_common(1)[0] # 4, 6 times
```
For older Python versions (< 2.7), you can use [this receipe](http://code.activestate.com/recipes/576611-counter-class/) to get the [`Counter`](http://docs.python.org/dev/library/collections.html#collections... |
Python - find the item with maximum occurrences | 6,987,285 | 16 | 2011-08-08T19:10:18Z | 6,987,402 | 10 | 2011-08-08T19:20:41Z | [
"python",
"list",
"max",
"counting"
] | In Python, I have a list
```
L = [1, 2, 45, 55, 5, 4, 4, 4, 4, 4, 4, 5456, 56, 6, 7, 67]
```
I want to figure out the number which occurred the maximum number of times. I am able to solve it but I need the fastest way to do so. I know there is a nice Pythonic answer to this. | Here is a `defaultdict` solution that will work with Python versions 2.5 and above:
```
from collections import defaultdict
L = [1,2,45,55,5,4,4,4,4,4,4,5456,56,6,7,67]
d = defaultdict(int)
for i in L:
d[i] += 1
result = max(d.iteritems(), key=lambda x: x[1])
print result
# (4, 6)
# The number 4 occurs 6 times
``... |
Python - find the item with maximum occurrences | 6,987,285 | 16 | 2011-08-08T19:10:18Z | 6,988,979 | 13 | 2011-08-08T21:41:41Z | [
"python",
"list",
"max",
"counting"
] | In Python, I have a list
```
L = [1, 2, 45, 55, 5, 4, 4, 4, 4, 4, 4, 5456, 56, 6, 7, 67]
```
I want to figure out the number which occurred the maximum number of times. I am able to solve it but I need the fastest way to do so. I know there is a nice Pythonic answer to this. | In your question, you asked for the fastest way to do it. As has been demonstrated repeatedly, particularly with Python, intuition is not a reliable guide: you need to measure.
Here's a simple test of several different implementations:
```
import sys
from collections import Counter, defaultdict
from itertools import ... |
Installing h5py on OS X | 6,988,010 | 5 | 2011-08-08T20:16:14Z | 7,719,717 | 10 | 2011-10-10T23:15:47Z | [
"python",
"osx",
"import",
"hdf5",
"h5py"
] | I've spent the day trying to get the `h5py` module of python working, but without success. I've installed HDF5 shared libraries, followed the instructions I could find on the web to get it right. But it doesn't work, below is the error message I get when trying to import the module into python. I tried installing throu... | Check that you are not inside the h5py installation directory. |
Using Chinese to build a dictionary in Python | 6,988,213 | 5 | 2011-08-08T20:36:07Z | 6,988,276 | 8 | 2011-08-08T20:41:29Z | [
"python",
"unicode",
"utf-8",
"dictionary",
"cjk"
] | so this is my first time here, and also I am new to the world of Python. I am studying Chinese also and I wanted to create a program to review Chinese vocabulary using a dictionary. Here is the code that I normally use:
```
#!/usr/bin/python
# -*- coding:utf-8-*-
dictionary = {"Hello" : "ä½ å¥½"} # Simple example to ... | When printing a dict, (e.g. `print(dictionary)`), the `repr`s of the keys and values are displayed.
Instead, try:
```
dictionary = {u"Hello" : u"ä½ å¥½"}
for key,value in dictionary.iteritems():
print(u'{k} --> {v}'.format(k=key,v=value))
```
yields:
```
Hello --> ä½ å¥½
``` |
Why is GCC ignoring ARCHFLAGS in Snow Leopard? | 6,988,528 | 4 | 2011-08-08T21:00:37Z | 6,989,055 | 13 | 2011-08-08T21:51:55Z | [
"python",
"osx",
"gcc",
"virtualenv",
"pip"
] | I'm trying to install [AMFAST](http://pypi.python.org/pypi/AmFast/0.5.2-r532) in a [virtual\_env](http://pypi.python.org/pypi/virtualenv) location based on a dependencies file. I have `export ARCHFLAGS="-arch x86_64"` in my local .profile, and have confirmed its presence by running `env` and seeing it listed. However, ... | Most likely the problem is that the `ARCHFLAGS` environment variable is not being passed through by `sudo`. By default, some versions of `sudo` filter out most env variables as a security measure (see `man sudo`). Try running it this way:
```
sudo ARCHFLAGS="-arch x86_64" pip install -E ~/Documents/project/project_env... |
Getting NameError when calling function in constructor | 6,988,779 | 3 | 2011-08-08T21:21:52Z | 6,988,827 | 11 | 2011-08-08T21:25:09Z | [
"python",
"constructor"
] | I ran the code below, by calling the function in the constructor
First --
```
>>> class PrintName:
... def __init__(self, value):
... self._value = value
... printName(self._value)
... def printName(self, value):
... for c in value:
... print c
...
>>> o = PrintName('Chaitanya')
C
h
a
i
t
... | You need to call `self.printName` since your function is a method belonging to the PrintName class.
Or, since your printname function doesn't need to rely on object state, you could just make it a module level function.
```
class PrintName:
def __init__(self, value):
self._value = value
printName(... |
Securing RESTapi in flask | 6,988,977 | 8 | 2011-08-08T21:41:24Z | 6,989,035 | 14 | 2011-08-08T21:49:36Z | [
"python",
"rest",
"restful-authentication",
"flask"
] | The app I'm deving uses a lot of ajax calls. Unfortunately I hit a snag when researching on how to restrict access to the api. For example:
* i have table that does an ajax call to <http://site/api/tasks/bob>
i need to make sure that only bob, logged in, can read that table
(otherwise somebody who knows the patt... | The thousand-foot view is you need to authenticate the user either with:
A) HTTP-Auth (either [basic](http://en.wikipedia.org/wiki/Basic_access_authentication) or [digest](http://en.wikipedia.org/wiki/Digest_access_authentication)) on each request.
B) Server-side sessions. (The user authenticates and receives a sessi... |
How do I start up remote debugging with PyCharm? | 6,989,965 | 33 | 2011-08-08T23:56:58Z | 7,061,956 | 63 | 2011-08-15T05:30:40Z | [
"python",
"django",
"remote-debugging",
"pycharm"
] | I'm trying to get debugging up between PyCharm (on windows host) and a debian virtual host running my django application. The instructions say to install the egg, add the import, and then invoke a command. I assume these things need to be done on the debian host?
Ok, then, in what file should I put these two lines?
`... | PyCharm (or your ide of choice) acts as the "server" and your application is the "client"; so you start the server first - tell the IDE to 'debug' - then run the client - which is some code with the `settrace` statement in it. When your python code hits the `settrace` it connects to the server - pycharm - and starts fe... |
How can I override the keyboard interrupt? (Python) | 6,990,474 | 4 | 2011-08-09T01:26:17Z | 6,990,487 | 15 | 2011-08-09T01:29:17Z | [
"python",
"signals",
"interrupt"
] | Is there anyway I can make my script execute one of my functions when `Ctrl+c` is hit when the script is running? | Take a look at [signal handlers](http://docs.python.org/library/signal.html#example). CTRL-C corresponds to [SIGINT](http://en.wikipedia.org/wiki/SIGINT_%28POSIX%29) (signal #2 on posix systems).
Example:
```
#!/usr/bin/env python
import signal
import sys
def signal_handler(signal, frame):
print 'You pressed Ctrl... |
Computing cross-correlation function? | 6,991,471 | 19 | 2011-08-09T04:46:17Z | 6,991,597 | 20 | 2011-08-09T05:08:04Z | [
"python",
"statistics",
"numpy",
"scipy"
] | In `R`, I am using `ccf` or `acf` to compute the pair-wise cross-correlation function so that I can find out which shift gives me the maximum value. From the looks of it, `R` gives me a normalized sequence of values. Is there something similar in Python's scipy or am I supposed to do it using the `fft` module? Currentl... | To cross-correlate 1d arrays use [numpy.correlate](http://docs.scipy.org/doc/numpy/reference/generated/numpy.correlate.html).
For 2d arrays, use [scipy.signal.correlate2d](http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.correlate2d.html).
There is also [scipy.stsci.convolve.correlate2d](http://docs.s... |
Computing cross-correlation function? | 6,991,471 | 19 | 2011-08-09T04:46:17Z | 7,588,117 | 9 | 2011-09-28T18:56:30Z | [
"python",
"statistics",
"numpy",
"scipy"
] | In `R`, I am using `ccf` or `acf` to compute the pair-wise cross-correlation function so that I can find out which shift gives me the maximum value. From the looks of it, `R` gives me a normalized sequence of values. Is there something similar in Python's scipy or am I supposed to do it using the `fft` module? Currentl... | If you are looking for a rapid, normalized cross correlation in either one or two dimensions
I would recommend the openCV library (see ~~<http://opencv.willowgarage.com/wiki/>~~ <http://opencv.org/>). The cross-correlation code maintained by this group is the fastest you will find, and it will be normalized (results be... |
Computing cross-correlation function? | 6,991,471 | 19 | 2011-08-09T04:46:17Z | 12,254,905 | 9 | 2012-09-03T23:05:03Z | [
"python",
"statistics",
"numpy",
"scipy"
] | In `R`, I am using `ccf` or `acf` to compute the pair-wise cross-correlation function so that I can find out which shift gives me the maximum value. From the looks of it, `R` gives me a normalized sequence of values. Is there something similar in Python's scipy or am I supposed to do it using the `fft` module? Currentl... | I just finished writing my own optimised implementation of normalized cross-correlation for N-dimensional arrays. You can get it from **[here](http://pastebin.com/x1NJqWWm)**.
It will calculate cross-correlation either directly, using `scipy.ndimage.correlate`, or in the frequency domain, using `scipy.fftpack.fftn`/`i... |
Setting default value for integer field in django models | 6,992,364 | 4 | 2011-08-09T06:47:08Z | 6,992,632 | 15 | 2011-08-09T07:16:45Z | [
"python",
"django",
"integer",
"django-models"
] | I'm trying to set a default value for the integer field in Django model using
```
models.PositiveSmallIntegerField(default='0')
```
Why isn't it working? | No, it is not correct, because your [default value](https://docs.djangoproject.com/en/dev/ref/models/fields/#default) is set to string not integer. Try this instead:
```
models.PositiveSmallIntegerField(default=0)
``` |
Only one python program running (like Firefox)? | 6,992,427 | 14 | 2011-08-09T06:53:07Z | 6,992,797 | 8 | 2011-08-09T07:30:04Z | [
"python",
"firefox",
"google-chrome",
"process"
] | When I open Firefox, then run the command:
```
firefox http://somewebsite
```
the url opens in a new tab of Firefox (same thing happens with Chromium as well). Is there some way to replicate this behavior in Python? For example, calling:
```
processStuff.py file/url
```
then calling:
```
processStuff.py anotherfil... | You could create a data directory where you create a "locking file" once your program is running, after having checked if the file doesn't exist yet.
If it exists, you should try to communicate with the existing process, which creates a socket or a pipe or something like this and communicates its address or its path i... |
Only one python program running (like Firefox)? | 6,992,427 | 14 | 2011-08-09T06:53:07Z | 7,047,309 | 24 | 2011-08-12T23:16:19Z | [
"python",
"firefox",
"google-chrome",
"process"
] | When I open Firefox, then run the command:
```
firefox http://somewebsite
```
the url opens in a new tab of Firefox (same thing happens with Chromium as well). Is there some way to replicate this behavior in Python? For example, calling:
```
processStuff.py file/url
```
then calling:
```
processStuff.py anotherfil... | The way Firefox does it is: the first instance creates a socket file (or a named pipe on Windows). This serves both as a way for the next instances of Firefox to detect and communicate with the first instance, and forward it the URL before dying. A socket file or named pipe being only accessible from processes running ... |
copy list in python | 6,993,531 | 2 | 2011-08-09T08:46:08Z | 6,993,543 | 12 | 2011-08-09T08:47:13Z | [
"python",
"list",
"memory",
"multidimensional-array"
] | As I am trying to make a copy of a list and do some stuff with the copy of the list. Somehow my original list is modified as well. I already looked at different memory allocatinos and different ways of assigning the lists. So far no luck... Any ideas?
```
row = 0
column = 0
table1 = copy.copy(table[:])
... | Your original list contains inner lists:
```
[[0, 'ZZZ', 'XXX', 'YYY', 'AAA', 0, 0],
['BBB', 1, 1, 0, 26, 28, 0], ...
]
```
The inner list are actually stored as references, i.e.:
```
[ location-of-list-0,
location-of-list-1, ...
]
```
When you copied the list, you actually copied a list of references to the s... |
TestSuite with testsuites and testcases | 6,993,711 | 4 | 2011-08-09T09:00:19Z | 6,993,876 | 9 | 2011-08-09T09:15:59Z | [
"python",
"unit-testing",
"selenium",
"testcase",
"test-suite"
] | I need to make a big python suitecase consisted of other suitcases and testcase which I have already made to execute together.
How do I do this?
For example, here there is a suitecase (suiteFilter.py) which I want to add:
```
import testFilter1
import testFilter2
import unittest
import sys
def suite():
return u... | You could give some additional information like the structure of your program / test cases and suites. The way I do it is define a suite() for each module. So I have say for UserServiceTest module:
```
def suite():
"""
Gather all the tests from this module in a test suite.
"""
test_suite = unittest... |
How can I allow django admin to set a field to NULL? | 6,993,780 | 19 | 2011-08-09T09:07:19Z | 6,993,885 | 12 | 2011-08-09T09:16:48Z | [
"python",
"mysql",
"sql",
"django",
"django-admin"
] | I've set my Model field to `null=True`, which allows NULL in MySQL, but I can't seem to assign NULL to the field through Django Admin. I've tried also setting `blank=True`, but that just sets the field to an empty string. Following [this](http://stackoverflow.com/questions/4446652/django-how-to-set-a-field-to-null) did... | [This section in the docs](https://docs.djangoproject.com/en/dev/ref/models/fields/#null) makes it sound like you **can't** set a string-based field to `NULL` through the admin; it will use the empty string. This is just the way Django does it. It will work for other types of fields.
You'll either have to hack on the ... |
How can I allow django admin to set a field to NULL? | 6,993,780 | 19 | 2011-08-09T09:07:19Z | 6,999,101 | 18 | 2011-08-09T15:54:25Z | [
"python",
"mysql",
"sql",
"django",
"django-admin"
] | I've set my Model field to `null=True`, which allows NULL in MySQL, but I can't seem to assign NULL to the field through Django Admin. I've tried also setting `blank=True`, but that just sets the field to an empty string. Following [this](http://stackoverflow.com/questions/4446652/django-how-to-set-a-field-to-null) did... | Try to overwrite the save() method of the model, to check for empty values:
```
class MyModel(models.Model):
my_nullable_string = models.CharField(max_length=15, null=True, blank=True)
def save(self, *args, **kwargs):
if not self.my_nullable_string:
self.my_nullable_string = None
... |
testing for empty/null string in django | 6,995,066 | 2 | 2011-08-09T10:54:29Z | 15,236,738 | 7 | 2013-03-06T00:21:27Z | [
"python",
"django",
"django-models",
null
] | I have a charfield with the following:
```
myString = models.CharField(max_length=50,null=True,blank=True)
```
In many of my objects, this particular string is often left blank, when created through the django admin interface. In MySQL, the column is VARCHAR(50) with default=NULL.
Whatever test I try to do in my vie... | Some empty fields return empty strings while others return `None`. A nullable boolean field however, will return `False` when it has been set. This will not pass the test in Srikar's answer. A more robust solution is this:
```
if d in [None, '']:
# This field is empty.
``` |
How to create an object for a Django model with a many to many field? | 6,996,176 | 78 | 2011-08-09T12:26:46Z | 6,996,358 | 146 | 2011-08-09T12:43:42Z | [
"python",
"django",
"django-models",
"django-orm"
] | My model ->
```
class Sample(models.Model):
users = models.ManyToManyField(User)
```
I want to do this (save users, user1 and user2 in this model ) ->
```
user1 = User.objects.get(pk=1)
user2 = User.objects.get(pk=2)
sample_object = Sample( users = user1, users=user2 )
sample_object.save()
```
I know that's wr... | You cannot create m2m relations from unsaved objects. If you have the pks, try this:
```
sample_object = Sample()
sample_object.save()
sample_object.users.add(1,2)
```
**Update:** After reading the [saverio's answer](http://stackoverflow.com/questions/6996176/how-to-create-an-object-for-a-django-model-with-a-many-to-... |
How to create an object for a Django model with a many to many field? | 6,996,176 | 78 | 2011-08-09T12:26:46Z | 10,116,452 | 68 | 2012-04-12T02:02:13Z | [
"python",
"django",
"django-models",
"django-orm"
] | My model ->
```
class Sample(models.Model):
users = models.ManyToManyField(User)
```
I want to do this (save users, user1 and user2 in this model ) ->
```
user1 = User.objects.get(pk=1)
user2 = User.objects.get(pk=2)
sample_object = Sample( users = user1, users=user2 )
sample_object.save()
```
I know that's wr... | For future visitors, you can create an object and all of its m2m objects in **2 queries** using the new **[bulk\_create](https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.bulk_create)** in django 1.4. Note that this is only usable if you don't require *any* pre or post-processi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.