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 |
|---|---|---|---|---|---|---|---|---|---|
Convert a python dict to a string and back | 4,547,274 | 70 | 2010-12-28T15:52:32Z | 4,547,289 | 11 | 2010-12-28T15:54:37Z | [
"python",
"dictionary",
"serialization"
] | I am writing a program that stores data in a dictionary object, but this data needs to be saved at some point during the program execution and loaded back into the dictionary object when the program is run again.
How would I convert a dictionary object into a string that can be written to a file and loaded back into a ... | Use the [`pickle`](http://wiki.python.org/moin/UsingPickle) module to save it to disk and load later on. |
Convert a python dict to a string and back | 4,547,274 | 70 | 2010-12-28T15:52:32Z | 4,547,331 | 37 | 2010-12-28T15:59:52Z | [
"python",
"dictionary",
"serialization"
] | I am writing a program that stores data in a dictionary object, but this data needs to be saved at some point during the program execution and loaded back into the dictionary object when the program is run again.
How would I convert a dictionary object into a string that can be written to a file and loaded back into a ... | json module is a good solution here, and has the advantage over pickle that it only produces plain text output, and is cross-platform and cross-version. |
Convert a python dict to a string and back | 4,547,274 | 70 | 2010-12-28T15:52:32Z | 4,550,359 | 86 | 2010-12-28T23:26:28Z | [
"python",
"dictionary",
"serialization"
] | I am writing a program that stores data in a dictionary object, but this data needs to be saved at some point during the program execution and loaded back into the dictionary object when the program is run again.
How would I convert a dictionary object into a string that can be written to a file and loaded back into a ... | If your dictionary isn't too big maybe str + eval can do the work:
```
dict1 = {'one':1, 'two':2, 'three': {'three.1': 3.1, 'three.2': 3.2 }}
str1 = str(dict1)
dict2 = eval(str1)
print dict1==dict2
```
You can use [ast.literal\_eval](http://docs.python.org/library/ast.html) instead of eval for additional security i... |
Convert a python dict to a string and back | 4,547,274 | 70 | 2010-12-28T15:52:32Z | 22,630,069 | 56 | 2014-03-25T09:20:42Z | [
"python",
"dictionary",
"serialization"
] | I am writing a program that stores data in a dictionary object, but this data needs to be saved at some point during the program execution and loaded back into the dictionary object when the program is run again.
How would I convert a dictionary object into a string that can be written to a file and loaded back into a ... | I use [`json`](https://docs.python.org/2/library/json.html):
```
import json
# convert to string
input = json.dumps({'id': id })
# load to dict
my_dict = json.loads(input)
``` |
Iterating over a stack (reverse list), is there an isempty() method? | 4,547,310 | 5 | 2010-12-28T15:56:50Z | 4,547,350 | 15 | 2010-12-28T16:02:12Z | [
"python",
"stack",
"iteration"
] | What's the best way to iterate over a stack in Python?
```
a = [1,2,3,4]
while (len(a) > 0)
print a.pop()
# prints 4, 3, 2, 1 in sequence
```
I couldn't find an `isempty` method, and checking the length each time seems wrong somehow. | The usual convention for containers is that they are True while not empty and False when empty, so you can just do:
```
while a:
print a.pop()
``` |
Django - CSRF verification failed | 4,547,639 | 16 | 2010-12-28T16:43:02Z | 4,547,721 | 30 | 2010-12-28T16:53:43Z | [
"python",
"django"
] | I'm getting a CSRF verification failed message when trying to make a simple form from a tutorial. I did a little research into what CSRF verification actually is, and to my knowledge, in order to use it you need one of those csrf\_token tags in your html, but I don't have that
Here's my template:
```
<form action="/t... | **1**. include `{% csrf_token %}` **inside** the form tag in the template.
**2**. use a RequestContext in render\_to\_response
```
return render_to_response('contact.html', {'form': form},
context_instance=RequestContext(request))
```
[update]
Nowadays I use `render` instead of `render_to_respons... |
How to get the seconds since epoch from the time + date output of gmtime() in Python? | 4,548,684 | 77 | 2010-12-28T19:08:46Z | 4,548,711 | 71 | 2010-12-28T19:13:30Z | [
"python",
"datetime",
"time"
] | In python, how do you do reverse `gmtime()`, where you put the time + date and get the number of seconds?
I have strings like 'Jul 9, 2009 @ 20:02:58 UTC', and i want to get back the number of seconds between the epoch and July 9, 2009.
I have tried `time.strftime` but I don't know how to use it properly, or if it is... | You want `calendar.timegm()`.
```
>>> calendar.timegm(time.gmtime())
1293581619.0
```
You can turn your string into a time tuple with `time.strptime()`, which returns a time tuple that you can pass to `calendar.timegm()`:
```
>>> import calendar
>>> import time
>>> calendar.timegm(time.strptime('Jul 9, 2009 @ 20:02:... |
How to get the seconds since epoch from the time + date output of gmtime() in Python? | 4,548,684 | 77 | 2010-12-28T19:08:46Z | 13,342,744 | 292 | 2012-11-12T11:17:34Z | [
"python",
"datetime",
"time"
] | In python, how do you do reverse `gmtime()`, where you put the time + date and get the number of seconds?
I have strings like 'Jul 9, 2009 @ 20:02:58 UTC', and i want to get back the number of seconds between the epoch and July 9, 2009.
I have tried `time.strftime` but I don't know how to use it properly, or if it is... | Use the [time](https://docs.python.org/2/library/time.html) module:
```
epoch_time = int(time.time())
``` |
What's the Python version for âCode against an interface, not an objectâ? | 4,549,018 | 32 | 2010-12-28T19:55:14Z | 4,549,229 | 45 | 2010-12-28T20:23:49Z | [
"python",
"oop",
"interface",
"inversion-of-control"
] | Inspired by a great question (and bunch of great answers) from [here.](http://stackoverflow.com/questions/4456424/what-do-programmers-mean-when-they-say-code-against-an-interface-not-an-object)
Does the statement "Code against an interface, not an object" have any significance in Python?
I'm looking for answers like ... | "Code against an interface, not an object" doesn't make literal sense in Python because the language doesn't have an interface feature. The *rough* Python equivalent is "use duck typing." If you want to see if an object is a duck, in other words, you should check to see whether it has a `quack()` method, or better yet ... |
What's the Python version for âCode against an interface, not an objectâ? | 4,549,018 | 32 | 2010-12-28T19:55:14Z | 4,549,261 | 25 | 2010-12-28T20:29:18Z | [
"python",
"oop",
"interface",
"inversion-of-control"
] | Inspired by a great question (and bunch of great answers) from [here.](http://stackoverflow.com/questions/4456424/what-do-programmers-mean-when-they-say-code-against-an-interface-not-an-object)
Does the statement "Code against an interface, not an object" have any significance in Python?
I'm looking for answers like ... | To understand interfaces in Python you have to understand duck-typing. From the very Python [glossary](http://docs.python.org/glossary.html):
> **duck-typing**: A programming style which does not look at an objectâs type to determine if it has the right interface; instead, the method or attribute is simply called or... |
What's the Python version for âCode against an interface, not an objectâ? | 4,549,018 | 32 | 2010-12-28T19:55:14Z | 4,549,292 | 16 | 2010-12-28T20:33:16Z | [
"python",
"oop",
"interface",
"inversion-of-control"
] | Inspired by a great question (and bunch of great answers) from [here.](http://stackoverflow.com/questions/4456424/what-do-programmers-mean-when-they-say-code-against-an-interface-not-an-object)
Does the statement "Code against an interface, not an object" have any significance in Python?
I'm looking for answers like ... | An interface means you expect certain methods to be present and standardised across objects; that is the point of an interface or abstract base class, or whatever implementation you wish to consider.
For example (Java), one might have an interface for symmetric encryption like so:
```
public interface cipher
{
p... |
Make a window transparent using Win32? | 4,549,213 | 4 | 2010-12-28T20:21:51Z | 4,550,243 | 9 | 2010-12-28T23:06:55Z | [
"python",
"windows",
"winapi",
"pywin32",
"pywin"
] | Using Python Win32 extensions, how do you make an arbitrary window on Windows XP transparent? | SetLayeredWindowsAttributes example:
```
import win32gui
import win32con
import winxpgui
import win32api
import subprocess
import time
subprocess.Popen("notepad.exe", shell=True)
time.sleep(1)
hwnd = win32gui.FindWindow(None, "New file - metapad") ## The caption of my empty notepad (MetaPad)
win32gui.SetWindowLong ... |
How do I create an alias to a Python class through Swig? | 4,549,588 | 3 | 2010-12-28T21:15:01Z | 4,549,685 | 7 | 2010-12-28T21:31:41Z | [
"python",
"templates",
"swig",
"alias",
"rename"
] | I've created a C++ library and have successfully used swig to make it accessible through python. Templating is used heavily in the library and each template type is mapped to its own python class by swig like so:
```
%template(Imageint) Image<int>;
%template(Imagedouble) Image<double>;
```
However, I would really lik... | In case this helps someone in the future, the way to do what is describe above is to add the following to the interface file:
```
%pythoncode %{
Image = Imagedouble
%}
```
I did not realize there was a way to write standard python code in the interface file. |
Removing multiple MongoDB documents in Python | 4,549,871 | 9 | 2010-12-28T22:00:16Z | 4,549,963 | 12 | 2010-12-28T22:14:36Z | [
"python",
"nosql",
"mongodb",
"pymongo"
] | Greetings,
I am attempting to remove multiple documents from a MongoDB collection using the following syntax. I don't know if this is correct as I found it somewhere on the internet and haven't been able to find anything since enforcing the legitimacy of this statement:
```
pymongo_collection_object.remove(
[
... | You can do so by using $or / $in operators.
Try this:
```
pymongo_collection_object.remove({'$or': [{'sku': '100-00'}, {'sku': '200-00'}]}, safe=True)
```
or
```
pymongo_collection_object.remove({'sku': {'$in': ['100-00', '200-00']}}, safe=True)
``` |
Iterating over key/value pairs in a dict sorted by keys | 4,550,645 | 54 | 2010-12-29T00:32:21Z | 4,550,652 | 74 | 2010-12-29T00:34:30Z | [
"python"
] | I have the following code, which just print the key/value pairs in a dict (the pairs are sorted by keys):
```
for word, count in sorted(count_words(filename).items()):
print word, count
```
However, calling `iteritems()` instead of `items()` produces the same output
```
for word, count in sorted(count_words(file... | In Python 2.x both will give you the same result. The difference between them is that `items` constructs a list containing the entire contents of the dictionary whereas `iteritems` gives you an iterator that fetches the items one at a time. In general `iteritems` is a better choice because it doesn't require so much me... |
Iterating over key/value pairs in a dict sorted by keys | 4,550,645 | 54 | 2010-12-29T00:32:21Z | 4,552,974 | 10 | 2010-12-29T09:39:24Z | [
"python"
] | I have the following code, which just print the key/value pairs in a dict (the pairs are sorted by keys):
```
for word, count in sorted(count_words(filename).items()):
print word, count
```
However, calling `iteritems()` instead of `items()` produces the same output
```
for word, count in sorted(count_words(file... | As per Marks answer: In Python 2, use `iteritems()`, in Python 3 use `items()`.
And additionally; If you need to support both (and don't use `2to3`) use:
```
counts = count_words(filename)
for word in sorted(counts):
count = counts[word]
``` |
How can I write this without so many floats? | 4,550,717 | 2 | 2010-12-29T00:47:39Z | 4,550,725 | 10 | 2010-12-29T00:48:57Z | [
"python"
] | ```
float(float(1)/float(i) * float(score))
``` | Assuming Python 2.x: `1.0 / i * score`
The main case you need to worry about is the division because in Python 2.x, division is defaulted to integer division. In order to have floating-point division, either the dividend or divisor needs to be a float, hence the `1.0`. Thus, `1.0/i` will be a float, and multiplying a ... |
In Python, without using the /proc filesystem, how do I tell if a given PID is running? | 4,551,187 | 5 | 2010-12-29T03:08:25Z | 4,551,198 | 11 | 2010-12-29T03:11:17Z | [
"python",
"linux",
"unix",
"operating-system",
"pid"
] | Say I have a PID, like 555. I want to see if that pid is running or has completed. I can check /proc/ but I don't have access to that in my production environment. What's the best way to do this, short of something hackish like opening a pipe to "ps"? | Use the [`os.kill()`](http://docs.python.org/library/os.html#os.kill) function with a signal number of 0. If the process *pid* exists, then the call will be successful, else it will raise an `OSError` exception:
```
try:
os.kill(pid, 0)
print("process exists")
except OSError:
print("process does not exist"... |
Does Ctypes Structures and POINTERS automatically free the memory when the Python object is deleted? | 4,551,436 | 9 | 2010-12-29T04:18:55Z | 4,551,549 | 10 | 2010-12-29T04:48:25Z | [
"python",
"ctypes"
] | When using Python CTypes there are the Structures, that allow you to clone c-structures on the Python side, and the POINTERS objects that create a sofisticated Python Object from a memory address value and can be used to pass objects by reference back and forth C code.
What I could not find on the documentation or els... | The memory is not freed, because Python has no idea if or how it should be freed. Compare these two functions:
```
void testfunc1(PIX *pix)
{
static char staticBuffer[256] = "static memory";
pix->text = staticBuffer;
}
void testfunc2(PIX *pix)
{
pix->text = (char *)malloc(32);
strcpy(pix->text, "dynam... |
Python-like decorators in Java? | 4,551,457 | 16 | 2010-12-29T04:22:59Z | 4,551,491 | 8 | 2010-12-29T04:32:27Z | [
"java",
"python"
] | I spend most of my time programming in Python, so forgive me if my approach to this problem is short-sited:
I want to have certain methods of a class require login credentials. Simply, each method should check whether the class variable `user` is set, and if so, continue, but if not, spit out a "you need to login" mes... | One way to solve this in Java is to use an [Aspect-oriented programming](http://en.wikipedia.org/wiki/Aspect-oriented_programming) tool. One such tool is [AspectJ](http://www.eclipse.org/aspectj/). You will probably find that this type of problem is an example that is commonly used to motivate AOP.
AOP might be a pret... |
Split string and just get number in python? | 4,553,113 | 10 | 2010-12-29T09:58:48Z | 4,553,134 | 13 | 2010-12-29T10:02:19Z | [
"python",
"string",
"split"
] | I have a string like `"GoTo: 7018 6453 12654\n"` I just want get the number something like this `['7018', '6453', '12654']`, I tries regular expression but I can't split string to get just number here is my code:
Sample 1:
```
splitter = re.compile(r'\D');
match1 = splitter.split("GoTo: 7018 6453 12654\n")
my output... | If all your numbers are positive integers, you can do that without regular expressions by using the [isdigit()](http://docs.python.org/library/stdtypes.html#str.isdigit) method:
```
>>> text = "GoTo: 7018 6453 12654\n"
>>> [token for token in text.split() if token.isdigit()]
['7018', '6453', '12654']
``` |
When to use os.name, sys.platform, or platform.system? | 4,553,129 | 56 | 2010-12-29T10:01:22Z | 11,672,585 | 7 | 2012-07-26T15:21:32Z | [
"python",
"operating-system",
"python-import"
] | As far as I know, Python has 3 ways of finding out what operating system is running on:
1. `os.name`
2. `sys.platform`
3. `platform.system()`
Knowing this information is often useful in conditional imports, or using functionality that differs between platforms (e.g. `time.clock()` on Windows v.s. `time.time()` on UNI... | From [`sys.platform` docs](http://docs.python.org/dev/library/sys.html#sys.platform):
* [`os.name`](http://docs.python.org/dev/library/os.html#os.name) has a coarser granularity
* [`os.uname()`](http://docs.python.org/dev/library/os.html#os.uname) gives system-dependent version information
* The [`platform`](http://do... |
When to use os.name, sys.platform, or platform.system? | 4,553,129 | 56 | 2010-12-29T10:01:22Z | 11,674,977 | 34 | 2012-07-26T17:43:48Z | [
"python",
"operating-system",
"python-import"
] | As far as I know, Python has 3 ways of finding out what operating system is running on:
1. `os.name`
2. `sys.platform`
3. `platform.system()`
Knowing this information is often useful in conditional imports, or using functionality that differs between platforms (e.g. `time.clock()` on Windows v.s. `time.time()` on UNI... | Dived a bit into the source code.
The output of `sys.platform` and `os.name` are determined at compile time. `platform.system()` determines the system type at run time.
* `sys.platform` is specified as a compiler define during the build configuration.
* `os.name` checks whether certain os specific modules are availab... |
When to use os.name, sys.platform, or platform.system? | 4,553,129 | 56 | 2010-12-29T10:01:22Z | 14,301,083 | 15 | 2013-01-13T05:58:35Z | [
"python",
"operating-system",
"python-import"
] | As far as I know, Python has 3 ways of finding out what operating system is running on:
1. `os.name`
2. `sys.platform`
3. `platform.system()`
Knowing this information is often useful in conditional imports, or using functionality that differs between platforms (e.g. `time.clock()` on Windows v.s. `time.time()` on UNI... | There is a thin line difference between `platform.system()` and `sys.platform` and interestingly for most cases `platform.system()` degenerates to `sys.platform`
Here is what the Source `Python2.7\Lib\Platform.py\system` says
```
def system():
""" Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.
... |
When to use os.name, sys.platform, or platform.system? | 4,553,129 | 56 | 2010-12-29T10:01:22Z | 14,302,878 | 7 | 2013-01-13T11:12:56Z | [
"python",
"operating-system",
"python-import"
] | As far as I know, Python has 3 ways of finding out what operating system is running on:
1. `os.name`
2. `sys.platform`
3. `platform.system()`
Knowing this information is often useful in conditional imports, or using functionality that differs between platforms (e.g. `time.clock()` on Windows v.s. `time.time()` on UNI... | It depends on whether you prefer raising exception or trying anything on an untested system and whether your code is so high level or so low level that it can or can't work on a similar untested system (e.g. untested Mac - 'posix' or on embedded ARM systems). More pythonic is to not enumerate all known systems but to t... |
How do I add additional arguments to button.connect in PyGTK? | 4,553,591 | 2 | 2010-12-29T11:17:07Z | 4,553,649 | 8 | 2010-12-29T11:26:07Z | [
"python",
"pygtk"
] | I want to pass 2 ComboBox instances to a a method and use them there (e.g., print their active selection). I have something similar to the following:
```
class GUI():
...
def gui(self):
...
combobox1 = gtk.combo_box_new_text()
# code for inserting some values into the combobox
combobox2 = gtk.comb... | do something like this:
```
btn_new.connect("clicked", self.comboprint, combobox1, combobox2)
```
and in your callback `comboprint` it should be something like this:
```
def comboprint(self, widget, *data):
# Widget = btn_new
# data = [clicked_event, combobox1, combobox2]
...
``` |
sorting tuples in python with a custom key | 4,554,115 | 2 | 2010-12-29T12:34:40Z | 9,245,005 | 8 | 2012-02-11T23:31:47Z | [
"python",
"sorting",
"tuples"
] | Hi:
I'm trying to sort a list of tuples in a custom way:
For example:
```
lt = [(2,4), (4,5), (5,2)]
```
must be sorted:
```
lt = [(5,2), (2,4), (4,5)]
```
Rules:
\* b tuple is greater than a tuple if a[1] == b[0]
\* a tuple is greater than b tuple if a[0] == b[1]
I've implemented a cmp function like this:
... | Sounds a lot to me you are trying to solve one of the Google's Python class problems, which is to sort a list of tuples in increasing order based on their last element.
This how I did it:
```
def sort_last(tuples):
def last_value_tuple(t):
return t[-1]
return sorted(tuples, key=last_value_tuple)
```
EDIT: ... |
Fastest way to swap elements in Python list | 4,554,130 | 37 | 2010-12-29T12:36:05Z | 4,554,221 | 108 | 2010-12-29T12:48:50Z | [
"python",
"performance"
] | Is there any any faster way to swap two list elements in Python than
```
L[a], L[b] = L[b], L[a]
```
or would I have to resort to [Cython](http://cython.org/) or [Weave](http://www.scipy.org/Weave) or the like? | Looks like the Python compiler optimizes out the temporary tuple with this construct:
### code:
```
import dis
def swap1():
a=5
b=4
a, b = b, a
def swap2():
a=5
b=4
c = a
a = b
b = c
print 'swap1():'
dis.dis(swap1)
print 'swap2():'
dis.dis(swap2)
```
### output:
```
swap1():
6 0 LOAD_... |
which Forms libaray to use with Flask and SQLAlchemy | 4,555,188 | 4 | 2010-12-29T15:05:47Z | 4,555,220 | 12 | 2010-12-29T15:09:45Z | [
"python",
"forms",
"sqlalchemy",
"flask"
] | I am working on a web app based on Flask and SQLAlchemy. Most of forms/models are related and therefore need to use a library that's flexible enough to handle multiple forms and allows easy overriding [or creation] of default widgets.
Can someone recommend a good forms library (other than formalchemy). I really liked ... | [WTForms](http://wtforms.simplecodes.com/) should suit your taste, with Flask and SQLAlchemy. |
How to load current buffer into Python interpreter in Emacs? | 4,555,224 | 7 | 2010-12-29T15:10:11Z | 4,555,319 | 9 | 2010-12-29T15:23:27Z | [
"python",
"emacs"
] | I'm trying to use emacs to edit and run python programs (emacs23 and python 2.6 on Ubuntu 10.10).
* I read a file into Emacs (`C-x -C-f`)
* I start the interperter (Menu Python - Start interpreter, I haven't found the keyboard shortcut for this yet)
* Emacs split the frame in two windows
* I place the cursor in the py... | You may want to hit "C-c C-z" (switch to interpreter) to see the results of and buffers or regions you evaluated. |
Bug or feature: cloning a numpy array w/ slicing | 4,555,431 | 3 | 2010-12-29T15:37:01Z | 4,555,476 | 11 | 2010-12-29T15:41:38Z | [
"python",
"numpy"
] | Following up to David Morrissey's answer on '[How to clone a list in python?](http://stackoverflow.com/questions/2612802/how-to-clone-a-list-in-python)' I was running some performance tests and hit unexpected behavior when working w/ numpy arrays. I know that a numpy array can/ should be cloned w/
```
clone = numpy.ar... | In numpy, slices are references or "views" on the original array, so they are not copies. That is by design, not a bug. The reason is that a copy is not as useful as a view. |
Generating a characterized unique id in Python | 4,555,511 | 2 | 2010-12-29T15:45:29Z | 4,555,546 | 16 | 2010-12-29T15:49:08Z | [
"python"
] | am planning to create a unique ID from characters and numbers as well. The ID should look something like this
XXXX-XXXX-XXXX-XXXX
where X is a combination of numbers, small and cap letters. This Id will be stored in a mysql database and will be incremented to maintain consistency of data.
Any advice on how to start? | Use the `uuid` module;
```
>>> import uuid
# make a UUID based on the host ID and current time
>>> uuid.uuid1()
UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')
# make a UUID using an MD5 hash of a namespace UUID and a name
>>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')
# ... |
How can I partially sort a Python list? | 4,555,820 | 9 | 2010-12-29T16:24:13Z | 4,555,852 | 14 | 2010-12-29T16:29:32Z | [
"python",
"sorting"
] | I wrote a [compiler cache for MSVC](https://github.com/frerich/clcache) (much like [ccache](http://ccache.samba.org) for [gcc](http://gcc.gnu.org)). One of the things I have to do is to remove the oldest object files in my cache directory to trim the cache to a user-defined size.
Right now, I basically have a list of ... | You could use the [`heapq`](http://docs.python.org/library/heapq.html) module. Call `heapify()` on the list, followed by `heappop()` until your condition is met. `heapify()` is linear and `heappop()` logarithmic, so it's likely as fast as you can get.
```
heapq.heapify(items)
size = 0
while items and size < 45000:
i... |
"public" or "private" attribute in Python ? What is the best way? | 4,555,932 | 28 | 2010-12-29T16:41:39Z | 4,555,970 | 50 | 2010-12-29T16:47:21Z | [
"python",
"oop",
"properties",
"encapsulation"
] | In Python, I have the following example class :
```
class Foo:
self._attr = 0
@property
def attr(self):
return self._attr
@attr.setter
def attr(self, value):
self._attr = value
@attr.deleter
def attr(self):
del self._attr
```
As you can see, I have a simple "priv... | Typically, Python code strives to adhere to the [Uniform Access Principle](http://en.wikipedia.org/wiki/Uniform_access_principle). Specifically, the accepted approach is:
* Expose your instance variables directly, allowing, for instance, `foo.x = 0`, not `foo.set_x(0)`
* If you need to wrap the accesses inside methods... |
Django (Python) problem with sessionid | 4,555,956 | 4 | 2010-12-29T16:45:27Z | 4,556,331 | 9 | 2010-12-29T17:38:05Z | [
"python",
"django"
] | I am having a problem with sessionid: `request.session.session_key` Generates a key every page refresh / form submission.
While this: `request.COOKIES[settings.SESSION_COOKIE_NAME]` complains that 'sessionid' key is not found.
Am I missing something? I need a "key" that is persistent across page requests on my site. ... | It sounds like your browser is not accepting the session cookies that Django is sending.
Your browser should be able to tell you what cookies are being set with a page response from your application. Check to see that a 'sessionid' cookie is actually being sent, and that the domain and path are correct.
If you have `... |
how to make my python script easy portable? or how to compile into binary with all module dependencies? | 4,556,424 | 5 | 2010-12-29T17:50:15Z | 4,558,781 | 12 | 2010-12-29T23:30:11Z | [
"python",
"binary",
"freebsd"
] | Is there any way to compile python script into binary?
I have one file python script which uses a lot of modules.
What I would like is to have its copy on other machines (freebsd) but without installing all needed modules on every host.
What are possible solutions in such cases?
Thanks in advance! | Programs that can do what you ask for are:
* PyInstaller: <http://www.pyinstaller.org/> [Windows, Linux, OS X]
* cx\_freeze: <http://cx-freeze.sourceforge.net/> [Windows, Linux]
* py2exe: <http://www.py2exe.org/> [Windows]
* py2app: <http://svn.pythonmac.org/py2app/py2app/trunk/doc/index.html> [os x]
But as mentioned... |
How to parse xml in Python on Google App Engine | 4,556,924 | 5 | 2010-12-29T18:53:11Z | 4,557,112 | 7 | 2010-12-29T19:19:33Z | [
"python",
"xml",
"google-app-engine",
"beautifulsoup",
"elementtree"
] | For this [following xml](http://www.boardgamegeek.com/xmlapi/boardgame/13), how do I fetch the xml and then parse it to get out the value for `<age>`?
```
<boardgames>
<boardgame objectid="13">
<yearpublished>1995</yearpublished>
<minplayers>3</minplayers>
<maxplayers>4</maxplayers>
<playingtime>90</playingt... | `xml.findtext('age')` or `xml.findtext('boardgames/age')` would normally get you the 10 inside `<age>10</age>`, but the parsing appears to fail due to invalid xml. `ElementTree` does a rather poor job of parsing invalid xml in my experience.
Instead use [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/), w... |
Multiple commands within Supervisor - Python/Linux | 4,556,984 | 5 | 2010-12-29T19:03:53Z | 4,557,108 | 8 | 2010-12-29T19:18:49Z | [
"python",
"django",
"linux",
"ubuntu",
"supervisord"
] | I'm using the amazing utility `supervisord`
---
I'm happily running a few apps editing the config file as follows:
```
[program: Django Dev Server]
command=python /path/to/project/manage.py runserver 127.0.0.1:8000
[program: MongoDB]
command=sudo /path/to/mongod
```
---
**Now problem is that some apps need a few ... | Instead of calling `manage.py`, write a script (call it, say, `start_manage.py`) which verifies conditions, cleans folders, etc, and then calls `manage.py` (using `subprocess.Popen`). Or, of course, `start_manage` could be a shell script if that fits your needs better.
Then change the config file to run
```
command=p... |
Django custom template tag which accepts a boolean parameter | 4,557,114 | 7 | 2010-12-29T19:19:44Z | 4,557,741 | 14 | 2010-12-29T20:51:28Z | [
"python",
"django",
"django-templates"
] | According to [this thread](http://groups.google.com/group/django-developers/browse_thread/thread/e72cd474c819d15a) on the django-developers list, I can't pass the constant `False` as a parameter to a Django template tag because it will be treated as a variable name not a builtin constant.
But if I want to create a tem... | I came up against this problem a while ago, and arrived at the conclusion that using 1 and 0 was the simplest solution.
However an idea might be to add a context processor which adds `True` and `False` to the template context using respective names:
```
# projectname/appname/context_processors.py
def booleans():
... |
better for-loop syntax for detecting empty sequences? | 4,557,255 | 7 | 2010-12-29T19:42:14Z | 4,557,281 | 7 | 2010-12-29T19:46:48Z | [
"python",
"syntax",
"for-loop"
] | Is there a better way to write the following:
```
row_counter = 0
for item in iterable_sequence:
# do stuff with the item
counter += 1
if not row_counter:
# handle the empty-sequence-case
```
Please keep in mind that I can't use len(iterable\_sequence) because 1) not all sequences have kn... | ```
for item in iterable:
break
else:
# handle the empty-sequence-case here
```
Or
```
item = next(iterator, sentinel)
if item is sentinel:
# handle the empty-sequence-case here
```
In each case one item is consumed if it is present.
---
An example of `empty_adapter()`'s implementation mentioned in the ... |
Python random sequence with seed | 4,557,444 | 3 | 2010-12-29T20:08:44Z | 4,557,800 | 13 | 2010-12-29T20:58:58Z | [
"python",
"random"
] | Hi
I'm doing this for a school project (so I can't use any advanced features) and I'm using Python 2.6.6.
I have a list of numbers from 1 to 1000 and my seed will be, lets say, 448.
How can i generate a random sequence with that seed so that the numbers in my list will be in a different index?
And is it possible, kn... | ```
import random
SEED = 448
myList = [ 'list', 'elements', 'go', 'here' ]
random.seed(SEED)
random.shuffle(myList)
print myList
```
results in
```
['here', 'go', 'list', 'elements']
```
Your list is now pseudorandomized.
'Pseudo' is important, because all lists having the same seed and number of items will retur... |
Feedback on implementation of function which compares integer signs in Python | 4,558,326 | 3 | 2010-12-29T22:13:56Z | 4,558,344 | 14 | 2010-12-29T22:16:49Z | [
"python",
"sign"
] | I've made a small function which, given a tuple, compares if all elements in this tuple is of the same sign.
E.g., tuple = `[-1, -4, -6, -8]` is good, while `[-1, -4, 12, -8]` is bad. I am not sure I've made the smartest implementation, so I know this is the place to ask.
```
def check_consistent_categories(queryset)... | This might help you:
```
def all_same_sign(ints):
return all(x < 0 for x in ints) or all(x > 0 for x in ints)
```
You may want to change < and > to <= and >= depending on how you want to treat 0. |
Python/Django: log to console under runserver, log to file under Apache | 4,558,879 | 77 | 2010-12-29T23:44:57Z | 4,558,901 | 61 | 2010-12-29T23:48:23Z | [
"python",
"django",
"logging"
] | How can I send trace messages to the console (like `print`) when I'm running my Django app under `manage.py runserver`, but have those messages sent to a log file when I'm running the app under Apache?
I reviewed [Django logging](http://docs.djangoproject.com/en/dev/topics/logging/) and although I was impressed with i... | Text printed to stderr will show up in httpd's error log when running under mod\_wsgi. You can either use `print` directly, or use `logging` instead.
```
print >>sys.stderr, 'Goodbye, cruel world!'
``` |
Python/Django: log to console under runserver, log to file under Apache | 4,558,879 | 77 | 2010-12-29T23:44:57Z | 4,665,835 | 18 | 2011-01-12T06:09:24Z | [
"python",
"django",
"logging"
] | How can I send trace messages to the console (like `print`) when I'm running my Django app under `manage.py runserver`, but have those messages sent to a log file when I'm running the app under Apache?
I reviewed [Django logging](http://docs.djangoproject.com/en/dev/topics/logging/) and although I was impressed with i... | You can configure logging in your `settings.py` file.
One example:
```
if DEBUG:
# will output to your console
logging.basicConfig(
level = logging.DEBUG,
format = '%(asctime)s %(levelname)s %(message)s',
)
else:
# will output to logging file
logging.basicConfig(
level = lo... |
Python/Django: log to console under runserver, log to file under Apache | 4,558,879 | 77 | 2010-12-29T23:44:57Z | 10,155,661 | 76 | 2012-04-14T17:19:32Z | [
"python",
"django",
"logging"
] | How can I send trace messages to the console (like `print`) when I'm running my Django app under `manage.py runserver`, but have those messages sent to a log file when I'm running the app under Apache?
I reviewed [Django logging](http://docs.djangoproject.com/en/dev/topics/logging/) and although I was impressed with i... | Here's a Django logging-based solution. It uses the DEBUG setting rather than actually checking whether or not you're running the development server, but if you find a better way to check for that it should be easy to adapt.
```
LOGGING = {
'version': 1,
'formatters': {
'verbose': {
'format... |
Slicing a dictionary by keys that start with a certain string | 4,558,983 | 28 | 2010-12-30T00:05:02Z | 4,558,999 | 56 | 2010-12-30T00:08:51Z | [
"python",
"dictionary",
"ironpython",
"slice"
] | This is pretty simple but I'd love a pretty, pythonic way of doing it. Basically, given a dictionary, return the subdictionary that contains only those keys that start with a certain string.
```
» d = {'Apple': 1, 'Banana': 9, 'Carrot': 6, 'Baboon': 3, 'Duck': 8, 'Baby': 2}
» print slice(d, 'Ba')
{'Banana': 9, 'Baby... | How about this:
in python 2.x :
```
def slicedict(d, s):
return {k:v for k,v in d.iteritems() if k.startswith(s)}
```
In python 3.x :
```
def slicedict(d, s):
return {k:v for k,v in d.items() if k.startswith(s)}
``` |
Slicing a dictionary by keys that start with a certain string | 4,558,983 | 28 | 2010-12-30T00:05:02Z | 4,559,015 | 8 | 2010-12-30T00:14:58Z | [
"python",
"dictionary",
"ironpython",
"slice"
] | This is pretty simple but I'd love a pretty, pythonic way of doing it. Basically, given a dictionary, return the subdictionary that contains only those keys that start with a certain string.
```
» d = {'Apple': 1, 'Banana': 9, 'Carrot': 6, 'Baboon': 3, 'Duck': 8, 'Baby': 2}
» print slice(d, 'Ba')
{'Banana': 9, 'Baby... | In functional style:
`dict(filter(lambda item: item[0].startswith(string),sourcedict.iteritems()))` |
about Speed: Python VS Java | 4,559,618 | 9 | 2010-12-30T02:43:24Z | 4,559,631 | 13 | 2010-12-30T02:45:21Z | [
"java",
"python"
] | Just curious about speed of Python and Java..
Intuitively, Python should be much slower than java, but I want to know more...Could anybody give me more? or introduce some nice post to read? | The current standard implementation of Python (CPython) is slower than Java because the standard CPython implementation doesn't have a powerful [JIT compiler](http://en.wikipedia.org/wiki/Just-in-time_compilation). Yet.
There have been several projects with the aim of producing a faster implement of Python:
* [Psyco]... |
about Speed: Python VS Java | 4,559,618 | 9 | 2010-12-30T02:43:24Z | 4,560,512 | 9 | 2010-12-30T06:29:04Z | [
"java",
"python"
] | Just curious about speed of Python and Java..
Intuitively, Python should be much slower than java, but I want to know more...Could anybody give me more? or introduce some nice post to read? | The lack of a JIT mentioned is one reason, but another reason is that Python is dynamic. Yes, that does make the language slower. You can see for yourself by using Cython.
A function written in Python can often be compiled to C with Cython. It makes it faster. But it get's really fast when you start adding type inform... |
Python: MySQLdb and "Library not loaded: libmysqlclient.16.dylib" | 4,559,699 | 56 | 2010-12-30T03:01:20Z | 4,559,775 | 53 | 2010-12-30T03:22:55Z | [
"python",
"mysql",
"osx",
"osx-snow-leopard"
] | ## The setup...
Trying to set up a clean Mac os X 10.6 install to develop python/django and I didn't remember running into this on 10.5.
After installing MySQL from the installer on `mysql-5.5.8-osx10.6-x86_64.dmg` I ran
```
$ sudo pip install MySQL-python
```
and it seemed to go smoothly (output below)
```
Downlo... | `_mysql.so` refers to `libmysqlclient.16.dylib`. That is, the shared library that serves as the bridge between Python and the MySQL client library, `_mysql.so`, refers to the dynamic library for the MySQL client library, and that library cannot be loaded for some reason.
Questions you need to answer:
* Is there a `li... |
Python: MySQLdb and "Library not loaded: libmysqlclient.16.dylib" | 4,559,699 | 56 | 2010-12-30T03:01:20Z | 4,581,254 | 83 | 2011-01-03T00:17:15Z | [
"python",
"mysql",
"osx",
"osx-snow-leopard"
] | ## The setup...
Trying to set up a clean Mac os X 10.6 install to develop python/django and I didn't remember running into this on 10.5.
After installing MySQL from the installer on `mysql-5.5.8-osx10.6-x86_64.dmg` I ran
```
$ sudo pip install MySQL-python
```
and it seemed to go smoothly (output below)
```
Downlo... | Just set the `DYLD_LIBRARY_PATH` after running `pip install` or `easy_install`:
```
export DYLD_LIBRARY_PATH=/usr/local/mysql/lib/
```
Should do the job assuming your MySQL installation lives under `/usr/local/mysql`. |
Python: MySQLdb and "Library not loaded: libmysqlclient.16.dylib" | 4,559,699 | 56 | 2010-12-30T03:01:20Z | 6,527,726 | 8 | 2011-06-29T21:53:28Z | [
"python",
"mysql",
"osx",
"osx-snow-leopard"
] | ## The setup...
Trying to set up a clean Mac os X 10.6 install to develop python/django and I didn't remember running into this on 10.5.
After installing MySQL from the installer on `mysql-5.5.8-osx10.6-x86_64.dmg` I ran
```
$ sudo pip install MySQL-python
```
and it seemed to go smoothly (output below)
```
Downlo... | It can also crop up if your MySQL client is newer than your MySQL-python package. In my case, I had a libmysqlclient\_r.18.dylib on my machine, but not a libmysqlclient\_r.16.dylib. Running `pip search mysql` revealed
> MySQL-python - Python
> interface to MySQL INSTALLED: 1.2.3
> LATEST: 1.2.3c1
and running `pip ins... |
Python: MySQLdb and "Library not loaded: libmysqlclient.16.dylib" | 4,559,699 | 56 | 2010-12-30T03:01:20Z | 14,029,674 | 34 | 2012-12-25T10:08:45Z | [
"python",
"mysql",
"osx",
"osx-snow-leopard"
] | ## The setup...
Trying to set up a clean Mac os X 10.6 install to develop python/django and I didn't remember running into this on 10.5.
After installing MySQL from the installer on `mysql-5.5.8-osx10.6-x86_64.dmg` I ran
```
$ sudo pip install MySQL-python
```
and it seemed to go smoothly (output below)
```
Downlo... | After easy\_install, I create a soft link that solved the problem
```
sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/local/lib/libmysqlclient.18.dylib
``` |
Python try/except: Showing the cause of the error after displaying my variables | 4,560,288 | 12 | 2010-12-30T05:43:26Z | 4,560,295 | 8 | 2010-12-30T05:45:34Z | [
"python",
"exception-handling"
] | I'm not even sure what the right words are to search for. I want to display parts of the error object in an except block (similar to the err object in VBScript, which has Err.Number and Err.Description). For example, I want to show the values of my variables, then show the exact error. Clearly, I am causing a divided-b... | The string value of [the exception object](http://docs.python.org/tutorial/errors.html) will give you the reason. The [`traceback`](http://docs.python.org/library/traceback.html) module will allow you access to the full traceback. |
Python try/except: Showing the cause of the error after displaying my variables | 4,560,288 | 12 | 2010-12-30T05:43:26Z | 4,560,334 | 15 | 2010-12-30T05:55:28Z | [
"python",
"exception-handling"
] | I'm not even sure what the right words are to search for. I want to display parts of the error object in an except block (similar to the err object in VBScript, which has Err.Number and Err.Description). For example, I want to show the values of my variables, then show the exact error. Clearly, I am causing a divided-b... | If you're expecting a DivideByZero error, you can catch that particular error
```
import traceback
try:
x = 5
y = 0
print x/y
except ZeroDivisionError:
print "Error Dividing %d/%d" % (x,y)
traceback.print_exc()
except:
print "A non-ZeroDivisionError occurred"
```
You can manually get the line number and o... |
Python try/except: Showing the cause of the error after displaying my variables | 4,560,288 | 12 | 2010-12-30T05:43:26Z | 4,560,341 | 26 | 2010-12-30T05:56:46Z | [
"python",
"exception-handling"
] | I'm not even sure what the right words are to search for. I want to display parts of the error object in an except block (similar to the err object in VBScript, which has Err.Number and Err.Description). For example, I want to show the values of my variables, then show the exact error. Clearly, I am causing a divided-b... | ```
try:
1 / 0
except Exception as e:
print e
``` |
why do we invoke print after importing print_function (in Python 2.6) | 4,560,804 | 56 | 2010-12-30T07:24:21Z | 4,560,928 | 46 | 2010-12-30T07:46:56Z | [
"python",
"import"
] | To get the 3.0 print function we do the following in Python 2.6:
```
from __future__ import print_function
```
But to use the function we invoke print() not print\_function(). Is this just an inconsistency or is there a good reason for this?
Why not the following:
```
from __future__ import print
``` | The reason is that when you import from `__future__` you're really just setting a flag that tells the interpreter to behave a bit differently than usual -- in the case of `print_function`, the `print()` function is made available in place of the statement. The `__future__` module is thus "special" or "magic" -- it does... |
why do we invoke print after importing print_function (in Python 2.6) | 4,560,804 | 56 | 2010-12-30T07:24:21Z | 4,560,942 | 9 | 2010-12-30T07:50:15Z | [
"python",
"import"
] | To get the 3.0 print function we do the following in Python 2.6:
```
from __future__ import print_function
```
But to use the function we invoke print() not print\_function(). Is this just an inconsistency or is there a good reason for this?
Why not the following:
```
from __future__ import print
``` | `print_function` is a `FeatureName` not be confused with the `print` built-in function itself.
It is a feature that is available from the future so that you can use the built-in function that it can provide.
Other Features include:
```
all_feature_names = [
"nested_scopes",
"generators",
"division",
"... |
Why truncate when we open a file in 'w' mode in python | 4,562,100 | 27 | 2010-12-30T11:12:30Z | 4,562,126 | 24 | 2010-12-30T11:17:01Z | [
"python"
] | I am going through Zed Shaw's Python Book. I am currently working on the opening and reading files chapters. I am wondering why we need to do a truncate, when we are already opening the file in a 'w' mode?
```
print "Opening the file..."
target = open(filename, 'w')
print "Truncating the file. Goodbye!"
target.trunca... | Its redundant since, as you noticed, opening in write mode will overwrite the file, more info at [`Input and Output`](http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files) section of Python documentation. |
Why truncate when we open a file in 'w' mode in python | 4,562,100 | 27 | 2010-12-30T11:12:30Z | 4,562,477 | 23 | 2010-12-30T12:11:46Z | [
"python"
] | I am going through Zed Shaw's Python Book. I am currently working on the opening and reading files chapters. I am wondering why we need to do a truncate, when we are already opening the file in a 'w' mode?
```
print "Opening the file..."
target = open(filename, 'w')
print "Truncating the file. Goodbye!"
target.trunca... | So Zed Shaw calls truncate() on a file that is already truncated. OK, that's pretty pointless. Why does he do that? Who knows!? Ask him!
Maybe he does it to show that the method exists? Could be, but that would be pretty daft, since I've never needed to truncate a file in my 15 years as a programmer so it has no place... |
Why truncate when we open a file in 'w' mode in python | 4,562,100 | 27 | 2010-12-30T11:12:30Z | 6,480,227 | 8 | 2011-06-25T20:11:12Z | [
"python"
] | I am going through Zed Shaw's Python Book. I am currently working on the opening and reading files chapters. I am wondering why we need to do a truncate, when we are already opening the file in a 'w' mode?
```
print "Opening the file..."
target = open(filename, 'w')
print "Truncating the file. Goodbye!"
target.trunca... | If you would READ the questions before asking it, he answers it for you.
"Extra Credit
If you feel you do not understand this, go back through and use the comment trick to get it squared away in your mind. One simple English comment above each line will help you understand, or at least let you know what you need to res... |
Django - How to deal with the paths in settings.py on collaborative projects | 4,562,252 | 13 | 2010-12-30T11:35:25Z | 4,562,278 | 27 | 2010-12-30T11:39:08Z | [
"python",
"django"
] | I have just started a feasibility study on Django for my company and I have noticed the need for absolute paths on settings.py:
```
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absol... | ```
import os.path
#Get the absolute path of the settings.py file's directory
PWD = os.path.dirname(os.path.realpath(__file__ ))
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or
# "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to u... |
How to convert a python utc datetime to a local datetime using only python standard library? | 4,563,272 | 60 | 2010-12-30T14:14:41Z | 4,563,487 | 28 | 2010-12-30T14:42:23Z | [
"python",
"datetime",
"timezone",
"python-datetime"
] | I have a python datetime instance that was created using datetime.utcnow() and persisted in database.
For display, I would like to convert the datetime instance reloaded from database to local datetime using the default local timezone (e.g. as if the datetime was create using datetime.now())
How can I convert the utc... | You can't do it with only the standard library as the standard library doesn't have any timezones. You need [pytz](http://pypi.python.org/pypi/pytz) or [dateutil](http://pypi.python.org/pypi/python-dateutil/1.5).
```
>>> from datetime import datetime
>>> now = datetime.utcnow()
>>> from dateutil import tz
>>> HERE = t... |
How to convert a python utc datetime to a local datetime using only python standard library? | 4,563,272 | 60 | 2010-12-30T14:14:41Z | 13,287,083 | 84 | 2012-11-08T10:22:27Z | [
"python",
"datetime",
"timezone",
"python-datetime"
] | I have a python datetime instance that was created using datetime.utcnow() and persisted in database.
For display, I would like to convert the datetime instance reloaded from database to local datetime using the default local timezone (e.g. as if the datetime was create using datetime.now())
How can I convert the utc... | In Python 3.3+:
```
from datetime import timezone
def utc_to_local(utc_dt):
return utc_dt.replace(tzinfo=timezone.utc).astimezone(tz=None)
```
In Python 2/3:
```
import calendar
from datetime import datetime, timedelta
def utc_to_local(utc_dt):
# get integer timestamp to avoid precision lost
timestamp ... |
How to retrieve information from curl using python subprocess | 4,563,315 | 2 | 2010-12-30T14:20:13Z | 4,563,372 | 7 | 2010-12-30T14:27:51Z | [
"python",
"curl"
] | I'm using curl.exe on windows. But unfortunately I can't get back data from console.
python code looks like this:
```
tid = subprocess.Popen("C:/users/zero/Desktop/lm/curl.exe -i -H \"Cookie: login=" + userhash + "\" -F \"type=" + caid + "\" -F \"description=\" -F \"descr=" + cleaned + "\" -F \"filetype=2\" -F \"name... | Using curl via subprocess is the hard way. Spare yourself the trouble and use [urllib](http://docs.python.org/library/urllib2.html) or [pycurl](http://pycurl.sourceforge.net/).
[update]
Currently, the [requests](http://docs.python-requests.org/en/latest/) library is the best option for this kind of thing. |
What was the first version of Python that included SQLite? | 4,563,415 | 2 | 2010-12-30T14:33:13Z | 4,563,436 | 8 | 2010-12-30T14:35:48Z | [
"python",
"sqlite"
] | * What was the first version of Python that included SQLite?
* What version of SQLite was included?
I thought Python 2.5 was the first version to include SQLite, but I was hoping someone could confirm that and the version of SQLite that was first included. | From [the docs](http://docs.python.org/library/sqlite3.html):
> 11.13. sqlite3 â DB-API 2.0 interface for SQLite databases
>
> **New in version 2.5.** |
Count letters in a word in python debug | 4,563,552 | 3 | 2010-12-30T14:52:16Z | 4,563,613 | 9 | 2010-12-30T14:58:42Z | [
"python",
"count",
"letter"
] | I am trying to count the number of times 'e' appears in a word.
```
def has_no_e(word): #counts 'e's in a word
letters = len(word)
count = 0
while letters >= 0:
if word[letters-1] == 'e':
count = count + 1
letters = letters - 1
print count
```
It seems to work fine exce... | As others mention, you can implement the test with a simple `word.count('e')`. Unless you're doing this as a simple exercise, this is far better than trying to reinvent the wheel.
The problem with your code is that it counts the last character twice because you are testing index `-1` at the end, which in Python return... |
Count letters in a word in python debug | 4,563,552 | 3 | 2010-12-30T14:52:16Z | 4,563,614 | 7 | 2010-12-30T14:58:43Z | [
"python",
"count",
"letter"
] | I am trying to count the number of times 'e' appears in a word.
```
def has_no_e(word): #counts 'e's in a word
letters = len(word)
count = 0
while letters >= 0:
if word[letters-1] == 'e':
count = count + 1
letters = letters - 1
print count
```
It seems to work fine exce... | ```
>>> word = 'eeeooooohoooooeee'
>>> word.count('e')
6
```
Why not this? |
Get exception description and stack trace which caused an exception, all as a string | 4,564,559 | 183 | 2010-12-30T16:59:39Z | 4,564,595 | 266 | 2010-12-30T17:05:13Z | [
"python",
"exception-handling",
"stack-trace"
] | I've seen a lot of posts about stack trace and exceptions in Python. But haven't found what I need.
I have a chunk of Python 2.7 code that may raise an exception. I would like to catch it and assign to a **string** its full description and the stack trace that caused the error (simply all we use to see on the console)... | See the `traceback` module, specifically the `format_exc()` function. [Here](http://docs.python.org/library/traceback.html#traceback.format_exc).
```
import traceback
try:
raise ValueError
except:
tb = traceback.format_exc()
else:
tb = "No error"
finally:
print tb
``` |
Get exception description and stack trace which caused an exception, all as a string | 4,564,559 | 183 | 2010-12-30T16:59:39Z | 4,564,637 | 21 | 2010-12-30T17:10:40Z | [
"python",
"exception-handling",
"stack-trace"
] | I've seen a lot of posts about stack trace and exceptions in Python. But haven't found what I need.
I have a chunk of Python 2.7 code that may raise an exception. I would like to catch it and assign to a **string** its full description and the stack trace that caused the error (simply all we use to see on the console)... | ```
>>> import sys
>>> import traceback
>>> try:
... 5 / 0
... except ZeroDivisionError, e:
... type_, value_, traceback_ = sys.exc_info()
>>> traceback.format_tb(traceback_)
[' File "<stdin>", line 2, in <module>\n']
>>> value_
ZeroDivisionError('integer division or modulo by zero',)
>>> type_
<type 'exceptions.Z... |
How detect length of a numpy array with only one element? | 4,565,749 | 10 | 2010-12-30T19:48:36Z | 4,565,910 | 26 | 2010-12-30T20:12:33Z | [
"python",
"arrays",
"numpy"
] | I am reading in a file using numpy.genfromtxt which brings in columns of both strings and numeric values. One thing I need to do is detect the length of the input. This is all fine provided there are more than one value read into each array.
But...if there is only one element in the resulting array, the logic fails. I... | If you need a one-liner (assuming the answer you are expecting is 1):
```
In [1]: import numpy as np
In [2]: a = np.array(2.3)
In [3]: len(np.atleast_1d(a))
Out[3]: 1
```
[This page](http://projects.scipy.org/numpy/wiki/ZeroRankArray) explains why it was decided to implement 0-dimensional arrays in numpy. |
Django - User, UserProfile, and Admin | 4,565,814 | 10 | 2010-12-30T19:59:06Z | 4,565,957 | 25 | 2010-12-30T20:20:36Z | [
"python",
"django",
"django-admin"
] | I'm trying to get the Django Admin interface to display information about my profile. It displays all of my users but no profile information. I'm not quite sure how to get it to work.
I found this code after a quick google search:
```
from auth.models import UserProfile
from django.contrib import admin
from django.co... | I can't see exactly what's wrong, but here's a slightly simpler example that I know works. Put this is any working admin.py. Try adding a trailing comma to your inline-- some things break without it.
```
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from accounts.models import UserPr... |
Django staticfiles app help | 4,565,935 | 38 | 2010-12-30T20:16:50Z | 4,566,907 | 115 | 2010-12-30T22:54:02Z | [
"python",
"django",
"static",
"http-status-code-404"
] | I've having a little issue with Django's [staticfiles app](https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/).
I have added
```
'django.contrib.staticfiles',
```
to my INSTALLED\_APPS and have added
```
STATIC_URL = '/static/'
STATIC_ROOT = '/Users/kevdotbadger/django/mylook/static/'
```
to my `settin... | I implore you to read the howto docs here: <http://docs.djangoproject.com/en/dev/howto/static-files/>
In short: STATIC\_ROOT is only used if you call the collectstatic manangement command. It's not needed to add the directory to the STATICFILES\_DIRS setting to serve your static files!
During development (when the au... |
Web Python Question | 4,566,020 | 4 | 2010-12-30T20:28:26Z | 4,566,093 | 7 | 2010-12-30T20:38:04Z | [
"python",
"hosting",
"shared-hosting"
] | Can anyone assist me in getting a Python script running on Hostgator Shared hosting? I work with PHP mostly, but have taken a liking to Python, and would like to try to get it going on the web. The only way I've ever ran Python is with either the interpreter, or through a terminal, with >Python file.py. I tried just up... | Well, I got [this](http://support.hostgator.com/articles/getting-started/general-help/perl-and-python-http://docs.python.org/library/cgiscripts) from Hostgator's own support site.
Assuming your host is running Python 2.x, then you can adapt the linked-to script as follows:
```
#!/usr/bin/python
print "Content-type: t... |
Python Logger logging things twice to console | 4,566,327 | 13 | 2010-12-30T21:14:52Z | 4,566,411 | 37 | 2010-12-30T21:30:43Z | [
"python",
"logging"
] | I'm trying to put together a logger using Python. I'm working in 2.6 so I can't use the new dictionary style method and instead am going with the good old fashioned config file. The problem is, stuff outputs twice to the console and I can't understand why. Here's my test script:
```
import logging
import logging.confi... | Change your non-root loggers to set `propagate` to 0, to prevent messages from being propagated up to the root logger:
```
[logger_sloggerMain]
handlers=consoleHandler,infoFileHandler,debugFileHandler
level=DEBUG
qualname=sloggerMain
propagate=0
```
The `logging` module's [docs](http://docs.python.org/3.1/library/log... |
Python file iterator over a binary file with newer idiom | 4,566,498 | 18 | 2010-12-30T21:43:33Z | 4,566,523 | 26 | 2010-12-30T21:47:34Z | [
"python",
"file",
"iterator"
] | In Python, for a binary file, I can write this:
```
buf_size=1024*64 # this is an important size...
with open(file, "rb") as f:
while True:
data=f.read(buf_size)
if not data: break
# deal with the data....
```
With a text file that I want to read line-by-line, I can write this:
```
wit... | Try:
```
>>> with open('dups.txt','rb') as f:
... for chunk in iter((lambda:f.read(how_many_bytes_you_want_each_time)),''):
... i+=1
```
[`iter`](https://docs.python.org/2/library/functions.html#iter) needs a function with zero arguments.
* a plain [`f.read`](https://docs.python.org/2/library/stdtypes.html#... |
Python file iterator over a binary file with newer idiom | 4,566,498 | 18 | 2010-12-30T21:43:33Z | 4,566,550 | 19 | 2010-12-30T21:52:42Z | [
"python",
"file",
"iterator"
] | In Python, for a binary file, I can write this:
```
buf_size=1024*64 # this is an important size...
with open(file, "rb") as f:
while True:
data=f.read(buf_size)
if not data: break
# deal with the data....
```
With a text file that I want to read line-by-line, I can write this:
```
wit... | I don't know of any built-in way to do this, but a wrapper function is easy enough to write:
```
def read_in_chunks(infile, chunk_size=1024*64):
while True:
chunk = infile.read(chunk_size)
if chunk:
yield chunk
else:
# The chunk was empty, which means we're at the en... |
Class from variable | 4,566,655 | 2 | 2010-12-30T22:10:53Z | 4,566,678 | 9 | 2010-12-30T22:15:22Z | [
"python",
"class",
"object",
"new-operator"
] | I have a class, trying to instantiate another class, based off of a variable name passed to it. It is complaining that 'str' object is not callable. What is the proper way to do this?
```
def MyClass:
def __init__(self, otherName):
self.other = otherName()
```
EDIT: Here is the entirety of my code, is the... | You can do this *without* using strings at all. You can refer to classes in Python by name, and pass them around just like any other object. So, using your definition of `MyClass` above, instead of doing:
```
c = Controller("Blog")
```
you can use simply:
```
c = Controller(Blog)
```
Using `eval()` for something li... |
Can I memoize a Python generator? | 4,566,769 | 14 | 2010-12-30T22:30:35Z | 4,566,905 | 8 | 2010-12-30T22:53:42Z | [
"python",
"generator",
"memoization"
] | I have a function called `runquery` that makes calls to a database and then yields the rows, one by one. I wrote a memoize decorator (or more accurately, I just stole one from [this stackoverflow question](http://stackoverflow.com/questions/3377258/memoization-handler/3377272#3377272)) but on subsequent calls it just y... | ```
from itertools import tee
sequence, memoized_sequence = tee (sequence, 2)
```
Done.
It is easier for generators because the standard lib has this "tee" method! |
Can I memoize a Python generator? | 4,566,769 | 14 | 2010-12-30T22:30:35Z | 10,726,355 | 10 | 2012-05-23T19:11:16Z | [
"python",
"generator",
"memoization"
] | I have a function called `runquery` that makes calls to a database and then yields the rows, one by one. I wrote a memoize decorator (or more accurately, I just stole one from [this stackoverflow question](http://stackoverflow.com/questions/3377258/memoization-handler/3377272#3377272)) but on subsequent calls it just y... | I realise this is somewhat of an old question, but for those who want a full solution: here's one, based on jsbueno's suggestion:
```
from itertools import tee
from types import GeneratorType
Tee = tee([], 1)[0].__class__
def memoized(f):
cache={}
def ret(*args):
if args not in cache:
cac... |
abstract test case using python unittest | 4,566,910 | 25 | 2010-12-30T22:54:29Z | 4,566,992 | 46 | 2010-12-30T23:12:56Z | [
"python",
"unit-testing",
"testcase"
] | Is it possible to create an abstract `TestCase`, that will have some test\_\* methods, but this `TestCase` won't be called and those methods will only be used in subclasses? I think I am going to have one abstract `TestCase` in my test suite and it will be subclassed for a few different implementation of a single inter... | I didn't quite understand what do you plan to do --
the rule of thumb is "not to be smart with tests" -
just have them there, plain written.
But to achieve what you want, if you inherit from unittest.TestCase, whenever you call unittest.main() your "abstract" class will be executed - I think this is the situation you ... |
abstract test case using python unittest | 4,566,910 | 25 | 2010-12-30T22:54:29Z | 18,046,636 | 7 | 2013-08-04T19:15:59Z | [
"python",
"unit-testing",
"testcase"
] | Is it possible to create an abstract `TestCase`, that will have some test\_\* methods, but this `TestCase` won't be called and those methods will only be used in subclasses? I think I am going to have one abstract `TestCase` in my test suite and it will be subclassed for a few different implementation of a single inter... | Multiple inheritance isn't a great option here, chiefly for the two following reasons:
1. None of the methods in `TestCase` use `super()` so you'd have to list your class first for methods like `setUp()` and `tearDown()` to work.
2. pylint will warn that the base class uses `self.assertEquals()` etc which aren't defin... |
Creating readable html with django templates | 4,567,031 | 14 | 2010-12-30T23:20:04Z | 14,173,302 | 12 | 2013-01-05T15:36:58Z | [
"python",
"html",
"django",
"templates"
] | When using Django for html templating how do I create good html markup formatting.
I am trying to make use of content blocks. But the content blocks show up at different levels of indentation in different templates. How do I get the content blocks to show indented like it would be if someone was to hand write the html... | Christian S. Perone from Pyevolve has [exactly what you're looking for](http://blog.christianperone.com/?p=814). He uses middleware to intercept the HTTPResponse object and run it through [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/).
I'd imagine that your site will suffer a slight performance hit, th... |
Python Image Library: How to combine 4 images into a 2 x 2 grid? | 4,567,409 | 21 | 2010-12-31T01:02:59Z | 4,567,461 | 35 | 2010-12-31T01:15:56Z | [
"python",
"python-imaging-library"
] | I have 4 directories with images for an animation. I would like to take the set of images and generate a single image with the 4 images arranged into a 2x2 grid for each frame of the animation.
My code so far is:
```
import Image
fluid64 = "Fluid64_half_size/00"
fluid128 = "Fluid128_half_size/00"
fluid512 = "Fluid51... | The only problem there is that "paste" does not return an image object - it rather modifies the "blank" image inplace.
So, when the second paste is called (the one that uses the fuild128 image), it tries to be applied on "None" - which is the return value of the first image.
If that is the only problem you are having... |
Python Image Library: How to combine 4 images into a 2 x 2 grid? | 4,567,409 | 21 | 2010-12-31T01:02:59Z | 4,567,480 | 10 | 2010-12-31T01:23:08Z | [
"python",
"python-imaging-library"
] | I have 4 directories with images for an animation. I would like to take the set of images and generate a single image with the 4 images arranged into a 2x2 grid for each frame of the animation.
My code so far is:
```
import Image
fluid64 = "Fluid64_half_size/00"
fluid128 = "Fluid128_half_size/00"
fluid512 = "Fluid51... | You may want to be using something along the lines of :
```
blank_image = Image.new("RGB", (800, 600))
```
This will create a new area in memory in which you can generate your image. You should then be able to paste you images into that.
Then you'll need to save it out again later on with:
```
blank_image.save("bla... |
Using .aggregate() on a value introduced using .extra(select={...}) in a Django Query? | 4,567,543 | 20 | 2010-12-31T01:40:42Z | 5,195,517 | 13 | 2011-03-04T15:13:00Z | [
"python",
"mysql",
"django",
"django-queryset",
"django-aggregation"
] | I'm trying to get the count of the number of times a player played each week like this:
```
player.game_objects.extra(
select={'week': 'WEEK(`games_game`.`date`)'}
).aggregate(count=Count('week'))
```
But Django complains that
```
FieldError: Cannot resolve keyword 'week' into field. Choices are: <lists model fi... | You could use a custom aggregate function to produce your query:
```
WEEK_FUNC = 'STRFTIME("%%%%W", %s)' # use 'WEEK(%s)' for mysql
class WeekCountAggregate(models.sql.aggregates.Aggregate):
is_ordinal = True
sql_function = 'WEEK' # unused
sql_template = "COUNT(%s)" % (WEEK_FUNC.replace('%%', '%%%%') % '%... |
Are there benefits to running X86-64 Python on a 64-bit CPU in a 64-bit OS? | 4,567,856 | 17 | 2010-12-31T03:17:56Z | 4,567,870 | 17 | 2010-12-31T03:25:29Z | [
"python",
"windows-7",
"64bit",
"x86-64"
] | What kind of benefits are there to running the amd64 builds of Python and extensions? (Lots of extensions [compiled for amd64 here](http://www.lfd.uci.edu/~gohlke/pythonlibs/).) I have an i5 processor and Win7 64-bit, so it seems like it would be appropriate. But it also sounds like it is buggy, beta, unsupported, etc.... | The primary rationale to use a 64-bit Python is that you can access more than 2GB of main memory, e.g. if you have large dicts, lists, or long strings. This requires that you actually have that much memory in your system to be practical.
A secondary effect is that in AMD64 mode, the CPU has more registers, so the resu... |
Looping through a text file, readline() construction fails on large files | 4,568,171 | 2 | 2010-12-31T04:59:52Z | 4,568,176 | 10 | 2010-12-31T05:02:15Z | [
"python",
"file-io"
] | In Python 2.6 and 2.7 I would have thought that these two constructs would be identical:
**Method A**
```
i=0
f=open('fred.txt','r')
for line in f.readline():
i+=1
print i
```
**Method B**
```
i=0
f=open('fred.txt','r')
for line in f:
i+=1
print i
```
However, when fred.txt grew to be 74,000 lines, with ea... | Thereâs a typo, it should be `f.readlines()`. Youâre reading one line and looping through each character in the line.
Both methods (`readlines` vs iterating over the file directly) ought to give the same results, but `readlines` will store the entire contents in memory. |
Python glob multiple filetypes | 4,568,580 | 40 | 2010-12-31T06:39:15Z | 4,568,638 | 51 | 2010-12-31T06:53:41Z | [
"python",
"glob"
] | Is there a better way to use glob.glob in python to get a list of multiple file types such as .txt, .mdown, and .markdown? Right now I have something like this:
```
projectFiles1 = glob.glob( os.path.join(projectDir, '*.txt') )
projectFiles2 = glob.glob( os.path.join(projectDir, '*.mdown') )
projectFiles3 = glob.glob(... | Maybe there is a better way, but how about:
```
>>> import glob
>>> types = ('*.pdf', '*.cpp') # the tuple of file types
>>> files_grabbed = []
>>> for files in types:
... files_grabbed.extend(glob.glob(files))
...
>>> files_grabbed # the list of pdf and cpp files
```
Perhaps there is another way, so wait in c... |
Python glob multiple filetypes | 4,568,580 | 40 | 2010-12-31T06:39:15Z | 4,568,692 | 7 | 2010-12-31T07:07:23Z | [
"python",
"glob"
] | Is there a better way to use glob.glob in python to get a list of multiple file types such as .txt, .mdown, and .markdown? Right now I have something like this:
```
projectFiles1 = glob.glob( os.path.join(projectDir, '*.txt') )
projectFiles2 = glob.glob( os.path.join(projectDir, '*.mdown') )
projectFiles3 = glob.glob(... | with glob it is not possible. you can use only:
\* matches everything
? matches any single character
[seq] matches any character in seq
[!seq] matches any character not in seq
use os.listdir and a regexp to check patterns:
```
for x in os.listdir('.'):
if re.match('.*\.txt|.*\.sql', x):
print x
``` |
Python glob multiple filetypes | 4,568,580 | 40 | 2010-12-31T06:39:15Z | 4,829,130 | 14 | 2011-01-28T14:12:14Z | [
"python",
"glob"
] | Is there a better way to use glob.glob in python to get a list of multiple file types such as .txt, .mdown, and .markdown? Right now I have something like this:
```
projectFiles1 = glob.glob( os.path.join(projectDir, '*.txt') )
projectFiles2 = glob.glob( os.path.join(projectDir, '*.mdown') )
projectFiles3 = glob.glob(... | Chain the results:
```
import itertools as it, glob
def multiple_file_types(*patterns):
return it.chain.from_iterable(glob.glob(pattern) for pattern in patterns)
```
Then:
```
for filename in multiple_file_types("*.txt", "*.sql", "*.log"):
# do stuff
``` |
Python glob multiple filetypes | 4,568,580 | 40 | 2010-12-31T06:39:15Z | 26,403,164 | 11 | 2014-10-16T11:23:02Z | [
"python",
"glob"
] | Is there a better way to use glob.glob in python to get a list of multiple file types such as .txt, .mdown, and .markdown? Right now I have something like this:
```
projectFiles1 = glob.glob( os.path.join(projectDir, '*.txt') )
projectFiles2 = glob.glob( os.path.join(projectDir, '*.mdown') )
projectFiles3 = glob.glob(... | ```
from glob import glob
files = glob('*.gif')
files.extend(glob('*.png'))
files.extend(glob('*.jpg'))
print(files)
```
If you need to specify a path, loop over match patterns and keep the join inside the loop for simplicity:
```
from os.path import join
from glob import glob
files = []
for ext in ('*.gif', '*.pn... |
What does "Complex is better than complicated" mean? | 4,568,704 | 23 | 2010-12-31T07:11:05Z | 4,568,759 | 26 | 2010-12-31T07:25:26Z | [
"python"
] | In "The Zen of Python", by Tim Peters, the sentence "Complex is better than complicated" confused me. Can anyone give a more detailed explanation or an example? | although complex and complicated sound alike, they do not mean the same in this context.
The Zen therefore says: It is okay to build very complex applications, as long as the need for it is reasonable.
To give an example:
```
counter = 0
while counter < 5:
print counter
counter += 1
```
The code is very easy ... |
Ruby or Python for heavy import script? | 4,571,119 | 2 | 2010-12-31T16:23:22Z | 4,571,158 | 10 | 2010-12-31T16:30:39Z | [
"php",
"python",
"ruby",
"import",
"lisp"
] | I have an application I wrote in PHP (on symfony) that imports large CSV files (up to 100,000 lines). It has a real memory usage problem. Once it gets through about 15,000 rows, it grinds to a halt.
I know there are measures I could take within PHP but I'm kind of done with PHP, anyway.
If I wanted to write an app th... | What are you importing the CSV file into? Couldn't you parse the CSV file in a way that doesn't load the whole thing into memory at once (i.e. work with one line at a time)?
If so, then you can use Ruby's standard CSV library to do something like the following"
```
CSV.open('csvfile.csv', 'r') do |row|
#executes on... |
Ruby or Python for heavy import script? | 4,571,119 | 2 | 2010-12-31T16:23:22Z | 4,571,301 | 9 | 2010-12-31T17:02:50Z | [
"php",
"python",
"ruby",
"import",
"lisp"
] | I have an application I wrote in PHP (on symfony) that imports large CSV files (up to 100,000 lines). It has a real memory usage problem. Once it gets through about 15,000 rows, it grinds to a halt.
I know there are measures I could take within PHP but I'm kind of done with PHP, anyway.
If I wanted to write an app th... | What are you importing the CSV file into? Couldn't you parse the CSV file in a way that doesn't load the whole thing into memory at once (i.e. work with one line at a time)?
If so, then you can use Python's standard `csv` library to do something like the following
```
import csv
with open('csvfile.csv', 'rb') as sour... |
Creating a BAT file for python script | 4,571,244 | 18 | 2010-12-31T16:51:46Z | 4,571,260 | 24 | 2010-12-31T16:55:06Z | [
"python",
"batch-file"
] | How can I create a simple BAT file that will run my python script located at C:\somescript.py?
many thanks | ```
c:\python27\python.exe c:\somescript.py %*
``` |
Creating a BAT file for python script | 4,571,244 | 18 | 2010-12-31T16:51:46Z | 4,572,111 | 23 | 2010-12-31T20:10:12Z | [
"python",
"batch-file"
] | How can I create a simple BAT file that will run my python script located at C:\somescript.py?
many thanks | Open a command line (Windowskey+R, 'cmd',<enter>)
and type 'python -V', <enter>.
You should get a response back, something like 'Python 2.7.1'.
If you do not, you may not have Python installed. Fix this first.
Once you have Python, your batch file should look like
```
@echo off
python c:\somescript.py %*
pause
```
... |
Recursive expressions with pyparsing | 4,571,441 | 5 | 2010-12-31T17:34:16Z | 4,589,920 | 7 | 2011-01-04T01:25:48Z | [
"python",
"parsing",
"pyparsing",
"associativity"
] | I'm trying to figure out how to do a left-associative expression where recursive (not-enclosed in anything) expressions are possible. For example, I'd like to do:
```
expr + OP + expr
```
that parses 2 operations like `1 x 2 x 3` into `(expr OP expr) OP expr` result.
If I try to prevent `expr` parsing from infinite ... | Here is an example parse action that will take the flat lists of tokens and nest them as if parsed left-recursively:
```
from pyparsing import *
# parse action -maker
def makeLRlike(numterms):
if numterms is None:
# None operator can only by binary op
initlen = 2
incr = 1
else:
... |
Problem with re.findall (duplicates) | 4,571,468 | 3 | 2010-12-31T17:40:49Z | 4,571,510 | 9 | 2010-12-31T17:48:26Z | [
"python",
"html",
"regex"
] | I tried to fetch source of 4chan site, and get links to threads.
I have problem with regexp (isn't working). Source:
```
import urllib2, re
req = urllib2.Request('http://boards.4chan.org/wg/')
resp = urllib2.urlopen(req)
html = resp.read()
print re.findall("res/[0-9]+", html)
#print re.findall("^res/[0-9]+$", html)... | That's because there are multiple copies of the link in the source.
You can easily make them unique by putting them in a set.
```
>>> print set(re.findall("res/[0-9]+", html))
set(['res/3833795', 'res/3837945', 'res/3835377', 'res/3837941', 'res/3837942',
'res/3837950', 'res/3100203', 'res/3836997', 'res/3837643', 'r... |
Python dict to JSON via json.loads: | 4,571,684 | 17 | 2010-12-31T18:27:37Z | 4,572,176 | 27 | 2010-12-31T20:27:05Z | [
"python",
"django",
"json",
"http-post"
] | I have troubleshooting some code that uses HTTP POST to send data and should return a JSON result whose contents are a dictionary. I am using an XML-RPC wrapper to expose this service. When the wrapper receives the dict information from the http response variable, the dict contents are in a string in this form:
```
{'... | You are trying to use the wrong method. `json.loads` is for *loading JSON to Python*. If you want to convert Python to JSON, you need `json.dumps`.
```
result = json.dumps(response[1])
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.