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 |
|---|---|---|---|---|---|---|---|---|---|
python @abstractmethod decorator | 7,196,376 | 10 | 2011-08-25T19:53:10Z | 7,196,503 | 17 | 2011-08-25T20:02:26Z | [
"python",
"abc",
"abstract-methods"
] | I have read python docs about abstract base classes:
From [here](http://docs.python.org/library/abc.html):
> `abc.abstractmethod(function)`
> A decorator indicating abstract methods.
>
> Using this decorator requires that the classâs metaclass is `ABCMeta` or
> is derived from it. A class that has a metaclass deriv... | Are you using python3 to run that code ? if yes you should know that declaring metaclass in python 3 [have changes](http://www.python.org/dev/peps/pep-3115/) you should do it like this instead:
```
import abc
class AbstractClass(metaclass=abc.ABCMeta):
@abc.abstractmethod
def abstractMethod(self):
return
`... |
5 maximum values in a python dictionary | 7,197,315 | 18 | 2011-08-25T21:18:40Z | 7,197,351 | 26 | 2011-08-25T21:21:24Z | [
"python",
"dictionary",
"max"
] | I have a dictionary like this:
```
A = {'a':10, 'b':843, 'c': 39,.....}
```
I want to get the 5 maximum values of this dict and store a new dict with this. To get the maximum value I did:
```
max(A.iteritems(), key=operator.itemgetter(1))[0:]
```
Perhaps it is an easy task, but I am stuck on it for a long time. Ple... | You are close. You can *sort* the list using [`sorted` *[docs]*](http://docs.python.org/library/functions.html#sorted) and take the first five elements:
```
newA = dict(sorted(A.iteritems(), key=operator.itemgetter(1), reverse=True)[:5])
```
See also: [Python Sorting HowTo](http://wiki.python.org/moin/HowTo/Sorting/) |
5 maximum values in a python dictionary | 7,197,315 | 18 | 2011-08-25T21:18:40Z | 7,197,643 | 44 | 2011-08-25T21:49:37Z | [
"python",
"dictionary",
"max"
] | I have a dictionary like this:
```
A = {'a':10, 'b':843, 'c': 39,.....}
```
I want to get the 5 maximum values of this dict and store a new dict with this. To get the maximum value I did:
```
max(A.iteritems(), key=operator.itemgetter(1))[0:]
```
Perhaps it is an easy task, but I am stuck on it for a long time. Ple... | No need to use iteritems and itemgetter. The dict's own get method works fine.
```
max(A, key=A.get)
```
Similarly for sorting:
```
sorted(A, key=A.get, reverse=True)[:5]
```
Finally, if the dict size is unbounded, using a heap will eventually be faster than a full sort.
```
import heapq
heapq.nlargest(5, A, key=A... |
5 maximum values in a python dictionary | 7,197,315 | 18 | 2011-08-25T21:18:40Z | 22,916,447 | 9 | 2014-04-07T15:14:39Z | [
"python",
"dictionary",
"max"
] | I have a dictionary like this:
```
A = {'a':10, 'b':843, 'c': 39,.....}
```
I want to get the 5 maximum values of this dict and store a new dict with this. To get the maximum value I did:
```
max(A.iteritems(), key=operator.itemgetter(1))[0:]
```
Perhaps it is an easy task, but I am stuck on it for a long time. Ple... | You could use [collections.Counter](https://docs.python.org/2/library/collections.html) here:
`dict(Counter(A).most_common(5))`
Example:
```
>>> from collections import Counter
>>> A = {'a' : 1, 'b' : 3, 'c' : 2, 'd' : 4, 'e' : 0, 'f' :5}
>>> dict(Counter(A).most_common(5))
{'a': 1, 'c': 2, 'b': 3, 'd': 4, 'f': 5}
`... |
how to filter model with a list containing the field and the value? | 7,197,929 | 3 | 2011-08-25T22:23:25Z | 7,198,013 | 8 | 2011-08-25T22:35:42Z | [
"python",
"django"
] | see what I have:
```
> bar = [(u'code__regex', u'^[^J]'), (u'active__exact', u'0'), (u'type__id__exact', u'E01')]
```
There are the fields/values that I want to use to filter the model Foo.
```
> #want to have this equivalent:
> Foo.objects.filter(bar)
```
Thanks! | ```
Foo.objects.filter(**dict(bar))
```
This isn't a django issue, this is a python issue. You want to pass the keyword pairs as keyword arguments (kwargs) to the filter. Your `bar` is *perfect* as a kwarg set, so the `dict(bar)` converts it to the dictionary, and the `**` prefix informs the python parser that the dic... |
Python encoding problems | 7,199,179 | 4 | 2011-08-26T01:35:34Z | 7,199,333 | 9 | 2011-08-26T02:07:15Z | [
"python",
"django",
"encoding",
"twitter",
"utf-8"
] | So, I've read a lot about Python encoding and stuff - maybe not enough but I've been working on this for 2 days and still nothing - but I'm still getting troubles. I'll try to be as clear as I can. The main thing is that I'm trying to remove all accents and characters such as #, !, %, &...
The thing is, I do a query s... | See [this page](http://wiki.python.org/moin/UnicodeEncodeError).
The `decode()` method is to be applied to a str object, not a unicode object. Given a unicode string as input, it first tries to encode it to a str using the ascii codec, then decode as utf-8, which fails.
Try `return normalize('NFKD', unicode(txt) )`. |
How to Break Import Loop in python | 7,199,466 | 15 | 2011-08-26T02:37:19Z | 7,199,514 | 19 | 2011-08-26T02:46:28Z | [
"python"
] | I have a situation where there two related large python classes and hence i have put them in separate files. Let say classes are Cobra and Rat.
Now need to call methods of Rat from methods of Cobra and vice versa.
For this i need to import Cobra in Rat.py and Rat in Cobra.py
This creates an import loop and gives an e... | If you don't use Cobra in the class definition of Rat or vice versa i.e. only used inside methods, then you can actually move the import statement to the bottom of the file, by which time the class definition would already exist.
```
Class Cobra:
...
def check_prey(self, rat ):
Some logic rat.foo()
import Rat
i... |
Python3: writing csv files | 7,200,606 | 29 | 2011-08-26T06:05:55Z | 7,201,002 | 43 | 2011-08-26T06:49:25Z | [
"python",
"windows",
"csv",
"python-3.x"
] | I'm trying to use Python 3.2 on a Windows computer to write a simple CSV file, however I'm having no luck. From the [csv module documentation for Python 3.2](http://docs.python.org/release/3.2/library/csv.html#csv.writer):
```
>>> import csv
>>> spamWriter = csv.writer(open('eggs.csv', 'w'), delimiter=' ',
... ... | Documentation says that you should use `open('eggs.csv', 'w', newline='')`
<http://docs.python.org/py3k/library/csv.html#id2> |
Python3: writing csv files | 7,200,606 | 29 | 2011-08-26T06:05:55Z | 11,235,392 | 12 | 2012-06-27T21:59:36Z | [
"python",
"windows",
"csv",
"python-3.x"
] | I'm trying to use Python 3.2 on a Windows computer to write a simple CSV file, however I'm having no luck. From the [csv module documentation for Python 3.2](http://docs.python.org/release/3.2/library/csv.html#csv.writer):
```
>>> import csv
>>> spamWriter = csv.writer(open('eggs.csv', 'w'), delimiter=' ',
... ... | This will work on both Python 2 and Python 3:
```
if sys.version_info >= (3,0,0):
f = open(filename, 'w', newline='')
else:
f = open(filename, 'wb')
``` |
Python List of np arrays to array | 7,200,878 | 9 | 2011-08-26T06:36:20Z | 7,200,900 | 15 | 2011-08-26T06:37:58Z | [
"python",
"arrays",
"list",
"numpy"
] | I'm trying to turn a list of 2d numpy arrays into a 2d numpy array. For example,
```
dat_list = []
for i in range(10):
dat_list.append(np.zeros([5, 10]))
```
What I would like to get out of this list is an array that is (50, 10). However, when I try the following, I get a (10,5,10) array.
```
output = np.array(d... | you want to stack them:
```
np.vstack(dat_list)
``` |
How change a function's return with decorator in python? | 7,201,715 | 3 | 2011-08-26T08:05:55Z | 7,201,740 | 15 | 2011-08-26T08:08:57Z | [
"python",
"decorator"
] | I want create a decorator to change a function's return value like that, How to do that like below?:
```
def dec(func):
def wrapper():
#some code...
#change return value append 'c':3
return wrapper
@dec
def foo():
return {'a':1, 'b':2}
result = foo()
print result
{'a':1, 'b':2, 'c':3}
``` | Well.... you call the decorated function and change the return value:
```
def dec(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
result['c'] = 3
return result
return wrapper
``` |
Python map function, passing by reference/value? | 7,203,295 | 6 | 2011-08-26T10:23:10Z | 7,203,433 | 12 | 2011-08-26T10:35:22Z | [
"python"
] | I have a question about the `map` function in Python.
From what I understand, the function does not mutate the list it's operating on, but rather create a new one and return it. Is this correct ?
Additionally, I have the following piece of code
```
def reflect(p,dir):
if(dir == 'X'):
func = lambda (a,b) : (a *... | You misunderstand how references work in Python. Here, all names are references, there are no "values". Names are bound to objects. But `=` doesn't modify the object that's pointed to by the name â it rebinds the name to a different object:
```
x = 42
y = x
# now:
# 'is' is a identity operator â it checks whether ... |
pass callback from python to c++ using boost::python | 7,204,664 | 20 | 2011-08-26T12:32:19Z | 7,605,484 | 13 | 2011-09-30T02:53:05Z | [
"c++",
"python",
"callback",
"boost-python"
] | I want to pass callback from my python code to c++
I want my code look something like this:
In C++ :
```
typedef void (*MyCallback_t) (CallbackInfo);
class MyClass
{...
void setcallback(MyCallback_t cb);
...
}
```
And to use it in python :
```
import mylib
def myCallback(mylib_CallbackInfo):
...
t = mylib.My... | Ok, I'm still trying to figure this out too, but here's whats working for me so far:
```
#this is the variable that will hold a reference to the python function
PyObject *py_callback;
#the following function will invoked from python to populate the call back reference
PyObject *set_py_callback(PyObject *callable)
{
... |
Dictionaries of dictionaries merge | 7,204,805 | 42 | 2011-08-26T12:44:30Z | 7,205,107 | 55 | 2011-08-26T13:08:48Z | [
"python"
] | I need to merge multiple dictionaries, here's what I have for instance:
```
dict1 = {1:{"a":{A}},2:{"b":{B}}}
dict2 = {2:{"c":{C}}, 3:{"d":{D}}
```
With `A` `B` `C` and `D` being leaves of the tree, like `{"info1":"value", "info2":"value2"}`
There is an unknown level(depth) of dictionaries, it could be `{2:{"c":{"z... | this is actually quite tricky - particularly if you want a useful error message when things are inconsistent, while correctly accepting duplicate but consistent entries (something no other answer here does....)
assuming you don't have huge numbers of entries a recursive function is easiest:
```
def merge(a, b, path=N... |
Dictionaries of dictionaries merge | 7,204,805 | 42 | 2011-08-26T12:44:30Z | 7,205,672 | 13 | 2011-08-26T13:50:43Z | [
"python"
] | I need to merge multiple dictionaries, here's what I have for instance:
```
dict1 = {1:{"a":{A}},2:{"b":{B}}}
dict2 = {2:{"c":{C}}, 3:{"d":{D}}
```
With `A` `B` `C` and `D` being leaves of the tree, like `{"info1":"value", "info2":"value2"}`
There is an unknown level(depth) of dictionaries, it could be `{2:{"c":{"z... | Here's an easy way to do it using generators:
```
def mergedicts(dict1, dict2):
for k in set(dict1.keys()).union(dict2.keys()):
if k in dict1 and k in dict2:
if isinstance(dict1[k], dict) and isinstance(dict2[k], dict):
yield (k, dict(mergedicts(dict1[k], dict2[k])))
... |
Dictionaries of dictionaries merge | 7,204,805 | 42 | 2011-08-26T12:44:30Z | 15,836,901 | 11 | 2013-04-05T14:45:44Z | [
"python"
] | I need to merge multiple dictionaries, here's what I have for instance:
```
dict1 = {1:{"a":{A}},2:{"b":{B}}}
dict2 = {2:{"c":{C}}, 3:{"d":{D}}
```
With `A` `B` `C` and `D` being leaves of the tree, like `{"info1":"value", "info2":"value2"}`
There is an unknown level(depth) of dictionaries, it could be `{2:{"c":{"z... | One issue with this question is that the values of the dict can be arbitrarily complex pieces of data. Based upon these and other answers I came up with this code:
```
class YamlReaderError(Exception):
pass
def data_merge(a, b):
"""merges b into a and return merged result
NOTE: tuples and arbitrary objec... |
Paramiko Error: Error reading SSH protocol banner | 7,206,272 | 4 | 2011-08-26T14:33:49Z | 7,252,752 | 7 | 2011-08-31T05:04:21Z | [
"python",
"linux",
"ssh",
"fabric",
"paramiko"
] | I'm using Fabric for my build script. I just cloned one of my VMs and created a new server. The Fabric script (which uses paramiko underneath) works fine one server but not the other. Since it's a clone I don't know what could be different but everytime I run my Fabric script I get the error `Error reading SSH protocol... | This issue didn't lie with Paramiko, Fabric or the SSH daemon. It was simply a firewall configuration in ISPs internal network. For some reason, they don't allow communication between different subnets of theirs.
We couldn't really fix the firewall configuration so instead we switched all our IPs to be on the same sub... |
Match letter in any language | 7,206,499 | 11 | 2011-08-26T14:48:26Z | 7,207,366 | 14 | 2011-08-26T15:51:39Z | [
"python",
"regex",
"unicode"
] | How can I match a letter from any language using a regex in python 3?
`re.match([a-zA-Z])` will match the english language characters but I want all languages to be supported simultaneously.
I don't wish to match the `'` in `can't` or underscores or any other type of formatting. I do wish my regex to match: `c`, `a`,... | For Unicode regex work in Python, I very strongly recommend the following:
1. **Use [Matthew Barnettâs `regex` library](http://pypi.python.org/pypi/regex) instead of standard `re`, which is not really suitable for Unicode regular expressions.**
2. Use only Python 3, never Python 2. You want all your strings to be Un... |
Python: How can I run python functions in parallel? | 7,207,309 | 24 | 2011-08-26T15:46:45Z | 7,207,336 | 36 | 2011-08-26T15:48:32Z | [
"python"
] | I researched first and couldn't find an answer to my question. I am trying to run multiple functions in parallel in Python.
I have something like this:
```
files.py
import common #common is a util class that handles all the IO stuff
dir1 = 'C:\folder1'
dir2 = 'C:\folder2'
filename = 'test.txt'
addFiles = [25, 5, 15... | You could use [`threading`](http://docs.python.org/library/threading.html#module-threading) or [`multiprocessing`](http://docs.python.org/library/multiprocessing.html).
Due to [peculiarities of CPython](http://en.wikipedia.org/wiki/Global_Interpreter_Lock), `threading` is unlikely to achieve true parallelism. For this... |
replace characters not working in python | 7,208,861 | 6 | 2011-08-26T18:09:31Z | 7,208,922 | 22 | 2011-08-26T18:15:29Z | [
"python"
] | I am using beautiful soup and I am writing a crawler and have the following code in it:
```
print soup.originalEncoding
#self.addtoindex(page, soup)
links=soup('a')
for link in links:
if('href' in dict(link.attrs)):
... | string.replace() returns the string with the replaced values. It doesn't modify the original so do something like this:
```
link['href'] = link['href'].replace("..", "")
``` |
python prime crunching: processing pool is slower? | 7,209,657 | 8 | 2011-08-26T19:31:29Z | 7,210,377 | 14 | 2011-08-26T20:42:36Z | [
"python",
"multiprocessing",
"pool"
] | So I've been messing around with python's multiprocessing lib for the last few days and I really like the processing pool. It's easy to implement and I can visualize a lot of uses. I've done a couple of projects I've heard about before to familiarize myself with it and recently finished a program that brute forces game... | the most efficient way to use `multiprocessing` is to divide the work into n equal sized chunks, with n the size of the pool, which should be approximately the number of cores on your system. The reason for this is that the work of starting subprocesses and communicating between them is quite large. If the size of the ... |
from Crypto import Random -> ImportError: cannot import name Random | 7,210,873 | 9 | 2011-08-26T21:46:15Z | 7,210,909 | 12 | 2011-08-26T21:50:16Z | [
"python",
"pycrypto"
] | I have installed pycrypto (version 2.3) to /usr/local/lib/python2.6/dist-packages/Crypto/ and I am able to see the Random package there.
But when I try to import the Crypto.Random, it pomps me that
```
from Crypto.Random import *
ImportError: No module named Random
```
Does anyone know why this would even happen? Th... | You may have another `Crypto` module in your Python package. You can check that with
```
import Crypto
print(Crypto.__file__)
# should print /usr/lib/python2.6/dist-packages/Crypto/__init__.pyc
```
If you find another Crypto module, either rename/remove it or adjust `sys.path`
Also, your version of pycrypto may be o... |
Convert binary string representation of a byte to actual binary value in Python | 7,213,996 | 3 | 2011-08-27T10:37:05Z | 7,214,014 | 9 | 2011-08-27T10:41:09Z | [
"python",
"binary"
] | I have a binary string representation of a byte, such as
```
01010101
```
How can I convert it to a real binary value and write it to a binary file? | Use [the `int` function](http://docs.python.org/library/functions.html#int) with a `base` of `2` to read a binary value as an integer.
```
n = int('01010101', 2)
```
Python 2 uses strings to handle binary data, so you would use [the `chr()` function](http://docs.python.org/2/library/functions.html#chr) to convert the... |
Is there nice-looking one-liner to split into variables with type casting? | 7,214,730 | 2 | 2011-08-27T13:04:26Z | 7,214,744 | 9 | 2011-08-27T13:06:30Z | [
"python"
] | I use following code:
```
x,y = line.split()
x,y = float(x),float(y)
```
Is there any way to beautify that code into one-line? | You could use a [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions) or [generator expression](http://docs.python.org/reference/expressions.html#generator-expressions). As delnan points out in the comment, [`map`](http://docs.python.org/library/functions.html#map) is also an agr... |
Python create/import custom module in same directory | 7,215,320 | 9 | 2011-08-27T15:00:20Z | 7,215,345 | 12 | 2011-08-27T15:03:57Z | [
"python"
] | I'm trying to create a simple python script and import a couple of custom classes. I'd like to do this as one module. Here is what I have:
point/point.py
```
class Point:
"""etc."""
```
point/pointlist.py
```
class PointList:
"""etc."""
```
point/\_\_init\_\_.py
```
from . import point, pointlist
```
scrip... | Sorry, I seem to have made a blunder in my earlier answer and comments:
The problem here is that you should access the objects in `point` through the module you import:
`point/__init__.py`:
```
from point import Point
from pointlist import PointList
```
`script.py:`
```
import sys, point
verbose = False
pointlist ... |
In the Django admin site, how do I change the display format of time fields? | 7,216,764 | 11 | 2011-08-27T19:15:39Z | 7,216,843 | 11 | 2011-08-27T19:26:59Z | [
"python",
"django",
"date-formatting"
] | I recently added a new model to my site, and I'm using an admin.py file to specify exactly how I want it to appear in the admin site. It works great, but I can't figure out how to get one of my date fields to include seconds in it's display format. I'm only seeing values like "Aug. 27, 2011, 12:12 p.m." when what I wan... | Try this in the ModelAdmin:
```
def time_seconds(self, obj):
return obj.timefield.strftime("%d %b %Y %H:%M:%S")
time_seconds.admin_order_field = 'timefield'
time_seconds.short_description = 'Precise Time'
list_display = ('id', 'time_seconds', )
```
Replacing "timefield" with the appropriate field in your mod... |
In the Django admin site, how do I change the display format of time fields? | 7,216,764 | 11 | 2011-08-27T19:15:39Z | 32,355,642 | 7 | 2015-09-02T14:17:08Z | [
"python",
"django",
"date-formatting"
] | I recently added a new model to my site, and I'm using an admin.py file to specify exactly how I want it to appear in the admin site. It works great, but I can't figure out how to get one of my date fields to include seconds in it's display format. I'm only seeing values like "Aug. 27, 2011, 12:12 p.m." when what I wan... | digging around I ended here but applied a different approach to my app.
Changing django admin default formats could be done changing the django locale formats for every type you want.
Put the following on your admin.py file (or settings.py) to change datetime default format at your django admin.
```
from django.conf... |
Python - delete old files | 7,217,196 | 6 | 2011-08-27T20:36:59Z | 7,217,269 | 25 | 2011-08-27T20:49:50Z | [
"python"
] | I'm somewhat new to python and have been trying to figure this out on my own but only getting bits and pieces so far. Basically i'm looking for a script that will recursively search a directory and it's sub-directories and delete files that are at least 24 hours old but not alter the directories.
Any advice or examples... | This uses the [os.walk](http://docs.python.org/library/os.html#os.walk) method to recursively search a directory. For each file, it checks the modified date with [os.path.getmtime](http://docs.python.org/library/os.path.html#os.path.getmtime) and compares that with [datetime.now](http://docs.python.org/library/datetime... |
Turtle Graphics Not Responding | 7,217,405 | 6 | 2011-08-27T21:17:28Z | 9,936,922 | 7 | 2012-03-30T04:12:53Z | [
"python",
"windows-7"
] | I am creating diagrams with the turtle package in Python, and it is successful to some extent, except for one problem. Once turtle generates the diagram that I have in code, it causes the program to say "Not responding" and eventually I have to end the task. I am using Windows 7.
Have any of you experienced this or kn... | Just add a call to exitonclick at the end. The Turtle class is implemented using Tkinter and exitonclick() invokes mainloop() which will keep the turtle window open until you click anywhere in the canvas. So, a simple program looks like this:
```
from turtle import *
#make a square
for _ in range(4):
forward(100)
... |
Turtle Graphics Not Responding | 7,217,405 | 6 | 2011-08-27T21:17:28Z | 10,808,908 | 9 | 2012-05-30T01:29:14Z | [
"python",
"windows-7"
] | I am creating diagrams with the turtle package in Python, and it is successful to some extent, except for one problem. Once turtle generates the diagram that I have in code, it causes the program to say "Not responding" and eventually I have to end the task. I am using Windows 7.
Have any of you experienced this or kn... | I had the same problem (I was on Win 7 as well, and I then got the same problem on Win XP), and I just figured it out.
You have to say `turtle.done()` when you're done.
Now that I know this, it makes more sense, because since Python doesn't know that the turtle is done, it's probably waiting for another command for t... |
Query datetime by today's date in Django | 7,217,811 | 12 | 2011-08-27T22:32:19Z | 7,217,923 | 26 | 2011-08-27T23:00:11Z | [
"python",
"django"
] | I'm saving `datetime` in the db for an object. I'd like to query against the db and select anything from todays `date`, not datetime.
What's the easiest way to do this? This doesn't work:
```
invoice_for_today = Invoice.objects.get(user=user, date=date.today())
``` | I remember there being plans to add a `__date` field lookup to make this easier, but as it stands the "standard" way of doing it is
```
today_min = datetime.datetime.combine(datetime.date.today(), datetime.time.min)
today_max = datetime.datetime.combine(datetime.date.today(), datetime.time.max)
Invoice.objects.get(use... |
Query datetime by today's date in Django | 7,217,811 | 12 | 2011-08-27T22:32:19Z | 14,555,676 | 10 | 2013-01-28T04:58:18Z | [
"python",
"django"
] | I'm saving `datetime` in the db for an object. I'd like to query against the db and select anything from todays `date`, not datetime.
What's the easiest way to do this? This doesn't work:
```
invoice_for_today = Invoice.objects.get(user=user, date=date.today())
``` | You can also do something like this:
```
today = date.today()
invoice_for_today = Invoice.objects.filter(date__year=today.year, date__month=today.month, date__day=today.day)
``` |
How to intelligently parse last name | 7,218,310 | 4 | 2011-08-28T00:39:22Z | 7,218,330 | 17 | 2011-08-28T00:44:02Z | [
"python",
"regex",
"parsing",
"nlp"
] | Assuming western naming convention of `FirstName MiddleName(s) LastName`,
What would be the best way to correctly parse out the last name from a full name?
For example:
```
John Smith --> 'Smith'
John Maxwell Smith --> 'Smith'
John Smith Jr --> 'Smith Jr'
John van Damme --> 'van Damme'
John Smith, IV --> 'Smith, IV'... | Probably the best answer here is not to try. Names are individual and idosyncratic and, even limiting yourself to the Western tradition, you can never be sure that you'll have thought of all the edge cases. A friend of mine legally changed his name to be a single word, and he's had a hell of a time dealing with various... |
Django RedirectView and reverse() doesn't work together? | 7,218,453 | 8 | 2011-08-28T01:14:28Z | 7,249,228 | 9 | 2011-08-30T20:14:51Z | [
"python",
"django"
] | I'm having this weird problem.
When I did this:
```
from django.core.urlresolvers import reverse
reverse('account-reco-about-you')
# returns '/accounts/recommendations/about-you/'
```
But when I did this:
```
# Doesn't Work
recommendations = login_required(RedirectView.as_view(url=reverse('account-reco-about-you'))... | This problem is to do with trying to reverse something at import time before the URLs are ready to be reversed. This is not a problem with RedirectView itself - it would happen with anything where you tried to reverse in your urls.py file, or possibly in a file imported by it.
In the development version of Django, the... |
How do you map a fully qualified class name to its class object in Python? | 7,218,865 | 8 | 2011-08-28T03:25:12Z | 7,219,341 | 10 | 2011-08-28T06:10:19Z | [
"python",
"introspection"
] | You can get the fully qualified class name of a Python object like this (see [this question](http://stackoverflow.com/q/2020014/45935)):
```
>>> import Queue
>>> q = Queue.PriorityQueue()
>>> def fullname(o):
return o.__module__ + "." + o.__class__.__name__
...
>>> fullname(q)
'Queue.PriorityQueue'
>>>
```
H... | You can use importlib in 2.7:
```
from importlib import import_module
name = 'xml.etree.ElementTree.ElementTree'
parts = name.rsplit('.', 1)
ElementTree = getattr(import_module(parts[0]), parts[1])
tree = ElementTree()
```
In older versions you can use the [`__import__`](https://docs.python.org/2/library/functions.h... |
Removing rows in NumPy efficiently | 7,218,918 | 2 | 2011-08-28T03:38:41Z | 7,222,092 | 7 | 2011-08-28T16:13:26Z | [
"python",
"numpy"
] | I have a large numpy array with a lot of ID values (call it X):
```
X:
id rating
1 88
2 99
3 77
4 66
...
```
etc. I also have another numpy array of "bad IDs" -- which signify rows I'd like to remove from X.
```
B: [2, 3]
```
So when I'm done, I'd like:
```
X:
id rating
1 88
4 66
```
What is... | This is the fastest way I could come up with:
```
import numpy
x = numpy.arange(1000000, dtype=numpy.int32).reshape((-1,2))
bad = numpy.arange(0, 1000000, 2000, dtype=numpy.int32)
print x.shape
print bad.shape
cleared = numpy.delete(x, numpy.where(numpy.in1d(x[:,0], bad)), 0)
print cleared.shape
```
This prints:
... |
Uses of Python's "from" keyword? | 7,219,082 | 9 | 2011-08-28T04:42:23Z | 7,219,119 | 23 | 2011-08-28T04:57:16Z | [
"python",
"import",
"python-3.x",
"keyword",
"python-2.x"
] | Are there any other uses for Python's "from" keyword aside from `import` statements? | No and yes.
According to the [official Python 2.7.2 grammar](http://docs.python.org/reference/grammar.html), the only occurrence of the word `from` is in the clause `import_from`, so no.
In the [Python 3.1.3 grammar](http://docs.python.org/release/3.1.3/reference/grammar.html) a new clause
```
raise_stmt: 'raise' [t... |
Uses of Python's "from" keyword? | 7,219,082 | 9 | 2011-08-28T04:42:23Z | 7,219,255 | 11 | 2011-08-28T05:39:14Z | [
"python",
"import",
"python-3.x",
"keyword",
"python-2.x"
] | Are there any other uses for Python's "from" keyword aside from `import` statements? | In Python 2.x, the only use of `from` is for the `from x import y` statement. However, for Python 3.x, it can be used in conjunction with the `raise` statement, e.g.:
```
try:
raise Exception("test")
except Exception as e:
raise Exception("another exception") from e
``` |
Uses of Python's "from" keyword? | 7,219,082 | 9 | 2011-08-28T04:42:23Z | 7,267,871 | 9 | 2011-09-01T08:35:56Z | [
"python",
"import",
"python-3.x",
"keyword",
"python-2.x"
] | Are there any other uses for Python's "from" keyword aside from `import` statements? | There is a new [syntax for delegating to a subgenerator](http://www.python.org/dev/peps/pep-0380/) in Python 3.3 which uses the `from` keyword. |
Python and BeautifulSoup encoding issues | 7,219,361 | 16 | 2011-08-28T06:18:10Z | 7,222,658 | 12 | 2011-08-28T17:38:45Z | [
"python",
"unicode",
"utf-8",
"beautifulsoup"
] | I'm writing a crawler with Python using BeautifulSoup, and everything was going swimmingly till I ran into this site:
<http://www.elnorte.ec/>
I'm getting the contents with the requests library:
```
r = requests.get('http://www.elnorte.ec/')
content = r.content
```
If I do a print of the content variable at that po... | could you try:
```
r = urllib.urlopen('http://www.elnorte.ec/')
x = BeautifulSoup.BeautifulSoup(r.read)
r.close()
print x.prettify('latin-1')
```
I get the correct output.
Oh, in this special case you could also `x.__str__(encoding='latin1')`.
I guess this is because the content is in ISO-8859-1(5) and the meta htt... |
Python and BeautifulSoup encoding issues | 7,219,361 | 16 | 2011-08-28T06:18:10Z | 7,222,936 | 16 | 2011-08-28T18:18:23Z | [
"python",
"unicode",
"utf-8",
"beautifulsoup"
] | I'm writing a crawler with Python using BeautifulSoup, and everything was going swimmingly till I ran into this site:
<http://www.elnorte.ec/>
I'm getting the contents with the requests library:
```
r = requests.get('http://www.elnorte.ec/')
content = r.content
```
If I do a print of the content variable at that po... | In your case this page has wrong utf-8 data which confuses BeautifulSoup and makes it think that your page uses windows-1252, you can do this trick:
```
soup = BeautifulSoup.BeautifulSoup(content.decode('utf-8','ignore'))
```
by doing this you will discard any wrong symbols from the page source and BeautifulSoup will... |
What's the difference between io.open() and os.open() on Python? | 7,219,511 | 25 | 2011-08-28T07:03:07Z | 7,219,535 | 24 | 2011-08-28T07:10:37Z | [
"python",
"module",
"io",
"operating-system"
] | I realised that the `open()` function I've been using was an alias to `io.open()` and that importing `*` from `os` would overshadow that.
What's the difference between opening files through the `io` module and `os` module? | `io.open()` is the preferred, higher-level interface to file I/O. It wraps the OS-level file descriptor in an object that you can use to access the file in a Pythonic manner.
`os.open()` is just a wrapper for the lower-level POSIX syscall. It takes less symbolic (and more POSIX-y) arguments, and returns the file descr... |
What is the difference between semicolons in JavaScript and in Python? | 7,219,541 | 57 | 2011-08-28T07:12:05Z | 7,219,549 | 68 | 2011-08-28T07:13:51Z | [
"javascript",
"python",
"syntax"
] | Python and JavaScript both allow developers to use or to omit semicolons. However, I've often seen it suggested (in books and blogs) that I should not use semicolons in Python, while I should always use them in JavaScript.
Is there a technical difference between how the languages use semicolons or is this just a cultu... | Semicolons in Python are totally optional (unless you want to have multiple statements in a single line, of course). I personally think Python code with semicolons at the end of every statement looks very ugly.
Now in Javascript, if you don't write a semicolon, one is automatically inserted1 at the end of line. And th... |
What is the difference between semicolons in JavaScript and in Python? | 7,219,541 | 57 | 2011-08-28T07:12:05Z | 7,219,779 | 62 | 2011-08-28T08:15:27Z | [
"javascript",
"python",
"syntax"
] | Python and JavaScript both allow developers to use or to omit semicolons. However, I've often seen it suggested (in books and blogs) that I should not use semicolons in Python, while I should always use them in JavaScript.
Is there a technical difference between how the languages use semicolons or is this just a cultu... | This had me confused for the longest time. I thought it was just a cultural difference, and that everyone complaining about semicolon insertion being the worst feature in the language was an *idiot*. The oft-repeated example from [NullUserException's answer](http://stackoverflow.com/q/7219549/1114) didn't sway me becau... |
Is it normal behaviour for python? | 7,220,555 | 3 | 2011-08-28T11:07:09Z | 7,220,564 | 12 | 2011-08-28T11:08:42Z | [
"python",
"list",
"dictionary"
] | In the latest Python (3.2):
```
>>> l = [{}]*2
>>> l[1]['key'] = 'value'
>>> l
[{'key': 'value'}, {'key': 'value'}]
```
I expected l to be `[{}, {'key': 'value'}]` after this operation. Is it normal behaviour or a bug? | Normal. Try using `l = [{} for x in range(2)]` instead.
`[{}]*2` does not actually make 2 different dictionaries - it makes a list with two references to the same dictionary. Thus, updating that dictionary makes changes show up for both items in the list, because both items are actually the same dictionary, just refer... |
Get lat/long given current point, distance and bearing | 7,222,382 | 29 | 2011-08-28T16:56:14Z | 7,835,325 | 30 | 2011-10-20T11:34:51Z | [
"python",
"gis",
"distance",
"latitude-longitude"
] | Given an existing point in lat/long, distance in (in KM) and bearing (in degrees converted to radians), I would like to calculate the new lat/long. [This](http://www.movable-type.co.uk/scripts/latlong.html) site crops up over and over again, but I just can't get the formula to work for me.
The formulas as taken the ab... | Needed to convert answers from radians back to degrees. Working code below:
```
import math
R = 6378.1 #Radius of the Earth
brng = 1.57 #Bearing is 90 degrees converted to radians.
d = 15 #Distance in km
#lat2 52.20444 - the lat result I'm hoping for
#lon2 0.36056 - the long result I'm hoping for.
lat1 = math.rad... |
Get lat/long given current point, distance and bearing | 7,222,382 | 29 | 2011-08-28T16:56:14Z | 9,869,013 | 11 | 2012-03-26T08:44:05Z | [
"python",
"gis",
"distance",
"latitude-longitude"
] | Given an existing point in lat/long, distance in (in KM) and bearing (in degrees converted to radians), I would like to calculate the new lat/long. [This](http://www.movable-type.co.uk/scripts/latlong.html) site crops up over and over again, but I just can't get the formula to work for me.
The formulas as taken the ab... | The [geopy](http://code.google.com/p/geopy/) library supports this:
```
import geopy
from geopy.distance import VincentyDistance
# given: lat1, lon1, b = bearing in degrees, d = distance in kilometers
origin = geopy.Point(lat1, lon1)
destination = VincentyDistance(kilometers=d).destination(origin, b)
lat2, lon2 = d... |
Default constructor parameters in pyyaml | 7,224,033 | 7 | 2011-08-28T21:22:51Z | 7,227,326 | 8 | 2011-08-29T07:32:28Z | [
"python",
"yaml",
"pyyaml"
] | I haven't been able to find out how to do this in the PyYAML documentation. I want to represent python classes I've defined in YAML, and have a default value given to a parameter in the constructor if it's not specified in the YAML. For example:
```
>>> class Test(yaml.YAMLObject):
... yaml_tag = u"!Test"
... ... | I encountered the same problem: yaml\_tag doesn't work for some reason. So I used alternative approach:
```
import yaml
def constructor(loader, node) :
fields = loader.construct_mapping(node)
return Test(**fields)
yaml.add_constructor('!Test', constructor)
class Test(object) :
def __init__(self, foo, ba... |
What is PyMySQL and how does it differ from MySQLdb? Can it affect Django deployment? | 7,224,807 | 28 | 2011-08-28T23:49:18Z | 7,224,851 | 8 | 2011-08-28T23:57:44Z | [
"python",
"mysql",
"django",
"mysql-python",
"pymysql"
] | I just solved some problems in my Django 1.3 app by using PyMySQL instead of MySQLdb. I followed this tutorial on how to make the switch: <http://web-eng-help.blogspot.com/2010/09/install-mysql-5-for-python-26-and.html>
Now I want to know what PyMySQL actually is and how it is different from MySQLdb.
I am using it on... | PyMySQL and MySQLdb are both database connectors for Python, libraries to enable Python programs to talk to a MySQL server.
You would normally never upload core Django files when deploying an app. If Django is working fine on your deployment server, you definitely don't need to change anything there. The DB driver is ... |
What is PyMySQL and how does it differ from MySQLdb? Can it affect Django deployment? | 7,224,807 | 28 | 2011-08-28T23:49:18Z | 7,224,982 | 8 | 2011-08-29T00:26:12Z | [
"python",
"mysql",
"django",
"mysql-python",
"pymysql"
] | I just solved some problems in my Django 1.3 app by using PyMySQL instead of MySQLdb. I followed this tutorial on how to make the switch: <http://web-eng-help.blogspot.com/2010/09/install-mysql-5-for-python-26-and.html>
Now I want to know what PyMySQL actually is and how it is different from MySQLdb.
I am using it on... | Your first point:
According to [pymysql wiki](http://code.google.com/p/pymysql/wiki/Goals) page:
> MySQLdb, is a C extension module that has a reputation of being
> difficult to compile, especially if you're on a Mac. Additionally,
> end-users need to wait for new binaries to be compiled for each new
> release of Pyt... |
What is PyMySQL and how does it differ from MySQLdb? Can it affect Django deployment? | 7,224,807 | 28 | 2011-08-28T23:49:18Z | 14,076,841 | 37 | 2012-12-28T22:58:31Z | [
"python",
"mysql",
"django",
"mysql-python",
"pymysql"
] | I just solved some problems in my Django 1.3 app by using PyMySQL instead of MySQLdb. I followed this tutorial on how to make the switch: <http://web-eng-help.blogspot.com/2010/09/install-mysql-5-for-python-26-and.html>
Now I want to know what PyMySQL actually is and how it is different from MySQLdb.
I am using it on... | PyMySQL and MySQLdb provide the same functionality - they are both database connectors. The difference is in the implementation where MySQLdb is a C extension and PyMySQL is pure Python.
There are a few reasons to try PyMySQL:
* it might be easier to get running on some systems
* it works with PyPy
* it can be "green... |
Python: maximum recursion depth | 7,225,106 | 2 | 2011-08-29T00:51:27Z | 7,225,139 | 8 | 2011-08-29T01:00:58Z | [
"python",
"recursion"
] | A function for returning sum of the sizes of its arguments which could be single file/directory or a list of files/directories, is given below. The code gives an error message `RuntimeError: maximum recursion depth exceeded while calling a Python object` however I try to test this.
How to fix this?
Thanks
suresh
``... | Instead of writing your own adhoc directory-transversal method, use the built-in `os.walk` [(Documentation)](http://docs.python.org/library/os.html#os.walk) method.
In fact, the example in the documentation (link above) computes the total size of non-directory files. |
Testing divisibility by multiple numbers | 7,225,168 | 3 | 2011-08-29T01:06:49Z | 7,225,218 | 7 | 2011-08-29T01:16:24Z | [
"python",
"python-3.x"
] | In Python, is there a way to test if a number is divisible by multiple numbers without writing out the modulo operation for each factor?
More specifically, is there a better way to write this code instead of typing i % n == 0 ninety times?
```
if i % 11 == 0 and i % 12 == 0 and i % 13 == 0 ... and i % 100 == 0:
p... | Use`all()`and a Generator Expression:
```
if all(i % n == 0 for n in range(11, 101)):
print(i)
``` |
How to pip install packages according to requirements.txt from a local directory? | 7,225,900 | 385 | 2011-08-29T03:53:04Z | 10,429,168 | 165 | 2012-05-03T10:04:39Z | [
"python",
"virtualenv",
"pip"
] | Here is the problem
I have a requirements.txt that looks like:
```
BeautifulSoup==3.2.0
Django==1.3
Fabric==1.2.0
Jinja2==2.5.5
PyYAML==3.09
Pygments==1.4
SQLAlchemy==0.7.1
South==0.7.3
amqplib==0.6.1
anyjson==0.3
...
```
I have a local archive directory containing all the packages + others.
I have created a new vi... | This works for me:
```
$ pip install -r requirements.txt --no-index --find-links file:///tmp/packages
``` |
How to pip install packages according to requirements.txt from a local directory? | 7,225,900 | 385 | 2011-08-29T03:53:04Z | 15,593,865 | 605 | 2013-03-24T00:47:43Z | [
"python",
"virtualenv",
"pip"
] | Here is the problem
I have a requirements.txt that looks like:
```
BeautifulSoup==3.2.0
Django==1.3
Fabric==1.2.0
Jinja2==2.5.5
PyYAML==3.09
Pygments==1.4
SQLAlchemy==0.7.1
South==0.7.3
amqplib==0.6.1
anyjson==0.3
...
```
I have a local archive directory containing all the packages + others.
I have created a new vi... | I've read the above, realize this is an old question, but it's totally unresolved and still at the top of my google search results so here's an answer that works for everyone:
```
pip install -r /path/to/requirements.txt
``` |
How to pip install packages according to requirements.txt from a local directory? | 7,225,900 | 385 | 2011-08-29T03:53:04Z | 22,046,133 | 77 | 2014-02-26T15:38:12Z | [
"python",
"virtualenv",
"pip"
] | Here is the problem
I have a requirements.txt that looks like:
```
BeautifulSoup==3.2.0
Django==1.3
Fabric==1.2.0
Jinja2==2.5.5
PyYAML==3.09
Pygments==1.4
SQLAlchemy==0.7.1
South==0.7.3
amqplib==0.6.1
anyjson==0.3
...
```
I have a local archive directory containing all the packages + others.
I have created a new vi... | For virtualenv to install all files in the requirements.txt file.
1. cd to the directory where requirements.txt is located
2. activate your virtualenv
3. run: `pip install -r requirements.txt` in your shell |
How to pip install packages according to requirements.txt from a local directory? | 7,225,900 | 385 | 2011-08-29T03:53:04Z | 32,709,817 | 7 | 2015-09-22T06:27:07Z | [
"python",
"virtualenv",
"pip"
] | Here is the problem
I have a requirements.txt that looks like:
```
BeautifulSoup==3.2.0
Django==1.3
Fabric==1.2.0
Jinja2==2.5.5
PyYAML==3.09
Pygments==1.4
SQLAlchemy==0.7.1
South==0.7.3
amqplib==0.6.1
anyjson==0.3
...
```
I have a local archive directory containing all the packages + others.
I have created a new vi... | Often, you will want a fast install from local archives, without probing PyPI.
First, download the archives that fulfill your requirements:
```
$ pip install --download <DIR> -r requirements.txt
```
Then, install using `âfind-links` and `âno-index`:
```
$ pip install --no-index --find-links=[file://]<DIR> -r re... |
How to pip install packages according to requirements.txt from a local directory? | 7,225,900 | 385 | 2011-08-29T03:53:04Z | 34,969,495 | 25 | 2016-01-23T22:08:58Z | [
"python",
"virtualenv",
"pip"
] | Here is the problem
I have a requirements.txt that looks like:
```
BeautifulSoup==3.2.0
Django==1.3
Fabric==1.2.0
Jinja2==2.5.5
PyYAML==3.09
Pygments==1.4
SQLAlchemy==0.7.1
South==0.7.3
amqplib==0.6.1
anyjson==0.3
...
```
I have a local archive directory containing all the packages + others.
I have created a new vi... | I had a similar problem. I tried this:
```
pip install -U -r requirements.txt
```
*(-U = update if it had already installed)*
But the problem continued. I realized that some of generic libraries for development were missed.
```
sudo apt-get install libtiff5-dev libjpeg8-dev zlib1g-dev liblcms2-dev libwebp-dev tcl8.... |
South: run a migration for a column that is both unique and not null | 7,226,036 | 15 | 2011-08-29T04:23:10Z | 7,226,563 | 13 | 2011-08-29T05:51:32Z | [
"python",
"django",
"django-models",
"django-south"
] | Using South/Django, I am running into a problem where I'm trying to add a `UNIQUE` and `NOT NULL` column for a model with existing rows in the database. South prompts me to specify a default for the column, since it is `NOT NULL`. But since it also has a `UNIQUE` constraint, I can't add a default to the field in models... | Yes, this is the approach you should take. You should be doing schemamigration -> datamigration -> schemamigration for this. unfortunately if there is no way to do it in SQL, south cannot do it either. |
Python+Tornado vs Scala+Lift? | 7,227,850 | 12 | 2011-08-29T08:33:54Z | 7,286,848 | 13 | 2011-09-02T17:00:10Z | [
"python",
"scala",
"comet",
"lift",
"tornado"
] | I'm looking to start a Google Maps based web application.
My initial thoughts are that in the first phase the focus should be on the front-end, and the backend should be easy to write and to prototype, and should aid as much as possible the development of the frontend.
There will be no 'classic' pages, just a meebo.co... | I think Python and Tornado are a great team, for the following reasons
* Tornado is really an IOLoop that happens to come with an HTTP implementation that runs on it (and a few helpers).
This means that it comes with everything you need to do *web* development with it.
It also means that if you find, down the road, ... |
permission change of files in python | 7,228,296 | 7 | 2011-08-29T09:22:29Z | 7,228,338 | 15 | 2011-08-29T09:28:14Z | [
"python"
] | I want to change the file permission for all the files from my current directory tree. I am trying to open each directory and open the files and change the permission using `os.chmod()`, But getting an error.
```
import os
import stat
for files in os.walk('.'):
os.chmod(files,stat.S_IXGRP)
```
The error I ge... | You are using `os.walk` incorrectly.
```
for dirpath, dirnames, filenames in os.walk('.'):
for filename in filenames:
path = os.path.join(dirpath, filename)
os.chmod(path, 0o777) # for example
``` |
How to find the shortest string in a list in Python | 7,228,924 | 15 | 2011-08-29T10:30:11Z | 7,228,951 | 44 | 2011-08-29T10:33:32Z | [
"python"
] | This seems like a pretty simple problem, but I'm looking for a short and sweet way of doing it that is still understandable (this isn't code golf).
Given a list of strings, what's the easiest way to find the shortest string?
The way that is most obvious to me is roughly:
```
l = [...some strings...]
lens = map(l, le... | [The `min` function](http://docs.python.org/library/functions.html#min) has an optional parameter `key` that lets you specify a function to determine the "sorting value" of each item. We just need to set this to [the `len` function](http://docs.python.org/library/functions.html#len) to get the shortest value:
```
stri... |
2D grid data visualization in Python | 7,229,971 | 17 | 2011-08-29T12:18:27Z | 7,230,449 | 8 | 2011-08-29T13:02:28Z | [
"python",
"colors",
"grid",
"visualization",
"gradient"
] | I need to visualize some data. It's basic 2D grid, where each cell have float value. I know how to e.g. assign color to value and paint grid in OpenCV. But the point here is that there are so many values so it's nearly impossible to do that. I am looking for some method, where I could use gradient. For example value -5... | How about using matplotlib?
```
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FixedLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = Axes3D(fig)
Z = np.array([[-1.045, 2.0, 3.5, -4.890],
... |
2D grid data visualization in Python | 7,229,971 | 17 | 2011-08-29T12:18:27Z | 7,230,921 | 31 | 2011-08-29T13:38:59Z | [
"python",
"colors",
"grid",
"visualization",
"gradient"
] | I need to visualize some data. It's basic 2D grid, where each cell have float value. I know how to e.g. assign color to value and paint grid in OpenCV. But the point here is that there are so many values so it's nearly impossible to do that. I am looking for some method, where I could use gradient. For example value -5... | [Matplotlib](http://matplotlib.sourceforge.net/users/image_tutorial.html) has the `imshow` method for plotting arrays:
```
from matplotlib import mpl,pyplot
import numpy as np
# make values from -5 to 5, for this example
zvals = np.random.rand(100,100)*10-5
# make a color map of fixed colors
cmap = mpl.colors.Listed... |
What method calls `__init__()` in Python classes | 7,230,636 | 11 | 2011-08-29T13:18:05Z | 7,230,800 | 7 | 2011-08-29T13:30:34Z | [
"python",
"class",
"methods"
] | I was wondering how `__init__()` methods get called. Does `__new__()` calls it, or `__call__()` calls it after it created an instance with `__new__()`, or some other way? | Python determines whether [\_\_new\_\_()](http://docs.python.org/reference/datamodel.html#object.__new__) should call \_\_init\_\_():
> If \_\_new\_\_() returns an instance of cls, then the new instanceâs \_\_init\_\_() method will be invoked like \_\_init\_\_(self[, ...]), where self is the new instance and the rem... |
How to replace values at specific indexes of a python list? | 7,231,204 | 4 | 2011-08-29T14:04:36Z | 7,231,371 | 7 | 2011-08-29T14:19:03Z | [
"python",
"slice"
] | I got a list, say
```
s = [5,4,3,2,1,0]
```
and I got another 2 lists, say
```
a = [0,1,3,5]; m = [0,0,0,0]
```
What I want to is take `a`'s elements as index to `s`, then set corresponding elements in `a` to `m`, i.e. after running, `s` should be `[0,0,3,0,1,0]`.
Apparently, I can do this through a for loop:
```... | The biggest problem with your code is that it's unreadable. Python code rule number one, if it's not readable, no one's gonna look at it for long enough to get any useful information out of it. Always use descriptive variable names. Almost didn't catch the bug in your code, let's see it again with good names, slow-moti... |
How do I set custom HTML attributes in django forms? | 7,231,551 | 13 | 2011-08-29T14:33:58Z | 7,231,698 | 16 | 2011-08-29T14:45:05Z | [
"python",
"html",
"django",
"forms",
"custom-attributes"
] | I have a Django form that is part of page. Lets say I have a field:
```
search_input = forms.CharField(_(u'Search word'), required=False)
```
I can access it only in template via `{{ form.search_input }}`. How to set custom HTML attrs (such as name and value)? I would like to find flexible solution, that would allow ... | You can change the widget on the CharField to achieve the effect you are looking for.
```
search_input = forms.CharField(_(u'Search word'), required=False)
search_input.widget = forms.TextInput(attrs={'size': 10, 'title': 'Search',})
``` |
How do I set custom HTML attributes in django forms? | 7,231,551 | 13 | 2011-08-29T14:33:58Z | 7,231,962 | 7 | 2011-08-29T15:05:59Z | [
"python",
"html",
"django",
"forms",
"custom-attributes"
] | I have a Django form that is part of page. Lets say I have a field:
```
search_input = forms.CharField(_(u'Search word'), required=False)
```
I can access it only in template via `{{ form.search_input }}`. How to set custom HTML attrs (such as name and value)? I would like to find flexible solution, that would allow ... | You can also try this:
```
search_input = forms.CharField(_(u'Search word'), required=False, widget= forms.TextInput(attrs={'size': 10, 'title': 'Search',}))
``` |
Best practices for Python deployment -- multiple versions, standard install locations, packaging tools etc | 7,232,061 | 17 | 2011-08-29T15:12:38Z | 7,262,808 | 8 | 2011-08-31T20:11:04Z | [
"python",
"virtualenv",
"distutils",
"pip",
"multiple-versions"
] | Many posts on different aspects of this question but I haven't seen a post that brings it all together.
First a subjective statement: it seems like the simplicity we experience when working with the Python language is shot to pieces when we move outside the interpreter and start grappling with deployment issues. How b... | I've found that [virtualenv](http://pypi.python.org/pypi/virtualenv) is the only reliable way to configure and maintain multiple environments on the same machine. It even has as a way of packaging up environment and installing it on another machine.
For package management I always use [pip](http://pypi.python.org/pypi... |
Python: "subject" not shown when sending email using smtplib module | 7,232,088 | 22 | 2011-08-29T15:14:45Z | 7,232,181 | 45 | 2011-08-29T15:23:19Z | [
"python",
"smtplib"
] | I am successfully able to send email using the smtplib module. But when the emial is sent, it does not include the subject in the email sent.
```
import smtplib
SERVER = <localhost>
FROM = <from-address>
TO = [<to-addres>]
SUBJECT = "Hello!"
message = "Test"
TEXT = "This message was sent with Python's smtplib."
s... | Attach it as a header:
```
message = 'Subject: %s\n\n%s' % (SUBJECT, TEXT)
```
and then:
```
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()
```
Also consider using standard Python module [`email`](http://docs.python.org/library/email) - it will help you a lot while composing emails. |
Is there a way to add Python to Visual Studio 2010 Express (the free version)? | 7,232,629 | 7 | 2011-08-29T16:03:18Z | 7,232,682 | 10 | 2011-08-29T16:07:26Z | [
"python",
"visual-studio-2010",
"visual-studio-express"
] | Seems like Python can be easily integrated in Visual Studio 2010, I found various articles and the relative plugin needed.
I doesn't work for my VS 2010 Express though. I doubt it only works for the commercial version.
Is there some other way to enable the Python language in VS 2010 Express? | Express doesn't allow you to install extensions like IronPython Tools (which I assume you're talking about?).
Luckily according to [this](http://lists.ironpython.com/pipermail/users-ironpython.com/2010-May/012760.html) they have a standalone variant that works with the VS shell, which can be downloaded [here](http://w... |
What is the proper way to track indexes in python? | 7,233,575 | 10 | 2011-08-29T17:29:02Z | 7,233,597 | 17 | 2011-08-29T17:30:45Z | [
"python",
"indexing",
"lookup"
] | Right now I am tracking my index in side the loop like this
```
index = 0
for entry in longList:
if entry == 'foo':
print index
index += 1
```
is there a better way to do this? | ```
for index, entry in enumerate(longList):
if entry == 'foo':
print index
``` |
What is the proper way to track indexes in python? | 7,233,575 | 10 | 2011-08-29T17:29:02Z | 7,233,605 | 10 | 2011-08-29T17:31:29Z | [
"python",
"indexing",
"lookup"
] | Right now I am tracking my index in side the loop like this
```
index = 0
for entry in longList:
if entry == 'foo':
print index
index += 1
```
is there a better way to do this? | Use the `enumerate()` built-in function.
```
for index, entry in enumerate(longList):
if entry == 'foo':
print index
```
However, in your specific case, you can simply do `index = longList.index("foo")`
**EDIT**: If you want to find the indices of multiple matches pretty much as fast as is possible in pu... |
checking a Python dictionary for specific keys | 7,234,734 | 6 | 2011-08-29T19:14:48Z | 7,234,750 | 12 | 2011-08-29T19:16:21Z | [
"python"
] | There are several different ways to check if a Python dictionary contains a specific key, i.e.
```
d = {}
if key in d:
if d.contains(key):
if d.has_key(key):
```
it's silly for a language to allow you to do the same thing several different ways, UNLESS, each of the methods was doing something entirely different. C... | They're all the same and they're all around for historical reasons, but you [should use](http://docs.python.org/library/stdtypes.html#dict.has_key) `key in d`. |
checking a Python dictionary for specific keys | 7,234,734 | 6 | 2011-08-29T19:14:48Z | 7,234,799 | 7 | 2011-08-29T19:20:18Z | [
"python"
] | There are several different ways to check if a Python dictionary contains a specific key, i.e.
```
d = {}
if key in d:
if d.contains(key):
if d.has_key(key):
```
it's silly for a language to allow you to do the same thing several different ways, UNLESS, each of the methods was doing something entirely different. C... | Method #1 is the accepted way to do it. Method #2 doesn't actually exist, at least in any versions of Python that I'm aware of; I'd be interested to see where you found that. Method #3 used to be the accepted way, but is now [deprecated](http://docs.python.org/library/stdtypes.html#dict.has_key).
So there really is ju... |
Local Variable referenced before assignment | 7,234,881 | 4 | 2011-08-29T19:29:21Z | 7,234,908 | 11 | 2011-08-29T19:31:28Z | [
"python",
"django",
"django-models",
"django-views"
] | I was wondering if you guys could help. I'm trying to do a simple view where it sends the user to the client creation form, but I keep getting this error:
> local variable 'form' referenced before assignment
Looking at my code, I can't see whats wrong.
```
def add_client(request):
user = request.user
if requ... | This is what is happening:
1. The `if` block is not being entered.
2. The `form` variable is not defined.
3. You then attempt to refer to the `form` variable in the `return` statement.
As to how to fix it, that's really for you to decide. What the fix is depends on what you want your code to do in case the request me... |
Local Variable referenced before assignment | 7,234,881 | 4 | 2011-08-29T19:29:21Z | 7,235,126 | 7 | 2011-08-29T19:51:14Z | [
"python",
"django",
"django-models",
"django-views"
] | I was wondering if you guys could help. I'm trying to do a simple view where it sends the user to the client creation form, but I keep getting this error:
> local variable 'form' referenced before assignment
Looking at my code, I can't see whats wrong.
```
def add_client(request):
user = request.user
if requ... | You almost certainly want to de-indent this part:
```
else:
form = AddClientForm()
```
That is, on the initial GET of the page, use a blank client form, then when the page is POSTed, use the request POST data to fill in the form object. |
How to implement a long-running, event-driven python program? | 7,237,106 | 8 | 2011-08-29T23:20:01Z | 7,237,189 | 7 | 2011-08-29T23:32:02Z | [
"python"
] | I have a series of maintenance tasks for a python WSGI application that are a bit too complex for a crontab (jobs need to be run at frequencies derived from the size of the job queue, manage a connection pool to a group of EC2 instances, etc).
How should I implement a long-running, event-driven python program? I've ne... | Most of the large, modern python sites are using [Celery](http://celeryproject.org/) for this type of work. It is a distributed task queue that supports scheduling of tasks as well.
Though probably a bit heavyweight for a small site, it'll grow with you. I'm looking to implement it myself (sans Rabbit) shortly.
I rec... |
python 2 instead of python 3 as the (temporary) default python? | 7,237,415 | 17 | 2011-08-30T00:10:17Z | 7,237,433 | 7 | 2011-08-30T00:13:43Z | [
"python"
] | on my computer
```
~$ python -V
Python 3.2.1
```
but I get into problems when I run some python programs. my guess is (or at least I want to try this) that there is some backward compatibility issues, and I want to run those python scripts with
```
python2 2.7.2-2
```
which is also installed on my system but I do... | Just call the script using something like python2.7 or python2 instead of just python.
So:
```
python2 myscript.py
```
instead of:
```
python myscript.py
```
What you could alternatively do is to replace the symbolic link "python" in /usr/bin which currently links to python3 with a link to the required python2/2.x... |
python 2 instead of python 3 as the (temporary) default python? | 7,237,415 | 17 | 2011-08-30T00:10:17Z | 7,237,949 | 34 | 2011-08-30T01:57:41Z | [
"python"
] | on my computer
```
~$ python -V
Python 3.2.1
```
but I get into problems when I run some python programs. my guess is (or at least I want to try this) that there is some backward compatibility issues, and I want to run those python scripts with
```
python2 2.7.2-2
```
which is also installed on my system but I do... | You can use [virtualenv](http://pypi.python.org/pypi/virtualenv)
```
# Use this to create your temporary python "install"
# (Assuming that is the correct path to the python interpreter you want to use.)
virtualenv -p /usr/bin/python2.7 --distribute temp-python
# Type this command when you want to use your temporary p... |
Python ElementTree support for parsing unknown XML entities? | 7,237,466 | 14 | 2011-08-30T00:17:39Z | 7,265,260 | 9 | 2011-09-01T01:26:31Z | [
"python",
"xml",
"openstreetmap"
] | I have a set of super simple XML files to parse... but... they use custom defined entities. I don't need to map these to characters, but I do wish to parse and act on each one. For example:
```
<Style name="admin-5678">
<Rule>
<Filter>[admin_level]='5'</Filter>
&maxscale_zoom11;
</Rule>
</Style>
``... | I'm not sure if this is a bug in ElementTree or what, but you need to call UseForeignDTD(True) on the expat parser to behave the way it did in the past.
It's a bit hacky, but you can do this by creating your own instance of ElementTree.Parser, calling the method on it's instance of xml.parsers.expat, and then passing ... |
import win32api error in Python 2.6 | 7,238,403 | 31 | 2011-08-30T03:35:46Z | 7,279,374 | 43 | 2011-09-02T04:56:02Z | [
"python",
"pywin32"
] | When running python26 under windows OS (64bits).....
I have got errors like:
```
import win32api" error in Python 2.6: pywintypes26.dll
```
or
```
pythoncom26.dll missing
ImportError: DLL load failed: The specified module could not be found.
```
I have done the msi installation for python26
all dlls can be found un... | After I move/copy pywintypes26.dll and pythoncom26.dll to c:\Python26\Lib\site-packages\win32 -> Solve the problem! |
import win32api error in Python 2.6 | 7,238,403 | 31 | 2011-08-30T03:35:46Z | 21,564,008 | 21 | 2014-02-04T21:37:35Z | [
"python",
"pywin32"
] | When running python26 under windows OS (64bits).....
I have got errors like:
```
import win32api" error in Python 2.6: pywintypes26.dll
```
or
```
pythoncom26.dll missing
ImportError: DLL load failed: The specified module could not be found.
```
I have done the msi installation for python26
all dlls can be found un... | I also hit a problem importing win32api.
The post-install script for pywin32 failed, which should copy `pythoncom26.dll`, `pythoncomloader26.dll`, and `pywintypes26.dll`, among other things. I ran it by hand and my installation was fixed.
```
python scripts\pywin32_postinstall.py -install
``` |
can't compare datetime.datetime to datetime.date | 7,239,315 | 27 | 2011-08-30T06:08:14Z | 7,239,350 | 27 | 2011-08-30T06:13:21Z | [
"python"
] | I have the following code and am getting the above error. Since I'm new to python I'm having trouble understanding the syntax here and how I can fix the error:
```
if not start or date < start: start = date
``` | There is a `datetime.date()` method for converting from a datetime to a date.
To do the opposite conversion, you could use this function `datetime.datetime(d.year, d.month, d.day)` |
Python data scraping | 7,240,382 | 8 | 2011-08-30T08:11:18Z | 7,242,283 | 10 | 2011-08-30T11:14:31Z | [
"python",
"youtube",
"urllib2",
"scrape"
] | I want to download a couple songs off of <http://www.youtube-mp3.org/>. I'm using urllib2 and [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/).
The problem is that when I urllib2 open the site with my video ID plugged in, <http://www.youtube-mp3.org/?c#v=lV7r8PiuecQ>, I get the site but they are tricky a... | The API is JSON-based, so the contents of the html files won't give you any clue on where to find the files. A good idea when exploring web services like this one, is to open the Network tab in Chrome's developer tools and see what pages it loads when interacting with the page. That exercise showed me that two urls in ... |
How to convert current date to epoch timestamp? | 7,241,170 | 27 | 2011-08-30T09:29:35Z | 7,241,220 | 7 | 2011-08-30T09:34:41Z | [
"python"
] | How to convert current date to epoch timestamp ?
Format current date:
```
29.08.2011 11:05:02
``` | Assuming you are using a 24 hour time format:
```
import time;
t = time.mktime(time.strptime("29.08.2011 11:05:02", "%d.%m.%Y %H:%M:%S"));
``` |
How to convert current date to epoch timestamp? | 7,241,170 | 27 | 2011-08-30T09:29:35Z | 7,241,238 | 41 | 2011-08-30T09:36:30Z | [
"python"
] | How to convert current date to epoch timestamp ?
Format current date:
```
29.08.2011 11:05:02
``` | That should do it
```
import time
date_time = '29.08.2011 11:05:02'
pattern = '%d.%m.%Y %H:%M:%S'
epoch = int(time.mktime(time.strptime(date_time, pattern)))
print epoch
``` |
Asserting successive calls to a mock method | 7,242,433 | 42 | 2011-08-30T11:29:34Z | 7,244,481 | 14 | 2011-08-30T14:02:55Z | [
"python",
"mocking"
] | Mock has a [helpful `assert_called_with()` method](http://www.voidspace.org.uk/python/mock/mock.html#mock.Mock.assert_called_with). However, as far as I understand this only checks the *last* call to a method.
If I have code that calls the mocked method 3 times successively, each time with different parameters, how c... | You can use the [`Mock.call_args_list` attribute](http://www.voidspace.org.uk/python/mock/mock.html#mock.Mock.call_args_list) to compare parameters to previous method calls. That in conjunction with [`Mock.call_count` attribute](http://www.voidspace.org.uk/python/mock/mock.html#mock.Mock.call_count) should give you ful... |
Asserting successive calls to a mock method | 7,242,433 | 42 | 2011-08-30T11:29:34Z | 14,464,608 | 33 | 2013-01-22T17:33:15Z | [
"python",
"mocking"
] | Mock has a [helpful `assert_called_with()` method](http://www.voidspace.org.uk/python/mock/mock.html#mock.Mock.assert_called_with). However, as far as I understand this only checks the *last* call to a method.
If I have code that calls the mocked method 3 times successively, each time with different parameters, how c... | Usually, I don't care about the order of the calls, only that they happened. In that case, I combine [`assert_any_call`](http://www.voidspace.org.uk/python/mock/mock.html#mock.Mock.assert_any_call) with an assertion about [`call_count`](http://www.voidspace.org.uk/python/mock/mock.html#mock.Mock.call_count).
```
>>> i... |
Asserting successive calls to a mock method | 7,242,433 | 42 | 2011-08-30T11:29:34Z | 24,063,759 | 45 | 2014-06-05T15:05:45Z | [
"python",
"mocking"
] | Mock has a [helpful `assert_called_with()` method](http://www.voidspace.org.uk/python/mock/mock.html#mock.Mock.assert_called_with). However, as far as I understand this only checks the *last* call to a method.
If I have code that calls the mocked method 3 times successively, each time with different parameters, how c... | `assert_has_calls` is another approach to this problem.
From the docs:
> **assert\_has\_calls** *(calls, any\_order=False)*
>
> assert the mock has been
> called with the specified calls. The mock\_calls list is checked for
> the calls.
>
> If any\_order is False (the default) then the calls must be sequential.
> The... |
Sort a list of sets | 7,242,821 | 2 | 2011-08-30T12:01:14Z | 7,242,907 | 7 | 2011-08-30T12:09:55Z | [
"python"
] | I have a list of sets on which I want to perform intersection.
Is there an efficient way to sort those sets by length, in order to optimize calculations? | if L is the list of sets
```
sorted(L, key=len, reverse=True)
```
or to sort in place
```
L.sort(key=len, reverse=True)
``` |
Does Python optimize function calls from loops? | 7,243,444 | 16 | 2011-08-30T12:54:25Z | 7,243,559 | 15 | 2011-08-30T13:04:04Z | [
"python",
"optimization",
"compiler-optimization"
] | Say, I have a code which calls some function millions time from loop and I want the code to be fast:
```
def outer_function(file):
for line in file:
inner_function(line)
def inner_function(line):
# do something
pass
```
It's not necessarily a file processing, it could be for example a function dr... | Python does not inline function calls, because of its dynamic nature. Theoretically, `inner_function` can do something that re-binds the name `inner_function` to something else - Python has no way to know at compile time this might happen. For example:
```
def func1():
global inner_func
inner_func = func2
... |
Does Python optimize function calls from loops? | 7,243,444 | 16 | 2011-08-30T12:54:25Z | 7,243,564 | 12 | 2011-08-30T13:04:40Z | [
"python",
"optimization",
"compiler-optimization"
] | Say, I have a code which calls some function millions time from loop and I want the code to be fast:
```
def outer_function(file):
for line in file:
inner_function(line)
def inner_function(line):
# do something
pass
```
It's not necessarily a file processing, it could be for example a function dr... | *Which* Python? PyPy's JIT-compiler will - after a few hundred or dozen (depends on how many opcodes are executed on each iteration) iterations or so - start tracing execution, forget about Python function calls along the way, and compile the gathered information into a piece of optimized machine code which likely does... |
Download file from web in Python 3 | 7,243,750 | 86 | 2011-08-30T13:16:18Z | 7,244,263 | 172 | 2011-08-30T13:49:09Z | [
"python",
"python-3.x"
] | I am creating a program that will download a .jar (java) file from a web server, by reading the URL that is specified in the .jad file of the same game/application. I'm using Python 3.2.1
I've managed to extract the URL of the JAR file from the JAD file (every JAD file contains the URL to the JAR file), but as you may... | If you want to obtain the contents of a web page into a variable, just `read` the response of [**`urllib.request.urlopen`**](http://docs.python.org/dev/library/urllib.request.html#urllib.request.urlopen):
```
import urllib.request
...
url = 'http://example.com/'
response = urllib.request.urlopen(url)
data = response.r... |
Download file from web in Python 3 | 7,243,750 | 86 | 2011-08-30T13:16:18Z | 34,964,610 | 10 | 2016-01-23T14:21:13Z | [
"python",
"python-3.x"
] | I am creating a program that will download a .jar (java) file from a web server, by reading the URL that is specified in the .jad file of the same game/application. I'm using Python 3.2.1
I've managed to extract the URL of the JAR file from the JAD file (every JAD file contains the URL to the JAR file), but as you may... | I use `requests` package whenever I want something related to HTTP requests because its API is very easy to start with:
first install `requests`
```
pip install requests
```
then the code:
```
from requests import get # to make GET request
def download(url, file_name):
# open in binary mode
with open(fil... |
Appengine: put_async doesn't work (at least in the development server)? | 7,244,081 | 7 | 2011-08-30T13:38:45Z | 7,250,613 | 14 | 2011-08-30T22:36:32Z | [
"python",
"google-app-engine",
"gae-datastore"
] | **NOTE**:
IT DOES WORK IN PRODUCTION. I MEAN, WHEN I UPLOAD THE APPLICATION IT JUST WORKS FINE. THE PROBLEM IS IN THE DEVELOPMENT SERVER.
Here is some code that can show you what i'm trying to do:
```
e = Employee(key_name = 'some_key_name',name='John Bonham')
db.put_async(e)
```
If i do it, and after some time i tr... | If you don't call `.wait()` or `.get_result()` on an RPC, there is no way to guarantee it's completed. In the case of the `dev_appserver`, which is not multi-threaded, the actual work is done when you call those methods - it's not actually asynchronous in development, only in production. |
python equivalent of perl hmac_sha1_hex | 7,245,157 | 2 | 2011-08-30T14:52:02Z | 7,245,222 | 9 | 2011-08-30T14:57:09Z | [
"python",
"perl",
"sha1",
"hmac"
] | i need to reproduce in python what perl does
```
# perl
perl -e'use Digest::HMAC_SHA1 qw(hmac_sha1_hex); my $hmac = hmac_sha1_hex("string1", "string2"); print $hmac . "\n";'
25afd2da17e81972b535d15ebae464e291fb3635
#python
python -c 'import sha; import hmac; print hmac.new("string1", "string2", sha).hexdig... | Python's HMAC constructor just takes the key and the message in the opposite order -- Python's `hmac` takes the key first, Perl's `Digest::HMAC` takes the key second.
```
python -c 'import sha; import hmac; print hmac.new("string2", "string1", sha).hexdigest()'
25afd2da17e81972b535d15ebae464e291fb3635
```
Matches you... |
python doctest exception test handling | 7,245,698 | 4 | 2011-08-30T15:27:16Z | 7,247,412 | 7 | 2011-08-30T17:38:43Z | [
"python",
"testing",
"qa",
"doctest"
] | I have the following contents in a file called `test2.txt`.
```
>>> def faulty():
... yield 5
... return 7
Traceback(most recent call last):
SyntaxError: 'return' with argument inside generator(<doctest test.txt[0]>,line 3)
```
I invoke the test run with `python -m test2.txt`. The results below are quite out ... | doctest is extremely careful with the format of expected exceptions. You missed a space:
`Traceback(most recent call last):` should be `Traceback (most recent call last):`
Moreover, this would still fail, as your traceback message is overly specific (and also has incorrect whitespace)! Use the `ELLIPSIS` or `IGNORE_E... |
Delete or remove last column in CSV file using Python | 7,245,738 | 5 | 2011-08-30T15:29:56Z | 7,245,768 | 11 | 2011-08-30T15:32:03Z | [
"python",
"csv"
] | I have a CSV file with 5 columns. Using Python, how can I delete the last column (header5 in the example)? Is there an easy way I'm missing, or do I have to loop through all rows in the CSV and remove each value from the last column (which could still leave me with the undesired preceding comma)?
I'm not seeing anythi... | Use the [csv module](http://file:///usr/share/doc/python2.6/html/library/csv.html#module-csv). When writing out a row, use `row[:-1]` to chop off the last item:
```
import csv
with open(filename,"r") as fin:
with open(outname,"w") as fout:
writer=csv.writer(fout)
for row in csv.reader(fin):
... |
Python - String to list | 7,245,827 | 2 | 2011-08-30T15:36:44Z | 7,245,952 | 9 | 2011-08-30T15:46:43Z | [
"python",
"string",
"list",
"serialization"
] | I need cast a list to a string and get back the string to a list. There's a python way to make this behavior?
```
l1 = ['aa','bb','cc']
s = str(l1)
l2 = cast_string_to_list(s)
print l2
"['aa','bb','cc']"
``` | Use a serialization library like `json`:
```
import json
l1 = ['aa','bb','cc']
s = json.dumps(l1)
l2 = json.loads(s)
print s
print l1 == l2
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.