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 |
|---|---|---|---|---|---|---|---|---|---|
Django persistent database connection | 1,125,504 | 45 | 2009-07-14T13:47:00Z | 6,712,190 | 13 | 2011-07-15T19:26:17Z | [
"python",
"database",
"django",
"mod-wsgi",
"persistent"
] | I'm using django with apache and mod\_wsgi and PostgreSQL (all on same host), and I need to handle a lot of simple dynamic page requests (hundreds per second). I faced with problem that the bottleneck is that a django don't have persistent database connection and reconnects on each requests (that takes near 5ms).
While... | I created a small [Django patch](http://dumpz.org/67550/) that implements connection pooling of MySQL and PostgreSQL via sqlalchemy pooling.
This works perfectly on production of <http://grandcapital.net/> for a long period of time.
The patch was written after googling the topic a bit. |
Django persistent database connection | 1,125,504 | 45 | 2009-07-14T13:47:00Z | 19,438,241 | 17 | 2013-10-17T22:13:17Z | [
"python",
"database",
"django",
"mod-wsgi",
"persistent"
] | I'm using django with apache and mod\_wsgi and PostgreSQL (all on same host), and I need to handle a lot of simple dynamic page requests (hundreds per second). I faced with problem that the bottleneck is that a django don't have persistent database connection and reconnects on each requests (that takes near 5ms).
While... | Django **1.6** has added [persistent connections support (link to doc for django 1.9)](https://docs.djangoproject.com/en/1.9/ref/databases/#persistent-connections):
> Persistent connections avoid the overhead of re-establishing a
> connection to the database in each request. Theyâre controlled by the
> CONN\_MAX\_AG... |
Python: Persistent shell variables in subprocess | 1,126,116 | 8 | 2009-07-14T15:19:21Z | 1,126,137 | 13 | 2009-07-14T15:22:45Z | [
"python",
"shell",
"variables",
"subprocess",
"persistent"
] | I'm trying to execute a series of commands using Pythons subprocess module, however I need to set shell variables with export before running them. Of course the shell doesn't seem to be persistent so when I run a command later those shell variables are lost.
Is there any way to go about this? I could create a /bin/sh ... | `subprocess.Popen` takes an optional named argument `env` that's a dictionary to use as the subprocess's environment (what you're describing as "shell variables"). Prepare a dict as you need it (you may start with a copy of `os.environ` and alter that as you need) and pass it to all the `subprocess.Popen` calls you per... |
Is it possible to go into ipython from code? | 1,126,930 | 66 | 2009-07-14T17:45:59Z | 1,127,042 | 7 | 2009-07-14T18:08:30Z | [
"python",
"shell",
"debugging",
"ipython",
"pdb"
] | For my debugging needs, `pdb` is pretty good. However, it would be *much* cooler (and helpful) if I could go into `ipython`. Is this thing possible? | Normally, when I use ipython, I turn automatic debugging on with the "pdb" command inside it.
I then run my script with the "run myscript.py" command in the directory where my script is located.
If I get an exception, ipython stops the program inside the debugger. Check out the help command for the magic ipython comm... |
Is it possible to go into ipython from code? | 1,126,930 | 66 | 2009-07-14T17:45:59Z | 1,127,087 | 91 | 2009-07-14T18:18:53Z | [
"python",
"shell",
"debugging",
"ipython",
"pdb"
] | For my debugging needs, `pdb` is pretty good. However, it would be *much* cooler (and helpful) if I could go into `ipython`. Is this thing possible? | There is an `ipdb` project which embeds iPython into the standard pdb, so you can just do:
```
import ipdb; ipdb.set_trace()
```
It's installable via the usual `easy_install ipdb`.
`ipdb` is pretty short, so instead of easy\_installing you can also create a file `ipdb.py` somewhere on your Python path and paste the ... |
Is it possible to go into ipython from code? | 1,126,930 | 66 | 2009-07-14T17:45:59Z | 1,128,816 | 9 | 2009-07-15T00:40:39Z | [
"python",
"shell",
"debugging",
"ipython",
"pdb"
] | For my debugging needs, `pdb` is pretty good. However, it would be *much* cooler (and helpful) if I could go into `ipython`. Is this thing possible? | The equivalent of
```
import pdb; pdb.set_trace()
```
with IPython is something like:
```
from IPython.ipapi import make_session; make_session()
from IPython.Debugger import Pdb; Pdb().set_trace()
```
It's a bit verbose, but good to know if you don't have ipdb installed. The `make_session` call is required once to ... |
Is it possible to go into ipython from code? | 1,126,930 | 66 | 2009-07-14T17:45:59Z | 7,411,459 | 35 | 2011-09-14T05:00:59Z | [
"python",
"shell",
"debugging",
"ipython",
"pdb"
] | For my debugging needs, `pdb` is pretty good. However, it would be *much* cooler (and helpful) if I could go into `ipython`. Is this thing possible? | In IPython 0.11, you can embed IPython directly in your code like this
Your program might look like this
```
In [5]: cat > tmpf.py
a = 1
from IPython import embed
embed() # drop into an IPython session.
# Any variables you define or modify here
# will not affect program execution
c = 2
^D
```
This... |
Is it possible to go into ipython from code? | 1,126,930 | 66 | 2009-07-14T17:45:59Z | 12,528,973 | 9 | 2012-09-21T10:41:44Z | [
"python",
"shell",
"debugging",
"ipython",
"pdb"
] | For my debugging needs, `pdb` is pretty good. However, it would be *much* cooler (and helpful) if I could go into `ipython`. Is this thing possible? | If you're using a more modern version of IPython (> 0.10.2) you can use something like
```
from IPython.core.debugger import Pdb
Pdb().set_trace()
```
But it's probably better to just use ipdb |
Do I test a class that does nothing? | 1,127,626 | 4 | 2009-07-14T19:59:41Z | 1,127,637 | 12 | 2009-07-14T20:02:42Z | [
"python",
"unit-testing",
"testing",
"logging",
"polymorphism"
] | In my application, I have two classes: a logger that actually logs to the database and a dummy logger that does nothing (used when logging is disabled). Here is the entire DummyLog class:
```
class DummyLog(object):
def insert_master_log(self, spec_name, file_name, data_source,
environmen... | If you don't test, how will you really know it does nothing?
:)
Sorry - couldn't resist. Seriously - I would test because some day it might do more? |
Special chars in Python | 1,127,786 | 2 | 2009-07-14T20:21:58Z | 1,127,804 | 11 | 2009-07-14T20:24:50Z | [
"python",
"chars"
] | i have to use special chars in my python-application.
For example: Æ
I have information like this:
```
U+0183 LATIN SMALL LETTER B WITH TOPBAR
General Character Properties
In Unicode since: 1.1
Unicode category: Letter, Lowercase
Various Useful Representations
UTF-8: 0xC6 0x83
UTF-16: 0x0183
C octal escaped UTF-... | You should tell the interpreter which encoding you're using, because apparently on your system it defaults to ascii. See [PEP 263](http://www.python.org/dev/peps/pep-0263/). In your case, place the following at the top of your file:
```
# -*- coding: utf-8 -*-
```
Note that you don't have to write *exactly* that; PEP... |
wxPython, how do I fire events? | 1,128,074 | 2 | 2009-07-14T21:12:58Z | 1,128,992 | 9 | 2009-07-15T01:48:20Z | [
"python",
"events",
"wxpython"
] | I am making my own button class, subclass of a panel where I draw with a DC, and I need to fire wx.EVT\_BUTTON when my custom button is pressed. How do I do it? | The Wiki is pretty nice for reference. Andrea Gavana has a pretty complete recipe for building your own [custom controls](http://wiki.wxpython.org/CreatingCustomControls). The following is taken directly from there and extends what [FogleBird answered with](http://stackoverflow.com/questions/1128074/wxpython-how-do-i-f... |
How can I obtain the full AST in Python? | 1,128,234 | 4 | 2009-07-14T21:43:02Z | 1,128,283 | 8 | 2009-07-14T21:55:19Z | [
"python",
"abstract-syntax-tree"
] | I like the options offered by the **\_ast** module, it's really powerful. Is there a way of getting the full AST from it?
For example, if I get the AST of the following code :
```
import os
os.listdir(".")
```
by using :
```
ast = compile(source_string,"<string>","exec",_ast.PyCF_ONLY_AST)
```
the body of the **as... | You do get the whole tree this way -- all the way to the bottom -- but, it IS held as a tree, exactly... so at each level to get the children you have to explicitly visit the needed attributes. For example (i'm naming the `compile` result `cf` rather than `ast` because that would hide the standard library ast module --... |
Need some help with python string / slicing operations | 1,128,431 | 2 | 2009-07-14T22:31:09Z | 1,128,452 | 12 | 2009-07-14T22:35:41Z | [
"python",
"string",
"slice"
] | This is a very newbie question and i will probably get downvoted for it, but i quite honestly couldn't find the answer after at least an hour googling. I learned how to slice strings based on "exact locations" where you have to know exactly where the word ends. But i did not find any article that explained how do it on... | Why is split overkill?
```
verb, title, definition = myString.split (' ', 2)
``` |
How Do I Use A Decimal Number In A Django URL Pattern? | 1,128,693 | 5 | 2009-07-14T23:45:49Z | 1,128,700 | 13 | 2009-07-14T23:49:23Z | [
"python",
"regex",
"django",
"django-urls"
] | I'd like to use a number with a decimal point in a Django URL pattern but I'm not sure whether it's actually possible (I'm not a regex expert).
Here's what I want to use for URLs:
```
/item/value/0.01
/item/value/0.05
```
Those URLs would show items valued at $0.01 or $0.05. Sure, I could take the easy way out and p... | I don't know about Django specifically, but this should match the URL:
```
r"^/item/value/(\d+\.\d+)$"
``` |
How Do I Use A Decimal Number In A Django URL Pattern? | 1,128,693 | 5 | 2009-07-14T23:45:49Z | 1,128,740 | 12 | 2009-07-15T00:08:58Z | [
"python",
"regex",
"django",
"django-urls"
] | I'd like to use a number with a decimal point in a Django URL pattern but I'm not sure whether it's actually possible (I'm not a regex expert).
Here's what I want to use for URLs:
```
/item/value/0.01
/item/value/0.05
```
Those URLs would show items valued at $0.01 or $0.05. Sure, I could take the easy way out and p... | It can be something like
```
urlpatterns = patterns('',
(r'^item/value/(?P<value>\d+\.\d{2})/$', 'myapp.views.byvalue'),
... more urls
)
```
url should not start with slash.
in views you can have function:
```
def byvalue(request,value='0.99'):
try:
value = float(value)
except:
...
``` |
How can I make setuptools ignore subversion inventory? | 1,129,180 | 18 | 2009-07-15T03:00:19Z | 1,130,598 | 13 | 2009-07-15T10:27:16Z | [
"python",
"packaging",
"setuptools",
"egg"
] | When packaging a Python package with a setup.py that uses the setuptools:
```
from setuptools import setup
...
```
the source distribution created by:
```
python setup.py sdist
```
not only includes, as usual, the files specified in MANIFEST.in, but it also, gratuitously, includes all of the files that Subversion l... | I know you know much of this, Brandon, but I'll try to give as a complete answer as I can (although I'm no setuptools gury) for the benefit of others.
The problem here is that setuptools itself involves quite a lot of black magick, including using an entry point called setuptools.file\_finders where you can add plugin... |
How can I make setuptools ignore subversion inventory? | 1,129,180 | 18 | 2009-07-15T03:00:19Z | 1,959,924 | 8 | 2009-12-24T22:24:50Z | [
"python",
"packaging",
"setuptools",
"egg"
] | When packaging a Python package with a setup.py that uses the setuptools:
```
from setuptools import setup
...
```
the source distribution created by:
```
python setup.py sdist
```
not only includes, as usual, the files specified in MANIFEST.in, but it also, gratuitously, includes all of the files that Subversion l... | Create a MANIFEST.in file with:
```
recursive-exclude .
# other MANIFEST.in commands go here
# to explicitly include whatever files you want
```
See <http://docs.python.org/distutils/commandref.html#sdist-cmd> for the MANIFEST.in syntax. |
how do i filter an itertools chain() result? | 1,129,344 | 3 | 2009-07-15T04:00:25Z | 1,129,387 | 10 | 2009-07-15T04:15:09Z | [
"python",
"django",
"django-views",
"itertools"
] | in my views,
if i import an itertools module:
```
from itertools import chain
```
and i chain some objects with it:
```
franktags = Frank.objects.order_by('date_added').reverse().filter(topic__exact='art')
amytags = Amy.objects.order_by('date_added').reverse().filter(topic__exact='art')
timtags = Tim.objects.order... | ```
import operator
ourtags = sorted(ourtags, key=operator.attrgetter('date_added'))
``` |
most efficient data structure for a read-only list of strings (about 100,000) with fast prefix search | 1,130,992 | 6 | 2009-07-15T12:04:42Z | 1,131,014 | 15 | 2009-07-15T12:09:40Z | [
"python",
"data-structures",
"dictionary",
"lookup"
] | I'm writing an application that needs to read a list of strings from a file, save them in a data structure, and then look up those strings by prefixes. The list of strings is simply a list of words in a given language. For example, if the search function gets "stup" as a parameter, it should return ["stupid", "stupidit... | You want a trie.
<http://en.wikipedia.org/wiki/Trie>
I've used them in Scrabble and Boggle programs. They're perfect for the use case you described (fast prefix lookup).
Here's some sample code for building up a trie in Python. This is from a Boggle program I whipped together a few months ago. The rest is left as an... |
Get MD5 hash of big files in Python | 1,131,220 | 156 | 2009-07-15T12:52:07Z | 1,131,238 | 130 | 2009-07-15T12:55:07Z | [
"python",
"md5",
"hashlib"
] | I have used hashlib (which replaces md5 in Python 2.6/3.0) and it worked fine if I opened a file and put its content in [`hashlib.md5()`](https://docs.python.org/2/library/hashlib.html) function.
The problem is with very big files that their sizes could exceed RAM size.
How to get the MD5 hash of a file without loadi... | Break the file into 128-byte chunks and feed them to MD5 consecutively using `update()`.
This takes advantage of the fact that MD5 has 128-byte digest blocks. Basically, when MD5 `digest()`s the file, this is exactly what it is doing.
If you make sure you free the memory on each iteration (i.e. not read the entire fi... |
Get MD5 hash of big files in Python | 1,131,220 | 156 | 2009-07-15T12:52:07Z | 1,131,255 | 188 | 2009-07-15T12:59:25Z | [
"python",
"md5",
"hashlib"
] | I have used hashlib (which replaces md5 in Python 2.6/3.0) and it worked fine if I opened a file and put its content in [`hashlib.md5()`](https://docs.python.org/2/library/hashlib.html) function.
The problem is with very big files that their sizes could exceed RAM size.
How to get the MD5 hash of a file without loadi... | You need to read the file in chunks of suitable size:
```
def md5_for_file(f, block_size=2**20):
md5 = hashlib.md5()
while True:
data = f.read(block_size)
if not data:
break
md5.update(data)
return md5.digest()
```
NOTE: Make sure you open your file with the 'rb' to the... |
Get MD5 hash of big files in Python | 1,131,220 | 156 | 2009-07-15T12:52:07Z | 4,213,255 | 90 | 2010-11-18T09:24:09Z | [
"python",
"md5",
"hashlib"
] | I have used hashlib (which replaces md5 in Python 2.6/3.0) and it worked fine if I opened a file and put its content in [`hashlib.md5()`](https://docs.python.org/2/library/hashlib.html) function.
The problem is with very big files that their sizes could exceed RAM size.
How to get the MD5 hash of a file without loadi... | if you care about more pythonic (no 'while True') way of reading the file check this code:
```
import hashlib
def checksum_md5(filename):
md5 = hashlib.md5()
with open(filename,'rb') as f:
for chunk in iter(lambda: f.read(8192), b''):
md5.update(chunk)
return md5.digest()
```
Note t... |
Get MD5 hash of big files in Python | 1,131,220 | 156 | 2009-07-15T12:52:07Z | 11,143,944 | 45 | 2012-06-21T17:54:23Z | [
"python",
"md5",
"hashlib"
] | I have used hashlib (which replaces md5 in Python 2.6/3.0) and it worked fine if I opened a file and put its content in [`hashlib.md5()`](https://docs.python.org/2/library/hashlib.html) function.
The problem is with very big files that their sizes could exceed RAM size.
How to get the MD5 hash of a file without loadi... | Here's my version of @Piotr Czapla's method:
```
def md5sum(filename):
md5 = hashlib.md5()
with open(filename, 'rb') as f:
for chunk in iter(lambda: f.read(128 * md5.block_size), b''):
md5.update(chunk)
return md5.hexdigest()
``` |
Get MD5 hash of big files in Python | 1,131,220 | 156 | 2009-07-15T12:52:07Z | 17,782,753 | 24 | 2013-07-22T08:14:48Z | [
"python",
"md5",
"hashlib"
] | I have used hashlib (which replaces md5 in Python 2.6/3.0) and it worked fine if I opened a file and put its content in [`hashlib.md5()`](https://docs.python.org/2/library/hashlib.html) function.
The problem is with very big files that their sizes could exceed RAM size.
How to get the MD5 hash of a file without loadi... | Using multiple comment/answers in this thread, here is my solution :
```
import hashlib
def md5_for_file(path, block_size=256*128, hr=False):
'''
Block size directly depends on the block size of your filesystem
to avoid performances issues
Here I have blocks of 4096 octets (Default NTFS)
'''
md... |
Form validation in django | 1,131,232 | 8 | 2009-07-15T12:54:46Z | 1,131,248 | 15 | 2009-07-15T12:58:10Z | [
"python",
"django",
"django-forms"
] | I just started to use django. I came across forms and I need to know which one is the better way to validate a forms. Would it be using django forms or should we use javascript or some client side scripting language to do it? | You should ALWAYS validate your form on the server side, client side validation is but a convenience for the user only.
That being said, Django forms has a variable form.errors which shows if certain form fields were incorrect.
{{ form.name\_of\_field.errors }} can give you each individual error of each field that's ... |
Are Generators Threadsafe? | 1,131,430 | 26 | 2009-07-15T13:32:05Z | 1,131,458 | 40 | 2009-07-15T13:37:59Z | [
"python",
"multithreading",
"thread-safety",
"generator"
] | I have a multithreaded program where I create a generator function and then pass it to new threads. I want it to be shared/global in nature so each thread can get the next value from the generator.
Is it safe to use a generator like this, or will I run into problems/conditions accessing the shared generator from multi... | It's not thread-safe; simultaneous calls may interleave, and mess with the local variables.
The common approach is to use the master-slave pattern (now called farmer-worker pattern in PC). Make a third thread which generates data, and add a Queue between the master and the slaves, where slaves will read from the queue... |
Are Generators Threadsafe? | 1,131,430 | 26 | 2009-07-15T13:32:05Z | 1,133,605 | 33 | 2009-07-15T19:55:32Z | [
"python",
"multithreading",
"thread-safety",
"generator"
] | I have a multithreaded program where I create a generator function and then pass it to new threads. I want it to be shared/global in nature so each thread can get the next value from the generator.
Is it safe to use a generator like this, or will I run into problems/conditions accessing the shared generator from multi... | Edited to add benchmark below.
You can wrap a generator with a lock. For example,
```
import threading
class LockedIterator(object):
def __init__(self, it):
self.lock = threading.Lock()
self.it = it.__iter__()
def __iter__(self): return self
def next(self):
self.lock.acquire()
... |
Eliminating multiple inheritance | 1,131,599 | 9 | 2009-07-15T14:01:24Z | 1,131,655 | 8 | 2009-07-15T14:12:30Z | [
"python",
"oop",
"multiple-inheritance"
] | I have the following problem and I'm wondering if there's a nice way to model these objects without using multiple inheritance. If it makes any difference, I am using Python.
Students need contact information plus student information. Adults need contact information plus billing information. Students can be adult stud... | What you have is an example of Role -- it's a common trap to model Role by inheritance, but Roles can change, and changing an object's inheritance structure (even in languages where it's possible, like Python) is not recommended. Children grow and become adults, and some adults will also be parents of children students... |
"Least Astonishment" and the Mutable Default Argument | 1,132,941 | 1,504 | 2009-07-15T18:00:37Z | 1,133,013 | 166 | 2009-07-15T18:11:26Z | [
"python",
"language-design",
"least-astonishment"
] | Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:
```
def foo(a=[]):
a.append(5)
return a
```
Python novices would expect this function to always return a list with only one element: `[5]`. The result is instead very different, and very astonishing (for a nov... | Suppose you have the following code
```
fruits = ("apples", "bananas", "loganberries")
def eat(food=fruits):
...
```
When I see the declaration of eat, the least astonishing thing is to think that if the first parameter is not given, that it will be equal to the tuple `("apples", "bananas", "loganberries")`
How... |
"Least Astonishment" and the Mutable Default Argument | 1,132,941 | 1,504 | 2009-07-15T18:00:37Z | 1,133,255 | 53 | 2009-07-15T18:54:45Z | [
"python",
"language-design",
"least-astonishment"
] | Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:
```
def foo(a=[]):
a.append(5)
return a
```
Python novices would expect this function to always return a list with only one element: `[5]`. The result is instead very different, and very astonishing (for a nov... | Well, the reason is quite simply that bindings are done when code is executed, and the function definition is executed, well... when the functions is defined.
Compare this:
```
class BananaBunch:
bananas = []
def addBanana(self, banana):
self.bananas.append(banana)
```
This code suffers from the exa... |
"Least Astonishment" and the Mutable Default Argument | 1,132,941 | 1,504 | 2009-07-15T18:00:37Z | 1,133,375 | 29 | 2009-07-15T19:15:25Z | [
"python",
"language-design",
"least-astonishment"
] | Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:
```
def foo(a=[]):
a.append(5)
return a
```
Python novices would expect this function to always return a list with only one element: `[5]`. The result is instead very different, and very astonishing (for a nov... | This behavior is easy explained by:
1. function (class etc.) declaration is executed only once, creating all default value objects
2. everything is passed by reference
So:
```
def x(a=0, b=[], c=[], d=0):
a = a + 1
b = b + [1]
c.append(1)
print a, b, c
```
1. a doesn't change - every assignment call... |
"Least Astonishment" and the Mutable Default Argument | 1,132,941 | 1,504 | 2009-07-15T18:00:37Z | 1,133,737 | 21 | 2009-07-15T20:18:14Z | [
"python",
"language-design",
"least-astonishment"
] | Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:
```
def foo(a=[]):
a.append(5)
return a
```
Python novices would expect this function to always return a list with only one element: `[5]`. The result is instead very different, and very astonishing (for a nov... | What you're asking is why this:
```
def func(a=[], b = 2):
pass
```
isn't internally equivalent to this:
```
def func(a=None, b = None):
a_default = lambda: []
b_default = lambda: 2
def actual_func(a=None, b=None):
if a is None: a = a_default()
if b is None: b = b_default()
return... |
"Least Astonishment" and the Mutable Default Argument | 1,132,941 | 1,504 | 2009-07-15T18:00:37Z | 1,134,613 | 19 | 2009-07-15T23:18:36Z | [
"python",
"language-design",
"least-astonishment"
] | Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:
```
def foo(a=[]):
a.append(5)
return a
```
Python novices would expect this function to always return a list with only one element: `[5]`. The result is instead very different, and very astonishing (for a nov... | It's a performance optimization. As a result of this functionality, which of these two function calls do you think is faster?
```
def print_tuple(some_tuple=(1,2,3)):
print some_tuple
print_tuple() #1
print_tuple((1,2,3)) #2
```
I'll give you a hint. Here's the disassembly (see <http://docs.python.org/lib... |
"Least Astonishment" and the Mutable Default Argument | 1,132,941 | 1,504 | 2009-07-15T18:00:37Z | 1,134,623 | 68 | 2009-07-15T23:21:09Z | [
"python",
"language-design",
"least-astonishment"
] | Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:
```
def foo(a=[]):
a.append(5)
return a
```
Python novices would expect this function to always return a list with only one element: `[5]`. The result is instead very different, and very astonishing (for a nov... | I know nothing about the Python interpreter inner workings (and I'm not an expert in compilers and interpreters either) so don't blame me if I propose anything unsensible or impossible.
Provided that python objects **are mutable** I think that this should be taken into account when designing the default arguments stuf... |
"Least Astonishment" and the Mutable Default Argument | 1,132,941 | 1,504 | 2009-07-15T18:00:37Z | 1,136,611 | 35 | 2009-07-16T10:05:09Z | [
"python",
"language-design",
"least-astonishment"
] | Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:
```
def foo(a=[]):
a.append(5)
return a
```
Python novices would expect this function to always return a list with only one element: `[5]`. The result is instead very different, and very astonishing (for a nov... | I used to think that creating the objects at runtime would be the better approach. I'm less certain now, since you do lose some useful features, though it may be worth it regardless simply to prevent newbie confusion. The disadvantages of doing so are:
**1. Performance**
```
def foo(arg=something_expensive_to_compute... |
"Least Astonishment" and the Mutable Default Argument | 1,132,941 | 1,504 | 2009-07-15T18:00:37Z | 1,137,164 | 12 | 2009-07-16T12:19:23Z | [
"python",
"language-design",
"least-astonishment"
] | Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:
```
def foo(a=[]):
a.append(5)
return a
```
Python novices would expect this function to always return a list with only one element: `[5]`. The result is instead very different, and very astonishing (for a nov... | the shortest answer would probably be "definition is execution", therefore the whole argument makes no strict sense. as a more contrived example, you may cite this:
```
def a(): return []
def b(x=a()):
print x
```
hopefully it's enough to show that not executing the default argument expressions at the execution ... |
"Least Astonishment" and the Mutable Default Argument | 1,132,941 | 1,504 | 2009-07-15T18:00:37Z | 1,139,730 | 7 | 2009-07-16T19:17:59Z | [
"python",
"language-design",
"least-astonishment"
] | Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:
```
def foo(a=[]):
a.append(5)
return a
```
Python novices would expect this function to always return a list with only one element: `[5]`. The result is instead very different, and very astonishing (for a nov... | It may be true that:
1. Someone is using every language/library feature, and
2. Switching the behavior here would be ill-advised, but
it is entirely consistent to hold to both of the features above and still make another point:
1. It is a confusing feature and it is unfortunate in Python.
The other answers, or at l... |
"Least Astonishment" and the Mutable Default Argument | 1,132,941 | 1,504 | 2009-07-15T18:00:37Z | 1,145,781 | 1,037 | 2009-07-17T21:29:39Z | [
"python",
"language-design",
"least-astonishment"
] | Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:
```
def foo(a=[]):
a.append(5)
return a
```
Python novices would expect this function to always return a list with only one element: `[5]`. The result is instead very different, and very astonishing (for a nov... | Actually, this is not a design flaw, and it is not because of internals, or performance.
It comes simply from the fact that functions in Python are first-class objects, and not only a piece of code.
As soon as you get to think into this way, then it completely makes sense: a function is an object being evaluated on ... |
"Least Astonishment" and the Mutable Default Argument | 1,132,941 | 1,504 | 2009-07-15T18:00:37Z | 6,092,808 | 20 | 2011-05-23T04:24:30Z | [
"python",
"language-design",
"least-astonishment"
] | Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:
```
def foo(a=[]):
a.append(5)
return a
```
Python novices would expect this function to always return a list with only one element: `[5]`. The result is instead very different, and very astonishing (for a nov... | This actually has nothing to do with default values, other than that it often comes up as an unexpected behaviour when you write functions with mutable default values.
```
>>> def foo(a):
a.append(5)
print a
>>> a = [5]
>>> foo(a)
[5, 5]
>>> foo(a)
[5, 5, 5]
>>> foo(a)
[5, 5, 5, 5]
>>> foo(a)
[5, 5, 5, 5, 5]... |
"Least Astonishment" and the Mutable Default Argument | 1,132,941 | 1,504 | 2009-07-15T18:00:37Z | 9,791,799 | 12 | 2012-03-20T17:22:11Z | [
"python",
"language-design",
"least-astonishment"
] | Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:
```
def foo(a=[]):
a.append(5)
return a
```
Python novices would expect this function to always return a list with only one element: `[5]`. The result is instead very different, and very astonishing (for a nov... | The solutions here are:
1. Use `None` as your default value (or a nonce `object`), and switch on that to create your values at runtime; or
2. Use a `lambda` as your default parameter, and call it within a try block to get the default value (this is the sort of thing that lambda abstraction is for).
The second option ... |
"Least Astonishment" and the Mutable Default Argument | 1,132,941 | 1,504 | 2009-07-15T18:00:37Z | 10,304,917 | 14 | 2012-04-24T19:43:13Z | [
"python",
"language-design",
"least-astonishment"
] | Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:
```
def foo(a=[]):
a.append(5)
return a
```
Python novices would expect this function to always return a list with only one element: `[5]`. The result is instead very different, and very astonishing (for a nov... | This behavior is not surprising if you take the following into consideration:
1. The behavior of read-only class attributes upon assignment attempts, and that
2. Functions are objects (explained well in the accepted answer).
The role of **(2)** has been covered extensively in this thread. **(1)** is likely the astoni... |
"Least Astonishment" and the Mutable Default Argument | 1,132,941 | 1,504 | 2009-07-15T18:00:37Z | 11,416,002 | 130 | 2012-07-10T14:50:42Z | [
"python",
"language-design",
"least-astonishment"
] | Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:
```
def foo(a=[]):
a.append(5)
return a
```
Python novices would expect this function to always return a list with only one element: `[5]`. The result is instead very different, and very astonishing (for a nov... | AFAICS no one has yet posted the relevant part of the [documentation](http://docs.python.org/reference/compound_stmts.html#function-definitions):
> **Default parameter values are evaluated when the function definition is executed.** This means that the expression is evaluated once, when the function is defined, and th... |
"Least Astonishment" and the Mutable Default Argument | 1,132,941 | 1,504 | 2009-07-15T18:00:37Z | 13,518,071 | 20 | 2012-11-22T18:09:04Z | [
"python",
"language-design",
"least-astonishment"
] | Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:
```
def foo(a=[]):
a.append(5)
return a
```
Python novices would expect this function to always return a list with only one element: `[5]`. The result is instead very different, and very astonishing (for a nov... | 1) The so-called problem of "Mutable Default Argument" is in general a special example demonstrating that:
"All functions with this problem **suffer also from similar side effect problem on the actual parameter**,"
That is against the rules of functional programming, usually undesiderable and should be fixed both t... |
"Least Astonishment" and the Mutable Default Argument | 1,132,941 | 1,504 | 2009-07-15T18:00:37Z | 14,336,301 | 10 | 2013-01-15T11:02:03Z | [
"python",
"language-design",
"least-astonishment"
] | Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:
```
def foo(a=[]):
a.append(5)
return a
```
Python novices would expect this function to always return a list with only one element: `[5]`. The result is instead very different, and very astonishing (for a nov... | You can get round this by replacing the object (and therefore the tie with the scope):
```
def foo(a=[]):
a = list(a)
a.append(5)
return a
```
Ugly, but it works. |
"Least Astonishment" and the Mutable Default Argument | 1,132,941 | 1,504 | 2009-07-15T18:00:37Z | 15,133,978 | 11 | 2013-02-28T11:10:16Z | [
"python",
"language-design",
"least-astonishment"
] | Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:
```
def foo(a=[]):
a.append(5)
return a
```
Python novices would expect this function to always return a list with only one element: `[5]`. The result is instead very different, and very astonishing (for a nov... | A simple workaround using None
```
>>> def bar(b, data=None):
... data = data or []
... data.append(b)
... return data
...
>>> bar(3)
[3]
>>> bar(3)
[3]
>>> bar(3)
[3]
>>> bar(3, [34])
[34, 3]
>>> bar(3, [34])
[34, 3]
``` |
"Least Astonishment" and the Mutable Default Argument | 1,132,941 | 1,504 | 2009-07-15T18:00:37Z | 25,797,695 | 10 | 2014-09-11T22:05:43Z | [
"python",
"language-design",
"least-astonishment"
] | Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:
```
def foo(a=[]):
a.append(5)
return a
```
Python novices would expect this function to always return a list with only one element: `[5]`. The result is instead very different, and very astonishing (for a nov... | When we do this:
```
def foo(a=[]):
...
```
... we assign the argument `a` to an *unnamed* list, if the caller does not pass the value of a.
To make things simpler for this discussion, let's temporarily give the unnamed list a name. How about `pavlo` ?
```
def foo(a=pavlo):
...
```
At any time, if the calle... |
"Least Astonishment" and the Mutable Default Argument | 1,132,941 | 1,504 | 2009-07-15T18:00:37Z | 28,354,667 | 11 | 2015-02-05T21:44:51Z | [
"python",
"language-design",
"least-astonishment"
] | Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:
```
def foo(a=[]):
a.append(5)
return a
```
Python novices would expect this function to always return a list with only one element: `[5]`. The result is instead very different, and very astonishing (for a nov... | I sometimes exploit this behavior as an alternative to the following pattern:
```
singleton = None
def use_singleton():
global singleton
if singleton is None:
singleton = _make_singleton()
return singleton.use_me()
```
If `singleton` is only used by `use_singleton`, I like the following pattern... |
"Least Astonishment" and the Mutable Default Argument | 1,132,941 | 1,504 | 2009-07-15T18:00:37Z | 29,290,566 | 15 | 2015-03-26T23:14:01Z | [
"python",
"language-design",
"least-astonishment"
] | Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:
```
def foo(a=[]):
a.append(5)
return a
```
Python novices would expect this function to always return a list with only one element: `[5]`. The result is instead very different, and very astonishing (for a nov... | Already busy topic, but from what I read here, the following helped me realizing how it's working internally:
```
def bar(a=[]):
print id(a)
a = a + [1]
print id(a)
return a
>>> bar()
4484370232
4484524224
[1]
>>> bar()
4484370232
4484524152
[1]
>>> bar()
4484370232 # Never change, this is 'class ... |
"Least Astonishment" and the Mutable Default Argument | 1,132,941 | 1,504 | 2009-07-15T18:00:37Z | 29,344,819 | 26 | 2015-03-30T11:18:25Z | [
"python",
"language-design",
"least-astonishment"
] | Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:
```
def foo(a=[]):
a.append(5)
return a
```
Python novices would expect this function to always return a list with only one element: `[5]`. The result is instead very different, and very astonishing (for a nov... | # 5 points in defense of Python
1. **Simplicity**: The behavior is simple in the following sense:
Most people fall into this trap only once, not several times.
2. **Consistency**: Python *always* passes objects, not names.
The default parameter is, obviously, part of the function
heading (not the function bod... |
"Least Astonishment" and the Mutable Default Argument | 1,132,941 | 1,504 | 2009-07-15T18:00:37Z | 32,535,706 | 7 | 2015-09-12T06:00:51Z | [
"python",
"language-design",
"least-astonishment"
] | Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:
```
def foo(a=[]):
a.append(5)
return a
```
Python novices would expect this function to always return a list with only one element: `[5]`. The result is instead very different, and very astonishing (for a nov... | I am going to demonstrate an alternative structure to pass a default list value to a function (it works equally well with dictionaries).
As others have extensively commented, the list parameter is bound to the function when it is defined as opposed to when it is executed. Because lists and dictionaries are mutable, an... |
"Least Astonishment" and the Mutable Default Argument | 1,132,941 | 1,504 | 2009-07-15T18:00:37Z | 34,172,768 | 14 | 2015-12-09T07:13:28Z | [
"python",
"language-design",
"least-astonishment"
] | Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:
```
def foo(a=[]):
a.append(5)
return a
```
Python novices would expect this function to always return a list with only one element: `[5]`. The result is instead very different, and very astonishing (for a nov... | ## Why don't you introspect?
I'm actually *really* surprised no one has performed the insightfull introspection offered by Python (`2` and `3` certainly apply) on callables.
Given a simple little function `func` defined as:
```
>>> def func(a = []):
... a.append(5)
```
When Python encounters it, the first thing ... |
DateTime in python extracting different bits and pieces | 1,133,147 | 34 | 2009-07-15T18:37:27Z | 1,133,171 | 10 | 2009-07-15T18:41:17Z | [
"python",
"datetime"
] | I want to extract year from current date using python.
Do something like:
```
DateTime a = DateTime.Now()
a.Year # (this is in C#)
``` | ```
import datetime
a = datetime.datetime.today().year
```
or even (as Lennart suggested)
```
a = datetime.datetime.now().year
```
or even
```
a = datetime.date.today().year
``` |
DateTime in python extracting different bits and pieces | 1,133,147 | 34 | 2009-07-15T18:37:27Z | 1,133,190 | 43 | 2009-07-15T18:44:31Z | [
"python",
"datetime"
] | I want to extract year from current date using python.
Do something like:
```
DateTime a = DateTime.Now()
a.Year # (this is in C#)
``` | It's in fact almost the same in Python.. :-)
```
import datetime
year = datetime.date.today().year
```
Of course, date doesn't have a time associated, so if you care about that too, you can do the same with a complete datetime object:
```
import datetime
year = datetime.datetime.today().year
```
(Obviously no diffe... |
DateTime in python extracting different bits and pieces | 1,133,147 | 34 | 2009-07-15T18:37:27Z | 1,133,246 | 9 | 2009-07-15T18:52:54Z | [
"python",
"datetime"
] | I want to extract year from current date using python.
Do something like:
```
DateTime a = DateTime.Now()
a.Year # (this is in C#)
``` | The other answers to this question seem to hit it spot on. Now how would you figure this out for yourself without stack overflow? Check out [IPython](http://ipython.scipy.org/moin/), an interactive Python shell that has tab auto-complete.
```
> ipython
import Python 2.5 (r25:51908, Nov 6 2007, 16:54:01)
Type "copyrig... |
Adding tuples to produce a tuple with a subtotal per 'column' | 1,133,286 | 2 | 2009-07-15T19:00:35Z | 1,133,316 | 7 | 2009-07-15T19:06:07Z | [
"python",
"tuples"
] | What is the most pythonic way of adding the values of two or more tuples to produce a total for each 'column'?
Eg:
```
>>> a = (10, 20)
>>> b = (40, 50)
>>> c = (1, 3)
>>> ???
(51, 73)
```
I've so far considered the following:
```
def sumtuples(*tuples):
return (sum(v1 for v1,_ in tuples), sum(v2 for _,v2 in tu... | I guess you could use `reduce`, though it's debatable whether that's pythonic ..
```
In [13]: reduce(lambda s, t: (s[0]+t[0], s[1]+t[1]), [a, b, c], (0, 0))
Out[13]: (51, 73)
```
Here's another way using `map` and `zip`:
```
In [14]: map(sum, zip(a, b, c))
Out[14]: [51, 73]
```
or, if you're passing your collection... |
PHP equivalent to Python's yield operator | 1,133,371 | 19 | 2009-07-15T19:15:19Z | 1,133,448 | 12 | 2009-07-15T19:25:29Z | [
"php",
"python",
"lazy-evaluation"
] | In Python (and others), you can incrementally process large volumes of data by using the 'yield' operator in a function. What would be the similar way to do so in PHP?
For example, lets say in Python, if I wanted to read a potentially very large file, I could work on each line one at a time like so (this example is co... | PHP has a direct equivalent called [generators](http://se2.php.net/manual/en/language.generators.overview.php).
**Old (pre php 5.5 answer):**
Unfortunately, there isn't a language equivalent. The easiest way is to either to what you're already doing, or to create a object that uses instance variables to maintain stat... |
PHP equivalent to Python's yield operator | 1,133,371 | 19 | 2009-07-15T19:15:19Z | 1,133,863 | 11 | 2009-07-15T20:34:15Z | [
"php",
"python",
"lazy-evaluation"
] | In Python (and others), you can incrementally process large volumes of data by using the 'yield' operator in a function. What would be the similar way to do so in PHP?
For example, lets say in Python, if I wanted to read a potentially very large file, I could work on each line one at a time like so (this example is co... | I prototype everything in Python before implementing in any other languages, including PHP. I ended up using callbacks to achieve what I would with the `yield`.
```
function doSomething($callback)
{
foreach ($something as $someOtherThing) {
// do some computations that generates $data
call_user_f... |
PHP equivalent to Python's yield operator | 1,133,371 | 19 | 2009-07-15T19:15:19Z | 11,495,404 | 18 | 2012-07-15T20:34:16Z | [
"php",
"python",
"lazy-evaluation"
] | In Python (and others), you can incrementally process large volumes of data by using the 'yield' operator in a function. What would be the similar way to do so in PHP?
For example, lets say in Python, if I wanted to read a potentially very large file, I could work on each line one at a time like so (this example is co... | There is a rfc at <https://wiki.php.net/rfc/generators> adressing just that, which might be included in PHP 5.5.
In the mean time, check out this proof-of-concept of a poor mans "generator function" implemented in userland.
```
namespace Functional;
error_reporting(E_ALL|E_STRICT);
const BEFORE = 1;
const NEXT = 2;... |
Code lines of code in a Django Project | 1,133,391 | 9 | 2009-07-15T19:17:15Z | 1,133,411 | 14 | 2009-07-15T19:20:47Z | [
"python",
"django"
] | Is there an easy way to count the lines of code you have written for your django project?
Edit: The shell stuff is cool, but how about on Windows? | Yep:
```
shell]$ find /my/source -name "*.py" -type f -exec cat {} + | wc -l
```
Job's a good 'un. |
How can I retrieve last x elements in Django | 1,133,715 | 2 | 2009-07-15T20:15:07Z | 1,133,736 | 8 | 2009-07-15T20:18:06Z | [
"python",
"django",
"list"
] | I am trying to retrieve the latest 5 posts (by post time)
In the views.py, if I try `blog_post_list = blogPosts.objects.all()[:5]` It retreives the first 5 elements of the blogPosts objects, how can I reverse this to retreive the latest ones?
Cheers | ```
blog_post_list = blogPosts.objects.all().reverse()[:5]
# OR
blog_post_list = blogPosts.objects.all().order_by('-DEFAULT_ORDER_KEY')[:5]
```
I prefer the first. |
How accurate is python's time.sleep()? | 1,133,857 | 48 | 2009-07-15T20:33:42Z | 1,133,879 | 17 | 2009-07-15T20:37:01Z | [
"python",
"datetime",
"time",
"sleep"
] | I can give it floating point numbers, such as
```
time.sleep(0.5)
```
but how accurate is it? If i give it
```
time.sleep(0.05)
```
will it really sleep about 50 ms? | From the [documentation](http://docs.python.org/3.0/library/time.html):
> On the other hand, the precision of
> `time()` and `sleep()` is better than
> their Unix equivalents: times are
> expressed as floating point numbers,
> `time()` returns the most accurate time
> available (using Unix `gettimeofday`
> where avail... |
How accurate is python's time.sleep()? | 1,133,857 | 48 | 2009-07-15T20:33:42Z | 1,133,888 | 45 | 2009-07-15T20:38:44Z | [
"python",
"datetime",
"time",
"sleep"
] | I can give it floating point numbers, such as
```
time.sleep(0.5)
```
but how accurate is it? If i give it
```
time.sleep(0.05)
```
will it really sleep about 50 ms? | The accuracy of the time.sleep function depends on the accuracy of your underlying OS's sleep accuracy. For non-realtime OS's like a stock Windows the smallest interval you can sleep for is about 10-13ms. I have seen accurate sleeps within several milliseconds of that time when above the minimum 10-13ms.
Update:
Like ... |
How accurate is python's time.sleep()? | 1,133,857 | 48 | 2009-07-15T20:33:42Z | 1,133,984 | 12 | 2009-07-15T20:52:09Z | [
"python",
"datetime",
"time",
"sleep"
] | I can give it floating point numbers, such as
```
time.sleep(0.5)
```
but how accurate is it? If i give it
```
time.sleep(0.05)
```
will it really sleep about 50 ms? | Why don't you find out:
```
from datetime import datetime
import time
def check_sleep(amount):
start = datetime.now()
time.sleep(amount)
end = datetime.now()
delta = end-start
return delta.seconds + delta.microseconds/1000000.
error = sum(abs(check_sleep(0.050)-0.050) for i in xrange(100))*10
pri... |
How accurate is python's time.sleep()? | 1,133,857 | 48 | 2009-07-15T20:33:42Z | 15,967,564 | 29 | 2013-04-12T09:23:01Z | [
"python",
"datetime",
"time",
"sleep"
] | I can give it floating point numbers, such as
```
time.sleep(0.5)
```
but how accurate is it? If i give it
```
time.sleep(0.05)
```
will it really sleep about 50 ms? | People are quite right about the differences between operating systems and kernels, but I do not see any granularity in Ubuntu and I see a 1 ms granularity in MS7. Suggesting a different implementation of time.sleep, not just a different tick rate. Closer inspection suggests a 1μs granularity in Ubuntu by the way, but... |
How accurate is python's time.sleep()? | 1,133,857 | 48 | 2009-07-15T20:33:42Z | 30,672,412 | 7 | 2015-06-05T17:25:35Z | [
"python",
"datetime",
"time",
"sleep"
] | I can give it floating point numbers, such as
```
time.sleep(0.5)
```
but how accurate is it? If i give it
```
time.sleep(0.05)
```
will it really sleep about 50 ms? | Here's my follow-up to Wilbert's answer: the same for Mac OS X Yosemite, since it's not been mentioned much yet.
Looks like a lot of the time it sleeps about 1.25 times the time that you request and sometimes sleeps between 1 and 1.25 times the ... |
Keep ConfigParser output files sorted | 1,134,071 | 6 | 2009-07-15T21:03:18Z | 1,134,533 | 8 | 2009-07-15T22:45:03Z | [
"python",
"configuration",
"configparser"
] | I've noticed with my source control that the content of the output files generated with ConfigParser is never in the same order. Sometimes sections will change place or options inside sections even without any modifications to the values.
Is there a way to keep things sorted in the configuration file so that I don't h... | Looks like this was fixed in [Python 3.1](http://docs.python.org/dev/py3k/whatsnew/3.1.html) and 2.7 with the introduction of ordered dictionaries:
> The standard library now supports use
> of ordered dictionaries in several
> modules. The configparser module uses
> them by default. This lets
> configuration files be ... |
Python Exception handling | 1,134,607 | 15 | 2009-07-15T23:15:06Z | 1,134,614 | 18 | 2009-07-15T23:18:53Z | [
"python",
"exception",
"errno",
"ioerror"
] | C has perror and errno, which print and store the last error encountered. This is convenient when doing file io as I do not have to fstat() every file that fails as an argument to fopen() to present the user with a reason why the call failed.
I was wondering what is the proper way to grab errno when gracefully handlin... | The Exception has a errno attribute:
```
try:
fp = open("nother")
except IOError, e:
print e.errno
print e
``` |
Python Exception handling | 1,134,607 | 15 | 2009-07-15T23:15:06Z | 1,134,616 | 22 | 2009-07-15T23:19:32Z | [
"python",
"exception",
"errno",
"ioerror"
] | C has perror and errno, which print and store the last error encountered. This is convenient when doing file io as I do not have to fstat() every file that fails as an argument to fopen() to present the user with a reason why the call failed.
I was wondering what is the proper way to grab errno when gracefully handlin... | Here's how you can do it. Also see the `errno` module and `os.strerror` function for some utilities.
```
import os, errno
try:
f = open('asdfasdf', 'r')
except IOError as ioex:
print 'errno:', ioex.errno
print 'err code:', errno.errorcode[ioex.errno]
print 'err message:', os.strerror(ioex.errno)
```
... |
Python Exception handling | 1,134,607 | 15 | 2009-07-15T23:15:06Z | 1,134,622 | 18 | 2009-07-15T23:20:51Z | [
"python",
"exception",
"errno",
"ioerror"
] | C has perror and errno, which print and store the last error encountered. This is convenient when doing file io as I do not have to fstat() every file that fails as an argument to fopen() to present the user with a reason why the call failed.
I was wondering what is the proper way to grab errno when gracefully handlin... | ```
try:
fp = open("nothere")
except IOError as err:
print err.errno
print err.strerror
``` |
Django required field in model form | 1,134,667 | 51 | 2009-07-15T23:37:16Z | 1,134,693 | 10 | 2009-07-15T23:45:10Z | [
"python",
"django",
"forms",
"model",
"widget"
] | I have a form where a couple of fields are coming out as required when I don't want them too. Here is the form from models.py
```
class CircuitForm(ModelForm):
class Meta:
model = Circuit
exclude = ('lastPaged',)
def __init__(self, *args, **kwargs):
super(CircuitForm, self).__init__(*args, **kwa... | > If the model field has blank=True, then required is set to False on the form field. Otherwise, required=True
Says so here: <http://docs.djangoproject.com/en/dev/topics/forms/modelforms/>
Looks like you are doing everything right.
You could check the value of `self.fields['end'].required`. |
Django required field in model form | 1,134,667 | 51 | 2009-07-15T23:37:16Z | 1,429,646 | 84 | 2009-09-15T21:11:02Z | [
"python",
"django",
"forms",
"model",
"widget"
] | I have a form where a couple of fields are coming out as required when I don't want them too. Here is the form from models.py
```
class CircuitForm(ModelForm):
class Meta:
model = Circuit
exclude = ('lastPaged',)
def __init__(self, *args, **kwargs):
super(CircuitForm, self).__init__(*args, **kwa... | If you don't want to modify blank setting for your fields inside models (doing so will break normal validation in admin site), you can do the following in your Form class:
```
def __init__(self, *args, **kwargs):
super(CircuitForm, self).__init__(*args, **kwargs)
for key in self.fields:
self.fields[ke... |
increment int object | 1,135,335 | 13 | 2009-07-16T04:06:12Z | 1,135,347 | 11 | 2009-07-16T04:10:55Z | [
"python",
"int"
] | Is there a way in python to increment int object in place, int doesn't seem to implement `__iadd__` so += 1 actually returns a new object
```
>>> n=1
>>> id(n)
9788024
>>> n+=1
>>> id(n)
9788012
```
What I want is n to remain pointing to same object.
Purpose: I have class derived from int and I want to implement C t... | ints are immutable, so you'll have to build your own class with all the int's methods if you want a "mutable int" |
connecting Python 2.6.1 with MySQLdb | 1,135,625 | 4 | 2009-07-16T05:51:27Z | 1,473,805 | 13 | 2009-09-24T19:52:05Z | [
"python",
"mysql"
] | Hi All
I am using Python 2.6.1 and I want to connect to MySQLdb, I installed mySQL in my system, and I am trying to connect **MySQL-python-1.2.2.win32-py2.6** from **<http://www.codegood.com/archives/4>** site but its not working
while running my application its saying that **No module named MySQLdb**
please any one p... | The best setup for Windows that I've found:
<http://www.codegood.com/downloads?dl_cat=2>
EDIT: Removed original link (it's an ad farm now :( ) |
What is an efficent way of inserting thousands of records into an SQLite table using Django? | 1,136,106 | 49 | 2009-07-16T08:08:30Z | 1,136,248 | 84 | 2009-07-16T08:44:56Z | [
"python",
"sql",
"django",
"sqlite",
"insert"
] | I have to insert 8000+ records into a SQLite database using Django's ORM. This operation needs to be run as a cronjob about once per minute.
At the moment I'm using a for loop to iterate through all the items and then insert them one by one.
Example:
```
for item in items:
entry = Entry(a1=item.a1, a2=item.a2... | You want to check out `django.db.transaction.commit_manually`.
<http://docs.djangoproject.com/en/dev/topics/db/transactions/#django-db-transaction-commit-manually>
So it would be something like:
```
from django.db import transaction
@transaction.commit_manually
def viewfunc(request):
...
for item in items:
... |
What is an efficent way of inserting thousands of records into an SQLite table using Django? | 1,136,106 | 49 | 2009-07-16T08:08:30Z | 7,971,313 | 11 | 2011-11-01T18:45:49Z | [
"python",
"sql",
"django",
"sqlite",
"insert"
] | I have to insert 8000+ records into a SQLite database using Django's ORM. This operation needs to be run as a cronjob about once per minute.
At the moment I'm using a for loop to iterate through all the items and then insert them one by one.
Example:
```
for item in items:
entry = Entry(a1=item.a1, a2=item.a2... | Bulk creation is available in Django 1.4:
<https://django.readthedocs.io/en/1.4/ref/models/querysets.html#bulk-create> |
Allowing user to configure cron | 1,136,168 | 3 | 2009-07-16T08:25:31Z | 1,136,222 | 10 | 2009-07-16T08:37:38Z | [
"python",
"bash",
"cron"
] | I have this bash script on the server that runs every hour, via cron. I was perfectly happy, but now the user wants to be able to configure the frequency through the web interface.
I don't feel comfortable manipulating the cron configuration programmatically, but I'm not sure if the other options are any better.
The ... | Give your users some reasonable choices like every minute, every 5 minutes, every half an hour, ... and translate these values to a cron job string. This is user friendly and forbids users to tamper directly with the cron job string. |
Inserting a Python datetime.datetime object into MySQL | 1,136,437 | 72 | 2009-07-16T09:29:48Z | 4,508,923 | 105 | 2010-12-22T11:56:18Z | [
"python",
"mysql",
"datetime"
] | I have a date column in a MySQL table. I want to insert a `datetime.datetime()` object into this column. What should I be using in the execute statement?
I have tried:
```
now = datetime.datetime(2009,5,5)
cursor.execute("INSERT INTO table
(name, id, datecolumn) VALUES (%s, %s
, %s)",("name", 4,now))
```
I am getti... | For a time field, use:
```
import time
time.strftime('%Y-%m-%d %H:%M:%S')
```
I think strftime also applies to datetime. |
Inserting a Python datetime.datetime object into MySQL | 1,136,437 | 72 | 2009-07-16T09:29:48Z | 12,191,497 | 28 | 2012-08-30T06:59:51Z | [
"python",
"mysql",
"datetime"
] | I have a date column in a MySQL table. I want to insert a `datetime.datetime()` object into this column. What should I be using in the execute statement?
I have tried:
```
now = datetime.datetime(2009,5,5)
cursor.execute("INSERT INTO table
(name, id, datecolumn) VALUES (%s, %s
, %s)",("name", 4,now))
```
I am getti... | You are most likely getting the TypeError because you need quotes around the datecolumn value.
Try:
```
now = datetime.datetime(2009, 5, 5)
cursor.execute("INSERT INTO table (name, id, datecolumn) VALUES (%s, %s, '%s')",
("name", 4, now))
```
With regards to the format, I had success with the above c... |
how do I use the json google translate api? | 1,136,604 | 3 | 2009-07-16T10:03:38Z | 1,137,820 | 7 | 2009-07-16T14:02:54Z | [
"python",
"json",
"api",
"google-translate"
] | I am trying to use google translate from python with utf-8 text.
How do I call the json api? They have a document for embedding it in html but I can't find a proper API or wsdl anywhere.
Thanks
Raphael | Here is the code that finally works for me.
Using the website without the ajax api can get your ip banned, so this is better.
```
#!/usr/bin/env python
from urllib2 import urlopen
from urllib import urlencode
import urllib2
import urllib
import simplejson
import sys
# The google translate API can be found here:
# htt... |
When should I use varargs in designing a Python API? | 1,136,673 | 4 | 2009-07-16T10:20:20Z | 1,136,798 | 8 | 2009-07-16T10:48:23Z | [
"python",
"api",
"varargs"
] | Is there a good rule of thumb as to when you should prefer varargs function signatures in your API over passing an iterable to a function? ("varargs" being short for "variadic" or "variable-number-of-arguments"; i.e. `*args`)
For example, `os.path.join` has a vararg signature:
```
os.path.join(first_component, *rest)... | Consider using varargs when you expect your users to specify the list of arguments as code at the callsite or having a single value is the common case. When you expect your users to get the arguments from somewhere else, don't use varargs. When in doubt, err on the side of not using varargs.
Using your examples, the m... |
What does python sys.intern do, and when should it be used? | 1,136,826 | 27 | 2009-07-16T10:57:00Z | 1,136,852 | 35 | 2009-07-16T11:02:23Z | [
"python",
"memory",
"memory-management",
"python-3.x"
] | I came across [this question](http://stackoverflow.com/questions/327223/) about memory management of dictionaries, which mentions the **intern** function. What exactly does it do, and when would it be used?
To give an example:
If I have a set called **seen**, that contains tuples in the form (string1,string2), which ... | *From the [Python 3](http://docs.python.org/3.2/library/sys.html?highlight=sys.intern#sys.intern) documentation*:
```
sys.intern(string)
```
> Enter string in the table of âinternedâ strings and return the
> interned string â which is string itself or a copy. Interning strings
> is useful to gain a little perfo... |
What does python sys.intern do, and when should it be used? | 1,136,826 | 27 | 2009-07-16T10:57:00Z | 1,136,872 | 9 | 2009-07-16T11:06:19Z | [
"python",
"memory",
"memory-management",
"python-3.x"
] | I came across [this question](http://stackoverflow.com/questions/327223/) about memory management of dictionaries, which mentions the **intern** function. What exactly does it do, and when would it be used?
To give an example:
If I have a set called **seen**, that contains tuples in the form (string1,string2), which ... | They weren't talking about keyword `intern` because there is no such thing in Python. They were talking about [non-essential built-in function `intern`](http://docs.python.org/library/functions.html?highlight=intern#intern). Which in py3k has been moved to [`sys.intern`](http://docs.python.org/3.1/library/sys.html?high... |
What does python sys.intern do, and when should it be used? | 1,136,826 | 27 | 2009-07-16T10:57:00Z | 1,137,293 | 15 | 2009-07-16T12:39:19Z | [
"python",
"memory",
"memory-management",
"python-3.x"
] | I came across [this question](http://stackoverflow.com/questions/327223/) about memory management of dictionaries, which mentions the **intern** function. What exactly does it do, and when would it be used?
To give an example:
If I have a set called **seen**, that contains tuples in the form (string1,string2), which ... | Essentially intern looks up (or stores if not present) the string in a collection of interned strings, so all interned instances will share the same identity. You trade the one-time cost of looking up this string for faster comparisons (the compare can return True after just checking for identity, rather than having to... |
What is the correct way to document a **kwargs parameter? | 1,137,161 | 32 | 2009-07-16T12:18:43Z | 1,137,623 | 11 | 2009-07-16T13:32:54Z | [
"python",
"documentation",
"python-sphinx"
] | I'm using [sphinx](http://sphinx.pocoo.org) and the autodoc plugin to generate API documentation for my Python modules. Whilst I can see how to nicely document specific parameters, I cannot find an example of how to document a `**kwargs` parameter.
Does anyone have a good example of a clear way to document these? | I think [`subprocess`-module's docs](http://docs.python.org/library/subprocess.html) is a good example. Give an exhaustive list of all parameters for a [top/parent class](http://docs.python.org/2/library/subprocess.html#subprocess.Popen). Then just refer to that list for all other occurrences of `**kwargs`. |
Recommended Python cryptographic module? | 1,137,874 | 25 | 2009-07-16T14:09:39Z | 1,137,912 | 12 | 2009-07-16T14:15:34Z | [
"python",
"cryptography"
] | I've been exploring what cryptographic modules are available to Python, and I've found 3: ezPyCrypt, yawPyCrypt and KeyCzar (which actually supports a few languages, but Python is included amongst them). The first two rely on the PyCrypto module.
Are there choices I am missing? Is there a clear front-runner for ease a... | If you are in an environment which includes GnuPG and Python >= 2.4, then you could also consider a tool such as [python-gnupg](http://code.google.com/p/python-gnupg/). (Disclaimer: I'm the maintainer of this project.) It leaves the heavy lifting to `gpg` and provides a fairly straightforward API.
Overview of API:
``... |
Recommended Python cryptographic module? | 1,137,874 | 25 | 2009-07-16T14:09:39Z | 1,138,183 | 7 | 2009-07-16T14:51:25Z | [
"python",
"cryptography"
] | I've been exploring what cryptographic modules are available to Python, and I've found 3: ezPyCrypt, yawPyCrypt and KeyCzar (which actually supports a few languages, but Python is included amongst them). The first two rely on the PyCrypto module.
Are there choices I am missing? Is there a clear front-runner for ease a... | [pycrypt](http://code.google.com/p/pycrypt/) is actually a simple AES encrypt/decrypt module built on top of [pycrypto](http://www.pycrypto.org/) like other modules you mention -- note that the latter is transitioning to the pycrypto.org URL as it's changing maintainers, and stable versions and docs are still at the or... |
Recommended Python cryptographic module? | 1,137,874 | 25 | 2009-07-16T14:09:39Z | 22,033,391 | 12 | 2014-02-26T06:20:09Z | [
"python",
"cryptography"
] | I've been exploring what cryptographic modules are available to Python, and I've found 3: ezPyCrypt, yawPyCrypt and KeyCzar (which actually supports a few languages, but Python is included amongst them). The first two rely on the PyCrypto module.
Are there choices I am missing? Is there a clear front-runner for ease a... | A new cryptography library for Python has been in rapid development for a few months now. The 0.2.1 release just happened a few days ago.
<https://cryptography.io/en/latest/>
It is mainly a CFFI wrapper around existing C libraries such as OpenSSL. It is distributed as a pure python module and supports CPython version... |
Get first non-empty string from a list in python | 1,138,024 | 8 | 2009-07-16T14:30:41Z | 1,138,051 | 15 | 2009-07-16T14:35:12Z | [
"python",
"string",
"list"
] | In Python I have a list of strings, some of which may be the empty string. What's the best way to get the first non-empty string? | ```
next(s for s in list_of_string if s)
```
Edit: py3k proof version as advised by Stephan202 in comments, thanks. |
Alternative XML parser for ElementTree to ease UTF-8 woes? | 1,139,090 | 9 | 2009-07-16T17:32:17Z | 1,141,456 | 14 | 2009-07-17T04:43:54Z | [
"python",
"xml",
"utf-8",
"elementtree"
] | I am parsing some XML with the elementtree.parse() function. It works, except for some utf-8 characters(single byte character above 128). I see that the default parser is XMLTreeBuilder which is based on expat.
Is there an alternative parser that I can use that may be less strict and allow utf-8 characters?
This is t... | I'll start from the question: "Is there an alternative parser that I can use that may be less strict and allow utf-8 characters?"
All XML parsers will accept data encoded in UTF-8. In fact, UTF-8 is the default encoding.
An XML document may start with a declaration like this:
```
`<?xml version="1.0" encoding="UTF-8... |
Python inheritance and calling parent class constructor | 1,139,828 | 14 | 2009-07-16T19:37:13Z | 1,139,845 | 20 | 2009-07-16T19:39:04Z | [
"python",
"oop"
] | This is what I'm trying to do in Python:
```
class BaseClass:
def __init__(self):
print 'The base class constructor ran!'
self.__test = 42
class ChildClass(BaseClass):
def __init__(self):
print 'The child class constructor ran!'
BaseClass.__init__(self)
def doSomething(se... | From python documentation:
> Private name mangling: When an identifier that textually occurs in a class definition **begins with two or more underscore** characters and does not end in two or more underscores, it is considered a **private name** of that class. Private names are **transformed to a longer form** before ... |
In Python, how do I obtain the current frame? | 1,140,194 | 20 | 2009-07-16T20:45:55Z | 1,140,231 | 28 | 2009-07-16T20:52:27Z | [
"python"
] | In other languages I can obtain the current frame via a reflection api to determine what variables are local to the scope that I an currently in.
Is there a way to do this in Python? | ```
import sys
sys._getframe(number)
```
The number being 0 for the current frame and 1 for the frame up and so on up.
The best introduction I have found to frames in python is [here](http://farmdev.com/src/secrets/framehack/index.html)
However, look at the inspect module as it does most common things you want t... |
In Python, how do I obtain the current frame? | 1,140,194 | 20 | 2009-07-16T20:45:55Z | 1,140,513 | 17 | 2009-07-16T21:46:50Z | [
"python"
] | In other languages I can obtain the current frame via a reflection api to determine what variables are local to the scope that I an currently in.
Is there a way to do this in Python? | I use these little guys for debugging and logging:
```
import sys
def LINE( back = 0 ):
return sys._getframe( back + 1 ).f_lineno
def FILE( back = 0 ):
return sys._getframe( back + 1 ).f_code.co_filename
def FUNC( back = 0):
return sys._getframe( back + 1 ).f_code.co_name
def WHERE( back = 0 ):
frame = ... |
In Python, how do I obtain the current frame? | 1,140,194 | 20 | 2009-07-16T20:45:55Z | 16,502,277 | 16 | 2013-05-11T22:23:43Z | [
"python"
] | In other languages I can obtain the current frame via a reflection api to determine what variables are local to the scope that I an currently in.
Is there a way to do this in Python? | The best answer would be to use the [inspect](http://docs.python.org/2/library/inspect.html#inspect.currentframe) module; not a private function in `sys`.
```
import inspect
current_frame = inspect.currentframe()
``` |
Using Python to Automate Creation/Manipulation of Excel Spreadsheets | 1,140,311 | 3 | 2009-07-16T20:51:51Z | 1,140,370 | 7 | 2009-07-16T21:19:42Z | [
"python",
"excel"
] | I have some data in CSV format that I want to pull into an Excel spreadsheet and then create some standard set of graphs for. Since the data is originally generated in a Python app, I was hoping to simply extend the app so that it could do all the post processing and I wouldn't have to do it by hand. Is there an easy i... | [xlutils](http://pypi.python.org/pypi/xlutils) (and the included packages `xlrd` and `xlwt`) should allow your Python program to handily do any creation, reading and manipulation of Excel files you might want! |
Whatâs the best way to get an HTTP response code from a URL? | 1,140,661 | 38 | 2009-07-16T22:27:54Z | 1,140,675 | 19 | 2009-07-16T22:31:33Z | [
"python"
] | Iâm looking for a quick way to get an HTTP response code from a URL (i.e. 200, 404, etc). Iâm not sure which library to use. | You should use urllib2, like this:
```
import urllib2
for url in ["http://entrian.com/", "http://entrian.com/does-not-exist/"]:
try:
connection = urllib2.urlopen(url)
print connection.getcode()
connection.close()
except urllib2.HTTPError, e:
print e.getcode()
# Prints:
# 200 [f... |
Whatâs the best way to get an HTTP response code from a URL? | 1,140,661 | 38 | 2009-07-16T22:27:54Z | 1,140,822 | 55 | 2009-07-16T23:30:43Z | [
"python"
] | Iâm looking for a quick way to get an HTTP response code from a URL (i.e. 200, 404, etc). Iâm not sure which library to use. | Here's a solution that uses `httplib` instead.
```
import httplib
def get_status_code(host, path="/"):
""" This function retreives the status code of a website by requesting
HEAD data from the host. This means that it only requests the headers.
If the host cannot be reached or something else goes ... |
Whatâs the best way to get an HTTP response code from a URL? | 1,140,661 | 38 | 2009-07-16T22:27:54Z | 13,641,613 | 40 | 2012-11-30T08:40:39Z | [
"python"
] | Iâm looking for a quick way to get an HTTP response code from a URL (i.e. 200, 404, etc). Iâm not sure which library to use. | Update using the wonderful [requests library](http://docs.python-requests.org/en/latest/). Note we are using the HEAD request, which should happen more quickly then a full GET or POST request.
```
import requests
try:
r = requests.head("http://stackoverflow.com")
print(r.status_code)
# prints the int of th... |
xml.parsers.expat.ExpatError on parsing XML | 1,140,672 | 6 | 2009-07-16T22:30:28Z | 1,140,753 | 12 | 2009-07-16T23:03:34Z | [
"python",
"xml"
] | I am trying to parse XML with Python but not getting very far. I think it's due to wrong XML tree this API returns.
So this is what is returned by the GET request:
```
<codigo>3</codigo><valor></valor><operador>Dummy</operador>
```
The GET request goes here:
```
http://69.36.9.147:8090/clientes/SMS_API_OUT.jsp?codi... | The main problem here is that the XML code being returned by that service doesn't include a root node, which is invalid. I fixed this by simply wrapping the output in a `<root>` node.
```
import urllib
from xml.etree import ElementTree
url = 'http://69.36.9.147:8090/clientes/SMS_API_OUT.jsp?codigo=ABCDEFGH&cliente=XX... |
Parsing Meaning from Text | 1,140,908 | 9 | 2009-07-17T00:05:09Z | 1,140,917 | 8 | 2009-07-17T00:07:54Z | [
"python",
"parsing",
"nlp",
"lexical-analysis"
] | I realize this is a broad topic, but I'm looking for a good primer on parsing meaning from text, ideally in Python. As an example of what I'm looking to do, if a user makes a blog post like:
"Manny Ramirez makes his return for the Dodgers today against the Houston Astros",
what's a light-weight/ easy way of getting t... | You need to look at the [Natural Language Toolkit](http://www.nltk.org/), which is for exactly this sort of thing.
This section of the manual looks very relevant: [Categorizing and Tagging Words](http://nltk.googlecode.com/svn/trunk/doc/book/ch05.html) - here's an extract:
```
>>> text = nltk.word_tokenize("And now f... |
Parsing Meaning from Text | 1,140,908 | 9 | 2009-07-17T00:05:09Z | 1,140,938 | 7 | 2009-07-17T00:15:09Z | [
"python",
"parsing",
"nlp",
"lexical-analysis"
] | I realize this is a broad topic, but I'm looking for a good primer on parsing meaning from text, ideally in Python. As an example of what I'm looking to do, if a user makes a blog post like:
"Manny Ramirez makes his return for the Dodgers today against the Houston Astros",
what's a light-weight/ easy way of getting t... | Natural Language Processing (NLP) is the name for parsing, well, natural language. Many algorithms and heuristics exist, and it's an active field of research. Whatever algorithm you will code, it will need to be trained on a corpus. Just like a human: we learn a language by reading text written by other people (and/or ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.