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 auto_now and auto_now_add | 1,737,017 | 136 | 2009-11-15T08:47:56Z | 18,752,680 | 9 | 2013-09-11T22:58:15Z | [
"python",
"django",
"datetime",
"django-models",
"django-admin"
] | For Django 1.1.
I have this in my models.py:
```
class User(models.Model):
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
```
When updating a row I get:
```
[Sun Nov 15 02:18:12 2009] [error] /home/ptarjan/projects/twitter-meme/django/db/backends/mysql/base.... | I think the easiest (and maybe most elegant) solution here is to leverage the fact that you can set `default` to a callable. So, to get around admin's special handling of auto\_now, you can just declare the field like so:
```
from django.utils import timezone
date_filed = models.DateField(default=timezone.now)
```
It... |
Django auto_now and auto_now_add | 1,737,017 | 136 | 2009-11-15T08:47:56Z | 22,015,427 | 9 | 2014-02-25T13:18:16Z | [
"python",
"django",
"datetime",
"django-models",
"django-admin"
] | For Django 1.1.
I have this in my models.py:
```
class User(models.Model):
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
```
When updating a row I get:
```
[Sun Nov 15 02:18:12 2009] [error] /home/ptarjan/projects/twitter-meme/django/db/backends/mysql/base.... | I have find a solution
if i have a model class like:
```
class MyModel(models.Model):
time = models.DatetimeField(auto_now_add=True)
time.editable = True
```
Then this field will show up in my admin change page |
File open error by using codec utf-8 in python | 1,737,410 | 3 | 2009-11-15T12:20:50Z | 1,737,476 | 15 | 2009-11-15T12:59:46Z | [
"python",
"unicode",
"utf-8"
] | I execute following code on windows xp and python 2.6.4
But it show IOError.
How to open file whose name has utf-8 codec.
```
>>> open( unicode('íê¸.txt', 'euc-kr').encode('utf-8') )
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
open( unicode('íê¸.txt', 'euc-kr').encode('utf... | The C runtime interface that Windows exposes to Python uses the system code page to encode filenames. Unlike on OS X and modern Linux versions, on Windows the system code page is never UTF-8. So the UTF-8 byte string won't be any good.
You could encode the filename to the current code page using `.encode('mbcs')`, whi... |
The Matlab equivalent of Python's "None" | 1,737,523 | 6 | 2009-11-15T13:23:18Z | 1,737,565 | 10 | 2009-11-15T13:46:38Z | [
"python",
"matlab"
] | Is there a keyword in Matlab that is roughly equivalent to `None` in python?
I am trying to use it to mark an optional argument to a function. I am translating the following Python code
```
def f(x,y=None):
if y == None:
return g(x)
else:
return h(x,y)
```
into Matlab
```
function rtrn = f(x,y)
... | in your specific case. you may use `nargin` to determine how many input arguments here provided when calling the function.
from the [MATLAB documentation](http://www.mathworks.com/access/helpdesk/help/techdoc/matlab%5Fprog/bresuxt-1.html#br67di7-1):
> The nargin and nargout functions
> enable you to determine how man... |
Dict has key from list | 1,737,778 | 7 | 2009-11-15T15:13:00Z | 1,737,790 | 20 | 2009-11-15T15:17:10Z | [
"python",
"list",
"dictionary"
] | How can I determine if any of the list elements are a key to a dict?
The straight forward way is,
```
for i in myList:
if i in myDict:
return True
return False
```
but is there a faster / more concise way? | ```
#!python
any(x in MyDict for x in MyList)
set(MyList).intersection(MyDict)
``` |
How does the Python's range function work? | 1,738,109 | 8 | 2009-11-15T17:06:38Z | 1,738,118 | 27 | 2009-11-15T17:11:13Z | [
"python",
"for-loop",
"range"
] | all,I am not really understand for loop in the following,can anyone give some tips?thanks in advance
```
for i in range(5):
print i
```
then it gives 0,1,2,3,4 is that python assign 0,1,2,3,4 to i at the same time? however if i wrote:
```
for i in range(5):
a=i+1
```
then I call a, it gives 5 only, but ... | A "for loop" in most, if not all, programming languages is a mechanism to run a piece of code more than once.
This code:
```
for i in range(5):
print i
```
can be thought of working like this:
```
i = 0
print i
i = 1
print i
i = 2
print i
i = 3
print i
i = 4
print i
```
So you see, what happens is not that `i`... |
How does the Python's range function work? | 1,738,109 | 8 | 2009-11-15T17:06:38Z | 1,738,840 | 9 | 2009-11-15T21:08:07Z | [
"python",
"for-loop",
"range"
] | all,I am not really understand for loop in the following,can anyone give some tips?thanks in advance
```
for i in range(5):
print i
```
then it gives 0,1,2,3,4 is that python assign 0,1,2,3,4 to i at the same time? however if i wrote:
```
for i in range(5):
a=i+1
```
then I call a, it gives 5 only, but ... | When I'm teaching someone programming (just about any language) I introduce `for` loops with terminology similar to this code example:
```
for eachItem in someList:
doSomething(eachItem)
```
... which, conveniently enough, is syntactically valid Python code.
The Python `range()` function simple returns or genera... |
Pylons and Memcached | 1,738,250 | 3 | 2009-11-15T17:51:13Z | 1,738,519 | 7 | 2009-11-15T19:29:57Z | [
"python",
"memcached",
"pylons"
] | Anyone happen to use this combination in their web application? I'm having a bit of trouble finding some sort of tutorial or guideline for configuring this. Also seeing as how I started using Pylons recently I'm not familiar so please keep the advice very newbie friendly ( I haven't even used modules like Beaker all th... | `memcached` is nice and framework-agnostic, and you just have to write a bit of code to interact with it. The general idea of memcached is:
```
object = try_memcached()
if not object:
object = real_query()
put_in_memcached(object)
```
That will likely be done in your SQLAlchemy abstraction, in your case. Sinc... |
Python: how to make two lists from a dictionary | 1,738,392 | 4 | 2009-11-15T18:37:37Z | 1,738,411 | 13 | 2009-11-15T18:45:43Z | [
"python"
] | I have a dictionary.
```
{1 : [1.2, 2.3, 4.9, 2.0], 2 : [4.1, 5.1, 6.3], 3 : [4.9, 6.8, 9.5, 1.1, 7.1]}
```
I want to pass each key:value pair to an instance of `matplotlib.pyplot` as two lists: x values and y values.
Each key is an x value associated with each item in its value.
So I want two lists for each key:... | ```
for k, v in dictionary.iteritems():
x = [k] * len(v)
y = v
pyplot.plot(x, y)
``` |
More pythonic way to find a complementary DNA strand | 1,738,633 | 2 | 2009-11-15T20:02:05Z | 1,738,653 | 12 | 2009-11-15T20:09:05Z | [
"python"
] | Here's what I have, but it seems kind of redundant. Maybe someone more experienced in Python knows of a way to clean this up? Should be pretty self explanatory what it does.
```
def complementary_strand(self, strand):
''' Takes a DNA strand string and finds its opposite base pair match. '''
strand = st... | Probably the most efficient way to do it, if the string is long enough:
```
import string
def complementary_strand(self, strand):
return strand.translate(string.maketrans('TAGCtagc', 'ATCGATCG'))
```
This is making use of the [translate](http://docs.python.org/library/string.html#string.translate) and [maketrans... |
Python: Convert string into function name; getattr or equal? | 1,738,687 | 4 | 2009-11-15T20:19:14Z | 1,738,700 | 8 | 2009-11-15T20:24:01Z | [
"python",
"function",
"getattr"
] | I am editing PROSS.py to work with .cif files for protein structures. Inside the existing PROSS.py, there is the following functions (I believe that's the correct name if it's not associated with any class?), just existing within the .py file:
```
...
def unpack_pdb_line(line, ATOF=_atof, ATOI=_atoi, STRIP=string.stri... | Usually you just use a dict and store `(func_name, function)` pairs:
```
unpack_options = { 'unpack_pdb_line' : unpack_pdb_line,
'some_other' : some_other_function }
unpack_function = unpack_options[options.unpack_method]
``` |
Python: Split unicode string on word boundaries | 1,738,788 | 10 | 2009-11-15T20:53:40Z | 1,738,798 | 7 | 2009-11-15T20:57:22Z | [
"python",
"unicode",
"internationalization",
"character-properties"
] | I need to take a string, and shorten it to 140 characters.
Currently I am doing:
```
if len(tweet) > 140:
tweet = re.sub(r"\s+", " ", tweet) #normalize space
footer = "⦠" + utils.shorten_urls(post['url'])
avail = 140 - len(footer)
words = tweet.split()
result = ""
for word in words:
... | Chinese doesn't usually have whitespace between words, and the symbols can have different meanings depending on context. You will have to understand the text in order to split it at a word boundary. In other words, what you are trying to do is not easy in general. |
What is the max length of a python string? | 1,739,913 | 39 | 2009-11-16T03:37:28Z | 1,739,928 | 54 | 2009-11-16T03:42:33Z | [
"python",
"string"
] | If it is environment-independent, what is the theoretical maximum number of characters in a python string?
Also if it differs with version number I'd like to know it for python 2.5.2 | With a 64-bit Python installation, and (say) 64 GB of memory, a Python 2 string of around 63 GB should be quite feasible (if not maximally fast). If you can upgrade your memory much beyond that (which will cost you an arm and a leg, of course), your maximum feasible strings should get proportionally longer. (I don't re... |
Python: reload component Y imported with 'from X import Y'? | 1,739,924 | 39 | 2009-11-16T03:41:28Z | 1,739,931 | 24 | 2009-11-16T03:44:48Z | [
"python",
"python-import"
] | In Python, once I have imported a module X in an interpreter session using `import X`, and the module changes on the outside, I can reload the module with `reload(X)`. The changes then become available in my interpreter session.
I am wondering if this also possible when I import a component Y from module X using `from... | If Y is a module (and X a package) `reload(Y)` will be fine -- otherwise, you'll see why good Python style guides (such as my employer's) say to **never** import anything **except** a module (this is one out of many great reasons -- yet people still keep importing functions and classes directly, no matter how much I ex... |
Python: reload component Y imported with 'from X import Y'? | 1,739,924 | 39 | 2009-11-16T03:41:28Z | 1,740,401 | 7 | 2009-11-16T06:21:51Z | [
"python",
"python-import"
] | In Python, once I have imported a module X in an interpreter session using `import X`, and the module changes on the outside, I can reload the module with `reload(X)`. The changes then become available in my interpreter session.
I am wondering if this also possible when I import a component Y from module X using `from... | First off, you shouldn't be using reload at all, if you can avoid it. But let's assume you have your reasons (i.e. debugging inside IDLE).
Reloading the library won't get the names back into the module's namespace. To do this, just reassign the variables:
```
f = open('zoo.py', 'w')
f.write("snakes = ['viper','anacon... |
Python: reload component Y imported with 'from X import Y'? | 1,739,924 | 39 | 2009-11-16T03:41:28Z | 11,724,154 | 29 | 2012-07-30T15:04:18Z | [
"python",
"python-import"
] | In Python, once I have imported a module X in an interpreter session using `import X`, and the module changes on the outside, I can reload the module with `reload(X)`. The changes then become available in my interpreter session.
I am wondering if this also possible when I import a component Y from module X using `from... | # Answer
From my tests. The marked answer, which suggests a simple `reload(X)`, does not work.
From what I can tell the correct answer is:
```
import X
reload( X )
from X import Y
```
---
# Test
My test was the following (Python 2.6.5 + bpython 0.9.5.2)
X.py:
```
def Y():
print "Test 1"
```
bpython:
```
>... |
Documents and examples of PythonMagick | 1,740,158 | 18 | 2009-11-16T05:04:08Z | 5,188,661 | 24 | 2011-03-04T01:24:21Z | [
"python",
"imagemagick"
] | Where can I find the document and examples of [PythonMagick](http://wiki.python.org/moin/PythonMagick)?
I did a search on Google but no much information was found. | I could not find them anywhere either but this is how I went about using it anyway.
Example
```
import PythonMagick
image = PythonMagick.Image("sample_image.jpg")
print image.fileName()
print image.magick()
print image.size().width()
print image.size().height()
```
With output like this
```
sample_image.jpg
JPEG
34... |
Documents and examples of PythonMagick | 1,740,158 | 18 | 2009-11-16T05:04:08Z | 5,532,685 | 14 | 2011-04-03T21:33:37Z | [
"python",
"imagemagick"
] | Where can I find the document and examples of [PythonMagick](http://wiki.python.org/moin/PythonMagick)?
I did a search on Google but no much information was found. | To find out the methods type in Python:
```
import PythonMagick
dir(PythonMagick.Image())
```
Then you get an output like this:
> `['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__instance_size__', '__le__', '__lt__', '__mo... |
Documents and examples of PythonMagick | 1,740,158 | 18 | 2009-11-16T05:04:08Z | 11,317,673 | 14 | 2012-07-03T19:17:49Z | [
"python",
"imagemagick"
] | Where can I find the document and examples of [PythonMagick](http://wiki.python.org/moin/PythonMagick)?
I did a search on Google but no much information was found. | From what I can tell, PythonMagick wrapps the [Magick++ library](http://www.imagemagick.org/Magick++/Documentation.html). I have been able to copy and paste C++ code using this library into python and it works as expected. Plus the names of the classes and member functions match (where as MagickWand seems to be totally... |
Integrating a simple web server into a custom main loop in python? | 1,740,235 | 4 | 2009-11-16T05:24:49Z | 1,740,378 | 7 | 2009-11-16T06:11:21Z | [
"python",
"loops"
] | I have an application in python with a custom main loop (I don't believe the details are important). I'd like to integrate a simple non-blocking web server into the application which can introspect the application objects and possibly provide an interface to manipulate them. What's the best way to do this?
I'd like to... | [Twisted](http://docs.python.org/reference/compound%5Fstmts.html) is designed to make stuff like that fairly simple
```
import time
from twisted.web import server, resource
from twisted.internet import reactor
class Simple(resource.Resource):
isLeaf = True
def render_GET(self, request):
return "<html... |
bytes vs bytearray in Python 2.6 and 3 | 1,740,696 | 11 | 2009-11-16T07:50:25Z | 1,740,762 | 22 | 2009-11-16T08:09:55Z | [
"python",
"python-3.x",
"byte",
"bytearray",
"python-2.x"
] | I'm experimenting with `bytes` vs `bytearray` in Python 2.6. I don't understand the reason for some differences.
A `bytes` iterator returns strings:
```
for i in bytes(b"hi"):
print(type(i))
```
Gives:
```
<type 'str'>
<type 'str'>
```
But a `bytearray` iterator returns `int`s:
```
for i in bytearray(b"hi"):
... | **In Python 2.6 bytes is merely an alias for str**.
This "pseudo type" was introduced to [partially] prepare programs [and programmers!] to be converted/compatible with Python 3.0 where there is a strict distinction of semantics and use for str (which are systematically unicode) and bytes (which are arrays of octets,... |
Python:: Turn string into operator | 1,740,726 | 12 | 2009-11-16T08:00:19Z | 1,740,759 | 44 | 2009-11-16T08:09:15Z | [
"python"
] | How can I turn a string such as "+" into the operator plus? Thanks! | Use a lookup table:
```
import operator
ops = { "+": operator.add, "-": operator.sub } # etc.
print ops["+"](1,1) # prints 2
``` |
Python:: Turn string into operator | 1,740,726 | 12 | 2009-11-16T08:00:19Z | 1,740,761 | 11 | 2009-11-16T08:09:34Z | [
"python"
] | How can I turn a string such as "+" into the operator plus? Thanks! | ```
import operator
def get_operator_fn(op):
return {
'+' : operator.add,
'-' : operator.sub,
'*' : operator.mul,
'/' : operator.div,
'%' : operator.mod,
'^' : operator.xor,
}[op]
def eval_binary_expr(op1, operator, op2):
op1,op2 = int(op1), int(op2)
... |
How to use different formatters with the same logging handler in python | 1,741,972 | 12 | 2009-11-16T12:42:04Z | 1,742,512 | 11 | 2009-11-16T14:30:57Z | [
"python",
"logging"
] | Is it possible to log to a single destination (i.e. using one `FileHandler`) with multiple loggers (i.e. `logging.getLogger("base.foo")` and `logging.getLogger("base.bar")`), and use different formatters for each of the loggers.
To my understanding it's only possible to assign one formatter to each handle. Maybe it's ... | It's easy to dispatch to different formatters based on `record.name`. Below is prove-of-concept sample code:
```
import logging
class DispatchingFormatter:
def __init__(self, formatters, default_formatter):
self._formatters = formatters
self._default_formatter = default_formatter
def format... |
How do I get the selected text in desktop application using python-dbus? | 1,742,264 | 2 | 2009-11-16T13:41:22Z | 1,742,632 | 7 | 2009-11-16T14:50:51Z | [
"python",
"text",
"gtk",
"selection",
"dbus"
] | For example, I open a pdf file or a web page in gnome, use mouse double click some text, so a word is selected, how can I get this word in a background running daemon written with python-dbus?
Some simple but working piece of script is appreciated greatly.
Thanks! | You don't need D-Bus, simply listen to changes for the middle-click (Selection) clipboard with for example Gtk:
```
import gtk
def _clipboard_changed(clipboard, event):
text = clipboard.wait_for_text()
clip = gtk.clipboard_get(gtk.gdk.SELECTION_PRIMARY)
clip.connect("owner-change", _clipboard_changed)
``` |
Calling Method from Different Python File | 1,742,430 | 5 | 2009-11-16T14:15:43Z | 1,742,476 | 7 | 2009-11-16T14:23:56Z | [
"python",
"django",
"methods"
] | As I'm currently learning Django / Python, I've not really been using the concept of Classes, yet. As far as I'm aware the method isn't static.. it's just a standard definition.
So let's say I have this Package called `Example1` with a `views.py` that contains this method:
```
def adder(x,y):
return x + y
```
Then... | Python has module level and class level methods. In this concept a "module" is a very special class that you get by using `import` instead of `Name()`. Try
```
from Example1.views import adder as otherAdder
```
to get access to the module level method. Now you can call `otherAdder()` and it will execute the code in t... |
How to use python win32com to save as excel file | 1,742,471 | 4 | 2009-11-16T14:23:00Z | 1,742,556 | 9 | 2009-11-16T14:37:32Z | [
"python",
"win32com"
] | I have a small python code to open an Excel file. Now I want to "Save As" with a different name but same format.
How do I do that.. Any help will be great.
FK | Here is a [tutorial on using the win32com API with Exce](http://www.xsi-blog.com/archives/11)l and here is the COM method you will likely have to call, [Workbook.SaveAs](http://msdn.microsoft.com/en-us/library/bb214129.aspx). And here is an example of actually [making the call](http://aspn.activestate.com/ASPN/Mail/Mes... |
compute crc of file in python | 1,742,866 | 12 | 2009-11-16T15:23:47Z | 2,387,880 | 19 | 2010-03-05T15:35:38Z | [
"python",
"hash",
"crc"
] | I want to calculate the [CRC](http://en.wikipedia.org/wiki/Cyclic_redundancy_check) of file and get output like: `E45A12AC`. Here's my code:
```
#!/usr/bin/env python
import os, sys
import zlib
def crc(fileName):
fd = open(fileName,"rb")
content = fd.readlines()
fd.close()
for eachLine in content:
... | A little more compact and optimized code
```
def crc(fileName):
prev = 0
for eachLine in open(fileName,"rb"):
prev = zlib.crc32(eachLine, prev)
return "%X"%(prev & 0xFFFFFFFF)
```
PS2: Old PS is deprecated - therefore deleted -, because of the suggestion in the comment. Thank you. I don't get, how... |
Convert float to string with cutting zero decimals afer point in Python | 1,742,937 | 8 | 2009-11-16T15:35:45Z | 1,743,088 | 10 | 2009-11-16T15:55:39Z | [
"python",
"string",
"floating-point"
] | I am having difficulty converting a float to string in the following manner:
```
20.02 --> 20.02
20.016 --> 20.02
20.0 --> 20
```
It seems that`%g` format is the best for that, but I am getting strange results:
```
In [30]: "%.2g" % 20.03
Out[30]: '20'
In [31]: "%.2g" % 20.1
Out[31]: '20'
In [32]: "%.2g" % 20.3... | Using `%f` format specifier:
```
('%.2f' % (value,)).rstrip('0').rstrip('.')
```
Using `round()` function:
```
str(round(value)).rstrip('0').rstrip('.')
``` |
Why does my Python program average only 33% CPU per process? How can I make Python use all available CPU? | 1,743,293 | 7 | 2009-11-16T16:33:15Z | 1,743,312 | 21 | 2009-11-16T16:36:11Z | [
"python",
"performance",
"process",
"multiprocessing",
"cpu-usage"
] | I use Python 2.5.4. My computer: CPU AMD [Phenom X3](http://en.wikipedia.org/wiki/AMD%5FPhenom#Phenom%5FX3) 720BE, Mainboard 780G, 4GB RAM, Windows 7 32 bit.
I use Python threading but can not make every python.exe process consume 100% CPU. Why are they using only about 33-34% on average?.
I wish to direct all availa... | Try the [multiprocessing](http://docs.python.org/library/multiprocessing.html) module, as Python, while it has real, native threads, will restrict their concurrent use while the GIL is held. Another alternative, and something you should look at if you need *real* speed, is writing a C extension module and calling funct... |
Why does my Python program average only 33% CPU per process? How can I make Python use all available CPU? | 1,743,293 | 7 | 2009-11-16T16:33:15Z | 1,743,350 | 25 | 2009-11-16T16:42:55Z | [
"python",
"performance",
"process",
"multiprocessing",
"cpu-usage"
] | I use Python 2.5.4. My computer: CPU AMD [Phenom X3](http://en.wikipedia.org/wiki/AMD%5FPhenom#Phenom%5FX3) 720BE, Mainboard 780G, 4GB RAM, Windows 7 32 bit.
I use Python threading but can not make every python.exe process consume 100% CPU. Why are they using only about 33-34% on average?.
I wish to direct all availa... | It appears that you have a 3-core CPU. If you want to use more than one CPU core in native Python code, you have to spawn multiple processes. (Two or more Python threads cannot run concurrently on different CPUs)
As *R. Pate* said, Python's `multiprocessing` module is one way. However, I would suggest looking at **[Pa... |
Why does my Python program average only 33% CPU per process? How can I make Python use all available CPU? | 1,743,293 | 7 | 2009-11-16T16:33:15Z | 1,743,362 | 10 | 2009-11-16T16:44:30Z | [
"python",
"performance",
"process",
"multiprocessing",
"cpu-usage"
] | I use Python 2.5.4. My computer: CPU AMD [Phenom X3](http://en.wikipedia.org/wiki/AMD%5FPhenom#Phenom%5FX3) 720BE, Mainboard 780G, 4GB RAM, Windows 7 32 bit.
I use Python threading but can not make every python.exe process consume 100% CPU. Why are they using only about 33-34% on average?.
I wish to direct all availa... | [Global Interpreter Lock](http://en.wikipedia.org/wiki/Global%5FInterpreter%5FLock)
> The reasons of employing such a lock include:
>
> ```
> * increased speed of single-threaded programs (no necessity to acquire or release locks
> on all data structures separately)
> * easy integration of C libraries that usually a... |
Differences between Go and Cython | 1,743,526 | 4 | 2009-11-16T17:12:34Z | 1,749,058 | 8 | 2009-11-17T13:55:04Z | [
"python",
"go",
"cython"
] | Today a great friend of mine asked me what are the main differences between the newest Go language and [Cython](http://www.cython.org/), which is a set of C-extensions for Python. I don't have much knowledge on Python, can anyone tell me why Go is better/worse than Cython? | Cython isn't really a language in the conventional sense. It is a preprocessor for building Python extensions that takes Python-like syntax (actually they strive for full Python compatibility) and produces C code (using the Python C API). Doing this they are able to include some special case optimisations, but the real... |
Django Admin: OneToOne Relation as an Inline? | 1,744,203 | 38 | 2009-11-16T19:10:26Z | 1,744,445 | 53 | 2009-11-16T19:49:49Z | [
"python",
"django",
"django-admin",
"inline",
"one-to-one"
] | I am putting together the admin for a satchmo application. Satchmo uses OneToOne relations to extend the base `Product` model, and I'd like to edit it all on one page.
It is possible to have a OneToOne relation as an Inline? If not, what is the best way to add a few fields to a given page of my admin that will eventua... | It's perfectly possible to use an inline for a OneToOne relationship. However, the actual field defining the relationship has to be on the inline model, not the parent one - in just the same way as for a ForeignKey. Switch it over and it will work.
**Edit after comment**: you say the parent model is already registered... |
Is `import module` better coding style than `from module import function`? | 1,744,258 | 53 | 2009-11-16T19:18:49Z | 1,744,336 | 15 | 2009-11-16T19:32:11Z | [
"python",
"python-import"
] | Let `from module import function` be called the FMIF coding style.
Let `import module` be called the IM coding style.
Let `from package import module` be called the FPIM coding style.
Why is IM+FPIM considered a better coding style than FMIF? (See [this post](http://stackoverflow.com/questions/1739924/python-reload-... | The classic text on this, as so often, is from Fredrik Lundh, the effbot. His advice: [always use import](http://effbot.org/zone/import-confusion.htm) - except when you shouldn't.
In other words, be sensible. Personally I find that anything that's several modules deep tends to get imported via `from x.y.z import a` - ... |
Is `import module` better coding style than `from module import function`? | 1,744,258 | 53 | 2009-11-16T19:18:49Z | 1,744,439 | 34 | 2009-11-16T19:49:15Z | [
"python",
"python-import"
] | Let `from module import function` be called the FMIF coding style.
Let `import module` be called the IM coding style.
Let `from package import module` be called the FPIM coding style.
Why is IM+FPIM considered a better coding style than FMIF? (See [this post](http://stackoverflow.com/questions/1739924/python-reload-... | The negatives you list for IM/FPIM can often be ameliorated by appropriate use of an `as` clause. `from some.package import mymodulewithalongname as mymod` can usefully shorten your code and enhance its readability, and if you rename `mymodulewithalongname` to `somethingcompletelydifferent` tomorrow, the `as` clause ca... |
Does Django cache templates automatically? | 1,744,339 | 3 | 2009-11-16T19:32:46Z | 1,744,686 | 7 | 2009-11-16T20:35:45Z | [
"python",
"django",
"caching",
"django-templates"
] | I'm new to Django and trying to implement a voting system between two images. However, it looks like the page is being cached or something because when I refresh it, some values are wrong. I have no cache setup in my Settings.
Here is the View:
```
def rate(request, type):
photos = Photo.objects.order_by('?')[:2]... | Taking a look at this in some of my code, I have this in my template:
```
{{ mytable.0.pk }}
{{ mytable.1.pk }}
{{ mytable.0.pk }}
{{ mytable.3.pk }}
```
And I get this output:
```
91596
54774
156800
23593
```
Odd, until you consider that django executes database queries **very** lazily. This is what shows up in my... |
Read from File, or STDIN | 1,744,989 | 31 | 2009-11-16T21:32:22Z | 1,745,008 | 43 | 2009-11-16T21:35:51Z | [
"python",
"file",
"command-line",
"arguments",
"stdin"
] | I've written a command line utility that uses getopt for parsing arguments given on the command line. I would also like to have a filename be an optional argument, such as it is in other utilities like grep, cut etc. So, I would like it to have the following usage
```
tool -d character -f integer [filename]
```
How c... | The [fileinput](http://docs.python.org/library/fileinput.html) module may do what you want - assuming the non-option arguments are in `args` then:
```
import fileinput
for line in fileinput.input(args):
print line
```
If `args` is empty then `fileinput.input()` will read from stdin; otherwise it reads from each f... |
Read from File, or STDIN | 1,744,989 | 31 | 2009-11-16T21:32:22Z | 1,745,035 | 30 | 2009-11-16T21:40:54Z | [
"python",
"file",
"command-line",
"arguments",
"stdin"
] | I've written a command line utility that uses getopt for parsing arguments given on the command line. I would also like to have a filename be an optional argument, such as it is in other utilities like grep, cut etc. So, I would like it to have the following usage
```
tool -d character -f integer [filename]
```
How c... | In the simplest terms:
```
import sys
# parse command line
if file_name_given:
inf = open(file_name_given)
else:
inf = sys.stdin
```
At this point you would use `inf` to read from the file. Depending on whether a filename was given, this would read from the given file or from stdin.
When you need to close th... |
Read from File, or STDIN | 1,744,989 | 31 | 2009-11-16T21:32:22Z | 19,802,578 | 8 | 2013-11-06T01:49:06Z | [
"python",
"file",
"command-line",
"arguments",
"stdin"
] | I've written a command line utility that uses getopt for parsing arguments given on the command line. I would also like to have a filename be an optional argument, such as it is in other utilities like grep, cut etc. So, I would like it to have the following usage
```
tool -d character -f integer [filename]
```
How c... | To make use of python's `with` statement, one can use the following code:
```
import sys
with open(sys.argv[1], 'r') if len(sys.argv) > 1 else sys.stdin as f:
# read data using f
# ......
``` |
Convert date Python | 1,745,042 | 3 | 2009-11-16T21:42:22Z | 1,745,076 | 15 | 2009-11-16T21:49:07Z | [
"python",
"date"
] | I have `MMDDYY` dates, i.e. today is `111609`
How do I convert this to `11/16/2009`, in Python? | I suggest the following:
```
import datetime
date = datetime.datetime.strptime("111609", "%m%d%y")
print date.strftime("%m/%d/%Y")
```
This will convert `010199` to `01/01/1999` and `010109` to `01/01/2009`. |
Solving thread cleanup on paramiko | 1,745,232 | 10 | 2009-11-16T22:21:36Z | 1,745,344 | 7 | 2009-11-16T22:45:44Z | [
"python",
"ssh",
"paramiko"
] | I have an automated process using paramiko and have this error:
```
Exception in thread Thread-1 (most likely raised during interpreter
shutdown)
....
....
<type 'exceptions.AttributeError'>: 'NoneType' object has no attribute
'error'
```
I understand that is a problem in the cleanup/threading, but I don't know ho... | `__del__` is not a deconstructor. It's called when you delete a object's last name, which doesn't nessesarily happen when you exit the interpreter.
Anything that manages a context, such as connections, is a [`context manager`](http://docs.python.org/library/stdtypes.html#typecontextmanager) For example there is [`clos... |
Structured programming and Python generators? | 1,745,333 | 6 | 2009-11-16T22:43:30Z | 1,745,586 | 11 | 2009-11-16T23:34:58Z | [
"python",
"generator"
] | **Update:** What I really wanted all along were [greenlets](http://pypi.python.org/pypi/greenlet).
---
**Note:** This question mutated a bit as people answered and forced me to "raise the stakes", as my trivial examples had trivial simplifications; rather than continue to mutate it here, I will repose the question wh... | > However, I'd like to make my
> reusability criteria one notch harder:
> what if I need a control structure
> around my repeated generation?
`itertools` often helps even there - you need to provide concrete examples where you think it doesn't.
> For
> instance, I might want to call a
> subgenerator forever with diff... |
Validating Uploaded Files in Django | 1,745,743 | 20 | 2009-11-17T00:12:02Z | 1,750,810 | 14 | 2009-11-17T18:25:32Z | [
"python",
"django",
"security",
"file-upload"
] | A Django app that I am working has an `Event` model. An `Event` may have associated photos, static html files and pdf files.
I would like to allow trusted users to upload these files, but I am wary about security, especially having read the following [in the Django docs](http://docs.djangoproject.com/en/dev/ref/models... | For images you might be able to just use [Python Imaging Library](http://www.pythonware.com/library/pil/handbook/introduction.htm) (PIL).
```
Image.open(filepath)
```
If the file is not an image, an exception will be thrown. I'm pretty new to Python/Django so someone else might have a better way of validating images. |
Validating Uploaded Files in Django | 1,745,743 | 20 | 2009-11-17T00:12:02Z | 1,796,299 | 15 | 2009-11-25T11:20:19Z | [
"python",
"django",
"security",
"file-upload"
] | A Django app that I am working has an `Event` model. An `Event` may have associated photos, static html files and pdf files.
I would like to allow trusted users to upload these files, but I am wary about security, especially having read the following [in the Django docs](http://docs.djangoproject.com/en/dev/ref/models... | All the answers are focusing on validating files. This is pretty much impossible.
The Django devs aren't asking you to validate whether files can be executed *as* cgi files. They are just telling you not to put them in a place where they *will* be executed.
You should put all Django stuff in a specially Django direct... |
Regex, how to remove all non-alphanumeric except colon in a 12/24 hour timestamp? | 1,746,167 | 4 | 2009-11-17T02:07:02Z | 1,746,194 | 7 | 2009-11-17T02:16:29Z | [
"python",
"regex"
] | I have a string like:
```
Today, 3:30pm - Group Meeting to discuss "big idea"
```
How do you construct a regex such that after parsing it would return:
```
Today 3:30pm Group Meeting to discuss big idea
```
I would like it to remove all non-alphanumeric characters except for those that appear in a 12 or 24 hour tim... | ```
# this: D:DD, DD:DDam/pm 12/24 hr
re = r':(?=..(?<!\d:\d\d))|[^a-zA-Z0-9 ](?<!:)'
```
A colon must be preceded by at least one digit and followed by at least two digits: then it's a time. All other colons will be considered textual colons.
### How it works
```
: // match a colon
(?=.. // ma... |
Why won't my Python scatter plot work? | 1,746,312 | 5 | 2009-11-17T02:58:32Z | 2,367,735 | 9 | 2010-03-02T23:31:58Z | [
"python",
"graph",
"matplotlib",
"scatter"
] | I created a very simple scatter plot using pylab.
```
pylab.scatter(engineSize, fuelMile)
pylab.show()
```
The rest of the program isn't worth posting, because it's that line that's giving me the problem. When I change "scatter" to "plot" it graphs the data, but each point is part of a line and that makes the whole t... | I bet engineSize, fuelMile are stings, try printing them, if that is the case, you have to convert them to float before passing them as arguments to scatter
```
floatval = float(strval)
``` |
python csv headers | 1,746,489 | 13 | 2009-11-17T03:59:55Z | 1,746,622 | 9 | 2009-11-17T04:39:34Z | [
"python",
"csv"
] | I have set of csv headers that i am trying to match with uploads, it's not really working. Not all headers are required, just have to match what's in file
```
reader = csv.DictReader(open(PathFile))
headers = reader.fieldnames
for header in sorted(set(headers)):
if (header == 'ip') or (header == '... | Based on your edit, you need to [skip the initial space](http://docs.python.org/library/csv.html#csv.Dialect.skipinitialspace) after the comma.
This should do it:
```
>>> reader = csv.DictReader(open(PathFile),skipinitialspace=True)
``` |
Bitwise operation and usage | 1,746,613 | 58 | 2009-11-17T04:37:05Z | 1,746,639 | 28 | 2009-11-17T04:43:46Z | [
"python",
"binary",
"operators",
"bit-manipulation"
] | Consider this code:
```
x = 1 # 0001
x << 2 # Shift left 2 bits: 0100
# Result: 4
x | 2 # Bitwise OR: 0011
# Result: 3
x & 1 # Bitwise AND: 0001
# Result: 1
```
I can understand the arithmetic operators in Python (and other languages), but I never understood 'bitwise' operators quite well... | One typical usage:
`|` is used to set a certain bit to 1
`&` is used to test or clear a certain bit
* Set a bit (where n is the bit number, and 0 is the least significant bit):
`unsigned char a |= (1 << n);`
* Clear a bit:
`unsigned char b &= ~(1 << n);`
* Toggle a bit:
`unsigned char c ^= (1 << n);`
* Test... |
Bitwise operation and usage | 1,746,613 | 58 | 2009-11-17T04:37:05Z | 1,746,642 | 92 | 2009-11-17T04:44:42Z | [
"python",
"binary",
"operators",
"bit-manipulation"
] | Consider this code:
```
x = 1 # 0001
x << 2 # Shift left 2 bits: 0100
# Result: 4
x | 2 # Bitwise OR: 0011
# Result: 3
x & 1 # Bitwise AND: 0001
# Result: 1
```
I can understand the arithmetic operators in Python (and other languages), but I never understood 'bitwise' operators quite well... | Bitwise operators are operators that work on multi-bit values, but conceptually one bit at a time.
* `AND` is 1 only if *both* of its inputs are 1, otherwise it's 0.
* `OR` is 1 if *one or both* of its inputs are 1, otherwise it's 0.
* `XOR` is 1 only if *exactly one* of its inputs are 1, otherwise it's 0.
* `NOT` is ... |
Bitwise operation and usage | 1,746,613 | 58 | 2009-11-17T04:37:05Z | 1,746,850 | 22 | 2009-11-17T05:47:59Z | [
"python",
"binary",
"operators",
"bit-manipulation"
] | Consider this code:
```
x = 1 # 0001
x << 2 # Shift left 2 bits: 0100
# Result: 4
x | 2 # Bitwise OR: 0011
# Result: 3
x & 1 # Bitwise AND: 0001
# Result: 1
```
I can understand the arithmetic operators in Python (and other languages), but I never understood 'bitwise' operators quite well... | > what are bitwise operators actually used for? I'd appreciate some examples.
One of the most common uses of bitwise operations is for parsing hexadecimal colours.
For example, here's a [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29) function that accepts a String like `#FF09BE` and returns a... |
Python ValueError: insecure string pickle | 1,746,825 | 30 | 2009-11-17T05:39:44Z | 13,395,516 | 60 | 2012-11-15T10:25:42Z | [
"python",
"pickle"
] | PWhen I am trying to load something I dumped using cPickle, I get the error message:
```
ValueError: insecure string pickle
```
Both the dumping and loading work are done on the same computer, thus same OS: Ubuntu 8.04.
How could I solve this problem? | "are much more likely than a never-observed bug in Python itself in a functionality that's used billions of times a day all over the world": it always amazes me how cross people get in these forums.
One easy way to get this problem is by forgetting to close the stream that you're using for dumping the data structure. ... |
Django manage.py syncdb throwing No module named MySQLdb | 1,746,863 | 10 | 2009-11-17T05:52:15Z | 1,746,890 | 12 | 2009-11-17T06:01:22Z | [
"python",
"mysql",
"django",
"osx",
"osx-snow-leopard"
] | I am a newbie learning Python/Django...
Am using the following tutorial located [here](http://docs.djangoproject.com/en/dev/intro/tutorial01/#intro-tutorial01).
Created a mysite database in MySQL 5 running on Snow Leopard.
Edited the settings.py file to look like this:
```
DATABASE_ENGINE = 'mysql'
DATABASE... | The problem is that you are missing the Python module that interfaces with MySQL.
See the Django docs for [get your database running](http://docs.djangoproject.com/en/dev/topics/install/#get-your-database-running) which further points to [MySQL notes](http://docs.djangoproject.com/en/dev/ref/databases/#id2).
However,... |
Django manage.py syncdb throwing No module named MySQLdb | 1,746,863 | 10 | 2009-11-17T05:52:15Z | 1,749,102 | 14 | 2009-11-17T14:01:53Z | [
"python",
"mysql",
"django",
"osx",
"osx-snow-leopard"
] | I am a newbie learning Python/Django...
Am using the following tutorial located [here](http://docs.djangoproject.com/en/dev/intro/tutorial01/#intro-tutorial01).
Created a mysite database in MySQL 5 running on Snow Leopard.
Edited the settings.py file to look like this:
```
DATABASE_ENGINE = 'mysql'
DATABASE... | ```
sudo easy_install mysql-python
```
will install the MySQLdb module to allow you to work with MySQL from Python, or, if you want to work with virtualenv (which you should),
```
sudo easy_install virtualenv virtualenvwrapper
export WORKON_HOME=$HOME/.virtualenvs
export PIP_VIRTUALENV_BASE=$WORKON_HOME
source /usr/l... |
python reduce error? | 1,746,999 | 2 | 2009-11-17T06:37:30Z | 1,747,015 | 7 | 2009-11-17T06:42:49Z | [
"python",
"lambda",
"arguments",
"reduce"
] | The following is my python code:
```
>>> item = 1
>>> a = []
>>> a.append((1,2,3))
>>> a.append((7,2,4))
>>> sums=reduce(lambda x:abs(item-x[1]),a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: <lambda>() takes exactly 1 argument (2 given)
>>>
```
How can I fix it?
Thanks! | Your lambda takes only one argument, but `reduce` requires a function that takes two arguments. Make your lambda take two arguments.
Since you didn't say what you want this code to do, I'll just guess:
```
the_sum=reduce(lambda x,y:abs(y[1]-x[1]),a)
``` |
Is there a speed difference between WSGI and FCGI? | 1,747,266 | 25 | 2009-11-17T07:59:18Z | 1,747,336 | 17 | 2009-11-17T08:19:44Z | [
"python",
"wsgi",
"fastcgi"
] | From the web I've gleaned that WSGI is a CGI for python web development/frameworks. FCGI seems to be a more generalised gateway for a variety of languages. Don't know the performance difference between the two in reference to the languages python and C/++. | They are two different things. WSGI is a Python specific interface for writing web applications. There are wrappers for about any web server protocol to provide the WSGI interface. FastGCI (FCGI) is one of such web server protocols. So, WSGI is an abstraction layer, while CGI/FastCGI/mod\_python are how the actual web ... |
Is there a speed difference between WSGI and FCGI? | 1,747,266 | 25 | 2009-11-17T07:59:18Z | 1,748,161 | 60 | 2009-11-17T11:14:56Z | [
"python",
"wsgi",
"fastcgi"
] | From the web I've gleaned that WSGI is a CGI for python web development/frameworks. FCGI seems to be a more generalised gateway for a variety of languages. Don't know the performance difference between the two in reference to the languages python and C/++. | Correct, WSGI is a Python programmatic API definition and FASTCGI is a language agnostic socket wire protocol definition. Effectively they are at different layers with WSGI being a higher layer. In other words, one can implement WSGI on top of something that so happened to use FASTCGI to communicate with a web server, ... |
Integration Testing for a Web App | 1,747,772 | 8 | 2009-11-17T09:59:30Z | 1,747,804 | 11 | 2009-11-17T10:05:47Z | [
"python",
"ruby",
"perl",
"automated-tests",
"integration-testing"
] | I want to do full integration testing for a web application. I want to test many things like AJAX, positioning and presence of certain phrases and HTML elements **using several browsers**. I'm seeking a tool to do such automated testing.
On the other hand; this is my first time using integration testing. Are there any... | If you need to do full testing including exploiting browser features like AJAX then I would recomend [Selenium](http://seleniumhq.org/). Selenium launches a browser and controls it to run the tests.
It supports all the major [platforms and browsers](http://seleniumhq.org/about/platforms.html). Selenium itself is imple... |
Integration Testing for a Web App | 1,747,772 | 8 | 2009-11-17T09:59:30Z | 1,748,507 | 10 | 2009-11-17T12:22:22Z | [
"python",
"ruby",
"perl",
"automated-tests",
"integration-testing"
] | I want to do full integration testing for a web application. I want to test many things like AJAX, positioning and presence of certain phrases and HTML elements **using several browsers**. I'm seeking a tool to do such automated testing.
On the other hand; this is my first time using integration testing. Are there any... | [`Selenium`](http://seleniumhq.org/) is a good way to go. For using it with Perl then use the [`Test::WWW::Selenium`](http://search.cpan.org/dist/Test-WWW-Selenium/) CPAN module.
Here is [one example](http://search.cpan.org/dist/Test-WWW-Selenium/util/create%5Fwww%5Fselenium.pl) from its pod:
```
use WWW::Selenium;
... |
Create a dictionary with list comprehension in Python | 1,747,817 | 692 | 2009-11-17T10:07:53Z | 1,747,827 | 1,129 | 2009-11-17T10:09:32Z | [
"python",
"dictionary",
"language-features",
"list-comprehension"
] | I like the Python list comprehension syntax.
Can it be used to create dictionaries too? For example, by iterating over pairs of keys and values:
```
mydict = {(k,v) for (k,v) in blah blah blah} # doesn't work :(
``` | In Python 2.6 and earlier, the dict constructor can receive an iterable of key/value pairs:
```
d = dict((key, value) for (key, value) in iterable)
```
From Python 2.7 and 3 onwards, you can just use the [dict comprehension syntax](http://www.python.org/dev/peps/pep-0274/) directly:
```
d = {key: value for (key, val... |
Create a dictionary with list comprehension in Python | 1,747,817 | 692 | 2009-11-17T10:07:53Z | 1,747,888 | 123 | 2009-11-17T10:22:45Z | [
"python",
"dictionary",
"language-features",
"list-comprehension"
] | I like the Python list comprehension syntax.
Can it be used to create dictionaries too? For example, by iterating over pairs of keys and values:
```
mydict = {(k,v) for (k,v) in blah blah blah} # doesn't work :(
``` | In Python 3 / Python 2.7+ dict comprehensions works like this:
```
d = {k:v for k, v in iterable}
```
For Python 2.6 and earlier, see @fortan's answer. |
Create a dictionary with list comprehension in Python | 1,747,817 | 692 | 2009-11-17T10:07:53Z | 1,747,904 | 10 | 2009-11-17T10:27:29Z | [
"python",
"dictionary",
"language-features",
"list-comprehension"
] | I like the Python list comprehension syntax.
Can it be used to create dictionaries too? For example, by iterating over pairs of keys and values:
```
mydict = {(k,v) for (k,v) in blah blah blah} # doesn't work :(
``` | Use Python dict comprehensions. Here's the page to know more about it: *[Dict Comprehensions](http://www.python.org/dev/peps/pep-0274/)*. |
Create a dictionary with list comprehension in Python | 1,747,817 | 692 | 2009-11-17T10:07:53Z | 16,863,042 | 16 | 2013-05-31T17:48:45Z | [
"python",
"dictionary",
"language-features",
"list-comprehension"
] | I like the Python list comprehension syntax.
Can it be used to create dictionaries too? For example, by iterating over pairs of keys and values:
```
mydict = {(k,v) for (k,v) in blah blah blah} # doesn't work :(
``` | In fact, you don't even need to iterate over the iterable if it already comprehends some kind of mapping, the dict constructor doing it graciously for you:
```
>>> ts = [(1, 2), (3, 4), (5, 6)]
>>> dict(ts)
{1: 2, 3: 4, 5: 6}
>>> gen = ((i, i+1) for i in range(1, 6, 2))
>>> gen
<generator object <genexpr> at 0xb7201c5... |
Create a dictionary with list comprehension in Python | 1,747,817 | 692 | 2009-11-17T10:07:53Z | 33,005,845 | 13 | 2015-10-08T02:59:01Z | [
"python",
"dictionary",
"language-features",
"list-comprehension"
] | I like the Python list comprehension syntax.
Can it be used to create dictionaries too? For example, by iterating over pairs of keys and values:
```
mydict = {(k,v) for (k,v) in blah blah blah} # doesn't work :(
``` | In Python 2.7, it goes like:
```
>>> list1, list2 = ['a', 'b', 'c'], [1,2,3]
>>> dict( zip( list1, list2))
{'a': 1, 'c': 3, 'b': 2}
```
**Zip them**! |
Boolean in Python | 1,748,641 | 48 | 2009-11-17T12:48:39Z | 1,748,651 | 64 | 2009-11-17T12:51:13Z | [
"python",
"boolean"
] | Does Python actually contain a Boolean value? I know that you can do:
```
checker = 1
if checker:
#dostuff
```
But I'm quite pedantic and enjoy seeing booleans in Java. For instance:
```
Boolean checker;
if (someDecision)
{
checker = true;
}
if(checker)
{
//some stuff
}
```
Is there such a thing as this... | ```
checker = None # not necessary
if some_decision:
checker = True
if checker:
# some stuff
```
[Edit]
For more information: <http://docs.python.org/library/functions.html#bool>
Your code works too, since 1 is converted to True when necessary.
Actually Python didn't have a boolean type for a long time (as... |
Boolean in Python | 1,748,641 | 48 | 2009-11-17T12:48:39Z | 1,748,672 | 61 | 2009-11-17T12:54:43Z | [
"python",
"boolean"
] | Does Python actually contain a Boolean value? I know that you can do:
```
checker = 1
if checker:
#dostuff
```
But I'm quite pedantic and enjoy seeing booleans in Java. For instance:
```
Boolean checker;
if (someDecision)
{
checker = true;
}
if(checker)
{
//some stuff
}
```
Is there such a thing as this... | The boolean builtins are capitalized: `True` and `False`.
Note also that you can do `checker = bool(some_decision)` as a bit of shorthand -- [`bool`](http://docs.python.org/library/functions.html#bool) will only ever return `True` or `False`.
It's good to know for future reference that [classes defining `__nonzero__`... |
Boolean in Python | 1,748,641 | 48 | 2009-11-17T12:48:39Z | 1,748,727 | 7 | 2009-11-17T13:02:57Z | [
"python",
"boolean"
] | Does Python actually contain a Boolean value? I know that you can do:
```
checker = 1
if checker:
#dostuff
```
But I'm quite pedantic and enjoy seeing booleans in Java. For instance:
```
Boolean checker;
if (someDecision)
{
checker = true;
}
if(checker)
{
//some stuff
}
```
Is there such a thing as this... | `True` ... and `False` obviously.
Otherwise, `None` evaluates to False, as does the integer `0` and also the float `0.0` (although I wouldn't use floats like that).
Also, empty lists `[]`, empty tuplets `()`, and empty strings `''` or `""` evaluate to False.
Try it yourself with the function `bool()`:
```
bool([])
b... |
How to detect whether two files are identical in Python | 1,748,923 | 4 | 2009-11-17T13:36:40Z | 1,748,935 | 13 | 2009-11-17T13:38:09Z | [
"python",
"file",
"md5",
"compare"
] | Is making system call to "md5sum file1" and "md5sum file2" and compare two return values enough in this case? | Well, that will tell you whether they're definitely different or *probably* the same. It's *possible* for two files to have the same hash but not actually have the same data... just very unlikely.
In your situation, what is the impact if you get a false positive (i.e. if you think they're the same, but they're not)? M... |
How to detect whether two files are identical in Python | 1,748,923 | 4 | 2009-11-17T13:36:40Z | 1,748,996 | 12 | 2009-11-17T13:46:25Z | [
"python",
"file",
"md5",
"compare"
] | Is making system call to "md5sum file1" and "md5sum file2" and compare two return values enough in this case? | If you want to do more than just detect if they differ, or don't trust the hashing solution, there are modules called [difflib](http://docs.python.org/library/difflib.html) and [filecmp](http://docs.python.org/library/filecmp.html) that doesn't rely on external programs. |
How to detect whether two files are identical in Python | 1,748,923 | 4 | 2009-11-17T13:36:40Z | 1,749,019 | 7 | 2009-11-17T13:50:54Z | [
"python",
"file",
"md5",
"compare"
] | Is making system call to "md5sum file1" and "md5sum file2" and compare two return values enough in this case? | Of course there is a simple test that you should do before comparing the file content at all - if the files are different sizes, then they can not possibly be the same.
Wouldn't it be more efficient to simply read each file and do a byte-by-byte comparison, avoiding the hashing algorithm altogether. This avoids the th... |
What's the most pythonic way of normalizing lineends in a string? | 1,749,466 | 5 | 2009-11-17T15:02:46Z | 1,749,553 | 7 | 2009-11-17T15:14:46Z | [
"python",
"newline",
"line-breaks"
] | Given a text-string of unknown source, how does one best rewrite it to have a known lineend-convention?
I usually do:
```
lines = text.splitlines()
text = '\n'.join(lines)
```
... but this doesn't handle "mixed" text-files of utterly confused conventions (Yes, they still exist!).
## Edit
The oneliner of what I'm d... | > ... but this doesn't handle "mixed" text-files of utterly confused conventions (Yes, they still exist!)
Actually it should work fine:
```
>>> s = 'hello world\nline 1\r\nline 2'
>>> s.splitlines()
['hello world', 'line 1', 'line 2']
>>> '\n'.join(s.splitlines())
'hello world\nline 1\nline 2'
```
What version of ... |
What's the most pythonic way of normalizing lineends in a string? | 1,749,466 | 5 | 2009-11-17T15:02:46Z | 1,749,887 | 11 | 2009-11-17T16:04:07Z | [
"python",
"newline",
"line-breaks"
] | Given a text-string of unknown source, how does one best rewrite it to have a known lineend-convention?
I usually do:
```
lines = text.splitlines()
text = '\n'.join(lines)
```
... but this doesn't handle "mixed" text-files of utterly confused conventions (Yes, they still exist!).
## Edit
The oneliner of what I'm d... | ```
mixed.replace('\r\n', '\n').replace('\r', '\n')
```
should handle all possible variants. |
Replacement for python statvfs? | 1,749,928 | 6 | 2009-11-17T16:10:25Z | 1,749,950 | 7 | 2009-11-17T16:13:31Z | [
"python"
] | The [python statvfs module](http://docs.python.org/library/statvfs.html) was marked as deprecated since python 2.6 and it's now removed since python 3.0. I haven't been able to figure out what apps are supposed to use if they want to get information about a disk, specifically how to check the capacity and free space of... | It appears that only the module that contains the constants for sequential access is being deprecated.
Doing
```
x = os.statvfs('/')
x.f_favail
```
will still work.
Sidenote: according to the docs, this function is only available on unix based platforms. So OSX and linux variants are fine, as is freeBSD and others,... |
Fractal image scaling with Python | 1,750,290 | 4 | 2009-11-17T17:02:45Z | 1,750,331 | 9 | 2009-11-17T17:09:27Z | [
"python",
"image-processing",
"python-imaging-library",
"fractals"
] | I am in a position where **relatively low resolution** images are provided (via an API, higher resolution images are not available) and **high resolution** images need to be generated.
I've taken a look at [PIL](http://www.pythonware.com/products/pil/) and it's just great for about everything... Except scaling up imag... | There are algorithms, and you're definitely not going to find them in Python. To start with, you can take this paper:
Daniel Glasner, Shai Bagon, and Michal Irani, "Super-Resolution from a Single Image," in Proceedings of the IEEE International Conference on Computer Vision, Kyoto, Japan, 2009.
It is very much state ... |
Fastest way to search 1GB+ a string of data for the first occurence of a pattern in Python | 1,750,343 | 12 | 2009-11-17T17:11:40Z | 1,750,774 | 11 | 2009-11-17T18:19:04Z | [
"python",
"algorithm",
"search",
"large-data-volumes"
] | There's a 1 Gigabyte string of arbitrary data which you can assume to be equivalent to something like:
```
1_gb_string=os.urandom(1*gigabyte)
```
We will be searching this string, `1_gb_string`, for an infinite number of fixed width, 1 kilobyte patterns, `1_kb_pattern`. Every time we search the pattern will be differ... | As you clarify that long-ish preprocessing is acceptable, I'd suggest a variant of [Rabin-Karp](http://en.wikipedia.org/wiki/Rabin-karp): "an algorithm of choice for multiple pattern search", as wikipedia puts it.
Define a "rolling hash" function, i.e., one such that, when you know the hash for `haystack[x:x+N]`, comp... |
Django development server CPU intensive - how to analyse? | 1,750,676 | 4 | 2009-11-17T18:01:16Z | 1,756,874 | 9 | 2009-11-18T15:41:32Z | [
"python",
"django",
"cpu"
] | I'm noticing that my django development server (version 1.1.1) on my local windows7 machine is using a lot of CPU (~30%, according to task manager's python.exe entry), even in idle state, i.e. no request coming in/going out. Is there an established way of analysing what might be responsible for this?
Thanks!
Martin | FWIW, you should do the profiling, but when you do I'll bet you find that the answer is "polling for changes to your files so it can auto-reload." You might do a quick test with "python manage.py runserver --noreload" and see how that affects the CPU usage. |
Restarting a self-updating python script | 1,750,757 | 24 | 2009-11-17T18:16:55Z | 1,750,797 | 20 | 2009-11-17T18:23:27Z | [
"python",
"auto-update"
] | I have written a script that will keep itself up to date by downloading the latest version from a website and overwriting the running script.
I am not sure what the best way to restart the script after it has been updated.
Any ideas?
I don't really want to have a separate update script.
oh and it has to work on both... | In Linux, or any other form of unix, [os.execl](http://docs.python.org/library/os.html?highlight=os.exec#os.execl) and friends are a good choice for this -- you just need to re-exec [sys.executable](http://docs.python.org/library/sys.html?highlight=sys.executable#sys.executable) with the same parameters it was executed... |
Restarting a self-updating python script | 1,750,757 | 24 | 2009-11-17T18:16:55Z | 5,758,926 | 10 | 2011-04-22T18:54:14Z | [
"python",
"auto-update"
] | I have written a script that will keep itself up to date by downloading the latest version from a website and overwriting the running script.
I am not sure what the best way to restart the script after it has been updated.
Any ideas?
I don't really want to have a separate update script.
oh and it has to work on both... | The CherryPy project has code that restarts itself. Here's [how they do it](http://www.cherrypy.org/browser/trunk/py2/cherrypy/process/wspbus.py#L345):
```
args = sys.argv[:]
self.log('Re-spawning %s' % ' '.join(args))
args.insert(0, sys.executable)
if sys.platform == 'win32':
args = ['"%s"' %... |
Obtain MAC Address from Devices using Python | 1,750,803 | 12 | 2009-11-17T18:24:09Z | 1,750,931 | 12 | 2009-11-17T18:44:39Z | [
"python",
"ip-address",
"mac-address"
] | I'm looking for a way (with python) to obtain the layer II address from a device on my local network. Layer III addresses are known.
The goal is to build a script that will poll a databases of IP addresses on regular intervals ensuring that the mac addresses have not changed and if they have, email alerts to myself. | To answer the question with Python depends on your platform. I don't have Windows handy, so the following solution works on the Linux box I wrote it on. A small change to the regular expression will make it work in OS X.
First, you must ping the target. That will place the target -- as long as it's within your netmask... |
Peeking in a heap in python | 1,750,991 | 12 | 2009-11-17T18:57:07Z | 1,751,007 | 19 | 2009-11-17T19:00:17Z | [
"python",
"heap",
"peek"
] | What is the official way of peeking in a python heap as created by the heapq libs? Right now I have
```
def heappeak(heap):
smallest = heappop(heap)
heappush(heap, smallest)
return smallest
```
which is arguably, not very nice. Can I always assume that `heap[0]` is the top of the heap and use that? Or would tha... | Yes, you can make this assumption, because it is stated in the [documentation](http://docs.python.org/3.1/library/heapq.html):
> Heaps are arrays for which `heap[k] <= heap[2*k+1]` and `heap[k] <=
> heap[2*k+2]` for all *k*, counting
> elements from zero. For the sake of
> comparison, non-existing elements are
> consi... |
Python equivalent of ruby's StringScanner? | 1,751,949 | 2 | 2009-11-17T21:31:08Z | 1,752,076 | 9 | 2009-11-17T21:48:06Z | [
"python",
"ruby",
"string"
] | Is there a python class equivalent to ruby's [StringScanner class](http://ruby-doc.org/core/classes/StringScanner.html)? I Could hack something together, but i don't want to reinvent the wheel if this already exists. | Interestingly there's an undocumented [Scanner](http://code.activestate.com/recipes/457664/) class in the [re](http://docs.python.org/library/re.html) module:
```
import re
def s_ident(scanner, token): return token
def s_operator(scanner, token): return "op%s" % token
def s_float(scanner, token): return float(token)
... |
How can I append data to a text file with a line break using Python? | 1,752,019 | 2 | 2009-11-17T21:39:11Z | 1,752,047 | 10 | 2009-11-17T21:42:41Z | [
"python"
] | I've just been asked to come up with a script to find files with a certain filename length. I've decided to try out Python for the first time for this task as I've always wanted to learn it.
I've got the script to find the files and append them to a text file but it does not write a line break for each new entry. Is t... | You just need to explicitly append a `'\n'` each time you want a line break -- if you're appending to the output file in text mode, this will expand to the proper line separation where needed (e.g. Windows). (You could use [os.linesep](http://docs.python.org/library/os.html?highlight=linesep#os.linesep) instead, if you... |
How to loop until EOF in Python? | 1,752,107 | 8 | 2009-11-17T21:53:01Z | 1,752,155 | 9 | 2009-11-17T22:00:37Z | [
"python",
"eof",
"stringio"
] | I need to loop until I hit the end of a file-like object, but I'm not finding an "obvious way to do it", which makes me suspect I'm overlooking something, well, obvious. :-)
I have a stream (in this case, it's a StringIO object, but I'm curious about the general case as well) which stores an unknown number of records ... | Have you seen how to iterate over lines in a text file?
```
for line in file_obj:
use(line)
```
You can do the same thing with your own generator:
```
def read_blocks(file_obj, size):
while True:
data = file_obj.read(size)
if not data:
break
yield data
for block in read_blocks(file_obj, 4):
... |
How to loop until EOF in Python? | 1,752,107 | 8 | 2009-11-17T21:53:01Z | 1,752,208 | 22 | 2009-11-17T22:09:52Z | [
"python",
"eof",
"stringio"
] | I need to loop until I hit the end of a file-like object, but I'm not finding an "obvious way to do it", which makes me suspect I'm overlooking something, well, obvious. :-)
I have a stream (in this case, it's a StringIO object, but I'm curious about the general case as well) which stores an unknown number of records ... | You can combine iteration through [iter()](http://docs.python.org/library/functions.html#iter) with a sentinel:
```
for block in iter(lambda: file_obj.read(4), ""):
use(block)
``` |
In Python, what does getresponse() return? | 1,752,283 | 8 | 2009-11-17T22:20:45Z | 1,752,295 | 21 | 2009-11-17T22:22:59Z | [
"python",
"linux",
"http",
"unix"
] | ```
import httplib
conn = httplib.HTTPConnection(head)
conn.request("HEAD",tail)
res = conn.getresponse()
```
I can get the **res.status** , which is the http status code.
What other elements can I get?
Why is it that when I do print **res**, it won't print the dictionary? I just want to see the keys tha... | You can always inspect an object using [`dir`](http://docs.python.org/library/functions.html#dir); that will show you which attributes it has.
```
>>> import httplib
>>> conn = httplib.HTTPConnection("www.google.nl")
>>> conn.request("HEAD", "/index.html")
>>> res = conn.getresponse()
>>> dir(res)
['__doc__', '__init_... |
How to get the true URL of a file on the web. (Python) | 1,752,317 | 6 | 2009-11-17T22:26:55Z | 1,752,362 | 8 | 2009-11-17T22:35:47Z | [
"python",
"linux",
"http",
"unix",
"http-headers"
] | I notice that sometimes audio files on the internet have a "fake" URL.
```
http://garagaeband.com/3252243
```
And this will **302** to the real URL:
```
http://garageband.com/michael_jackson4.mp3
```
My question is...when supplied with the fake URL, how can you **get the REAL URL from headers**?
Currently, this is... | Use urllib.getUrl()
**edit:**
Sorry, I haven't done this in a while:
```
import urllib
urllib.urlopen(url).geturl()
```
For example:
```
>>> f = urllib2.urlopen("http://tinyurl.com/oex2e")
>>> f.geturl()
'http://www.amazon.com/All-Creatures-Great-Small-Collection/dp/B00006G8FI'
>>>
``` |
BeautifulSoup - easy way to to obtain HTML-free contents | 1,752,662 | 7 | 2009-11-17T23:38:20Z | 1,752,754 | 12 | 2009-11-18T00:04:22Z | [
"python",
"beautifulsoup",
"html-parsing",
"html-content-extraction"
] | I'm using this code to find all interesting links in a page:
```
soup.findAll('a', href=re.compile('^notizia.php\?idn=\d+'))
```
And it does its job pretty well. Unfortunately inside that **a** tag there are a lot of nested tags, like **font**, **b** and different things... I'd like to get just the text content, with... | I've used this:
```
def textOf(soup):
return u''.join(soup.findAll(text=True))
```
So...
```
texts = [textOf(n) for n in soup.findAll('a', href=re.compile('^notizia.php\?idn=\d+'))]
``` |
Can this breadth-first search be made faster? | 1,753,257 | 5 | 2009-11-18T02:33:23Z | 1,753,308 | 11 | 2009-11-18T02:44:36Z | [
"python",
"algorithm",
"computer-science",
"breadth-first-search"
] | I have a data set which is a large unweighted cyclic graph The cycles occur in loops of about 5-6 paths. It consists of about 8000 nodes and each node has from 1-6 (usually about 4-5) connections. I'm doing single pair shortest path calculations and have implemented the following code to do a breadth-first search.
```... | Well, given the upvotes on the comment, I'll make it an answer now.
The SQL in the tight loop is **definitely** slowing you down. I don't care how fast the call is. Think about it -- you're asking for a query to be parsed, a lookup to be run -- as fast as that is, it's still in a tight loop. What does your data set lo... |
Python optparse Values Instance | 1,753,460 | 43 | 2009-11-18T03:31:53Z | 1,753,466 | 74 | 2009-11-18T03:34:32Z | [
"python",
"dictionary",
"optparse"
] | How can I take the opt result of
```
opt, args = parser.parse_args()
```
and place it in a dict? Python calls opt a "Values Instance" and I can't find any way to turn a Values Instance into a list or dict. One can't copy items from opt in this way,
```
for i in opt:
myDict[i] = opt[i]
```
instead, its a clumsy,
`... | ```
options, args = parser.parse_args()
option_dict = vars(options)
```
[(Source is this python-ideas post.)](http://mail.python.org/pipermail/python-ideas/2009-March/003623.html) |
What approach(es) have you used for lightweight Python unit-tests on App Engine? | 1,753,897 | 38 | 2009-11-18T05:44:45Z | 1,755,291 | 13 | 2009-11-18T11:12:23Z | [
"python",
"unit-testing",
"google-app-engine"
] | I'm about to embark on some large Python-based App Engine projects, and I think I should check with Stack Overflow's "wisdom of crowds" before committing to a unit-testing strategy. I have an existing unit-testing framework (based on [unittest](http://docs.python.org/library/unittest.html?highlight=unittest#module-unit... | You don't need to write your own stubs - the SDK includes them, since they're what it uses to emulate the production APIs. Not all of them are suitable for use in unit-tests, but most are. Check out [this code](http://gist.github.com/186251) for an example of the setup/teardown code you need to make use of the built in... |
Qt Python radiobutton: activate event | 1,753,939 | 2 | 2009-11-18T05:56:55Z | 1,754,167 | 9 | 2009-11-18T07:10:11Z | [
"python",
"user-interface",
"qt",
"qt4",
"pyqt"
] | I am developing a project for one customer, where the design has a radio button with exclusive options.
Here is a piece of the code that runs and show two nice radio buttons:
```
self.performGroupBox = QtGui.QGroupBox(self.centralwidget)
self.performGroupBox.setGeometry(QtCore.QRect(50, 20, 181, 121))
sel... | Try this signal instead:
```
void toggled (bool)
```
<http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qabstractbutton.html#toggled> |
How can I run a Makefile in setup.py? | 1,754,966 | 24 | 2009-11-18T10:15:42Z | 1,763,900 | 27 | 2009-11-19T15:02:48Z | [
"python",
"distutils"
] | I need to compile [ICU](http://icu-project.org) using it's own build mechanism. Therefore the question:
How can I run a Makefile from `setup.py`? Obviously, I only want it to run during the build process, not while installing. | The method I normally use is to override the command in question:
```
from distutils.command.install import install as DistutilsInstall
class MyInstall(DistutilsInstall):
def run(self):
do_pre_install_stuff()
DistutilsInstall.run(self)
do_post_install_stuff()
...
setup(..., cmdclass={'in... |
Understanding Generators in Python | 1,756,096 | 92 | 2009-11-18T13:46:51Z | 1,756,152 | 17 | 2009-11-18T13:53:35Z | [
"python",
"generator"
] | Reading the Python cookbook at the minute and currently looking at generators. I'm finding it hard to get my head round.
As I come from a Java background, is there a Java equivalent? The book was speaking about 'Producer / Consumer', however when I hear that I think of threading.
Can anyone explain what a generator i... | Generators could be thought of as shorthand for creating an iterator. They behave like a Java Iterator. Example:
```
>>> g = (x for x in range(10))
>>> g
<generator object <genexpr> at 0x7fac1c1e6aa0>
>>> g.next()
0
>>> g.next()
1
>>> g.next()
2
>>> list(g) # force iterating the rest
[3, 4, 5, 6, 7, 8, 9]
>>> g.next... |
Understanding Generators in Python | 1,756,096 | 92 | 2009-11-18T13:46:51Z | 1,756,156 | 175 | 2009-11-18T13:54:07Z | [
"python",
"generator"
] | Reading the Python cookbook at the minute and currently looking at generators. I'm finding it hard to get my head round.
As I come from a Java background, is there a Java equivalent? The book was speaking about 'Producer / Consumer', however when I hear that I think of threading.
Can anyone explain what a generator i... | **Note: this post assumes Python 3.x syntax.**†
A [generator](http://www.python.org/dev/peps/pep-0255/) is simply a function which returns an object on which you can call `next`, such that for every call it returns some value, until it raises a `StopIteration` exception, signaling that all values have been generated. ... |
Understanding Generators in Python | 1,756,096 | 92 | 2009-11-18T13:46:51Z | 1,756,342 | 25 | 2009-11-18T14:24:02Z | [
"python",
"generator"
] | Reading the Python cookbook at the minute and currently looking at generators. I'm finding it hard to get my head round.
As I come from a Java background, is there a Java equivalent? The book was speaking about 'Producer / Consumer', however when I hear that I think of threading.
Can anyone explain what a generator i... | A generator is effectively a function that returns (data) before it is finished, but it pauses at that point, and you can resume the function at that point.
```
>>> def myGenerator():
... yield 'These'
... yield 'words'
... yield 'come'
... yield 'one'
... yield 'at'
... yield 'a'
... yield... |
Understanding Generators in Python | 1,756,096 | 92 | 2009-11-18T13:46:51Z | 1,756,430 | 14 | 2009-11-18T14:35:54Z | [
"python",
"generator"
] | Reading the Python cookbook at the minute and currently looking at generators. I'm finding it hard to get my head round.
As I come from a Java background, is there a Java equivalent? The book was speaking about 'Producer / Consumer', however when I hear that I think of threading.
Can anyone explain what a generator i... | First of all the term **generator** originally was somewhat ill-defined in Python, leading to lots of confusion. What you probably mean are **iterators** and **iterables** (see [here](http://docs.python.org/library/stdtypes.html#typeiter)). Then in Python there are also **generator functions** (which return a generator... |
What is causing ImportError: No module named pkg_resources after upgrade of Python on os X? | 1,756,721 | 76 | 2009-11-18T15:19:25Z | 1,757,269 | 71 | 2009-11-18T16:31:32Z | [
"python",
"ipython"
] | I just updated Python to 2.6.4 on my Mac.
I installed from the dmg package.
The binary did not seem to correctly set my Python path, so I added `'/usr/local/lib/python2.6/site-packages'` in `.bash_profile`
```
>>> pprint.pprint(sys.path)
['',
'/Users/Bryan/work/django-trunk',
'/usr/local/lib/python2.6/site-package... | [UPDATE] TL;DR `pkg_resources` is provided by either [Distribute](http://pypi.python.org/pypi/distribute/) or [setuptools](http://pypi.python.org/pypi/setuptools/).
[UPDATE 2] As announced at PyCon 2013, the `Distribute` and `setuptools` projects have re-merged. `Distribute` is now deprecated and you should just use t... |
What is causing ImportError: No module named pkg_resources after upgrade of Python on os X? | 1,756,721 | 76 | 2009-11-18T15:19:25Z | 9,883,577 | 7 | 2012-03-27T04:57:37Z | [
"python",
"ipython"
] | I just updated Python to 2.6.4 on my Mac.
I installed from the dmg package.
The binary did not seem to correctly set my Python path, so I added `'/usr/local/lib/python2.6/site-packages'` in `.bash_profile`
```
>>> pprint.pprint(sys.path)
['',
'/Users/Bryan/work/django-trunk',
'/usr/local/lib/python2.6/site-package... | In case of upgrading your python on mac os 10.7 and pkg\_resources doesn't work, the simplest way to fix this is just reinstall setuptools as Ned mentioned above.
```
sudo pip install setuptools --upgrade
or sudo easy_install install setuptools --upgrade
``` |
What is causing ImportError: No module named pkg_resources after upgrade of Python on os X? | 1,756,721 | 76 | 2009-11-18T15:19:25Z | 10,538,341 | 76 | 2012-05-10T16:25:53Z | [
"python",
"ipython"
] | I just updated Python to 2.6.4 on my Mac.
I installed from the dmg package.
The binary did not seem to correctly set my Python path, so I added `'/usr/local/lib/python2.6/site-packages'` in `.bash_profile`
```
>>> pprint.pprint(sys.path)
['',
'/Users/Bryan/work/django-trunk',
'/usr/local/lib/python2.6/site-package... | I encountered the same `ImportError`. Somehow the `setuptools` package had been deleted in my Python environment.
To fix the issue, run the setup script for `setuptools`:
```
curl https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py | python
```
If you have any version of [`distribute`](http://pythonhoste... |
removing the oldest element from a dictionary in python | 1,756,992 | 3 | 2009-11-18T15:56:50Z | 1,757,039 | 7 | 2009-11-18T16:01:30Z | [
"python",
"dictionary"
] | I would like to know the best way to remove the **oldest** element in a dictionary in order to control the maximum dictionary size.
**example**:
```
MAXSIZE = 4
dict = {}
def add(key,value):
if len(dict) == MAXSIZE:
old = get_oldest_key() # returns the key to the oldest item
del dict[old]
dict[key] = valu... | Dictionaries don't preserve order, so you can't tell which element had been added first. You could combine the dictionary with a list of it's keys to preserve order.
Here's an [activestate recipe](http://code.activestate.com/recipes/496761/) for an ordered dict that does just this.
There's also [PEP-0372](http://www.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.