title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
How to replicate tee behavior in Python when using subprocess? | 2,996,887 | 26 | 2010-06-08T11:36:13Z | 11,688,535 | 8 | 2012-07-27T13:18:09Z | [
"python",
"subprocess",
"stdout",
"stderr",
"tee"
] | I'm looking for a Python solution that will allow me to save the output of a command in a file without hiding it from the console.
FYI: I'm asking about [tee](https://en.wikipedia.org/wiki/Tee_%28command%29) (as the Unix command line utility) and not the function with the same name from Python intertools module.
### ... | I see that this is a rather old post but just in case someone is still searching for a way to do this:
```
proc = subprocess.Popen(["ping", "localhost"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
with open("logfile.txt", "w") as log_file:
while proc.poll() is ... |
importing classes python | 2,997,105 | 3 | 2010-06-08T12:09:34Z | 2,997,126 | 8 | 2010-06-08T12:14:00Z | [
"python",
"import"
] | Just wondering why
```
import sys
exit(0)
```
gives me this error:
```
Traceback (most recent call last):
File "<pyshell#1>", line 1, in ?
exit(0)
TypeError: 'str' object is not callable
```
but
```
from sys import exit
exit(0)
```
works fine? | Python imports only the chosen names into the namespace.
Your equivalent first solution should be
```
sys.exit(0)
```
since `import sys` imports only the `sys` keyword into the current namespace. |
Django: Filtering datetime field by *only* the year value? | 2,997,433 | 9 | 2010-06-08T12:57:37Z | 2,997,735 | 22 | 2010-06-08T13:35:54Z | [
"python",
"django",
"django-models",
"group-by",
"django-queryset"
] | I'm trying to spit out a django page which lists all entries by the year they were created. So, for example:
2010:
* Note 4
* Note 5
* Note 6
2009:
* Note 1
* Note 2
* Note 3
It's proving more difficult than I would have expected. The model from which the data comes is below:
```
class Note(models.Model):
bus... | Either construct custom SQL or use
```
date_list = Note.objects.all().dates('created', 'year')
for years in date_list:
Note.objects.filter(created__year = years.year)
```
This is the way it is done in date based generic views. |
Matching a+ in a regex | 2,997,869 | 6 | 2010-06-08T13:51:27Z | 2,997,888 | 8 | 2010-06-08T13:53:57Z | [
"python",
"regex"
] | This should be easy, but I've managed to stump 2 people so far at work & I've been at it for over 3 hours now, so here goes.
I need to replace a+ with aplus (along with a few other cases) with the Python re module.
eg. "I passed my a+ exam." needs to become "I passed my aplus exam."
Just using \ba+ works fine most of... | Turn that `\W` into an assertion.
```
\ba\+(?=\W)
```
or, better,
```
\ba\+(?!\w)
```
since the negative assertion allows matching the `a+` at end of string too. |
If Python is interpreted, what are .pyc files? | 2,998,215 | 510 | 2010-06-08T14:27:13Z | 2,998,228 | 351 | 2010-06-08T14:28:40Z | [
"python",
"compiled",
"interpreted",
"pyc"
] | I've been given to understand that Python is an interpreted language... However, when I look at my Python source code I see `.pyc` files, which Windows identifies as "Compiled Python Files". Where do these come in? | They contain [byte code](http://en.wikipedia.org/wiki/Bytecode), which is what the Python interpreter compiles the source to. This code is then executed by Python's virtual machine.
Python's documentation explains the definition like this:
> Python is an interpreted language, as
> opposed to a compiled one, though th... |
If Python is interpreted, what are .pyc files? | 2,998,215 | 510 | 2010-06-08T14:27:13Z | 2,998,248 | 46 | 2010-06-08T14:30:35Z | [
"python",
"compiled",
"interpreted",
"pyc"
] | I've been given to understand that Python is an interpreted language... However, when I look at my Python source code I see `.pyc` files, which Windows identifies as "Compiled Python Files". Where do these come in? | These are created by the Python interpreter when a `.py` file is imported, and they contain the "compiled bytecode" of the imported module/program, the idea being that the "translation" from source code to bytecode (which only needs to be done once) can be skipped on subsequent `import`s if the `.pyc` is newer than the... |
If Python is interpreted, what are .pyc files? | 2,998,215 | 510 | 2010-06-08T14:27:13Z | 2,998,544 | 542 | 2010-06-08T15:00:58Z | [
"python",
"compiled",
"interpreted",
"pyc"
] | I've been given to understand that Python is an interpreted language... However, when I look at my Python source code I see `.pyc` files, which Windows identifies as "Compiled Python Files". Where do these come in? | > I've been given to understand that
> Python is an interpreted language...
This popular meme is incorrect, or, rather, constructed upon a misunderstanding of (natural) language levels: a similar mistake would be to say "the Bible is a hardcover book". Let me explain that simile...
"The Bible" is "a book" in the sens... |
If Python is interpreted, what are .pyc files? | 2,998,215 | 510 | 2010-06-08T14:27:13Z | 2,998,549 | 14 | 2010-06-08T15:01:16Z | [
"python",
"compiled",
"interpreted",
"pyc"
] | I've been given to understand that Python is an interpreted language... However, when I look at my Python source code I see `.pyc` files, which Windows identifies as "Compiled Python Files". Where do these come in? | Python (at least the most common implementation of it) follows a pattern of compiling the original source to byte codes, then interpreting the byte codes on a virtual machine. This means (again, the most common implementation) is neither a pure interpreter nor a pure compiler.
The other side of this is, however, that ... |
If Python is interpreted, what are .pyc files? | 2,998,215 | 510 | 2010-06-08T14:27:13Z | 2,998,750 | 88 | 2010-06-08T15:25:36Z | [
"python",
"compiled",
"interpreted",
"pyc"
] | I've been given to understand that Python is an interpreted language... However, when I look at my Python source code I see `.pyc` files, which Windows identifies as "Compiled Python Files". Where do these come in? | There is no such thing as an interpreted language. Whether an interpreter or a compiler is used is purely a trait of the *implementation* and has absolutely nothing whatsoever to do with the language.
*Every* language can be implemented by either an interpreter or a compiler. The vast majority of languages have at lea... |
If Python is interpreted, what are .pyc files? | 2,998,215 | 510 | 2010-06-08T14:27:13Z | 29,272,458 | 7 | 2015-03-26T06:41:47Z | [
"python",
"compiled",
"interpreted",
"pyc"
] | I've been given to understand that Python is an interpreted language... However, when I look at my Python source code I see `.pyc` files, which Windows identifies as "Compiled Python Files". Where do these come in? | Python code goes through 2 stages. First step compiles the code into .pyc files which is actually a bytecode. Then this .pyc file(bytecode) is interpreted using CPython interpreter. Please refer to [this](http://www.techdarting.com/2014/04/python-compiled-or-interpreted-language.html) link. Here process of code compila... |
Does Python work in larger teams? | 2,999,160 | 6 | 2010-06-08T16:14:19Z | 2,999,269 | 12 | 2010-06-08T16:27:33Z | [
"python",
"large-teams"
] | I read this [post](http://teddziuba.com/2008/12/python-makes-me-nervous.html) last night and it got me thinking. I like python and "batteries", pypi and such. But I've only done python solo. Never tried it in a team.
Are the points that Ted mentions valid? If they are how do teams cope with them? Does Python work in t... | Python works fine in teams. Whether a language works in large teams is largely a factor of how well the team works together, and has little to do with the language. |
Does Python work in larger teams? | 2,999,160 | 6 | 2010-06-08T16:14:19Z | 2,999,317 | 7 | 2010-06-08T16:32:59Z | [
"python",
"large-teams"
] | I read this [post](http://teddziuba.com/2008/12/python-makes-me-nervous.html) last night and it got me thinking. I like python and "batteries", pypi and such. But I've only done python solo. Never tried it in a team.
Are the points that Ted mentions valid? If they are how do teams cope with them? Does Python work in t... | I currently work on a large Django app, and in my previous job I worked on a large Java project (desktop app, not web, but still appropriate to this discussion), and I'm kind of torn between agreeing and disagreeing with the author.
While I enjoy Python over Java, and have ample experience working with other dynamical... |
Specifying the Python interpreter for vim's :python command | 2,999,315 | 9 | 2010-06-08T16:32:38Z | 2,999,725 | 8 | 2010-06-08T17:30:58Z | [
"python",
"vim",
"environment-variables"
] | (Mac)Vim seems to be picking up `/usr/bin/python` instead of the one that's at the front of my path (`/Library/Frameworks/Python.framework/Versions/2.6/bin/python`) when I use the :python command. Is this entirely a compile-time thing or can I somehow override it? | Seems like it is an entirely compile-time thing:
```
$ ldd /usr/bin/vim | grep python
libpython2.5.so.1.0 => /usr/lib/libpython2.5.so.1.0 (0xb6bcc000)
```
my `vim --version` also reports being built against a specific python.
```
$ vim --version | tr '-' '\n' | grep python
+python +quickfix +reltime +rightleft +ruby... |
Python: split files using mutliple split delimiters | 2,999,373 | 2 | 2010-06-08T16:39:58Z | 2,999,477 | 14 | 2010-06-08T16:53:41Z | [
"python",
"csv"
] | I have multiple CSV files which I need to parse in a loop to gather information.
The problem is that while they are the same format, some are delimited by '\t' and others by ','.
After this, I want to remove the double-quote from around the string.
Can python split via multiple possible delimiters?
At the minute, I c... | Splitting the file like that is not a good idea: It will fail if there is a comma within one of the fields. For example (for a tab-delimited file): The line `"field1"\t"Hello, world"\t"field3"` will be split into 4 fields instead of 3.
Instead, you should use the [`csv`](http://docs.python.org/library/csv.html) module... |
How to stop attributes from being pickled in Python | 2,999,638 | 12 | 2010-06-08T17:19:42Z | 2,999,833 | 23 | 2010-06-08T17:46:56Z | [
"python",
"pickle"
] | I am using gnosis.xml.pickle to convert an object of my own class to xml. The object is initialized so that:
```
self.logger = MyLogger()
```
But when I do dump the object to a string I get an exception stating that the pickler encountered an unpickleable type (thread.lock).
Is there a way to 'tag' the logger attrib... | You can define two methods, `__getstate__` and `__setstate__`, to your class to override the default pickling behavior.
[`http://docs.python.org/library/pickle.html#object.__getstate__`](http://docs.python.org/library/pickle.html#object.__getstate__)
`__getstate__` should return a dict of attributes that you want to ... |
Unwanted behaviour from dict.fromkeys | 3,000,468 | 15 | 2010-06-08T19:14:37Z | 3,000,534 | 10 | 2010-06-08T19:23:09Z | [
"python"
] | I'd like to initialise a dictionary of sets (in Python 2.6) using `dict.fromkeys`, but the resulting structure behaves strangely. More specifically:
```
>>>> x = {}.fromkeys(range(10), set([]))
>>>> x
{0: set([]), 1: set([]), 2: set([]), 3: set([]), 4: set([]), 5: set([]), 6: set([]), 7: set([]), 8: set([]), 9: set([]... | The second argument to `dict.fromkeys` is just a value. You've created a dictionary that has the *same* set as the value for every key. Presumably you understand the way this works:
```
>>> a = set()
>>> b = a
>>> b.add(1)
>>> b
set([1])
>>> a
set([1])
```
you're seeing the same behavior there; in your case, `x[0]`, ... |
Unwanted behaviour from dict.fromkeys | 3,000,468 | 15 | 2010-06-08T19:14:37Z | 3,001,033 | 12 | 2010-06-08T20:30:43Z | [
"python"
] | I'd like to initialise a dictionary of sets (in Python 2.6) using `dict.fromkeys`, but the resulting structure behaves strangely. More specifically:
```
>>>> x = {}.fromkeys(range(10), set([]))
>>>> x
{0: set([]), 1: set([]), 2: set([]), 3: set([]), 4: set([]), 5: set([]), 6: set([]), 7: set([]), 8: set([]), 9: set([]... | You can do this with a generator expression:
```
x = dict( (i,set()) for i in range(10) )
```
In Python 3, you can use a dictionary comprehension:
```
x = { i : set() for i in range(10) }
```
In both cases, the expression `set()` is evaluated for each element, instead of being evaluated once and copied to each elem... |
Python Decorators and inheritance | 3,001,138 | 13 | 2010-06-08T20:42:40Z | 3,001,164 | 15 | 2010-06-08T20:45:51Z | [
"python",
"inheritance",
"decorator"
] | Help a guy out. Can't seem to get a decorator to work with inheritance. Broke it down to the simplest little example in my scratch workspace. Still can't seem to get it working.
```
class bar(object):
def __init__(self):
self.val = 4
def setVal(self,x):
self.val = x
def decor(self, func):
... | Define `decor` as a static method and use the form `@bar.decor`:
```
class bar(object):
def __init__(self):
self.val = 4
def setVal(self,x):
self.val = x
@staticmethod
def decor(func):
def increment(self, x):
return func(self, x) + self.val
return increment
... |
OS-independent Inter-program communication between Python and C | 3,001,827 | 6 | 2010-06-08T22:36:18Z | 3,001,851 | 7 | 2010-06-08T22:40:48Z | [
"python",
"c",
"networking",
"network-protocols",
"inter-process-communicat"
] | I have very little idea what I'm doing here, I've never done anything like this before, but a friend and I are writing competing chess programs and they need to be able to communicate to each other.
He'll be writing mainly in C, the bulk of mine will be in Python, and I can see a few options:
* Alternately write to a... | If you want and need truly OS independent, language independent inter process communication, sockets are probably the best option.
This will allow the two programs to communicate across machines, as well (without code changes).
For reading material, here's a [Python Socket Programming How To](http://docs.python.org/h... |
Python to print out status bar and percentage | 3,002,085 | 61 | 2010-06-08T23:27:00Z | 3,002,096 | 14 | 2010-06-08T23:31:14Z | [
"python"
] | To implement a status bar like below:
```
[========== ] 45%
[================ ] 60%
[==========================] 100%
```
I want to this to be printed out to stdout, and keep refreshing it, not print to another line. How to do this? | You can use `\r` ([carriage return](http://en.wikipedia.org/wiki/Carriage_return)). Demo:
```
import sys
total = 10000000
point = total / 100
increment = total / 20
for i in xrange(total):
if(i % (5 * point) == 0):
sys.stdout.write("\r[" + "=" * (i / increment) + " " * ((total - i)/ increment) + "]" + st... |
Python to print out status bar and percentage | 3,002,085 | 61 | 2010-06-08T23:27:00Z | 3,002,100 | 115 | 2010-06-08T23:32:02Z | [
"python"
] | To implement a status bar like below:
```
[========== ] 45%
[================ ] 60%
[==========================] 100%
```
I want to this to be printed out to stdout, and keep refreshing it, not print to another line. How to do this? | The `'\r'` character (carriage return) resets the cursor to the beginning of the line and allows you to write over what was previously on the line.
```
from time import sleep
import sys
for i in range(21):
sys.stdout.write('\r')
# the exact output you're looking for:
sys.stdout.write("[%-20s] %d%%" % ('='... |
Python to print out status bar and percentage | 3,002,085 | 61 | 2010-06-08T23:27:00Z | 3,002,114 | 50 | 2010-06-08T23:33:18Z | [
"python"
] | To implement a status bar like below:
```
[========== ] 45%
[================ ] 60%
[==========================] 100%
```
I want to this to be printed out to stdout, and keep refreshing it, not print to another line. How to do this? | There's a Python module that you can get from [PyPI](http://pypi.python.org/pypi) called [`progressbar`](http://pypi.python.org/pypi/progressbar) that implements such functionality. If you don't mind adding a dependency, it's a good solution. Otherwise, go with one of the other answers.
A simple example of how to use ... |
Python to print out status bar and percentage | 3,002,085 | 61 | 2010-06-08T23:27:00Z | 29,703,127 | 14 | 2015-04-17T15:14:28Z | [
"python"
] | To implement a status bar like below:
```
[========== ] 45%
[================ ] 60%
[==========================] 100%
```
I want to this to be printed out to stdout, and keep refreshing it, not print to another line. How to do this? | I found useful library tqdm (<https://github.com/tqdm/tqdm/>, previously: <https://github.com/noamraph/tqdm>). It automatically estimates time of completion and can be used as iterator.
Usage:
```
import tqdm
import time
for i in tqdm.tqdm(range(1000)):
time.sleep(0.01)
# or other long operations
```
Result... |
blank lines in file after sorting content of a text file in python | 3,002,392 | 12 | 2010-06-09T00:41:21Z | 3,002,501 | 25 | 2010-06-09T01:14:00Z | [
"python"
] | I have this small script that sorts the content of a text file
```
# The built-in function `open` opens a file and returns a file object.
# Read mode opens a file for reading only.
try:
f = open("tracks.txt", "r")
try:
# Read the entire contents of a file at once.
# string = f.read()
... | An "empty" line read from a text file is represented in Python by a string containing only a newline ("\n"). You may also want to avoid lines whose "data" consists only of spaces, tabs, etc ("whitespace"). The str.strip() method lets you detect both cases (a newline is whitespace).
```
f = open("tracks.txt", "r")
# om... |
blank lines in file after sorting content of a text file in python | 3,002,392 | 12 | 2010-06-09T00:41:21Z | 3,002,576 | 7 | 2010-06-09T01:33:38Z | [
"python"
] | I have this small script that sorts the content of a text file
```
# The built-in function `open` opens a file and returns a file object.
# Read mode opens a file for reading only.
try:
f = open("tracks.txt", "r")
try:
# Read the entire contents of a file at once.
# string = f.read()
... | This is a perfect opportunity to do some test-based development (see below). Some observations:
1. In the example below, I omit the aspect of reading from and writing to a file. That's not essential to this question, in my opinion.
2. I assume you want to strip trailing newlines and omit blank lines. If not, you'll ne... |
Fetching a random record from the Google App Engine Datastore? | 3,002,999 | 16 | 2010-06-09T03:55:24Z | 3,003,170 | 20 | 2010-06-09T04:56:09Z | [
"python",
"google-app-engine",
"google-cloud-datastore"
] | I have a datastore with around 1,000,000 entities in a model. I want to fetch 10 random entities from this.
I am not sure how to do this? can someone help? | Assign each entity a random number and store it in the entity. Then query for ten records whose random number is greater than (or less than) some other random number.
This isn't totally random, however, since entities with nearby random numbers will tend to show up together. If you want to beat this, do ten queries ba... |
Metaclass multiple inheritance inconsistency | 3,003,053 | 49 | 2010-06-09T04:15:33Z | 3,003,284 | 74 | 2010-06-09T05:29:52Z | [
"python",
"metaclass"
] | Why is this:
```
class MyType(type):
def __init__(cls, name, bases, attrs):
print 'created', cls
class MyMixin:
__metaclass__ = MyType
class MyList(list, MyMixin): pass
```
okay, and works as expected:
```
created <class '__main__.MyMixin'>
created <class '__main__.MyList'>
```
But this:
```
class ... | It's not a custom-metaclass problem (though it's *diagnosed* at metaclass stage):
```
>>> class Normal(object): pass
...
>>> class MyObject(object, Normal): pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Error when calling the metaclass bases
Cannot create a consiste... |
Web2py controllers with parameters? | 3,003,449 | 8 | 2010-06-09T06:12:10Z | 3,003,778 | 10 | 2010-06-09T07:19:55Z | [
"python",
"web2py"
] | I am building an app using Web2py framework... I don't want to have to use the request object to get all of the querystring parameters, instead I'd like to build my controller with named parameters and have the router unpack the querystring (or form data) dictionary into the named parameters and call my controller.
so... | No. As stated in the [book](http://www.web2py.com/books/default/chapter/29/04#Dispatching), an URL of the form
```
http://127.0.0.1:8000/a/c/f.html/x/y/z?p=1&q=2
```
maps to application (folder) `a`, controller (file) `c.py`, function `f`, and the additional arguments must be unpacked from the request object as
```
... |
ANT doesn't get exit code return by a python script | 3,004,057 | 9 | 2010-06-09T08:13:16Z | 3,005,249 | 14 | 2010-06-09T11:15:40Z | [
"python",
"ant",
"build",
"scripting"
] | I'm currently using ant for building my java project on a Windows XP machine. I have different tasks defined in the build.xml and one of this is the exec of a Python script for analyzing the application output.
I would like to make ANT failing when a particolar tag is discovered by script. I'm trying using:
```
sys.ex... | Try this:
```
<exec dir="${path}/scripts" executable="python" failonerror="true">
<arg line="log_analysis.py results.log" />
</exec>
```
Ant does not stop the build process if the command exits with a return code signaling failure by default; you have to set `failonerror="true"` to do that. |
cPickle ImportError: No module named multiarray | 3,004,792 | 4 | 2010-06-09T10:04:15Z | 6,953,049 | 7 | 2011-08-05T07:44:47Z | [
"python",
"serialization",
"numpy",
"pickle"
] | I'm using cPickle to save my Database into file. The code looks like that:
```
def Save_DataBase():
import cPickle
from scipy import *
from numpy import *
a=Results.VersionName
#filename='D:/results/'+a[a.find('/')+1:-a.find('/')-2]+Results.AssType[:3]+str(random.randint(0,100))+Results.Distribution+".lft"
filename='D... | I had the same problem on a Windows XP machine with Code that worked fine under Linux. It may have to do with the different handling of text and binary files. When writing your data try to create the file object explicitly stating that you want binary mode, i.e.
```
plik=open(filename,'wb')
```
instead of
```
plik=o... |
How to send html email with django with dynamic content in it? | 3,005,080 | 5 | 2010-06-09T10:47:55Z | 3,005,364 | 7 | 2010-06-09T11:31:38Z | [
"python",
"django"
] | Can anyone please help me sending html email with dynamic contents. One way is to copy the entire html code into a variable and populate the dynamic code within it in Django views, but that does not seem to be a good idea, as its a very large html file.
I would appreciate any suggestions.
Thanks. | This should do what you want:
```
from django.core.mail import EmailMessage
from django.template import Context
from django.template.loader import get_template
template = get_template('myapp/email.html')
context = Context({'user': user, 'other_info': info})
content = template.render(context)
if not user.email:
r... |
How to send html email with django with dynamic content in it? | 3,005,080 | 5 | 2010-06-09T10:47:55Z | 16,335,483 | 10 | 2013-05-02T10:15:14Z | [
"python",
"django"
] | Can anyone please help me sending html email with dynamic contents. One way is to copy the entire html code into a variable and populate the dynamic code within it in Django views, but that does not seem to be a good idea, as its a very large html file.
I would appreciate any suggestions.
Thanks. | # Example:
```
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.utils.html import strip_tags
subject, from_email, to = 'Hi', 'from@x.com', 'to@x.com'
html_content = render_to_string('the_template.html', {'varname':'value'}) # ...
text_content = strip... |
load a pickle file from a zipfile | 3,006,727 | 4 | 2010-06-09T14:22:44Z | 3,007,080 | 7 | 2010-06-09T15:04:47Z | [
"python",
"pickle",
"zipfile"
] | For some reason I cannot get cPickle.load to work on the file-type object returned by ZipFile.open().
If I call read() on the file-type object returned by ZipFile.open() I can use cPickle.loads though.
Example ....
```
import zipfile
import cPickle
# the data we want to store
some_data = {1: 'one', 2: 'two', 3: 'thr... | It's due to an imperfection in the pseudofile object implemented by the `zipfile` module (for the `.open` method of the `ZipFile` class introduced in Python 2.6). Consider:
```
>>> f = zf.open('data.pkl')
>>> f.read(1)
'('
>>> f.readline()
'dp1\n'
>>> f.read(1)
''
>>>
```
the sequence of `.read(1)` -- `.readline()` i... |
Xml comparison in Python | 3,007,330 | 23 | 2010-06-09T15:33:25Z | 3,007,729 | 17 | 2010-06-09T16:19:07Z | [
"python",
"xml",
"diff"
] | Building on [another SO question](http://stackoverflow.com/questions/794331/xml-comparison-in-c), how can one check whether two well-formed XML snippets are semantically equal. All I need is "equal" or not, since I'm using this for unit tests.
In the system I want, these would be equal (note the order of 'start'
and '... | You can use [formencode.doctest\_xml\_compare](http://bitbucket.org/ianb/formencode/src/tip/formencode/doctest_xml_compare.py#cl-70) -- the xml\_compare function compares two ElementTree or lxml trees. |
Xml comparison in Python | 3,007,330 | 23 | 2010-06-09T15:33:25Z | 23,368,371 | 12 | 2014-04-29T15:01:30Z | [
"python",
"xml",
"diff"
] | Building on [another SO question](http://stackoverflow.com/questions/794331/xml-comparison-in-c), how can one check whether two well-formed XML snippets are semantically equal. All I need is "equal" or not, since I'm using this for unit tests.
In the system I want, these would be equal (note the order of 'start'
and '... | The order of the elements can be significant in XML, this may be why most other methods suggested will compare unequal if the order is different... even if the elements have same attributes and text content.
But I also wanted an order-insensitive comparison, so I came up with this:
```
from lxml import etree
import x... |
Python: Decent config file format | 3,007,796 | 7 | 2010-06-09T16:27:13Z | 3,007,826 | 13 | 2010-06-09T16:30:51Z | [
"python",
"configuration",
"parsing",
"configuration-files",
"config"
] | I'd like to use a configuration file format which supports key value pairs and nestable, repeatable structures, and which is as light on syntax as possible. I'm imagining something along the lines of:
```
cachedir = /var/cache
mail_to = me@example.org
job {
name = my-media
frequency = 1 day
source {
fr... | I think YAML is great for this purpose, actually:
```
jobs:
- name: my-media
...
- name: something else
...
```
Or, as a dict instead of list:
```
jobs:
my-media:
frequency: 1 day
...
something-else:
frequency: 2 day
...
```
Another thing to consider, which you might not have, is using ... |
Python: Decent config file format | 3,007,796 | 7 | 2010-06-09T16:27:13Z | 3,008,051 | 8 | 2010-06-09T17:00:54Z | [
"python",
"configuration",
"parsing",
"configuration-files",
"config"
] | I'd like to use a configuration file format which supports key value pairs and nestable, repeatable structures, and which is as light on syntax as possible. I'm imagining something along the lines of:
```
cachedir = /var/cache
mail_to = me@example.org
job {
name = my-media
frequency = 1 day
source {
fr... | As Python's built-in `configparser` module does not seem to support nested sections, I'd first try [ConfigObj](http://www.voidspace.org.uk/python/configobj.html). (See an introductory tutorial [here](http://www.voidspace.org.uk/python/articles/configobj.shtml)). According to its homepage, this is the set of features wo... |
Python version 2.6 required, which was not found in the registry | 3,008,509 | 55 | 2010-06-09T18:01:58Z | 3,008,707 | 58 | 2010-06-09T18:28:08Z | [
"python",
"installation"
] | Can't download any python Windows modules and install. I wanted to experiment with scrapy framework and stackless but unable to install due to error "Python version 2.6 required, which was not found in the registry".
Trying to install it to
Windows 7, 64 bit machine | Warning for new viewers: this answer is now several years old (the clue is that it describes Windows 7 as "new"). By now (2014) most Python libraries should have 64-bit support. However, if you still have problems you can always take the advice of @KamilSzot and install 32-bit Python instead. In most cases [it probably... |
Python version 2.6 required, which was not found in the registry | 3,008,509 | 55 | 2010-06-09T18:01:58Z | 7,170,483 | 77 | 2011-08-24T04:35:21Z | [
"python",
"installation"
] | Can't download any python Windows modules and install. I wanted to experiment with scrapy framework and stackless but unable to install due to error "Python version 2.6 required, which was not found in the registry".
Trying to install it to
Windows 7, 64 bit machine | I realize this question is a year old - but I thought I would contribute one additional bit of info in case anyone else is Googling for this answer.
The issue only crops up on Win7 64-bit when you install Python "for all users". If you install it "for just me", you should not receive these errors. It seems that a lot ... |
Python version 2.6 required, which was not found in the registry | 3,008,509 | 55 | 2010-06-09T18:01:58Z | 8,712,435 | 21 | 2012-01-03T12:38:57Z | [
"python",
"installation"
] | Can't download any python Windows modules and install. I wanted to experiment with scrapy framework and stackless but unable to install due to error "Python version 2.6 required, which was not found in the registry".
Trying to install it to
Windows 7, 64 bit machine | For me this happens on a 32 bit system with activepython installed.
It seams that the regs are not in HKEY\_CURRENT\_USER so here is what I do to fix that.
1. Export the "Python" section under HKEY\_LOCAL\_MACHINE -> Software
2. Open the export in notepad notepad. Replace "LOCAL\_MACHINE" with "CURRENT\_USER"
3. Since... |
More elegant way to initialize list of duplicated items in Python | 3,009,091 | 10 | 2010-06-09T19:16:41Z | 3,009,524 | 9 | 2010-06-09T20:10:26Z | [
"python"
] | If I want a list initialized to 5 zeroes, that's very nice and easy:
```
[0] * 5
```
However if I change my code to put a more complicated data structure, like a list of zeroes:
```
[[0]] * 5
```
will not work as intended, since it'll be 10 copies of the same list. I have to do:
```
[[0] for i in xrange(5)]
```
t... | After thinking a bit about it, I came up with this solution: (7 lines without import)
```
# helper
def cl(n, func):
# return a lambda, that returns a list, where func(tion) is called
return (lambda: [func() for _ in range(n)])
def matrix(base, *ns):
# the grid lambda (at the start it returns the base-elem... |
Selecting dictionary items by key efficiently in Python | 3,010,326 | 5 | 2010-06-09T22:03:49Z | 3,010,349 | 15 | 2010-06-09T22:08:19Z | [
"python",
"numpy",
"scipy"
] | suppose I have a dictionary whose keys are strings. How can I efficiently make a new dictionary from that which contains only the keys present in some list?
for example:
```
# a dictionary mapping strings to stuff
mydict = {'quux': ...,
'bar': ...,
'foo': ...}
# list of keys to be selected from m... | ```
dict((k, mydict[k]) for k in keys_to_select)
```
if you know all the keys to select are also keys in `mydict`; if that's not the case,
```
dict((k, mydict[k]) for k in keys_to_select if k in mydict)
``` |
How do I filter values in a Django form using ModelForm? | 3,010,489 | 9 | 2010-06-09T22:36:01Z | 3,013,509 | 16 | 2010-06-10T10:23:40Z | [
"python",
"django",
"django-forms"
] | I am trying to use the ModelForm to add my data. It is working well, except that the ForeignKey dropdown list is showing all values and I only want it to display the values that a pertinent for the logged in user.
Here is my model for ExcludedDate, the record I want to add:
```
class ExcludedDate(models.Model):
date ... | You can customize your form in **init**
```
class ExcludedDateForm(ModelForm):
class Meta:
model = models.ExcludedDate
exclude = ('user', 'recurring',)
def __init__(self, user=None, **kwargs):
super(ExcludedDateForm, self).__init__(**kwargs)
if user:
self.fields['cat... |
In Django : How to serialize dict object to json? | 3,010,920 | 4 | 2010-06-10T00:34:25Z | 3,010,950 | 14 | 2010-06-10T00:43:05Z | [
"python",
"django",
"json",
"serialization"
] | I have this very basic problem,
```
>>> from django.core import serializers
>>> serializers.serialize("json", {'a':1})
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/lib/pymodules/python2.6/django/core/serializers/__init__.py", line 87, in serialize
s.serialize(queryset, **... | Also, since you seem to be using Python 2.6, you could just use the `json` module directly:
```
import json
data = json.dumps({'a': 1})
``` |
How to change language from Django URL? | 3,010,956 | 12 | 2010-06-10T00:45:12Z | 3,356,646 | 7 | 2010-07-28T19:25:02Z | [
"python",
"django",
"localization",
"internationalization"
] | i want to change the language when the user introduce in the url the locale, something like this <http://mysite.com/es/>, <http://mysite.com/es/article-name>, <http://mysite.com/en/>.
how can i do that?
Thanks | Checkout [django-locale-url](https://bitbucket.org/carljm/django-localeurl).
It provides a middleware that does exactly what you are asking for, so you don't need to check for the language in urls.py |
Django - The included urlconf doesn't have any patterns in it | 3,011,179 | 24 | 2010-06-10T02:03:14Z | 3,011,196 | 22 | 2010-06-10T02:09:12Z | [
"python",
"django"
] | My website, which was working before, suddenly started breaking with the error
"ImproperlyConfigured at /
The included urlconf resume.urls doesn't have any patterns in it"
The project base is called resume. In settings.py I have set
```
ROOT_URLCONF = 'resume.urls'
```
Here's my resume.urls, which sits in the proje... | Check your patterns for include statements that point to non-existent modules or modules that do not have a `urlpatterns` member. I see that you have an `include('urls.ajax')` which may not be correct. Should it be `ajax.urls`? |
Django - The included urlconf doesn't have any patterns in it | 3,011,179 | 24 | 2010-06-10T02:03:14Z | 22,903,110 | 35 | 2014-04-07T03:27:42Z | [
"python",
"django"
] | My website, which was working before, suddenly started breaking with the error
"ImproperlyConfigured at /
The included urlconf resume.urls doesn't have any patterns in it"
The project base is called resume. In settings.py I have set
```
ROOT_URLCONF = 'resume.urls'
```
Here's my resume.urls, which sits in the proje... | TL;DR: You probably need to use `reverse_lazy()` instead of `reverse()`
If your `urls.py` imports a class-based view that uses `reverse()`, you will get this error; using `reverse_lazy()` will fix it.
For me, the error
> The included urlconf project.urls doesn't have any patterns in it
got thrown because:
* `proje... |
How do I limit the amount of login retries in Django | 3,011,233 | 4 | 2010-06-10T02:20:52Z | 3,015,166 | 9 | 2010-06-10T14:10:08Z | [
"python",
"django"
] | I am trying to get a login form I have in django to only allow three login attempts before redirecting to a "login help" page. I am currently using the builtin "django.contrib.auth.views.login" view with a custom template. How do I force it to redirect to another page after n failed login attempts? | There's actually a project out there which provides a Django middleware to do just this, called [`django-axes`](https://github.com/philipn/django-axes). Simply install it with the instructions provided and then set `AXES_LOGIN_FAILURE_LIMIT` to the number of login attempts you want before a record is created for the fa... |
Python style: if statements vs. boolean evaluation | 3,011,763 | 7 | 2010-06-10T05:05:31Z | 3,011,781 | 9 | 2010-06-10T05:11:01Z | [
"python",
"coding-style",
"if-statement"
] | One of the ideas of Python's design philosophy is "There should be one ... obvious way to do it." [(PEP 20)](http://www.python.org/dev/peps/pep-0020/), but that can't always be true. I'm specifically referring to (simple) if statements versus boolean evaluation. Consider the following:
```
if words:
self.words = w... | "There *should* be only one" can perfectly well always be true; it's the positive assertion "there *is* only one" that cannot be -- "should" implies a target, a goal, not the possibility of always reaching it (e.g., for numbers `a` and `b`, forbidding either `b + a` or `a + b` would be so absurd that there just cannot ... |
what changes when your input is giga/terabyte sized? | 3,012,157 | 21 | 2010-06-10T06:34:47Z | 3,012,599 | 18 | 2010-06-10T07:55:52Z | [
"python",
"large-data-volumes",
"scientific-computing"
] | I just took my first baby step today into real scientific computing today when I was shown a data set where the smallest file is 48000 fields by 1600 rows (haplotypes for several people, for chromosome 22). And this is considered tiny.
I write Python, so I've spent the last few hours reading about HDF5, and Numpy, and... | I'm currently engaged in high-performance computing in a small corner of the oil industry and regularly work with datasets of the orders of magnitude you are concerned about. Here are some points to consider:
1. Databases don't have a lot of traction in this domain. Almost all our data is kept in files, some of those ... |
Python memoising/deferred lookup property decorator | 3,012,421 | 77 | 2010-06-10T07:26:23Z | 3,013,910 | 99 | 2010-06-10T11:27:08Z | [
"python",
"decorator"
] | Recently I've gone through an existing code base containing many classes where instance attributes reflect values stored in a database. I've refactored a lot of these attributes to have their database lookups be deferred, ie. not be initialised in the constructor but only upon first read. These attributes do not change... | Here is an example implementation of a lazy property decorator:
```
def lazyprop(fn):
attr_name = '_lazy_' + fn.__name__
@property
def _lazyprop(self):
if not hasattr(self, attr_name):
setattr(self, attr_name, fn(self))
return getattr(self, attr_name)
return _lazyprop
clas... |
Python memoising/deferred lookup property decorator | 3,012,421 | 77 | 2010-06-10T07:26:23Z | 6,849,299 | 78 | 2011-07-27T18:26:24Z | [
"python",
"decorator"
] | Recently I've gone through an existing code base containing many classes where instance attributes reflect values stored in a database. I've refactored a lot of these attributes to have their database lookups be deferred, ie. not be initialised in the constructor but only upon first read. These attributes do not change... | I wrote this one for myself... To be used for true *one-time* calculated lazy properties. I like it because it avoids sticking extra attributes on objects, and once activated does not waste time checking for attribute presence, etc.:
```
class lazy_property(object):
'''
meant to be used for lazy evaluation of ... |
How do I override a Python import? | 3,012,473 | 23 | 2010-06-10T07:33:15Z | 3,074,642 | 23 | 2010-06-19T06:49:46Z | [
"python",
"import",
"preprocessor",
"override"
] | I'm working on [pypreprocessor](http://code.google.com/p/pypreprocessor/) which is a preprocessor that takes c-style directives and I've been able to make it work like a traditional preprocessor (it's self-consuming and executes postprocessed code on-the-fly) except that it breaks library imports.
The problem is: The ... | Does this answer your question? The second import does the trick.
Mod\_1.py
```
def test_function():
print "Test Function -- Mod 1"
```
Mod\_2.py
```
def test_function():
print "Test Function -- Mod 2"
```
Test.py
```
#!/usr/bin/python
import sys
import Mod_1
Mod_1.test_function()
del sys.modules['Mod... |
How do I override a Python import? | 3,012,473 | 23 | 2010-06-10T07:33:15Z | 3,074,701 | 7 | 2010-06-19T07:14:10Z | [
"python",
"import",
"preprocessor",
"override"
] | I'm working on [pypreprocessor](http://code.google.com/p/pypreprocessor/) which is a preprocessor that takes c-style directives and I've been able to make it work like a traditional preprocessor (it's self-consuming and executes postprocessed code on-the-fly) except that it breaks library imports.
The problem is: The ... | To define a different import behavior or to totally subvert the import process you will need to write import hooks. See [PEP 302](http://www.python.org/dev/peps/pep-0302/).
For example,
```
import sys
class MyImporter(object):
def find_module(self, module_name, package_path):
# Return a loader
r... |
What is the python "with" statement designed for? | 3,012,488 | 219 | 2010-06-10T07:35:21Z | 3,012,543 | 7 | 2010-06-10T07:45:21Z | [
"python",
"language-features",
"with-statement"
] | I came across the Python `with` statement for the first time today. I've been using Python lightly for several months and didn't even know of its existence! Given its somewhat obscure status, I thought it would be worth asking:
1. What is the Python `with` statement
designed to be used for?
2. What do
you use it... | See [PEP 343 - The 'with' statement](http://www.python.org/dev/peps/pep-0343/), there is an example section at the end.
> ... new statement "with" to the Python
> language to make
> it possible to factor out standard uses of try/finally statements. |
What is the python "with" statement designed for? | 3,012,488 | 219 | 2010-06-10T07:35:21Z | 3,012,565 | 63 | 2010-06-10T07:49:10Z | [
"python",
"language-features",
"with-statement"
] | I came across the Python `with` statement for the first time today. I've been using Python lightly for several months and didn't even know of its existence! Given its somewhat obscure status, I thought it would be worth asking:
1. What is the Python `with` statement
designed to be used for?
2. What do
you use it... | I would suggest two interesting lectures:
* [PEP 343](http://www.python.org/dev/peps/pep-0343/) The "with" Statement
* [Effbot](http://effbot.org/zone/python-with-statement.htm) Understanding Python's
"with" statement
**1.**
The `with` statement is used to wrap the execution of a block with methods defined by a con... |
What is the python "with" statement designed for? | 3,012,488 | 219 | 2010-06-10T07:35:21Z | 3,012,921 | 233 | 2010-06-10T08:51:37Z | [
"python",
"language-features",
"with-statement"
] | I came across the Python `with` statement for the first time today. I've been using Python lightly for several months and didn't even know of its existence! Given its somewhat obscure status, I thought it would be worth asking:
1. What is the Python `with` statement
designed to be used for?
2. What do
you use it... | 1. I believe this has already been answered by other users before me, so I only add it for the sake of completeness: the `with` statement simplifies exception handling by encapsulating common preparation and cleanup tasks in so-called [context managers](http://docs.python.org/release/2.5.2/lib/typecontextmanager.html).... |
What is the python "with" statement designed for? | 3,012,488 | 219 | 2010-06-10T07:35:21Z | 3,013,327 | 26 | 2010-06-10T09:53:05Z | [
"python",
"language-features",
"with-statement"
] | I came across the Python `with` statement for the first time today. I've been using Python lightly for several months and didn't even know of its existence! Given its somewhat obscure status, I thought it would be worth asking:
1. What is the Python `with` statement
designed to be used for?
2. What do
you use it... | The Python `with` statement is built-in language support of the [`Resource Acquisition Is Initialization`](http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization) idiom commonly used in C++. It is intended to allow safe acquisition and release of operating system resources.
The `with` statement creates re... |
What is the python "with" statement designed for? | 3,012,488 | 219 | 2010-06-10T07:35:21Z | 3,013,514 | 16 | 2010-06-10T10:25:19Z | [
"python",
"language-features",
"with-statement"
] | I came across the Python `with` statement for the first time today. I've been using Python lightly for several months and didn't even know of its existence! Given its somewhat obscure status, I thought it would be worth asking:
1. What is the Python `with` statement
designed to be used for?
2. What do
you use it... | An example of an antipattern might be to use the `with` inside a loop when it would be more efficient to have the `with` outside the loop
for example
```
for row in lines:
with open("outfile","a") as f:
f.write(row)
```
vs
```
with open("outfile","a") as f:
for row in lines:
f.write(row)
```... |
What is the python "with" statement designed for? | 3,012,488 | 219 | 2010-06-10T07:35:21Z | 3,016,826 | 12 | 2010-06-10T17:22:32Z | [
"python",
"language-features",
"with-statement"
] | I came across the Python `with` statement for the first time today. I've been using Python lightly for several months and didn't even know of its existence! Given its somewhat obscure status, I thought it would be worth asking:
1. What is the Python `with` statement
designed to be used for?
2. What do
you use it... | Again for completeness I'll add my most useful use-case for `with` statements.
I do a lot of scientific computing and for some activities I need the `Decimal` library for arbitrary precision calculations. Some part of my code I need high precision and for most other parts I need less precision.
I set my default preci... |
python threading and performace? | 3,012,508 | 5 | 2010-06-10T07:39:04Z | 3,012,590 | 10 | 2010-06-10T07:54:10Z | [
"python",
"performance",
"multithreading"
] | I had to do heavy I/o bound operation, i.e Parsing large files and converting from one format to other format. Initially I used to do it serially, i.e parsing one after another..! Performance was very poor ( it used take 90+ seconds). So I decided to use threading to improve the performance. I created one thread for ea... | Under the usual Python interpreter, threading will not allocate more CPU cores to your program because of the [global interpreter lock](http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock) (aka. the GIL).
The [multiprocessing](http://docs.python.org/library/multiprocessing.html) module ... |
Plotting 3-tuple data points in a surface / contour plot using matplotlib | 3,012,783 | 17 | 2010-06-10T08:27:45Z | 3,013,199 | 22 | 2010-06-10T09:33:43Z | [
"python",
"matplotlib",
"rpy2"
] | I have some surface data that is generated by an external program as XYZ values. I want to create the following graphs, using matplotlib:
* Surface plot
* Contour plot
* Contour plot overlayed with a surface plot
I have looked at several examples for plotting surfaces and contours in matplotlib - however, the Z value... | for do a **contour plot** you need interpolate your data to a regular grid <http://www.scipy.org/Cookbook/Matplotlib/Gridding_irregularly_spaced_data>
a quick example:
```
>>> xi = linspace(min(X), max(X))
>>> yi = linspace(min(Y), max(Y))
>>> zi = griddata(X, Y, Z, xi, yi)
>>> contour(xi, yi, zi)
```
for the **surf... |
Character Encoding | 3,012,821 | 2 | 2010-06-10T08:34:11Z | 3,012,868 | 8 | 2010-06-10T08:42:31Z | [
"python",
"utf-8",
"ansi",
"utf-16"
] | My text editor allows me to code in several different character formats Ansi, UTF-8, UTF-8(No BOM), UTF-16LE, and UTF-16BE.
What is the difference between them?
What is commonly regarded as the best format (I'm using Python if that makes a diffrence)? | * "Ansi" is a misnomer and usually refers to some 8-bit encoding that's the default on the current platform (on "western" Windows installations that's usually [Windows-1252](http://en.wikipedia.org/wiki/Windows-1252)). It only supports a small set of characters (256 different characters at most).
* [UTF-8](http://en.wi... |
How do Django signals work? | 3,012,863 | 3 | 2010-06-10T08:40:34Z | 3,012,925 | 13 | 2010-06-10T08:52:50Z | [
"python",
"django",
"signals"
] | How does Django's event routing system work? | Django signals are synchronous. The handlers are executed as soon as the signal is fired, and control returns only when all appropriate handlers have finished. |
How to delete every reference of an object in Python? | 3,013,304 | 6 | 2010-06-10T09:48:27Z | 3,014,023 | 10 | 2010-06-10T11:44:15Z | [
"python"
] | Supose you have something like:
```
x = "something"
b = x
l = [b]
```
How can you delete the object only having one reference, say x?
`del x` won't do the trick; the object is still reachable from b, for example. | No no no. Python has a garbage collector that has very strong territory issues - it won't mess with you creating objects, you don't mess with it deleting objects.
Simply put, it can't be done, and for a good reason.
If, for instance, your need comes from cases of, say, caching algorithms that keep references, but sho... |
How to delete every reference of an object in Python? | 3,013,304 | 6 | 2010-06-10T09:48:27Z | 3,014,477 | 7 | 2010-06-10T12:54:48Z | [
"python"
] | Supose you have something like:
```
x = "something"
b = x
l = [b]
```
How can you delete the object only having one reference, say x?
`del x` won't do the trick; the object is still reachable from b, for example. | The only solution I see right now is that you should make sure that *you* are holding the only reference to `x`, everyone else must *not* get `x` itself but a weak reference pointing to `x`. Weak references are implemented in the [`weakref`](http://docs.python.org/library/weakref.html) module and you can use it this wa... |
List filtering: list comprehension vs. lambda + filter | 3,013,449 | 329 | 2010-06-10T10:14:00Z | 3,013,503 | 20 | 2010-06-10T10:22:36Z | [
"python",
"list",
"functional-programming",
"filter",
"lambda"
] | I happened to find myself having a basic filtering need: I have a list and I have to filter it by an attribute of the items.
My code looked like this:
```
my_list = [x for x in my_list if x.attribute == value]
```
But then I thought, wouldn't it be better to write it like this?
```
my_list = filter(lambda x: x.attr... | Although `filter` may be the "faster way", the "Pythonic way" would be not to care about such things unless performance is absolutely critical (in which case you wouldn't be using Python!). |
List filtering: list comprehension vs. lambda + filter | 3,013,449 | 329 | 2010-06-10T10:14:00Z | 3,013,686 | 222 | 2010-06-10T10:52:49Z | [
"python",
"list",
"functional-programming",
"filter",
"lambda"
] | I happened to find myself having a basic filtering need: I have a list and I have to filter it by an attribute of the items.
My code looked like this:
```
my_list = [x for x in my_list if x.attribute == value]
```
But then I thought, wouldn't it be better to write it like this?
```
my_list = filter(lambda x: x.attr... | It is strange how much beauty varies for different people. I find the list comprehension much clearer than the ugly filter+lambda, but use whichever you find easier. However, do stop giving your variables names already used for builtins, that's just ugly, and not open for discussion.
There are two things that may slow... |
List filtering: list comprehension vs. lambda + filter | 3,013,449 | 329 | 2010-06-10T10:14:00Z | 3,013,722 | 118 | 2010-06-10T10:58:17Z | [
"python",
"list",
"functional-programming",
"filter",
"lambda"
] | I happened to find myself having a basic filtering need: I have a list and I have to filter it by an attribute of the items.
My code looked like this:
```
my_list = [x for x in my_list if x.attribute == value]
```
But then I thought, wouldn't it be better to write it like this?
```
my_list = filter(lambda x: x.attr... | This is a somewhat religious issue in Python. Even though **[Guido considered removing `map`, `filter` and `reduce` from Python 3](http://www.artima.com/weblogs/viewpost.jsp?thread=98196)**, there was enough of a backlash that in the end only `reduce` was moved from built-ins to [functools.reduce](http://docs.python.or... |
List filtering: list comprehension vs. lambda + filter | 3,013,449 | 329 | 2010-06-10T10:14:00Z | 26,917,357 | 21 | 2014-11-13T20:00:35Z | [
"python",
"list",
"functional-programming",
"filter",
"lambda"
] | I happened to find myself having a basic filtering need: I have a list and I have to filter it by an attribute of the items.
My code looked like this:
```
my_list = [x for x in my_list if x.attribute == value]
```
But then I thought, wouldn't it be better to write it like this?
```
my_list = filter(lambda x: x.attr... | Since any speed difference is bound to be miniscule, whether to use filters or list comprehensions comes down to a matter of taste. In general I'm inclined to use comprehensions (which seems to agree with most other answers here), but there is one case where I prefer `filter`.
A very frequent use case is pulling out t... |
Django InlineModelAdmin - set inline field from request on save (set user field automatically) (save_formset vs save_model) | 3,016,158 | 11 | 2010-06-10T16:04:05Z | 3,016,335 | 8 | 2010-06-10T16:25:39Z | [
"python",
"django",
"django-admin",
"inline"
] | I have two models, a MainModel and a related InlineModel that i'd like to show as an inline in the admin. This InlineModel can be used for, say, making notes about the model and should track the logged in admin user making changes. While this seems simple (and indeed, the docs show an example for this when the user fie... | I have solved the first half of my question:
```
def save_formset(self, request, form, formset, change):
if formset.model != InlineModel:
return super(MainModelAdmin, self).save_formset(request, form, formset, change)
instances = formset.save(commit=False)
for instance in instances:
if not ... |
Create a color generator from given colormap in matplotlib | 3,016,283 | 11 | 2010-06-10T16:18:14Z | 3,018,380 | 15 | 2010-06-10T20:47:14Z | [
"python",
"matplotlib",
"color-mapping"
] | I have a series of lines that each need to be plotted with a separate colour. Each line is actually made up of several data sets (positive, negative regions etc.) and so I'd like to be able to create a generator that will feed one colour at a time across a spectrum, for example the `gist_rainbow` map [shown here](http:... | To index colors from a specific colormap you can use:
```
from pylab import *
NUM_COLORS = 22
cm = get_cmap('gist_rainbow')
for i in range(NUM_COLORS):
color = cm(1.*i/NUM_COLORS) # color will now be an RGBA tuple
# or if you really want a generator:
cgen = (cm(1.*i/NUM_COLORS) for i in range(NUM_COLORS))
``` |
How to get text in QlineEdit when QpushButton is pressed in a string? | 3,016,974 | 10 | 2010-06-10T17:42:23Z | 3,018,000 | 14 | 2010-06-10T19:59:33Z | [
"python",
"pyqt4",
"qlineedit"
] | I am trying to implement a function. My code is given below.
I want to get the text in lineedit with objectname 'host' in a string say 'shost' when the user clicks the pushbutton with name 'connect'. How can I do this? I tried and failed. How do I implement this function?
```
import sys
from PyQt4.QtCore import *
fro... | My first suggestion is to use Designer to create your GUIs. Typing them out yourself sucks, takes more time, and you will definitely make more mistakes than Designer.
Here are some [PyQt tutorials](https://web.archive.org/web/20130704101140/http://www.diotavelli.net/PyQtWiki/Tutorials) to help get you on the right tra... |
How should a Gnome applet store its configuration data? | 3,018,287 | 6 | 2010-06-10T20:35:44Z | 3,030,665 | 7 | 2010-06-13T00:53:59Z | [
"python",
"applet",
"gnome"
] | I have a Gnome applet written in Python. In order to save configuration data/settings, it creates a file `~/.appname`.
However, this prevents multiple instances of the applet from being added to the panel because each cannot have its own settings.
How can I store the settings in a way that allows each instance to hav... | The recommend way for an applet would be to use [GConf to store preferences](http://people.gnome.org/~tvachon/doc/tutorial.html#gconf) and to use one key per instance so that you can store individual settings. From [Panel Applet GConf Utilities](http://library.gnome.org/devel/panel-applet/stable/panel-applet-Panel-Appl... |
Determine precision and scale of particular number in Python | 3,018,758 | 4 | 2010-06-10T21:40:51Z | 3,019,027 | 9 | 2010-06-10T22:32:45Z | [
"python",
"string",
"floating-point",
"scale",
"precision"
] | I have a variable in Python containing a floating point number (e.g. `num = 24654.123`), and I'd like to determine the number's precision and scale values (in the Oracle sense), so 123.45678 should give me (8,5), 12.76 should give me (4,2), etc.
I was first thinking about using the string representation (via `str` or ... | Getting the number of digits to the left of the decimal point is easy:
```
int(log10(x))+1
```
The number of digits to the right of the decimal point is trickier, because of the inherent inaccuracy of floating point values. I'll need a few more minutes to figure that one out.
**Edit:** Based on that principle, here'... |
Cannot redirect output when I run Python script on Windows using just script's name | 3,018,848 | 14 | 2010-06-10T21:55:19Z | 3,021,809 | 7 | 2010-06-11T09:54:11Z | [
"python",
"command-line",
"winapi",
"windows-7",
"redirect"
] | This is running on Windows 7 (64 bit), Python 2.6 with Win32 Extensions for Python.
I have a simple script that just print "hello world". I can launch it with `python hello.py`. In this case I can redirect the output to a file. But if I run it by just typing `hello.py` on the command line and redirect the output, I ge... | UPDATED ANSWER
A Microsoft KB issue ([STDIN/STDOUT Redirection May Not Work If Started from a File Association](http://support.microsoft.com/kb/321788)) may be exactly this issue. The page has instructions for downloading a Win2000 hotfix, but that might not be needed on more recent Windows versions. After the hotfix ... |
Cannot redirect output when I run Python script on Windows using just script's name | 3,018,848 | 14 | 2010-06-10T21:55:19Z | 3,026,098 | 14 | 2010-06-11T20:43:15Z | [
"python",
"command-line",
"winapi",
"windows-7",
"redirect"
] | This is running on Windows 7 (64 bit), Python 2.6 with Win32 Extensions for Python.
I have a simple script that just print "hello world". I can launch it with `python hello.py`. In this case I can redirect the output to a file. But if I run it by just typing `hello.py` on the command line and redirect the output, I ge... | Are you asking about this?
Windows: When executing Python scripts on the command line using file type
associations (i.e. starting "script.py" instead of "python script.py"),
redirects may not work unless you set a specific registry key. See
the Knowledge Base article [STDIN/STDOUT Redirection May Not Work If Started f... |
How do I get the key of an item when doing a FOR loop through a dictionary or list in Python? | 3,019,049 | 5 | 2010-06-10T22:38:34Z | 3,019,057 | 10 | 2010-06-10T22:40:26Z | [
"python"
] | I am new to Python.
Say I have a list:
```
list = ['A','B','C','D']
```
The key for each item respectively here is 0,1,2,3 - right?
Now I am going to loop through it with a for loop...
```
for item in list:
print item
```
That's great, I can print out my list.
How do I get the key here? For example being abl... | You want the index, not the key. For this you can use [enumerate](http://docs.python.org/library/functions.html#enumerate):
```
for index, item in enumerate(l):
print index
print item
```
This is mentioned in the section [Looping Techniques](http://docs.python.org/tutorial/datastructures.html#looping-techniqu... |
how to make a python or perl script portable to both linux and windows? | 3,020,267 | 9 | 2010-06-11T04:53:39Z | 3,020,286 | 14 | 2010-06-11T05:01:06Z | [
"python",
"perl",
"scripting",
"cross-platform",
"shebang"
] | I was wondering how to make a python script portable to both linux and windows?
One problem I see is shebang. How to write the shebang so that the script can be run on both windows and linux?
Are there other problems besides shebang that I should know?
Is the solution same for perl script?
Thanks and regards! | Windows will just ignore the shebang (which is, after all, a comment); in Windows you need to associate the `.py` extension to the Python executable in the registry, but you can perfectly well leave the shebang on, it will be perfectly innocuous there.
There are many bits and pieces which are platform-specific (many o... |
how to make a python or perl script portable to both linux and windows? | 3,020,267 | 9 | 2010-06-11T04:53:39Z | 3,021,611 | 7 | 2010-06-11T09:16:10Z | [
"python",
"perl",
"scripting",
"cross-platform",
"shebang"
] | I was wondering how to make a python script portable to both linux and windows?
One problem I see is shebang. How to write the shebang so that the script can be run on both windows and linux?
Are there other problems besides shebang that I should know?
Is the solution same for perl script?
Thanks and regards! | Make sure you don't handle files and directories as strings and simply concatenate them with a slash in between. Perl:
```
$path = File::Spec->catfile("dir1", "dir2", "file")
```
Remember that Windows has volumes:
```
($volume, $path, $file) = File::Spec->splitpath($full_path);
@directories = File::Spec->splitdir($p... |
Is it possible to give a python dict an initial capacity (and is it useful) | 3,020,514 | 10 | 2010-06-11T06:00:16Z | 3,020,810 | 17 | 2010-06-11T07:03:17Z | [
"python",
"dictionary",
"capacity"
] | I am filling a python dict with around 10,000,000 items. My understanding of dict (or hashtables) is that when too much elements get in them, the need to resize, an operation that cost quite some time.
Is there a way to say to a python dict that you will be storing at least n items in it, so that it can allocate memor... | First off, I've heard rumor that you can set the size of a dictionary at initialization, but I have never seen any documentation or PEP describing how this would be done.
With this in mind I ran an analysis on your quantity of items, described below. While it may take some time to resize the dictionary each time I wou... |
jython syntaxerror? | 3,020,966 | 9 | 2010-06-11T07:33:23Z | 3,020,988 | 12 | 2010-06-11T07:35:54Z | [
"python",
"jython"
] | Hi guys i got the following syntax error at the following line when i run my program in jython:
```
except Exception as detail:
```
SyntaxError: mismatched input 'as' expecting COLON
but on python its ok? What's wrong? I'm trying to use the stanford pos tagger api (java) in my python program.are there other ways? | There are 2 current versions of Jython: the 2.5 version is the stable one, and 2.7 is a release candidate. The `as` syntax for `except` appeared in CPython 2.6 and thus will be supported in Jython 2.7; I guess you're using Jython 2.5,
You can use the older (Python 3 incompatible) `except` syntax in Jython 2.5:
```
ex... |
send xml file to http using python | 3,020,979 | 7 | 2010-06-11T07:35:15Z | 3,021,241 | 9 | 2010-06-11T08:19:19Z | [
"python",
"xml",
"http"
] | how can i send an xml file on my system to an http server using python standard library?? | ```
import urllib
URL = "http://host.domain.tld/resource"
XML = "<xml />"
parameter = urllib.urlencode({'XML': XML})
```
a) using HTTP POST
```
response = urllib.urlopen(URL, parameter)
print response.read()
```
b) using HTTP GET
```
response = urllib.urlopen(URL + "?%s" % parameter)
print response.read()
```
Th... |
Python tips for memory optimization | 3,021,264 | 8 | 2010-06-11T08:22:46Z | 4,139,753 | 10 | 2010-11-09T23:23:07Z | [
"python",
"optimization",
"memory-management"
] | I need to optimize the RAM usage of my application.
PLEASE spare me the lectures telling me I shouldn't care about memory when coding Python. I have a memory problem because I use very large default-dictionaries (yes, I also want to be fast). My current memory consumption is 350MB and growing. I already cannot use sh... | I suggest the following: store all the values in a DB, and keep an in-memory dictionary with string hashes as keys. If a collision occurs, fetch values from the DB, otherwise (vast majority of the cases) use the dictionary. Effectively, it will be a giant cache.
A problem with dictionaries in Python is that they use a... |
Concatenation of many lists in Python | 3,021,641 | 13 | 2010-06-11T09:22:54Z | 3,021,662 | 16 | 2010-06-11T09:27:31Z | [
"python",
"list",
"concatenation"
] | Suppose I have a function like this:
```
def getNeighbors(vertex)
```
which returns a list of vertices that are neighbors of the given vertex. Now I want to create a list with all the neighbors of the neighbors. I do that like this:
```
listOfNeighborsNeighbors = []
for neighborVertex in getNeighbors(vertex):
li... | ```
[x for n in getNeighbors(vertex) for x in getNeighbors(n)]
```
or
```
sum(getNeighbors(n) for n in getNeighbors(vertex), [])
``` |
Concatenation of many lists in Python | 3,021,641 | 13 | 2010-06-11T09:22:54Z | 3,021,669 | 14 | 2010-06-11T09:28:08Z | [
"python",
"list",
"concatenation"
] | Suppose I have a function like this:
```
def getNeighbors(vertex)
```
which returns a list of vertices that are neighbors of the given vertex. Now I want to create a list with all the neighbors of the neighbors. I do that like this:
```
listOfNeighborsNeighbors = []
for neighborVertex in getNeighbors(vertex):
li... | Appending lists can be done with + and sum():
```
>>> c = [[1, 2], [3, 4]]
>>> sum(c, [])
[1, 2, 3, 4]
``` |
Concatenation of many lists in Python | 3,021,641 | 13 | 2010-06-11T09:22:54Z | 3,021,851 | 21 | 2010-06-11T10:01:33Z | [
"python",
"list",
"concatenation"
] | Suppose I have a function like this:
```
def getNeighbors(vertex)
```
which returns a list of vertices that are neighbors of the given vertex. Now I want to create a list with all the neighbors of the neighbors. I do that like this:
```
listOfNeighborsNeighbors = []
for neighborVertex in getNeighbors(vertex):
li... | As usual, the itertools module contains a solution:
```
>>> l1=[1, 2, 3]
>>> l2=[4, 5, 6]
>>> l3=[7, 8, 9]
>>> import itertools
>>> list(itertools.chain(l1, l2, l3))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
``` |
Concatenation of many lists in Python | 3,021,641 | 13 | 2010-06-11T09:22:54Z | 11,739,570 | 7 | 2012-07-31T11:56:43Z | [
"python",
"list",
"concatenation"
] | Suppose I have a function like this:
```
def getNeighbors(vertex)
```
which returns a list of vertices that are neighbors of the given vertex. Now I want to create a list with all the neighbors of the neighbors. I do that like this:
```
listOfNeighborsNeighbors = []
for neighborVertex in getNeighbors(vertex):
li... | If speed matters, it may be better to use this:
```
from operator import iadd
reduce(iadd, (getNeighbors(n) for n in getNeighbors(vertex)))
```
The point of this code is in concatenating whole lists by `list.extend` where list comprehension would add one item by one, as if calling `list.append`. That saves a bit of o... |
Windows can't find the file on subprocess.call() | 3,022,013 | 41 | 2010-06-11T10:27:39Z | 4,616,867 | 72 | 2011-01-06T16:00:29Z | [
"python",
"path",
"python-3.x"
] | I am getting the following error:
```
WindowsError: [Error 2] The system cannot find the file specified
```
My code is:
```
subprocess.call(["<<executable file found in PATH>>"])
```
Windows 7, 64 bit. Python 3.x latest, stable.
Any ideas?
Thanks, | I am not sure why but, on my windows machine I had to add a 'shell=True' to the call.
E.g. for `dir` you would type:
```
import subprocess
subprocess.call('dir', shell=True)
```
Hope this helps,
Douglas
To quote from the documentation:
The only time you need to specify shell=True on Windows is when the command you... |
What's a better choice for SQL-backed number crunching - Ruby 1.9, Python 2, Python 3, or PHP 5.3? | 3,022,232 | 4 | 2010-06-11T11:13:57Z | 3,022,242 | 10 | 2010-06-11T11:16:05Z | [
"php",
"python",
"ruby",
"performance",
"math"
] | Criteria for 'better': fast in math and simple (few fields, many records) db transactions, convenient to develop/read/extend, flexible, connectible.
The task is to use a common web development scripting language to process and calculate long time series and multidimensional surfaces (mostly selecting/inserting sets of... | I would suggest Python with it's great Scientifical/Mathematical libraries (SciPy, NumPy). Otherwise the languages are not differing so much, although I doubt that Ruby, PHP or JS can keep up with the speed of Python or Perl.
And what the comments below here say: at this moment, go for the latest Python2 (which is Pyt... |
Test assertions for tuples with floats | 3,022,952 | 4 | 2010-06-11T13:07:51Z | 3,137,397 | 7 | 2010-06-29T02:08:48Z | [
"python",
"unit-testing",
"floating-point",
"tuples",
"assert"
] | I have a function that returns a tuple that, among others, contains a float value. Usually I use `assertAlmostEquals` to compare those, but this does not work with tuples. Also, the tuple contains other data-types as well. Currently I am asserting every element of the tuple individually, but that gets too much for a li... | Well how about pimping up your function with couple of zips:
```
def testF(self):
for tuple1, tuple2 in zip(f(range(1,3)), [(1.0, 2), (0.5, 4)]):
for val1, val2 in zip(tuple1, tuple2):
if type(val2) is float:
self.assertAlmostEquals(val1, val2, 5)
else:
... |
How can I check if an object is an iterator in Python? | 3,023,503 | 15 | 2010-06-11T14:16:06Z | 3,023,965 | 28 | 2010-06-11T15:11:51Z | [
"python",
"iterator"
] | I can check for a `next()` method, but is that enough? Is there an ideomatic way? | In Python 2.6 or better, the designed-in idiom for such behavioral checks is a "membership check" with the abstract base class in the `collections` module of the standard library:
```
>>> import collections
>>> isinstance('ciao', collections.Iterable)
True
>>> isinstance(23, collections.Iterable)
False
>>> isinstance(... |
Printing Unicode in eclipse Pydev console and in Idle | 3,023,972 | 4 | 2010-06-11T15:13:34Z | 3,026,611 | 10 | 2010-06-11T22:16:32Z | [
"python",
"eclipse",
"unicode",
"console",
"pydev"
] | My configuration: Win7 + Python 2.6 + eclipse + PyDev
How do I enable Unicode print statements in:
1. PyDev console in eclipse
2. Idle Python GUI
Example print statement:
```
print(u"ש××× ×¢×××")
```
This comes out as:
```
ùìåà òåìÃ
``` | For eclipse unicode console support:
1. Add `-Dfile.encoding=UTF-8` to `eclipse.ini` which is in the eclipse install directory.
2. In eclipse - `Run\Run Configurations\Python Run\configuration\Common\` make sure UTF-8 is selected
3. In eclipse - `Window\Preferences\General\Workspace\Text file encoding\` making sure UT... |
How to expire session due to inactivity in Django? | 3,024,153 | 63 | 2010-06-11T15:39:04Z | 3,025,372 | 32 | 2010-06-11T18:45:08Z | [
"python",
"django",
"session",
"cookies"
] | Our Django application has the following session management requirements.
1. Sessions expire when the user closes the browser.
2. Sessions expire after a period of inactivity.
3. Detect when a session expires due to inactivity and display appropriate message to the user.
4. Warn users of a impending session expiry a f... | Here's an idea... Expire the session on browser close with the `SESSION_EXPIRE_AT_BROWSER_CLOSE` setting. Then set a timestamp in the session on every request like so.
```
request.session['last_activity'] = datetime.now()
```
and add a middleware to detect if the session is expired. something like this should handle ... |
How to expire session due to inactivity in Django? | 3,024,153 | 63 | 2010-06-11T15:39:04Z | 14,943,164 | 18 | 2013-02-18T18:41:02Z | [
"python",
"django",
"session",
"cookies"
] | Our Django application has the following session management requirements.
1. Sessions expire when the user closes the browser.
2. Sessions expire after a period of inactivity.
3. Detect when a session expires due to inactivity and display appropriate message to the user.
4. Warn users of a impending session expiry a f... | [django-session-security](http://github.com/yourlabs/django-session-security) does just that...
... with an additional requirement: if the server doesn't respond or an attacker disconnected the internet connection: it should expire anyway.
Disclamer: I maintain this app. But I've been watching this thread for a very,... |
python: create a "with" block on several context managers | 3,024,925 | 79 | 2010-06-11T17:39:03Z | 3,024,953 | 12 | 2010-06-11T17:42:49Z | [
"python",
"with-statement",
"contextmanager"
] | Suppose you have three objects you acquire via context manager, for instance A lock, a db connection and an ip socket.
You can acquire them by:
```
with lock:
with db_con:
with socket:
#do stuff
```
But is there a way to do it in one block? something like
```
with lock,db_con,socket:
#do stu... | The first part of your question is possible in [Python 3.1](http://docs.python.org/py3k/reference/compound_stmts.html#with).
> With more than one item, the context managers are processed as if multiple with statements were nested:
>
> ```
> with A() as a, B() as b:
> suite
> ```
>
> is equivalent to
>
> ```
> with... |
python: create a "with" block on several context managers | 3,024,925 | 79 | 2010-06-11T17:39:03Z | 3,025,119 | 146 | 2010-06-11T18:06:21Z | [
"python",
"with-statement",
"contextmanager"
] | Suppose you have three objects you acquire via context manager, for instance A lock, a db connection and an ip socket.
You can acquire them by:
```
with lock:
with db_con:
with socket:
#do stuff
```
But is there a way to do it in one block? something like
```
with lock,db_con,socket:
#do stu... | **In Python 2.6 and below**, you can use [`contextlib.nested`](https://docs.python.org/2/library/contextlib.html#contextlib.nested):
```
from contextlib import nested
with nested(A(), B(), C()) as (X, Y, Z):
do_something()
```
is equivalent to:
```
m1, m2, m3 = A(), B(), C()
with m1 as X:
with m2 as Y:
... |
Statistics: combinations in Python | 3,025,162 | 73 | 2010-06-11T18:13:16Z | 3,025,283 | 80 | 2010-06-11T18:29:58Z | [
"python",
"statistics",
"combinations"
] | I need to compute combinatorials (nCr) in Python but cannot find the function to do that in `math`, `numpy` or `stat` libraries. Something like a function of the type:
```
comb = calculate_combinations(n, r)
```
I need the number of possible combinations, not the actual combinations, so `itertools.combinations` does ... | See [scipy.misc.comb](http://docs.scipy.org/doc/scipy/reference/misc.html#scipy.misc.comb). When `exact` is False, it uses the gammaln function to obtain good precision without taking much time. In the exact case it returns an arbitrary-precision integer, which might take a long time to compute. |
Statistics: combinations in Python | 3,025,162 | 73 | 2010-06-11T18:13:16Z | 3,025,547 | 34 | 2010-06-11T19:12:11Z | [
"python",
"statistics",
"combinations"
] | I need to compute combinatorials (nCr) in Python but cannot find the function to do that in `math`, `numpy` or `stat` libraries. Something like a function of the type:
```
comb = calculate_combinations(n, r)
```
I need the number of possible combinations, not the actual combinations, so `itertools.combinations` does ... | A quick search on google code gives (it uses formula from [@Mark Byers's answer](http://stackoverflow.com/questions/3025162/statistics-combinations-in-python/3025194#3025194)):
```
def choose(n, k):
"""
A fast way to calculate binomial coefficients by Andrew Dalke (contrib).
"""
if 0 <= k <= n:
... |
Statistics: combinations in Python | 3,025,162 | 73 | 2010-06-11T18:13:16Z | 3,026,306 | 34 | 2010-06-11T21:15:40Z | [
"python",
"statistics",
"combinations"
] | I need to compute combinatorials (nCr) in Python but cannot find the function to do that in `math`, `numpy` or `stat` libraries. Something like a function of the type:
```
comb = calculate_combinations(n, r)
```
I need the number of possible combinations, not the actual combinations, so `itertools.combinations` does ... | If you want exact results **and** speed, try [gmpy](http://code.google.com/p/gmpy/) -- `gmpy.comb` should do exactly what you ask for, *and* it's pretty fast (of course, as `gmpy`'s original author, I *am* biased;-). |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.