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 |
|---|---|---|---|---|---|---|---|---|---|
finding elements by attribute with lxml | 5,093,002 | 28 | 2011-02-23T15:29:22Z | 5,093,086 | 37 | 2011-02-23T15:36:09Z | [
"python",
"attributes",
"find",
"lxml"
] | I need to parse a xml file to extract some data.
I only need some elements with certain attributes, here's an exemple of document:
```
<root>
<articles>
<article type="news">
<content>some text</content>
</article>
<article type="info">
<content>some text</content>... | You can use xpath, e.g. `root.xpath("//article[@type='news']")`
This xpath expression will return a list of all `<article/>` elements with "type" attributes with value "news". You can then iterate over it to do what you want, or pass it wherever.
To get just the text content, you can extend the xpath like so:
```
ro... |
How can I log current line, and stack info with Python? | 5,093,075 | 13 | 2011-02-23T15:34:53Z | 5,093,228 | 15 | 2011-02-23T15:47:33Z | [
"python",
"logging",
"traceback"
] | I have logging function as follows.
```
logging.basicConfig(
filename = fileName,
format = "%(levelname) -10s %(asctime)s %(message)s",
level = logging.DEBUG
)
def printinfo(string):
if DEBUG:
logging.info(string)
def printerror(string):
if DEBUG:
logging.error(string)
print s... | ```
import inspect
import traceback
def method():
frame = inspect.currentframe()
stack_trace = traceback.format_stack(frame)
print ''.join(stack_trace)
```
Use stack\_trace[:-1] to avoid including method/printinfo in the stack trace. |
How can I log current line, and stack info with Python? | 5,093,075 | 13 | 2011-02-23T15:34:53Z | 5,093,389 | 16 | 2011-02-23T16:01:06Z | [
"python",
"logging",
"traceback"
] | I have logging function as follows.
```
logging.basicConfig(
filename = fileName,
format = "%(levelname) -10s %(asctime)s %(message)s",
level = logging.DEBUG
)
def printinfo(string):
if DEBUG:
logging.info(string)
def printerror(string):
if DEBUG:
logging.error(string)
print s... | Current function name, module and line number you can do simply by changing your format string to include them.
```
logging.basicConfig(
filename = fileName,
format = "%(levelname) -10s %(asctime)s %(module)s:%(lineno)s %(funcName)s %(message)s",
level = logging.DEBUG
)
```
Most people only want the stack... |
How can I log current line, and stack info with Python? | 5,093,075 | 13 | 2011-02-23T15:34:53Z | 5,098,141 | 7 | 2011-02-23T22:40:08Z | [
"python",
"logging",
"traceback"
] | I have logging function as follows.
```
logging.basicConfig(
filename = fileName,
format = "%(levelname) -10s %(asctime)s %(message)s",
level = logging.DEBUG
)
def printinfo(string):
if DEBUG:
logging.info(string)
def printerror(string):
if DEBUG:
logging.error(string)
print s... | As of Python 3.2, this can be simplified to passing the `stack_info=True` flag to the [logging calls](http://docs.python.org/dev/py3k/library/logging#logging.Logger.debug). However, you'll need to use one of the above answers for any earlier version. |
Use app engine yaml parser in scripts | 5,093,080 | 4 | 2011-02-23T15:35:35Z | 5,093,146 | 8 | 2011-02-23T15:41:03Z | [
"python",
"google-app-engine",
"yaml"
] | I have some configuration files I want to write in yaml and read in a Python script running on Google app engine. Given that app engine uses app.yaml, index.yaml among others it seems reasonable to assume there is a python yaml parser available.
1. How can I gain access to this parser (what is the import) and where ca... | The YAML library is included with the AppEngine SDK. It is located in google\_appengine/lib/yaml. You should be able to use it in your AppEngine code just by having `import yaml` in your code.
For non-AppEngine work, a quick Google search reveals <http://pyyaml.org/> home to many and various Python implementations. |
Problem using the with-statement | 5,093,382 | 2 | 2011-02-23T16:00:18Z | 5,093,418 | 8 | 2011-02-23T16:04:09Z | [
"python",
"with-statement"
] | Why doesn`t this work:
```
class X:
var1 = 1
def __enter__(self): pass
def __exit__(self, type, value, traceback): pass
class Y:
x = X()
y = Y()
with y.x as z:
print z.var1
```
I get:
```
print z.var1
AttributeError: 'NoneType' object has no attribute 'var1'
``` | Change the definition of `X` to
```
class X(object):
var1 = 1
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
pass
```
`with` assigns the return value of the `__enter__()` method to the name after `as`. Your `__enter__()` returned `None`, which was assigned to ... |
find the "overlap" between 2 python lists | 5,094,083 | 12 | 2011-02-23T16:54:24Z | 5,095,171 | 15 | 2011-02-23T18:17:41Z | [
"python",
"list"
] | Given 2 lists:
```
a = [3,4,5,5,5,6]
b = [1,3,4,4,5,5,6,7]
```
I want to find the "overlap":
```
c = [3,4,5,5,6]
```
I'd also like it if i could extract the "remainder" the part of a and b that's not in c.
```
a_remainder = [5,]
b_remainder = [1,4,7,]
```
Note:
a has three 5's in it and b has two.
b has two 4's i... | `collection.Counter` available in Python 2.7 can be used to implement multisets that do exactly what you want.
```
a = [3,4,5,5,5,6]
b = [1,3,4,4,5,5,6,7]
a_multiset = collections.Counter(a)
b_multiset = collections.Counter(b)
overlap = list((a_multiset & b_multiset).elements())
a_remainder = list((a_multiset - b_mu... |
Django: Display a custom error message for admin validation error | 5,096,082 | 8 | 2011-02-23T19:35:19Z | 5,096,654 | 10 | 2011-02-23T20:25:08Z | [
"python",
"django",
"validation",
"django-admin"
] | I'm using Django 1.2.4. I have a model that has a field that needs to be validated. When validation fails, I'd like to display a custom error message to the user. Model editing is done in the admin interface.
This is what I'm doing currently:
```
def clean_fields(self, exclude=None):
# do validation
if proble... | Without looking, it sounds like the admin is looking for an iterable as the value for `field_name`. Try:
```
raise ValidationError({'field_name': ["error message",]})
```
I think the admin expects any number of validation messages to be associated with each field on a form. |
unicode().decode('utf-8', 'ignore') raising UnicodeEncodeError | 5,096,776 | 29 | 2011-02-23T20:36:28Z | 5,096,928 | 45 | 2011-02-23T20:49:55Z | [
"python",
"unicode"
] | Here is the code:
```
>>> z = u'\u2022'.decode('utf-8', 'ignore')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'latin-1' codec can't encode character u'... | When I first started messing around with python strings and unicode, It took me awhile to understand the jargon of *decode* and *encode* too, so here's my post from [here](http://stackoverflow.com/questions/4474430/how-can-i-get-unicode-characters-from-a-url-parameter/4474614#4474614) that may help:
---
Think of *dec... |
unicode().decode('utf-8', 'ignore') raising UnicodeEncodeError | 5,096,776 | 29 | 2011-02-23T20:36:28Z | 5,097,106 | 11 | 2011-02-23T21:06:31Z | [
"python",
"unicode"
] | Here is the code:
```
>>> z = u'\u2022'.decode('utf-8', 'ignore')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'latin-1' codec can't encode character u'... | From <http://wiki.python.org/moin/UnicodeEncodeError>
> Paradoxically, a UnicodeEncodeError may happen when
> *decoding*. The cause of it seems to be the
> coding-specific decode() functions that normally expect
> a parameter of type str. It appears that on seeing a
> unicode parameter, the decode() functions "down-co... |
implementing argmax in Python | 5,098,580 | 18 | 2011-02-23T23:22:44Z | 5,098,586 | 22 | 2011-02-23T23:23:38Z | [
"python",
"itertools"
] | How should argmax be implemented in Python? It should be as efficient as possible, so it should work with iterables.
Three ways it could be implemented:
* given an iterable of pairs return the key corresponding to the greatest value
* given an iterable of values return the index of the greatest value
* given an itera... | I modified the best solution I found:
```
# given an iterable of pairs return the key corresponding to the greatest value
def argmax(pairs):
return max(pairs, key=lambda x: x[1])[0]
# given an iterable of values return the index of the greatest value
def argmax_index(values):
return argmax(enumerate(values))
... |
implementing argmax in Python | 5,098,580 | 18 | 2011-02-23T23:22:44Z | 8,417,193 | 18 | 2011-12-07T14:46:46Z | [
"python",
"itertools"
] | How should argmax be implemented in Python? It should be as efficient as possible, so it should work with iterables.
Three ways it could be implemented:
* given an iterable of pairs return the key corresponding to the greatest value
* given an iterable of values return the index of the greatest value
* given an itera... | Is the following code a fast and pythonic way?
```
idx_max = max(enumerate(x), key=lambda x:x[1])[0]
``` |
Embedding a Low Performance Scripting Language in Python | 5,099,043 | 15 | 2011-02-24T00:27:30Z | 5,190,693 | 11 | 2011-03-04T06:57:52Z | [
"python",
"scripting-language",
"embedded-language"
] | I have a web-application. As part of this, I need users of the app to be able to write (or copy and paste) very simple scripts to run against their data.
The scripts really can be very simple, and performance is only the most minor issue. And example of the sophistication of script I mean are something like:
```
rati... | Here is my take on this problem. Requiring that the user scripts run inside vanilla CPython means you either need to write an interpreter for your mini language, or compile it to Python bytecode (or use Python as your source language) and then "sanitize" the bytecode before executing it.
I've gone for a quick example ... |
Python modulus result is incorrect | 5,099,745 | 3 | 2011-02-24T02:36:49Z | 5,099,763 | 14 | 2011-02-24T02:39:09Z | [
"python"
] | I am totally stumped. I was computing the cipher of the number 54 in RSA with the following values:
p=5; q=29; n=145
d=9; e=137
So the number 54 encrypted would be:
54^137 mod 145
or equivalently in python:
```
import math
math.pow(54,137)%145
```
My calculator gives me 24, my python statement gives me 54.0. Pyth... | ```
>>> pow(54,137,145)
24
```
`math.pow` is floating point. You don't want that. Floating-point values have less than 17 digits of useful precision. The 54\*\*137 has 237 digits. |
Python modulus result is incorrect | 5,099,745 | 3 | 2011-02-24T02:36:49Z | 5,099,767 | 7 | 2011-02-24T02:39:38Z | [
"python"
] | I am totally stumped. I was computing the cipher of the number 54 in RSA with the following values:
p=5; q=29; n=145
d=9; e=137
So the number 54 encrypted would be:
54^137 mod 145
or equivalently in python:
```
import math
math.pow(54,137)%145
```
My calculator gives me 24, my python statement gives me 54.0. Pyth... | That's because using the `math` module is basically just a Python wrapper for the C math library which doesn't have arbitrary precision numbers. That means `math.pow(54,137)` is calculating 54^137 as a 64-bit floating point number, which means it will not be precise enough to hold all the digits of such a large number.... |
Django CSRF check failing with an Ajax POST request | 5,100,539 | 110 | 2011-02-24T04:58:11Z | 5,107,878 | 133 | 2011-02-24T16:59:02Z | [
"python",
"ajax",
"django",
"csrf"
] | I could use some help complying with Django's CSRF protection mechanism via my AJAX post. I've followed the directions here:
<http://docs.djangoproject.com/en/dev/ref/contrib/csrf/>
I've copied the AJAX sample code they have on that page exactly:
<http://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax>
I put a... | **Real solution**
Ok, I managed to trace the problem down. It lies in the Javascript (as I suggested below) code.
What you need is this:
```
$.ajaxSetup({
beforeSend: function(xhr, settings) {
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.... |
Django CSRF check failing with an Ajax POST request | 5,100,539 | 110 | 2011-02-24T04:58:11Z | 5,131,012 | 10 | 2011-02-27T02:18:52Z | [
"python",
"ajax",
"django",
"csrf"
] | I could use some help complying with Django's CSRF protection mechanism via my AJAX post. I've followed the directions here:
<http://docs.djangoproject.com/en/dev/ref/contrib/csrf/>
I've copied the AJAX sample code they have on that page exactly:
<http://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax>
I put a... | The issue is because django is expecting the value from the cookie to be passed back as part of the form data. The code from the previous answer is getting javascript to hunt out the cookie value and put it into the form data. Thats a lovely way of doing it from a technical point of view, but it does look a bit verbose... |
Django CSRF check failing with an Ajax POST request | 5,100,539 | 110 | 2011-02-24T04:58:11Z | 6,170,377 | 87 | 2011-05-29T20:56:52Z | [
"python",
"ajax",
"django",
"csrf"
] | I could use some help complying with Django's CSRF protection mechanism via my AJAX post. I've followed the directions here:
<http://docs.djangoproject.com/en/dev/ref/contrib/csrf/>
I've copied the AJAX sample code they have on that page exactly:
<http://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax>
I put a... | If you use the `$.ajax` function, you can simply add the `csrf` token in the data body:
```
$.ajax({
data: {
somedata: 'somedata',
moredata: 'moredata',
csrfmiddlewaretoken: '{{ csrf_token }}'
},
``` |
Django CSRF check failing with an Ajax POST request | 5,100,539 | 110 | 2011-02-24T04:58:11Z | 7,715,325 | 55 | 2011-10-10T15:44:34Z | [
"python",
"ajax",
"django",
"csrf"
] | I could use some help complying with Django's CSRF protection mechanism via my AJAX post. I've followed the directions here:
<http://docs.djangoproject.com/en/dev/ref/contrib/csrf/>
I've copied the AJAX sample code they have on that page exactly:
<http://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax>
I put a... | Add this line to your jQuery code:
```
$.ajaxSetup({
data: {csrfmiddlewaretoken: '{{ csrf_token }}' },
});
```
and done. |
Django CSRF check failing with an Ajax POST request | 5,100,539 | 110 | 2011-02-24T04:58:11Z | 27,128,044 | 7 | 2014-11-25T13:27:27Z | [
"python",
"ajax",
"django",
"csrf"
] | I could use some help complying with Django's CSRF protection mechanism via my AJAX post. I've followed the directions here:
<http://docs.djangoproject.com/en/dev/ref/contrib/csrf/>
I've copied the AJAX sample code they have on that page exactly:
<http://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax>
I put a... | The `{% csrf_token %}` put in html templates inside `<form></form>`
translates to something like:
```
<input type='hidden' name='csrfmiddlewaretoken' value='Sdgrw2HfynbFgPcZ5sjaoAI5zsMZ4wZR' />
```
so why not just grep it in your JS like this:
```
token = $("#change_password-form").find('input[name=csrfmiddlewareto... |
Python code for Earth mover's Distance | 5,101,004 | 8 | 2011-02-24T06:05:47Z | 10,670,028 | 19 | 2012-05-20T01:10:00Z | [
"python",
"image"
] | I am looking for an Earth Mover's distance(or Fast EMD) implementation in python.
Any clues on where to find it, I have looked enough on the web.
I want to use it in an image retrieval project that I am doing.
Thanks.
EDIT:
I found a very nice solution using the [pulp libararies](http://www.coin-or.org/PuLP/main/insta... | There is an excellent implementation in [OpenCv](http://opencv.willowgarage.com/wiki/) for Python. The name of the function is [CalcEMD2](http://www.seas.upenn.edu/~bensapp/opencvdocs/ref/opencvref_cv.htm#decl_cvCalcEMD2) and a simple code to compare histograms of two images would look like this:
```
#Import OpenCv li... |
Python: Different constructor footprint in derived class | 5,102,051 | 3 | 2011-02-24T08:21:22Z | 13,091,764 | 8 | 2012-10-26T17:40:01Z | [
"python",
"inheritance",
"constructor",
"abstract-class"
] | How can I have a different constructor in a derived class in Python?
If I try something like this:
```
from abc import ABCMeta, abstractproperty, abstractmethod
class AbstractClass(object):
__metaclass__ = ABCMeta
def __init__(self):
pass
```
and
```
import AbstractClass
class DerivedClass(Abstra... | Ensure you inherit from a class, not a module.
I got the same error message when using django models
The mistake was in inheriting my model from models.Model
I had something like
```
class Entry(models):
content = models.TextField()
pub_date = models.DateTimeField()
```
when it should have been
```
class ... |
Convert a tuple into a dictionary | 5,102,477 | 3 | 2011-02-24T09:04:23Z | 5,102,528 | 8 | 2011-02-24T09:08:09Z | [
"python",
"dictionary",
"tuples"
] | I've looked all over the internet and consulted a few books but I can't seem to find an example that illustrates what I am trying to do. I loathe to ask this on SO because it feels like a really basic question but I've been banging my head against the wall for the last few hours so here it goes:
How do i turn this:
`... | ```
{'item': [dict(value=value, label=label) for value, label in item]}
``` |
How to find out what methods, properties, etc a python module possesses | 5,103,329 | 9 | 2011-02-24T10:24:38Z | 5,103,392 | 14 | 2011-02-24T10:30:33Z | [
"python",
"import"
] | Sorry if my question is unclear, I'm new to python and still coming to grips with its terminology.
My question maybe a bit general. Lets say I import a module, in order for me to make the best use of it, I would like to know what properties, methods, etc I can use. Is there a way to find that out?
As an example: [Det... | As for Python modules, you can do
```
>>> import module
>>> help(module)
```
and you'll get a list of supported methods (more exactly, you get the docstring, which might not contain every single method). If you want that, you can use
```
>>> dir(module)
```
although now you'd just get a long list of all properties,... |
Better way to log method calls in Python? | 5,103,735 | 9 | 2011-02-24T11:02:58Z | 5,103,845 | 7 | 2011-02-24T11:12:52Z | [
"python",
"logging"
] | We can code out some sort of logging decorator to echo function/method calls like the following:
```
def log(fn):
...
@log
def foo():
...
class Foo(object):
@log
def foo(self):
...
@log
def bar(self, a, b):
...
@log
def foobar(self, x, y, z):
...
```
But wha... | See [Attaching a decorator to all functions within a class](http://stackoverflow.com/questions/3467526/attaching-a-decorator-to-all-functions-within-a-class)
However, as the accepted answer to that question points out, it generally isn't a good idea.
If you decide to go the aspect oriented programming route, I sugges... |
Better way to log method calls in Python? | 5,103,735 | 9 | 2011-02-24T11:02:58Z | 5,103,895 | 7 | 2011-02-24T11:17:56Z | [
"python",
"logging"
] | We can code out some sort of logging decorator to echo function/method calls like the following:
```
def log(fn):
...
@log
def foo():
...
class Foo(object):
@log
def foo(self):
...
@log
def bar(self, a, b):
...
@log
def foobar(self, x, y, z):
...
```
But wha... | I'm not sure what your use case is for this, but generally, I would think more about what exactly is the problem that you're trying to solve.
That said, here's an example that might do what you want but without a decorator:
```
#!/usr/bin/env python
import inspect
class Foo(object):
def foo(self):
pass... |
Better way to log method calls in Python? | 5,103,735 | 9 | 2011-02-24T11:02:58Z | 5,104,943 | 8 | 2011-02-24T12:54:25Z | [
"python",
"logging"
] | We can code out some sort of logging decorator to echo function/method calls like the following:
```
def log(fn):
...
@log
def foo():
...
class Foo(object):
@log
def foo(self):
...
@log
def bar(self, a, b):
...
@log
def foobar(self, x, y, z):
...
```
But wha... | This might be overkill, but there is a trace function facility that will inform you of a great deal of activity within your program:
```
import sys
def trace(frame, event, arg):
if event == "call":
filename = frame.f_code.co_filename
if filename == "path/to/myfile.py":
lineno = frame.f... |
How to create a tree view with checkboxes in Python | 5,104,330 | 9 | 2011-02-24T11:58:07Z | 5,105,327 | 13 | 2011-02-24T13:33:00Z | [
"python",
"tkinter",
"ttk",
"tix"
] | I've been using Tkinter and Tix to write a small program.
I'm at a point where I need a tree view with checkboxes (checkbuttons) so I can select items from the tree view.
Is there an easy way to do this?
I've been looking at ttk.Treeview () and it looks easy to get the tree view but is there a way to insert a checkbutt... | 
```
import Tix
class View(object):
def __init__(self, root):
self.root = root
self.makeCheckList()
def makeCheckList(self):
self.cl = Tix.CheckList(self.root, browsecmd=self.selectItem)
self.cl.pack()
... |
disallow access to filesystem inside exec and eval in Python | 5,104,356 | 4 | 2011-02-24T12:00:50Z | 5,104,590 | 10 | 2011-02-24T12:22:36Z | [
"python",
"filesystems",
"exec",
"eval",
"sandbox"
] | I want to disallow access to file system from clients code, so I think I could overwrite open function
```
env = {
'open': lambda *a: StringIO("you can't use open")
}
exec(open('user_code.py'), env)
```
but I got this
```
unqualified exec is not allowed in function 'my function' it contains a
nested function wi... | There's no way to prevent access to the file system inside exec/eval. Here's an example code that demonstrates a way for the user code to call otherwise restricted classes that always works:
```
import subprocess
code = """[x for x in ().__class__.__bases__[0].__subclasses__()
if x.__name__ == 'Popen'][0](... |
How do I create a file at a specific path? | 5,104,957 | 6 | 2011-02-24T12:55:57Z | 5,105,328 | 8 | 2011-02-24T13:33:01Z | [
"python"
] | In python I´m creating a file doing:
```
f = open("test.py", "a")
```
where is the file created? How can I create a file on a specific path?
```
f = open("C:\Test.py", "a")
```
returns error. | The file path `"c:\Test\blah"` will have a tab character for the `\T'. You need to use either:
```
"C:\\Test"
```
or
```
r"C:\Test"
``` |
Compile main Python program using Cython | 5,105,482 | 30 | 2011-02-24T13:48:32Z | 5,108,595 | 13 | 2011-02-24T18:00:24Z | [
"python",
"cython"
] | I have a Python2.6 program that can load Python modules compiled to .so files using Cython. I used Cython to compile the .py modules to .so files and everything works fine.
This is the setup.py file I use with Cython:
```
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils... | Take a look at the answers to [Can Cython compile to an EXE?](http://stackoverflow.com/q/2581784/87699) which, contrary to all the other answers here say that yes, it is possible to compile to an executable.
The links at [Embedding Cython](https://github.com/cython/cython/wiki/EmbeddingCython) seem to be a good place ... |
Compile main Python program using Cython | 5,105,482 | 30 | 2011-02-24T13:48:32Z | 22,040,484 | 57 | 2014-02-26T11:50:15Z | [
"python",
"cython"
] | I have a Python2.6 program that can load Python modules compiled to .so files using Cython. I used Cython to compile the .py modules to .so files and everything works fine.
This is the setup.py file I use with Cython:
```
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils... | Contrary to what Adam Matan and others assert, you ***can*** in fact create a single executable binary file using Cython, from a pure Python (.py) file.
Yes, Cython is intended to be used as stated - as a way of simplifying writing C/C++ extension modules for the CPython python runtime.
But, as nudzo alludes to in th... |
Deep copy of a dict in python | 5,105,517 | 105 | 2011-02-24T13:52:22Z | 5,105,554 | 165 | 2011-02-24T13:55:41Z | [
"python",
"python-3.x"
] | I would like to make a deep copy of a `dict` in python. Unfortunately the `.deepcopy()` method doesn't exist for the `dict`. How do I do that?
```
>>> my_dict = {'a': [1, 2, 3], 'b': [4, 5, 6]}
>>> my_copy = my_dict.deepcopy()
Traceback (most recent calll last):
File "<stdin>", line 1, in <module>
AttributeError: 'd... | How about:
```
import copy
d = { ... }
d2 = copy.deepcopy(d)
```
Python 2 or 3:
```
Python 3.2 (r32:88445, Feb 20 2011, 21:30:00) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import copy
>>> my_dict = {'a': [1, 2, 3], 'b': [4, 5, 6]}
>>> my_copy = co... |
List of Python Object Databases | 5,106,212 | 10 | 2011-02-24T14:50:07Z | 5,465,943 | 7 | 2011-03-28T22:49:17Z | [
"python",
"database",
"nosql",
"object-database"
] | I am looking for an object database for Python (no handmade pickles :D).
What are my options (besides the obvious [ZODB](http://www.zope.org/Documentation/Articles/ZODB1))? | [Dobbin](http://pypi.python.org/pypi/dobbin). Somewhat similar to ZODB, but much simpler. It looks nice but I haven't tried it myself. I haven't been able to find much information about it. It has been at version 0.2 for over a year. I don't know if it is still being actively maintained, if it is reliable enough for mi... |
getting every possible combination in a list | 5,106,228 | 4 | 2011-02-24T14:51:19Z | 5,106,348 | 13 | 2011-02-24T14:59:59Z | [
"python",
"list",
"combinations"
] | suppose I had something like this:
```
L1=['cat', 'dog', 'fish', 'rabbit', 'horse', 'bird', 'frog', 'mouse'...]
for x in L1:
input1= open('file_%s'%(x), 'r')
file1= pickle.load(input1)
for x in L1:
input2= open('file_%s'%(x), 'r')
file2= pickle.load(input2)
```
and I wanted to get every c... | This will give you the names:
```
L1=['cat', 'dog', 'fish', 'rabbit', 'horse', 'bird', 'frog', 'mouse']
from itertools import combinations
for combo in combinations(L1, 2):
print '_'.join(combo)
```
Output:
```
cat_dog
cat_fish
cat_rabbit
cat_horse
cat_bird
cat_frog
cat_mouse
dog_fish
dog_rabbit
dog_horse
dog_... |
Improving Performance of Django ForeignKey Fields in Admin | 5,108,080 | 11 | 2011-02-24T17:18:25Z | 5,108,150 | 18 | 2011-02-24T17:22:44Z | [
"python",
"django",
"django-admin"
] | By default, Django's admin renders ForeignKey fields in admin as a select field, listing every record in the foreign table as an option. In one admin-accessible model, I'm referencing the User model as a ForeignKey, and since I have thousands of users Django is populating the select with thousands of options. This is c... | Add [`raw_id_fields`](https://docs.djangoproject.com/en/1.7/ref/contrib/admin/#django.contrib.admin.ModelAdmin.raw_id_fields) to your model to only show the ID instead of a dropdown. |
Improving Performance of Django ForeignKey Fields in Admin | 5,108,080 | 11 | 2011-02-24T17:18:25Z | 5,108,496 | 7 | 2011-02-24T17:50:45Z | [
"python",
"django",
"django-admin"
] | By default, Django's admin renders ForeignKey fields in admin as a select field, listing every record in the foreign table as an option. In one admin-accessible model, I'm referencing the User model as a ForeignKey, and since I have thousands of users Django is populating the select with thousands of options. This is c... | You can use one of the few autocomplete apps for Django. Check them at [Django Packages](http://djangopackages.com/grids/g/auto-complete/).
There's also [django-extensions](https://github.com/django-extensions/django-extensions) that have [`ForeignKeyAutocompleteAdmin`](http://packages.python.org/django-extensions/adm... |
pass argument to __enter__ | 5,109,507 | 20 | 2011-02-24T19:34:53Z | 5,109,578 | 24 | 2011-02-24T19:41:03Z | [
"python",
"with-statement"
] | Just learning about with statements [especially from this article](http://effbot.org/zone/python-with-statement.htm)
question is, can I pass an argument to `__enter__`?
I have code like this:
```
class clippy_runner:
def __enter__(self):
self.engine = ExcelConnection(filename = "clippytest\Test.xlsx")
... | No. You can't. You pass arguments to `__init__()`.
```
class Clippy_Runner( object ):
def __init__( self, args ):
pass
def __enter__( self ):
etc.
with Clippy_Runner( args ) as something:
# work with "something"
``` |
USB devices UDev and D-BUS | 5,109,879 | 15 | 2011-02-24T20:11:16Z | 5,111,493 | 10 | 2011-02-24T22:45:27Z | [
"python",
"linux",
"ubuntu",
"dbus",
"udev"
] | I am trying to get a list of currently plugged in USB devices in Ubuntu 10.10 and monitor changes that happen, like devices being plugged in or out using UDev and D-BUS. I'm fairly new to programming using D-BUS. I saw one example: [Linux : How to detect is usb keyboard is plugged and unplugged](http://stackoverflow.co... | The [udisks](http://www.freedesktop.org/wiki/Software/udisks) D-Bus service, obviously, only reports disks.
Just monitor udev directly (through libudev, through [pyudev](http://packages.python.org/pyudev/)).
```
import pyudev
context = pyudev.Context()
monitor = pyudev.Monitor.from_netlink(context)
observer = pyudev.... |
Linux/Python: encoding a unicode string for print | 5,109,970 | 16 | 2011-02-24T20:21:11Z | 5,110,036 | 16 | 2011-02-24T20:28:09Z | [
"python",
"linux",
"unicode",
"encoding",
"locale"
] | I have a fairly large python 2.6 application with lots of print statements sprinkled about. I'm using unicode strings throughout, and it usually works great. However, if I redirect the output of the application (like "myapp.py >output.txt"), then I occasionally get errors such as this:
```
UnicodeEncodeError: 'ascii' ... | If you're dumping to an ASCII terminal, encode manually using `unicode.encode`, and specify that errors should be ignored.
```
u = u'\xa0'
u.encode('ascii') # This fails
u.encode('ascii', 'ignore') # This replaces failed encoding attempts with empty string
```
If you want to store unicode files, try this:
```
u = u'... |
How do I display current time using Python + Django? | 5,110,352 | 4 | 2011-02-24T20:54:52Z | 5,111,517 | 7 | 2011-02-24T22:48:43Z | [
"python",
"django",
"google-app-engine"
] | I am learning how to use Python and Django to produce a small webapp that prints out the current time. I am using this with the Google App Engine.
Right now it's only displaying a blank page, but I want it to display the current time. I also want to map the function to the home page.. not /time/.
```
from django.http... | Use the [now template tag](http://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#now). For example:
```
{% now "jS F Y H:i" %}
```
but you'll need to send your string through template engine before sending the response for it to work. |
How do I display current time using Python + Django? | 5,110,352 | 4 | 2011-02-24T20:54:52Z | 19,266,907 | 12 | 2013-10-09T08:36:10Z | [
"python",
"django",
"google-app-engine"
] | I am learning how to use Python and Django to produce a small webapp that prints out the current time. I am using this with the Google App Engine.
Right now it's only displaying a blank page, but I want it to display the current time. I also want to map the function to the home page.. not /time/.
```
from django.http... | Maybe this documentation is useful to you: [Time Zones](https://docs.djangoproject.com/en/dev/topics/i18n/timezones/)
# Formatting time in a view
You can get the current time using:
```
import datetime
now = datetime.datetime.now()
```
**or**
to get time depending on timezone:
```
import datetime
from django.utils... |
Customize Python Slicing, please advise | 5,112,019 | 7 | 2011-02-24T23:51:04Z | 5,112,177 | 16 | 2011-02-25T00:14:36Z | [
"python",
"list",
"slice"
] | I have a class that subclasses the list object. Now I need to handle slicing. From everything I read on the intertubes this has to be done using the `__getitem__` method. At least in Python 2.7+ which is what I'm using. I have done this (see below), but the `__getitem__` method isn't called when I pass in a slice. Inst... | See [this note](http://docs.python.org/reference/datamodel.html#additional-methods-for-emulation-of-sequence-types):
> `object.__getslice__(self, i, j)`
>
> Deprecated since version 2.0: Support
> slice objects as parameters to the
> `__getitem__()` method. (However, built-in types in CPython currently
> still impleme... |
Reading data from 3d models with python | 5,112,739 | 5 | 2011-02-25T01:46:38Z | 5,112,750 | 7 | 2011-02-25T01:48:31Z | [
"python",
"parsing",
"3d"
] | I want to extract the vertices and faces (as lists of vertices) from a 3d model. The format of the 3d model doesn't matter as long as it's generatable in Maya.
I would like to do this in Python. Are there any libraries, file types, etc. that you would recommend? | I'm pretty sure Maya exports in OBJ file format, which is very heavily documented and implemented. Python's cgkit implements an OBJ parser, which you can find here: <http://cgkit.sourceforge.net/doc2/objmtl.html>
Edit: Actually, cgkit can read a lot more formats from Maya than just OBJ. I searched for OBJ since I knew... |
why do python strings not have __iter__ function? | 5,113,133 | 19 | 2011-02-25T03:00:05Z | 5,113,141 | 35 | 2011-02-25T03:03:07Z | [
"python",
"string",
"iteration"
] | How is it that we can iterate over python strings when strings don't have an `__iter__` function?
```
$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> "asdf".__iter__
Traceback (most recent call last):
File "<s... | From your link:
> or it must support the sequence
> protocol (the `__getitem__()` method
> with integer arguments starting at 0).
```
In [1]: 'foo'.__getitem__(0)
Out[1]: 'f'
``` |
How do I tell Python that sys.argv is in Unicode? | 5,113,618 | 9 | 2011-02-25T04:29:44Z | 5,113,874 | 14 | 2011-02-25T05:14:24Z | [
"python",
"osx",
"unicode",
"terminal"
] | Here is a little program:
```
import sys
f = sys.argv[1]
print type(f)
print u"f=%s" % (f)
```
Here is my running of the program:
```
$ python x.py 'Recent/רש××ת ×שתתפ××.LNK'
<type 'str'>
Traceback (most recent call last):
File "x.py", line 5, in <module>
print u"f=%s" % (f)
UnicodeDecodeError: 'a... | The `UnicodeDecodeError` error you see is due to you're mixing the Unicode string `u"f=%s"` and the `sys.argv[1]` bytestring:
* both bytestrings:
```
$ python -c'import sys; print "f=%s" % (sys.argv[1],)' 'Recent/רש××ת ×שתתפ××'
```
This passes bytes transparently from/to your terminal. It works f... |
break/interrupt a time.sleep() in python | 5,114,292 | 16 | 2011-02-25T06:26:00Z | 5,114,409 | 8 | 2011-02-25T06:44:04Z | [
"python"
] | I need to break from time.sleep() using ctrl c.
```
While 1:
time.sleep(60)
```
In the above code when the control enters time.sleep function an entire 60 seconds needs to elapsed for python to handled the CTRL C
Is there any elegant way to do it. such that I can interrupt even when the control is in time.sleep ... | Not sure what the sense of this code is - but if necessary use a shorter sleep() interval and put a for loop around it:
```
for i in range(60):
sleep(1)
```
Catching the **KeyboardInterrupt** exception using try..except is straight-forward |
break/interrupt a time.sleep() in python | 5,114,292 | 16 | 2011-02-25T06:26:00Z | 5,114,437 | 9 | 2011-02-25T06:47:55Z | [
"python"
] | I need to break from time.sleep() using ctrl c.
```
While 1:
time.sleep(60)
```
In the above code when the control enters time.sleep function an entire 60 seconds needs to elapsed for python to handled the CTRL C
Is there any elegant way to do it. such that I can interrupt even when the control is in time.sleep ... | The KeyboardInterrupt exception is raised when a user hits the interrupt key, Ctrl-C. In python this is translated from a SIGINT signal. That means, you can get handle it however you want using the signal module:
```
import signal
def handler(signum, frame):
print "do whatever, like call thread.interrupt_main()"
... |
using print() with compound operators in python | 5,115,551 | 2 | 2011-02-25T09:25:52Z | 5,115,593 | 8 | 2011-02-25T09:30:46Z | [
"python",
"python-3.x",
"compound-operator"
] | The following code doesn't work in python
```
x = 11
print(x += 5)
```
while this code does
```
x = 11
x += 5
print(x)
```
why is that? | x += 5 is a statement, not an expression. You can only use expressions as arguments in function calls.
I'm assuming you are used to a C-like language, where x += 5 is an expression, but in Python it's not. |
using print() with compound operators in python | 5,115,551 | 2 | 2011-02-25T09:25:52Z | 5,115,710 | 8 | 2011-02-25T09:44:04Z | [
"python",
"python-3.x",
"compound-operator"
] | The following code doesn't work in python
```
x = 11
print(x += 5)
```
while this code does
```
x = 11
x += 5
print(x)
```
why is that? | The problem is the due to the difference between a Statement and an Expression. [This question has an excellent answer which explains the difference](http://stackoverflow.com/questions/19132/expression-versus-statement), the key point being:
> **Expression:** Something which evaluates to a value. Example: 1+2/x
>
> **... |
Python namespacing and classes | 5,117,194 | 7 | 2011-02-25T12:26:08Z | 5,117,212 | 8 | 2011-02-25T12:28:55Z | [
"python",
"class",
"module",
"scope"
] | I'm trying to write some (in my opinion) readable code in Python. I need a module that will contain a number of classes. Theoretically I know everything that is needed to accomplish this: I can simply put class definitions in a single module file.
For readability purposes I want to put every class definition into sepa... | Import them all within `__init__.py`, and then have the consumer import the package.
```
from .module1 import Class1
from .module2 import Class2
...
``` |
WTForms-How to prepopulate a textarea field? | 5,117,479 | 13 | 2011-02-25T12:54:51Z | 5,122,606 | 15 | 2011-02-25T21:02:00Z | [
"python",
"flask",
"wtforms"
] | Hi I have been trying to pepopulate a textareafield using something
like this in the template.
```
{{form.content(value="please type content")}}
```
This works when the field is textfield primarily because the html
accepts value for `<input type="text">`
but the same does not work for textarea...
Can someone please h... | For `textarea` widgets, you set the default content with the `default` argument in your field constructors.
```
class YourForm(Form):
your_text_area = TextAreaField("TextArea", default="please add content")
```
Then when you render:
```
{{form.content()}}
```
WTForms will render the default text. I have not bee... |
WTForms-How to prepopulate a textarea field? | 5,117,479 | 13 | 2011-02-25T12:54:51Z | 5,175,227 | 23 | 2011-03-03T00:30:38Z | [
"python",
"flask",
"wtforms"
] | Hi I have been trying to pepopulate a textareafield using something
like this in the template.
```
{{form.content(value="please type content")}}
```
This works when the field is textfield primarily because the html
accepts value for `<input type="text">`
but the same does not work for textarea...
Can someone please h... | You can do it before rendering, something like:
```
form.content.data = 'please type content'
```
I'm new to WTForms though. |
WTForms-How to prepopulate a textarea field? | 5,117,479 | 13 | 2011-02-25T12:54:51Z | 14,658,972 | 8 | 2013-02-02T05:33:57Z | [
"python",
"flask",
"wtforms"
] | Hi I have been trying to pepopulate a textareafield using something
like this in the template.
```
{{form.content(value="please type content")}}
```
This works when the field is textfield primarily because the html
accepts value for `<input type="text">`
but the same does not work for textarea...
Can someone please h... | I recently had the same problem, I solved it like this:
```
{% set f = form.content.process_data("please type content") %}
{{ form.content() }}
```
For a test, you can try run the follow snippet:
```
>>> import wtforms
>>> import jinja2
>>> from wtforms.fields import TextAreaField
>>> class MyForm(wtforms.Form):
...... |
Python: Get max pair in a list of pairs with min y | 5,118,249 | 3 | 2011-02-25T14:15:34Z | 5,118,288 | 17 | 2011-02-25T14:18:55Z | [
"python",
"list",
"max",
"min"
] | How i get max pair in a list of pairs with min y?
I got this list:
```
L =[[1,3],[2,5],[-4,0],[2,1],[0,9]]
```
With max(L) i get [2,5], but i want [2,1]. | ```
max(L, key=lambda item: (item[0], -item[1]))
```
Output:
```
[2, 1]
``` |
Identifying points with the smallest Euclidean distance | 5,119,644 | 8 | 2011-02-25T16:17:17Z | 5,119,676 | 8 | 2011-02-25T16:20:06Z | [
"python",
"algorithm",
"numpy",
"nearest-neighbor",
"euclidean-distance"
] | I have a collection of n dimensional points and I want to find which 2 are the closest. The best I could come up for 2 dimensions is:
```
from numpy import *
myArr = array( [[1, 2],
[3, 4],
[5, 6],
[7, 8]] )
n = myArr.shape[0]
cross = [[sum( ( myArr[i] - myArr[j] ) ** 2... | There's a whole Wikipedia page on just this problem, see: <http://en.wikipedia.org/wiki/Closest_pair_of_points>
Executive summary: you can achieve O(n log n) with a recursive divide and conquer algorithm (outlined on the Wiki page, above). |
Identifying points with the smallest Euclidean distance | 5,119,644 | 8 | 2011-02-25T16:17:17Z | 5,119,899 | 11 | 2011-02-25T16:38:20Z | [
"python",
"algorithm",
"numpy",
"nearest-neighbor",
"euclidean-distance"
] | I have a collection of n dimensional points and I want to find which 2 are the closest. The best I could come up for 2 dimensions is:
```
from numpy import *
myArr = array( [[1, 2],
[3, 4],
[5, 6],
[7, 8]] )
n = myArr.shape[0]
cross = [[sum( ( myArr[i] - myArr[j] ) ** 2... | Try `scipy.spatial.distance.pdist(myArr)`. This will give you a condensed distance matrix. You can use `argmin` on it and find the index of the smallest value. This can be converted into the pair information. |
'True' and 'False' in Python | 5,119,709 | 29 | 2011-02-25T16:23:32Z | 5,119,742 | 72 | 2011-02-25T16:25:39Z | [
"python",
"boolean"
] | I tried running this piece of code:
```
path = '/bla/bla/bla'
if path is True:
print "True"
else:
print "False"
```
And it prints **False**. I thought Python treats anything with value as **True**. Why is this happening? | `is` compares identity. A string will never be identical to a not-string.
`==` is equality. But a string will never be equal to either `True` or `False`.
You want neither.
```
path = '/bla/bla/bla'
if path:
print "True"
else:
print "False"
``` |
'True' and 'False' in Python | 5,119,709 | 29 | 2011-02-25T16:23:32Z | 5,120,113 | 43 | 2011-02-25T16:53:20Z | [
"python",
"boolean"
] | I tried running this piece of code:
```
path = '/bla/bla/bla'
if path is True:
print "True"
else:
print "False"
```
And it prints **False**. I thought Python treats anything with value as **True**. Why is this happening? | From <http://docs.python.org/reference/expressions.html#boolean-operations>:
> > In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including string... |
Django - Get ContentType model by model name (Generic Relations) | 5,120,071 | 9 | 2011-02-25T16:50:26Z | 5,120,163 | 28 | 2011-02-25T16:57:23Z | [
"python",
"django",
"content-type"
] | I'm thinking about this for a while now,
I'm creating a chat application, in chat.models a class Room is specified, however, a Room can be related to anything in my project, since it uses a generic relation in it's foreign key.
Is there a way to know which model that Room is related knowing only the models name?
Lik... | <http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#methods-on-contenttype-instances>
```
user_type = ContentType.objects.get(app_label="auth", model="user")
user_type = ContentType.objects.get(model="user")
# but this can throw an error if you have 2 models with the same name.
```
Very similar to django'... |
Avoiding Python UnicodeDecodeError in Jinja's nl2br filter | 5,120,302 | 6 | 2011-02-25T17:09:30Z | 5,120,327 | 13 | 2011-02-25T17:11:15Z | [
"python",
"unicode",
"jinja2",
"flask"
] | I'm using Jinja2's nl2br filter, which looks like:
```
import re
from jinja2 import environmentfilter, Markup, escape
_paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')
@evalcontextfilter
def nl2br(eval_ctx, value):
result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', '<br>\n')
for p in _par... | Use `unicode` literals everywhere.
["Unicode in Python, Completely Demystified"](http://farmdev.com/talks/unicode/) |
Python find object in a list | 5,120,391 | 5 | 2011-02-25T17:16:44Z | 5,120,437 | 8 | 2011-02-25T17:21:25Z | [
"python",
"list",
"search",
"indexing"
] | I have a list of people:
```
[
{'name' : 'John', 'wins' : 10 },
{'name' : 'Sally', 'wins' : 0 },
{'name' : 'Fred', 'wins' : 3 },
{'name' : 'Mary', 'wins' : 6 }
]
```
I am adding wins using a list of names (`['Fred', 'Mary', 'Sally']`). I don't know if the name is in the list of people already, and I n... | Yes, use a dict.
```
wins = {}
for name in winners:
wins.setdefault(name, 0)
wins[name] += 1
```
**edit:**
```
index = {}
for name in wins:
person = index.setdefault(name, { 'name' : name, 'wins': 0 })
if person['wins'] == 0:
person_list.append(person)
person['wins'] += 1
``` |
Python find object in a list | 5,120,391 | 5 | 2011-02-25T17:16:44Z | 5,120,509 | 8 | 2011-02-25T17:27:04Z | [
"python",
"list",
"search",
"indexing"
] | I have a list of people:
```
[
{'name' : 'John', 'wins' : 10 },
{'name' : 'Sally', 'wins' : 0 },
{'name' : 'Fred', 'wins' : 3 },
{'name' : 'Mary', 'wins' : 6 }
]
```
I am adding wins using a list of names (`['Fred', 'Mary', 'Sally']`). I don't know if the name is in the list of people already, and I n... | I'm assuming here that you don't want to use any structure other than the list. Your code should work, although you unnecessarily write the dictionary back to the list after updating it. Dictionaries are copied by reference, so once you update it, it stays updated in the list. After a little housekeeping, your code cou... |
How can I convert a WAV from stereo to mono in Python? | 5,120,555 | 4 | 2011-02-25T17:31:21Z | 13,384,150 | 8 | 2012-11-14T17:37:07Z | [
"python",
"audio",
"wav"
] | I don't want to use any other apps (like sox) - I want to do this in pure Python. Installing needed Python libs is fine. | I maintain an open source library, [pydub](http://pydub.com), which make this pretty simple
```
from pydub import AudioSegment
sound = AudioSegment.from_wav("/path/to/file.wav")
sound = sound.set_channels(1)
sound.export("/output/path.wav", format="wav")
```
One caveat: it uses ffmpeg to handle audio format conversio... |
Is there a way to set metaclass after the class definition? | 5,120,688 | 9 | 2011-02-25T17:43:47Z | 5,121,381 | 9 | 2011-02-25T18:55:07Z | [
"python",
"metaclass"
] | In order to set metaclass of a class, we use the `__metaclass__` attribute. Metaclasses are used at the time the class is defined, so setting it explicitly after the class definition has no effect.
This is what happens when I try to set metaclasses explicitly;
```
>>> class MetaClass(type):
def __new__(cls, name,... | You can change the metaclass after class creation the same way that you can change the class of an object, however you'd have a lot of issues. For starters, the initial metaclass needs to be different from `type`, the `__init__` and `__new__` of the new metaclass won't be called (though you can manually call `__init__`... |
wxPython import error | 5,121,574 | 11 | 2011-02-25T19:14:11Z | 10,707,477 | 15 | 2012-05-22T18:00:17Z | [
"python",
"wxpython",
"importerror",
"python-import"
] | I'm having trouble figuring out an error message in Python.
yesterday, I've installed python using the latest EPD package, and wxPython2.9 using the wxPython2.9-osx-cocoa-py2.7 package for Mac OS.
I then added wx to my PYTHONPATH.
```
export WXDIR=/usr/local/lib/wxPython-2.9.1.1/lib/python2.7/site-packages/wx-2.9.1-o... | In Ubuntu 12.04, this problem can be solved by running the command
```
sudo apt-get install libjpeg62
```
I realize this may not be useful here, but I wanted to document it somewhere on teh interwebz so I can find it when I run into this problem again myself which will undoubtedly happen. |
Python SQLAlchemy - Mocking a model attribute's "desc" method | 5,121,595 | 7 | 2011-02-25T19:16:19Z | 5,287,881 | 12 | 2011-03-13T06:30:10Z | [
"python",
"unit-testing",
"mocking",
"sqlalchemy",
"mox"
] | In my application, there is a class for each model that holds commonly used queries (I guess it's somewhat of a "Repository" in DDD language). Each of these classes is passed the SQLAlchemy session object to create queries with upon construction. I'm having a little difficulty in figuring the best way to assert certain... | I don't think you're really gaining much benefit by using mocks for testing your queries. Testing should be testing the **logic** of the code, not the **implementation**. A better solution would be to create a fresh database, add some objects to it, run the query on that database, and determine if you're getting the co... |
Installing scipy for python 2.7 | 5,121,826 | 10 | 2011-02-25T19:39:41Z | 5,121,843 | 19 | 2011-02-25T19:42:04Z | [
"python",
"install",
"scipy",
"python-2.7"
] | I cannot seem to get SciPy working for Python 2.7 on a 32 bit Windows XP platform. I'd rather not build my own copy. Does anyone know where I could find a installer for it? I tried this [site](http://www.lfd.uci.edu/~gohlke/pythonlibs/), but it didn't work. | Download it from [here](http://sourceforge.net/projects/scipy/files/scipy/0.9.0rc5/scipy-0.9.0rc5-win32-superpack-python2.7.exe/download).
I'm not sure about that site you referred to, but I always start at: <http://www.scipy.org> |
In Python, how can you load YAML mappings as OrderedDicts? | 5,121,931 | 63 | 2011-02-25T19:52:12Z | 5,121,963 | 12 | 2011-02-25T19:55:12Z | [
"python",
"dictionary",
"yaml",
"pyyaml"
] | I'd like to get [PyYAML](http://pyyaml.org/)'s loader to load mappings (and ordered mappings) into the Python 2.7+ [OrderedDict](http://docs.python.org/library/collections.html#collections.OrderedDict) type, instead of the vanilla `dict` and the list of pairs it currently uses.
What's the best way to do that? | I doubt very much that this is the best way to do it, but this is the way I came up with, and it does work. Also available [as a gist](https://gist.github.com/844388).
```
import yaml
import yaml.constructor
try:
# included in standard lib from Python 2.7
from collections import OrderedDict
except ImportError... |
In Python, how can you load YAML mappings as OrderedDicts? | 5,121,931 | 63 | 2011-02-25T19:52:12Z | 21,048,064 | 29 | 2014-01-10T15:26:03Z | [
"python",
"dictionary",
"yaml",
"pyyaml"
] | I'd like to get [PyYAML](http://pyyaml.org/)'s loader to load mappings (and ordered mappings) into the Python 2.7+ [OrderedDict](http://docs.python.org/library/collections.html#collections.OrderedDict) type, instead of the vanilla `dict` and the list of pairs it currently uses.
What's the best way to do that? | The yaml module allow you to specify custom 'representers' to convert Python objects to text and 'constructors' to reverse the process.
```
_mapping_tag = yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG
def dict_representer(dumper, data):
return dumper.represent_dict(data.iteritems())
def dict_constructor(loader,... |
In Python, how can you load YAML mappings as OrderedDicts? | 5,121,931 | 63 | 2011-02-25T19:52:12Z | 21,912,744 | 63 | 2014-02-20T15:47:31Z | [
"python",
"dictionary",
"yaml",
"pyyaml"
] | I'd like to get [PyYAML](http://pyyaml.org/)'s loader to load mappings (and ordered mappings) into the Python 2.7+ [OrderedDict](http://docs.python.org/library/collections.html#collections.OrderedDict) type, instead of the vanilla `dict` and the list of pairs it currently uses.
What's the best way to do that? | I like @James' [solution](http://stackoverflow.com/a/21048064/650222) for its simplicity. However, it changes the default global `yaml.Loader` class, which can lead to troublesome side effects. Especially, when writing library code this is a bad idea. Also, it doesn't directly work with `yaml.safe_load()`.
Fortunately... |
Reason for uncommon OOP in Python? | 5,122,034 | 8 | 2011-02-25T20:02:04Z | 5,122,215 | 13 | 2011-02-25T20:22:45Z | [
"python",
"oop"
] | Instead of using common OOP, like Java and C# do with their base class `Object` or `object`, Python uses special methods for basic behaviour of objects. Python uses `__str__` which is used when the object is passed to `print`:
```
>>> class Demo:
>>> def __str__(self):
>>> return "representation"
>>> d = Demo()... | The reason for this is explained well in the Python documentation here:
<http://docs.python.org/faq/design.html#why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list>
> The major reason is history. Functions
> were used for those operations that
> were generic for a gr... |
Extracting the a value from a tuple when the other values are unused | 5,122,041 | 5 | 2011-02-25T20:02:36Z | 5,122,098 | 7 | 2011-02-25T20:09:14Z | [
"python"
] | I have a tuple `foo` which contains something I don't care about and something I do.
```
foo = (something_i_dont_need, something_i_need)
```
Is it more correct to use
```
_, x = foo
```
or
```
x = foo[1]
```
The only things I can think of are different behaviour if `foo` isn't of length two.
I suppose this is fai... | I've been using `_` for over a decade. It is much more readable, especially when extracting more than one value:
```
_, _, name, _, _, city, _ = whatever
```
Even with only one variable, the other way forces humans readers to count if they want to truly understand the code, and more likely their eyes are just going... |
Printing tabular data in Python | 5,122,347 | 9 | 2011-02-25T20:38:19Z | 5,122,401 | 9 | 2011-02-25T20:44:25Z | [
"python",
"tabular-form"
] | What's the best way to print tabular data in Python? Say the data is in a 2D list and I want to create a smart looking table. What I actually have is a list of dictionaries and I want to print an intersection depending on values in the dictionaries. Something like
```
for val1 in my_dict:
for val2 in my_dict:
i... | Do you know about [PyPi](http://pypi.python.org)?
[DataGrid](http://pypi.python.org/pypi/DataGrid/0.2.0) and [PrettyTable](http://pypi.python.org/pypi/PrettyTable/0.5) seem like two good alternatives I found with a brief search. You may have to assemble the data in the format you want it (with "x" for when your condit... |
Printing tabular data in Python | 5,122,347 | 9 | 2011-02-25T20:38:19Z | 5,122,411 | 13 | 2011-02-25T20:45:11Z | [
"python",
"tabular-form"
] | What's the best way to print tabular data in Python? Say the data is in a 2D list and I want to create a smart looking table. What I actually have is a list of dictionaries and I want to print an intersection depending on values in the dictionaries. Something like
```
for val1 in my_dict:
for val2 in my_dict:
i... | ```
print "%20s" % somevar
```
Will print the value 'somevar' and use up to 20 spaces. Add a comma behind the print statement in order to avoid the line-break - and of course: read the [string formatting operations docs](http://docs.python.org/2/library/stdtypes.html#string-formatting) on the '%' operator |
Angle between points? | 5,122,372 | 32 | 2011-02-25T20:41:38Z | 28,530,929 | 28 | 2015-02-15T20:42:21Z | [
"python",
"algorithm",
"math"
] | I have a triangle (A, B, C) and am trying to find the angle between each pair of the three points.
The problem is that the algorithms I can find online are for determining the angle between vectors. Using the vectors I would compute the angle between the vector that goes from (0, 0) to the point I have, and that doesn... | There are two errors here.
* You missed a factor of π when translating from radians to degrees (it's × 180 / π)
* You have to be careful about the signs of vectors, since they are directed line segments.
If I make these modifications I get a result that makes sense:
```
import numpy as np
points = np.array([[343.899... |
Can a PyQt4 QObject be queried to determine if the underlying C++ instance has been destroyed? | 5,122,451 | 7 | 2011-02-25T20:48:14Z | 5,149,364 | 15 | 2011-03-01T00:54:38Z | [
"python",
"qt",
"pyqt",
"pyqt4"
] | The [destroyed()](http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qobject.html#destroyed) signal can be trapped for a QObject, but I would like to simply test if the Python object still references a valid C++ Qt object. Is there a method for doing so directly? | If you import the sip module you can call its .isdeleted function.
```
import sip
from PyQt4.QtCore import QObject
q = QObject()
sip.isdeleted(q)
False
sip.delete(q)
q
<PyQt4.QtCore.QObject object at 0x017CCA98>
q.isdeleted(q)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: un... |
Can I "fake" a package ( or at least a module ) in python for testing purposes? | 5,122,465 | 10 | 2011-02-25T20:49:33Z | 5,122,529 | 15 | 2011-02-25T20:55:20Z | [
"python",
"unit-testing",
"mocking"
] | I want to fake a package in python. I want to define something so that the code can do
```
from somefakepackage.morefakestuff import somethingfake
```
And somefakepackage is defined in code and so is everything below it. Is that possible? The reason for doing this is to trick my unittest that I got a package ( or as ... | Sure. Define a class, put the stuff you need inside that, assign the class to `sys.modules["classname"]`.
```
class fakemodule(object):
@staticmethod
def method(a, b):
return a+b
import sys
sys.modules["package.module"] = fakemodule
```
You could also use a separate module (call it `fakemodule.py`):... |
python - extract coordinates from a variable string | 5,123,508 | 3 | 2011-02-25T22:41:27Z | 5,123,532 | 11 | 2011-02-25T22:43:35Z | [
"python"
] | I have a latitude and longitude that come in a string like this:
```
my_string ='(31.251, -98.877)'
```
I would like to use Python to extract the coordinates from the above string.
The problem is that sometimes the string has variable length so one time it might look like this `(31.25134, -98.877)` or `(31.25134, -9... | ```
>>> ast.literal_eval('(31.251, -98.877)')
(31.251, -98.877)
``` |
Fastest way to get the first object from a queryset in django? | 5,123,839 | 101 | 2011-02-25T23:26:15Z | 5,123,866 | 47 | 2011-02-25T23:30:36Z | [
"python",
"django",
"performance",
"django-models"
] | Often I find myself wanting to get the first object from a queryset in Django, or return `None` if there aren't any. There are lots of ways to do this which all work. But I'm wondering which is the most performant.
```
qs = MyModel.objects.filter(blah = blah)
if qs.count() > 0:
return qs[0]
else:
return None
`... | ```
r = list(qs[:1])
if r:
return r[0]
return None
``` |
Fastest way to get the first object from a queryset in django? | 5,123,839 | 101 | 2011-02-25T23:26:15Z | 5,162,274 | 111 | 2011-03-02T00:58:14Z | [
"python",
"django",
"performance",
"django-models"
] | Often I find myself wanting to get the first object from a queryset in Django, or return `None` if there aren't any. There are lots of ways to do this which all work. But I'm wondering which is the most performant.
```
qs = MyModel.objects.filter(blah = blah)
if qs.count() > 0:
return qs[0]
else:
return None
`... | The correct answer is
```
Entry.objects.all()[:1].get()
```
**Which can be used in:**
```
Entry.objects.filter()[:1].get()
```
You wouldn't want to first turn it into a list because that would force a full database call of all the records. Just do the above and it will only pull the first. You could even use `.orde... |
Fastest way to get the first object from a queryset in django? | 5,123,839 | 101 | 2011-02-25T23:26:15Z | 20,049,773 | 183 | 2013-11-18T14:07:42Z | [
"python",
"django",
"performance",
"django-models"
] | Often I find myself wanting to get the first object from a queryset in Django, or return `None` if there aren't any. There are lots of ways to do this which all work. But I'm wondering which is the most performant.
```
qs = MyModel.objects.filter(blah = blah)
if qs.count() > 0:
return qs[0]
else:
return None
`... | [Django 1.6 (released Nov 2013)](https://www.djangoproject.com/weblog/2013/nov/06/django-16-released/) introduced the [convenience methods](https://docs.djangoproject.com/en/dev/ref/models/querysets/#first) `first()` and `last()` which swallow the resulting exception and return `None` if the queryset returns no objects... |
Python/Scipy Interpolation (map_coordinates) | 5,124,126 | 9 | 2011-02-26T00:15:55Z | 5,124,235 | 15 | 2011-02-26T00:39:52Z | [
"python",
"numpy",
"scipy",
"interpolation"
] | I'm trying to do some interpolation with scipy. I've gone through many examples, but I'm not finding exactly what I want.
Let's say I have some data where the row and column variable can vary from 0 to 1. The delta changes between each row and column is not always the same (see below).
```
| 0.00 0.25 0.80 ... | I think you want a [bivariate spline on a rectangular structured mesh](http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.RectBivariateSpline.html#scipy.interpolate.RectBivariateSpline):
```
import numpy
from scipy import interpolate
x = numpy.array([0.0, 0.60, 1.0])
y = numpy.array([0.0, 0.25, 0.80... |
What is the difference between import modx and from modx import *? | 5,124,232 | 14 | 2011-02-26T00:38:46Z | 5,124,255 | 27 | 2011-02-26T00:43:38Z | [
"python",
"module",
"import"
] | If I were to import some module called modx, how would that be different from saying
```
from modx import *
```
Wouldn't all the contents be imported from each either way? This is in python just to clarify. | If you `import somemodule` the contained globals will be available via `somemodule.someglobal`. If you `from somemodule import *` ALL its globals (or those listed in `__all__` if it exists) will be made globals, i.e. you can access them using `someglobal` without the module name in front of it.
Using `from module impo... |
What is the difference between import modx and from modx import *? | 5,124,232 | 14 | 2011-02-26T00:38:46Z | 5,124,281 | 12 | 2011-02-26T00:47:42Z | [
"python",
"module",
"import"
] | If I were to import some module called modx, how would that be different from saying
```
from modx import *
```
Wouldn't all the contents be imported from each either way? This is in python just to clarify. | If `a` defines `a.b` and `a.c`...
```
import a
a.b()
a.c()
```
vs.
```
from a import b
b()
c() # fails because c isn't imported
```
vs.
```
from a import *
b()
c()
```
Note that `from foo import *` is generally frowned upon since:
1. It puts things into the global namespace without giving you fine control
2. It ... |
convert nan value to zero | 5,124,376 | 20 | 2011-02-26T01:08:12Z | 5,124,402 | 37 | 2011-02-26T01:16:44Z | [
"python",
"numpy",
null
] | I have a 2D numpy array. Some of the values in this array are `NaN`. I want to perform certain operations using this array. For example consider the array:
```
[[ 0. 43. 67. 0. 38.]
[ 100. 86. 96. 100. 94.]
[ 76. 79. 83. 89. 56.]
[ 88. NaN 67. 89. 81.]
[ 94. 79. 67. 89. ... | Where `A` is your 2D array:
```
import numpy as np
A[np.isnan(A)] = 0
```
The function `isnan` produces a bool array indicating where the `NaN` values are. A boolean array can by used to index an array of the same shape. Think of it like a mask. |
convert nan value to zero | 5,124,376 | 20 | 2011-02-26T01:08:12Z | 5,124,409 | 38 | 2011-02-26T01:18:45Z | [
"python",
"numpy",
null
] | I have a 2D numpy array. Some of the values in this array are `NaN`. I want to perform certain operations using this array. For example consider the array:
```
[[ 0. 43. 67. 0. 38.]
[ 100. 86. 96. 100. 94.]
[ 76. 79. 83. 89. 56.]
[ 88. NaN 67. 89. 81.]
[ 94. 79. 67. 89. ... | This should work:
```
from numpy import *
a = array([[1, 2, 3], [0, 3, NaN]])
where_are_NaNs = isnan(a)
a[where_are_NaNs] = 0
```
In the above case where\_are\_NaNs is:
```
In [12]: where_are_NaNs
Out[12]:
array([[False, False, False],
[False, False, True]], dtype=bool)
``` |
convert nan value to zero | 5,124,376 | 20 | 2011-02-26T01:08:12Z | 5,124,448 | 14 | 2011-02-26T01:28:29Z | [
"python",
"numpy",
null
] | I have a 2D numpy array. Some of the values in this array are `NaN`. I want to perform certain operations using this array. For example consider the array:
```
[[ 0. 43. 67. 0. 38.]
[ 100. 86. 96. 100. 94.]
[ 76. 79. 83. 89. 56.]
[ 88. NaN 67. 89. 81.]
[ 94. 79. 67. 89. ... | How about [nan\_to\_num()](http://docs.scipy.org/doc/numpy/reference/generated/numpy.nan_to_num.html)? |
How to use django-debug-toolbar on AJAX calls? | 5,124,975 | 44 | 2011-02-26T04:04:30Z | 19,419,235 | 27 | 2013-10-17T05:55:50Z | [
"python",
"django",
"django-debug-toolbar"
] | I'm curious if there's a reasonable way to use the (amazing) django-debug-toolbar with AJAX queries.
For example, I use a jQuery $.get with a bunch of parameters to hit a Django URL and load it inline. If I have an error with that, it isn't registered on the toolbar. I also can't use it by copying the AJAX URL because... | I had the same problem before!
And as I'm doing more and more AJAX heavy applications, I released a [Django Application](https://github.com/recamshak/django-debug-panel) and a [Chrome extension](https://chrome.google.com/webstore/detail/django-debug-panel/nbiajhhibgfgkjegbnflpdccejocmbbn) that together solved exactly t... |
Why list doesn't have safe "get" method like dictionary? | 5,125,619 | 86 | 2011-02-26T07:18:43Z | 5,125,636 | 36 | 2011-02-26T07:23:05Z | [
"python"
] | ```
>>> d = {'a':'b'}
>>> d['a']
'b'
>>> d['c']
KeyError: 'c'
>>> d.get('c', 'fail')
'fail'
>>> l = [1]
>>> l[10]
IndexError: list index out of range
``` | Ultimately it probably doesn't have a safe `.get` method because a `dict` is an associative collection (values are associated with names) where it is inefficient to check if a key is present (and return its value) without throwing an exception, while it is super trivial to avoid exceptions accessing list elements (as t... |
Why list doesn't have safe "get" method like dictionary? | 5,125,619 | 86 | 2011-02-26T07:18:43Z | 5,125,712 | 14 | 2011-02-26T07:40:37Z | [
"python"
] | ```
>>> d = {'a':'b'}
>>> d['a']
'b'
>>> d['c']
KeyError: 'c'
>>> d.get('c', 'fail')
'fail'
>>> l = [1]
>>> l[10]
IndexError: list index out of range
``` | Probably because it just didn't make much sense for list semantics. However, you can easily create your own by subclassing.
```
class safelist(list):
def get(self, index, default=None):
try:
return self.__getitem__(index)
except IndexError:
return default
def _test():
l... |
Why list doesn't have safe "get" method like dictionary? | 5,125,619 | 86 | 2011-02-26T07:18:43Z | 5,125,733 | 23 | 2011-02-26T07:46:29Z | [
"python"
] | ```
>>> d = {'a':'b'}
>>> d['a']
'b'
>>> d['c']
KeyError: 'c'
>>> d.get('c', 'fail')
'fail'
>>> l = [1]
>>> l[10]
IndexError: list index out of range
``` | Instead of using .get, using like this should be ok for lists. Just a usage difference.
```
>>> l = [1]
>>> l[10] if 10 < len(l) else 'fail'
'fail'
``` |
Why list doesn't have safe "get" method like dictionary? | 5,125,619 | 86 | 2011-02-26T07:18:43Z | 23,003,811 | 13 | 2014-04-11T04:56:54Z | [
"python"
] | ```
>>> d = {'a':'b'}
>>> d['a']
'b'
>>> d['c']
KeyError: 'c'
>>> d.get('c', 'fail')
'fail'
>>> l = [1]
>>> l[10]
IndexError: list index out of range
``` | This works if you want the first element, like `my_list.get(0)`
```
>>> my_list = [1,2,3]
>>> next(iter(my_list), 'fail')
1
>>> my_list = []
>>> next(iter(my_list), 'fail')
'fail'
```
I know it's not exactly what you asked for but it might help others. |
What kind of things can be done with Java but not Python? | 5,126,346 | 8 | 2011-02-26T10:26:28Z | 5,126,356 | 12 | 2011-02-26T10:29:43Z | [
"java",
"python",
"programming-languages"
] | I would to pick up a new programming language - Java, having been using Python for some time. But it seems most things that can be done with Java can be done with Python. So I would like to know
1. What kind of things can be done with Java but not Python?
* mobile programming (Android).
* POSIX Threads Programmi... | Both languages are Turing complete, both have vast libraries, and both support extensions written in C so that you can access low level code if needed. The main difference is where they are currently supported. Java in general has wider support than Python.
Your example of Android is one place where Java is the standa... |
setDaemon function in thread | 5,127,401 | 13 | 2011-02-26T14:22:12Z | 5,127,459 | 24 | 2011-02-26T14:31:54Z | [
"python",
"multithreading"
] | I am a newbie in python programming, what I understand is that a process can be a daemon, but a thread in a daemon mode, I couldn't understand the usecase of this, I would request the python gurus to help me in understanding this. Thanks in advance. | Here is some basic code using threading:
```
import Queue
import threading
def basic_worker(queue):
while True:
item = queue.get()
# do_work(item)
print(item)
queue.task_done()
def basic():
# http://docs.python.org/library/queue.html
queue = Queue.Queue()
for i in range... |
How to visualize scalar 2D data with Matplotlib? | 5,127,668 | 10 | 2011-02-26T15:10:28Z | 5,128,003 | 9 | 2011-02-26T16:08:01Z | [
"python",
"matplotlib"
] | So i have a meshgrid (matrices X and Y) together with scalar data (matrix Z), and i need to visualize this. Preferably some 2D image with colors at the points showing the value of Z there.
I've done some research but haven't found anything which does exactly what i want.
pyplot.imshow(Z) has a good look, but it doesn'... | This looks nice, but it's inefficient:
```
from pylab import *
origin = 'lower'
delta = 0.025
x = y = arange(-3.0, 3.01, delta)
X, Y = meshgrid(x, y)
Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = 10 * (Z1 - Z2)
nr, nc = Z.shape
CS = contourf(
X, Y, Z,
level... |
Can mmap and gzip collaborate? | 5,127,921 | 7 | 2011-02-26T15:57:04Z | 5,127,976 | 10 | 2011-02-26T16:04:04Z | [
"python",
"gzip",
"mmap"
] | I'm trying to figure how to use mmap with a gzip compressed file. Is that even possible ?
```
import mmap
import os
import gzip
filename = r'C:\temp\data.gz'
file = gzip.open(filename, "rb+")
size = os.path.getsize(filename)
file = mmap.mmap(file.fileno(), size)
print file.read(8)
```
The output data is compresse... | Well, not the way you want.
mmap() can be used to access the gzipped file if the compressed data is what you want.
mmap() is a system call for mapping disk blocks into RAM almost as if you were adding swap.
You can't map the uncompressed data into RAM with mmap() as it is not on the disk. |
Can mmap and gzip collaborate? | 5,127,921 | 7 | 2011-02-26T15:57:04Z | 6,884,989 | 12 | 2011-07-30T18:02:18Z | [
"python",
"gzip",
"mmap"
] | I'm trying to figure how to use mmap with a gzip compressed file. Is that even possible ?
```
import mmap
import os
import gzip
filename = r'C:\temp\data.gz'
file = gzip.open(filename, "rb+")
size = os.path.getsize(filename)
file = mmap.mmap(file.fileno(), size)
print file.read(8)
```
The output data is compresse... | You can do easilly. Indeed the gzip module gets as optional argument a file-like object.
```
import mmap
import gzip
filename = "a.gz"
handle = open(filename, "rb")
mapped = mmap.mmap(handle.fileno(), 0, access=mmap.ACCESS_READ)
gzfile = gzip.GzipFile(mode="r", fileobj=mapped)
print gzfile.read()
```
The same appli... |
Can I get a view of a numpy array at specified indexes? (a view from "fancy indexing") | 5,127,991 | 9 | 2011-02-26T16:05:52Z | 5,128,065 | 11 | 2011-02-26T16:18:20Z | [
"python",
"numpy"
] | What i need is a way to get "fancy indexing" (y = x[[0, 5, 21]]) to return a view instead of a copy.
I have an array, but i want to be able to work with a subset of this array (specified by a list of indices) in such a way that the changes in this subset is also put into the right places in the large array. If i just ... | I don't think there is a way around this. My understanding is that 'fancy indexing' will always return a copy. The best solution I can think of is to manipulate `y` and then use the same fancy indexes to change the values of `x` afterwards:
```
ii = [0, 5, 21]
y = x[ii]
<manipulate y>
x[ii] = y
``` |
How efficient is threading in Python? | 5,128,072 | 8 | 2011-02-26T16:19:11Z | 5,128,129 | 14 | 2011-02-26T16:29:20Z | [
"python",
"multithreading"
] | I heard threading is not very efficient in Python (compared to other languages).
Is this true? If so, how can a Python programmer overcome this? | The reason people say that multi-threading is not very efficient in python is because of the Global Interpreter Lock. Because of the way the interpreter is written, only one thread can safely execute code in the interpreter at the same time.
This means that if you have threads which are quite heavily compute bound, th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.