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 |
|---|---|---|---|---|---|---|---|---|---|
Adding custom JS to a django admin field | 1,816,444 | 6 | 2009-11-29T19:07:12Z | 1,816,992 | 16 | 2009-11-29T22:24:14Z | [
"python",
"django",
"google-maps",
"user-interface",
"django-admin"
] | In a django application I have the following model:
```
class Appointment(models.Model):
#some other fields
#address fields
zipcode=models.CharField(max_length=5)
address=models.CharField(max_length=120)
latitude=models.FloatField()
longitude=models.FloatField()
```
When I'm rendering an Appoi... | What is primarily being dealt with is client-side markup and client-side javascript. Being the case, it would seem that using a facility that's designed to handle those would be the proper choice. I'd also recommend making a custom admin widget. I've used this pattern myself. Depending on the size of the client-side ma... |
Python: How does inheritance of __slots__ in subclasses actually work? | 1,816,483 | 40 | 2009-11-29T19:20:06Z | 1,816,511 | 9 | 2009-11-29T19:34:53Z | [
"python",
"inheritance",
"subclass"
] | In the [Python data model reference section on slots](http://docs.python.org/reference/datamodel.html#slots) there is a list of notes on using `__slots__`. I am thoroughly confused by the 1st and 6th items, because they seem to be contradicting each other.
**First item:**
* When inheriting from a class without
`__s... | ```
class WithSlots(object):
__slots__ = "a_slot"
class NoSlots(object): # This class has __dict__
pass
```
## First Item
```
class A(NoSlots): # even though A has __slots__, it inherits __dict__
__slots__ = "a_slot" # from NoSlots, therefore __slots__ has no effect
```
## Sixth Ite... |
Python: How does inheritance of __slots__ in subclasses actually work? | 1,816,483 | 40 | 2009-11-29T19:20:06Z | 1,816,648 | 75 | 2009-11-29T20:20:43Z | [
"python",
"inheritance",
"subclass"
] | In the [Python data model reference section on slots](http://docs.python.org/reference/datamodel.html#slots) there is a list of notes on using `__slots__`. I am thoroughly confused by the 1st and 6th items, because they seem to be contradicting each other.
**First item:**
* When inheriting from a class without
`__s... | As others have mentioned, the sole reason for defining `__slots__` is to save some memory, when you have simple objects with a predefined set of attributes and don't want each to carry around a dictionary. This is meaningful only for classes of which you plan to have many instances, of course.
The savings may not be i... |
Why does csvwriter.writerow() put a comma after each character? | 1,816,880 | 36 | 2009-11-29T21:45:43Z | 1,816,897 | 63 | 2009-11-29T21:50:37Z | [
"python",
"csv"
] | This code opens the url and appends the `/names` at the end and opens the page and prints the string to `test1.csv`:
```
import urllib2
import re
import csv
url = ("http://www.example.com")
bios = [u'/name1', u'/name2', u'/name3']
csvwriter = csv.writer(open("/test1.csv", "a"))
for l in bios:
OpenThisLink = url ... | It expects a sequence (eg: a list or tuple) of strings. You're giving it a single string. A string happens to be a sequence of strings too, but it's a sequence of 1 character strings, which isn't what you want.
If you just want one string per row you could do something like this:
```
csvwriter.writerow([JD])
```
Thi... |
Can't pickle <type 'instancemethod'> when using python's multiprocessing Pool.map() | 1,816,958 | 125 | 2009-11-29T22:08:35Z | 1,816,969 | 74 | 2009-11-29T22:16:14Z | [
"python",
"multithreading",
"multiprocessing",
"pickle",
"pool"
] | I'm trying to use multiprocessing's Pool.map() function to divide out work simultaneously. When I use the following code, it works fine:
```
import multiprocessing
def f(x):
return x*x
def go():
pool = multiprocessing.Pool(processes=4)
print pool.map(f, range(10))
if __name__== '__main__' :
... | The problem is that multiprocessing must pickle things to sling them among processes, and bound methods are not picklable. The workaround (whether you consider it "easy" or not;-) is to add the infrastructure to your program to allow such methods to be pickled, registering it with the [copy\_reg](http://docs.python.org... |
Can't pickle <type 'instancemethod'> when using python's multiprocessing Pool.map() | 1,816,958 | 125 | 2009-11-29T22:08:35Z | 6,975,654 | 22 | 2011-08-07T20:40:35Z | [
"python",
"multithreading",
"multiprocessing",
"pickle",
"pool"
] | I'm trying to use multiprocessing's Pool.map() function to divide out work simultaneously. When I use the following code, it works fine:
```
import multiprocessing
def f(x):
return x*x
def go():
pool = multiprocessing.Pool(processes=4)
print pool.map(f, range(10))
if __name__== '__main__' :
... | You could also define a `__call__()` method inside your `someClass()`, which calls `someClass.go()` and then pass an instance of `someClass()` to the pool. This object is pickleable and it works fine (for me)... |
Can't pickle <type 'instancemethod'> when using python's multiprocessing Pool.map() | 1,816,958 | 125 | 2009-11-29T22:08:35Z | 7,309,686 | 14 | 2011-09-05T14:50:52Z | [
"python",
"multithreading",
"multiprocessing",
"pickle",
"pool"
] | I'm trying to use multiprocessing's Pool.map() function to divide out work simultaneously. When I use the following code, it works fine:
```
import multiprocessing
def f(x):
return x*x
def go():
pool = multiprocessing.Pool(processes=4)
print pool.map(f, range(10))
if __name__== '__main__' :
... | Some limitations though to Steven Bethard's solution :
When you register your class method as a function, the destructor of your class is surprisingly called every time your method processing is finished. So if you have 1 instance of your class that calls n times its method, members may disappear between 2 runs and yo... |
Can't pickle <type 'instancemethod'> when using python's multiprocessing Pool.map() | 1,816,958 | 125 | 2009-11-29T22:08:35Z | 21,345,273 | 34 | 2014-01-25T01:11:46Z | [
"python",
"multithreading",
"multiprocessing",
"pickle",
"pool"
] | I'm trying to use multiprocessing's Pool.map() function to divide out work simultaneously. When I use the following code, it works fine:
```
import multiprocessing
def f(x):
return x*x
def go():
pool = multiprocessing.Pool(processes=4)
print pool.map(f, range(10))
if __name__== '__main__' :
... | All of these solutions are ugly because multiprocessing and pickling is broken and limited unless you jump outside the standard library.
If you use a fork of `multiprocessing` called `pathos.multiprocesssing`, you can directly use classes and class methods in multiprocessing's `map` functions. This is because `dill` i... |
Constants in python? | 1,817,144 | 3 | 2009-11-29T23:32:25Z | 1,817,153 | 12 | 2009-11-29T23:35:36Z | [
"python"
] | I have the following variables declared in a lot of functions, as I need those values in each one of them. Is there anyway I can declare them at a global scope or something, such as I won't have to declare them in all my methods? I am using all this methods on instance methods of a class of mine.
```
x = 0
y = 1
t = 2... | If they're all within a single module, then they only live in that module's namespace and you don't have to worry about name clashes. (And you can still import them into other namesapaces)
For example
MyModWithContstants.py
```
x = 0
y = 0
def someFunc():
dosomethingwithconstants(x,y)
```
and we can also do
ano... |
Using super with a class method | 1,817,183 | 24 | 2009-11-29T23:45:58Z | 1,817,840 | 31 | 2009-11-30T04:22:56Z | [
"python",
"class",
"object",
"super",
"class-method"
] | **I'm trying to learn myself the super() function in Python.**
I though I got a grasp of it untill I came over this example (2.6) and found myself stuck.
[http://www.cafepy.com/article/python\_attributes\_and\_methods/python\_attributes\_and\_methods.html#super-with-classmethod-example](http://www.cafepy.com/article/... | Sometimes texts have to be read more for the flavor of the idea rather than for the details. This is one of those cases.
In the [linked page](http://www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.html#a-super-solution), Examples 2.5, 2.6 and 2.7 should all use one method, `do_your_s... |
Python: How to get StringIO.writelines to accept unicode string? | 1,817,695 | 21 | 2009-11-30T03:23:28Z | 1,817,732 | 20 | 2009-11-30T03:39:32Z | [
"python",
"string",
"unicode",
"ascii",
"stringio"
] | I'm getting a
```
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa3' in position 34: ordinal not in range(128)
```
on a string stored in 'a.desc' below as it contains the '£' character. It's stored in the underlying Google App Engine datastore as a unicode string so that's fine. The cStringIO.StringIO.... | [StringIO documentation](http://docs.python.org/library/stringio.html):
> Unlike the memory files implemented by the StringIO module, those provided by [cStringIO] are not able to accept Unicode strings that cannot be encoded as plain ASCII strings.
If possible, use StringIO instead of cStringIO. |
Python: How to get StringIO.writelines to accept unicode string? | 1,817,695 | 21 | 2009-11-30T03:23:28Z | 1,819,009 | 33 | 2009-11-30T10:30:28Z | [
"python",
"string",
"unicode",
"ascii",
"stringio"
] | I'm getting a
```
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa3' in position 34: ordinal not in range(128)
```
on a string stored in 'a.desc' below as it contains the '£' character. It's stored in the underlying Google App Engine datastore as a unicode string so that's fine. The cStringIO.StringIO.... | You can wrap the StringIO object in a `codecs.StreamReaderWriter` object to automatically encode and decode unicode.
Like this:
```
import cStringIO, codecs
buffer = cStringIO.StringIO()
codecinfo = codecs.lookup("utf8")
wrapper = codecs.StreamReaderWriter(buffer,
codecinfo.streamreader, codecinfo.streamwrit... |
what functional tools remain in Python 3k? | 1,817,771 | 4 | 2009-11-30T03:55:59Z | 1,817,785 | 10 | 2009-11-30T03:59:56Z | [
"python",
"functional-programming",
"python-3.x"
] | I have have read several entries regarding dropping several functional functions from future python, including map and reduce.
What is the official policy regarding functional extensions?
is lambda function going to stay? | Well, Python 3.0 and 3.1 are already released, so you can check this out for yourself. The end result was that map and filter were kept as built-ins, and lambda was also kept. The only change was that reduce was moved to the functools module; you just need to do
```
from functools import reduce
```
to use it.
Future... |
Django-Use of unicode | 1,818,224 | 8 | 2009-11-30T06:52:42Z | 1,818,240 | 12 | 2009-11-30T07:01:15Z | [
"python",
"django"
] | Why is a unicode function is required in models.py?
i.e,
```
def __unicode__(self)
return sumid;
``` | It's not. If you define a `__unicode__()` method, Django will call it when it needs to render an object in a context where a string representation is needed (e.g. in the model's admin pages).
The [documentation](http://docs.djangoproject.com/en/dev/ref/models/instances/#unicode) says:
> The `__unicode__()` method is ... |
Executing a subprocess fails | 1,818,774 | 12 | 2009-11-30T09:33:00Z | 1,818,902 | 20 | 2009-11-30T10:04:17Z | [
"python",
"subprocess"
] | I tried to call a process via Python with several arguments. Executing the batch file itself works fine for me but translating it into Python makes me scream. Here the contents of the batch file:
```
"C:\Program Files\bin\cspybat" "C:\Program Files\bin\armproc.dll" "C:\Program Files\bin\armjlink.dll" "C:\Documents and... | To execute a batch file in Windows:
```
from subprocess import Popen
p = Popen("batchfile.bat", cwd=r"c:\directory\containing\batchfile")
stdout, stderr = p.communicate()
```
If you don't want to execute the batch file, but rather execute the command in your question directly from Python, you need to experiment a bit... |
Image comparison algorithm | 1,819,124 | 31 | 2009-11-30T10:57:54Z | 1,819,262 | 13 | 2009-11-30T11:27:37Z | [
"python",
"image",
"image-processing",
"compare",
"computer-vision"
] | I'm trying to compare images to each other to find out whether they are different. First I tried to make a Pearson correleation of the RGB values, which works also quite good unless the pictures are a litte bit shifted. So if a have a 100% identical images but one is a little bit moved, I get a bad correlation value.
... | I have one done this with an image histogram comparison. My basic algorithm was this:
1. Split image into red, green and blue
2. Create normalized histograms for red, green and blue channel and concatenate them into a vector `(r0...rn, g0...gn, b0...bn)` where n is the number of "buckets", 256 should be enough
3. subt... |
Image comparison algorithm | 1,819,124 | 31 | 2009-11-30T10:57:54Z | 1,821,664 | 31 | 2009-11-30T18:51:30Z | [
"python",
"image",
"image-processing",
"compare",
"computer-vision"
] | I'm trying to compare images to each other to find out whether they are different. First I tried to make a Pearson correleation of the RGB values, which works also quite good unless the pictures are a litte bit shifted. So if a have a 100% identical images but one is a little bit moved, I get a bad correlation value.
... | A [similar question](http://stackoverflow.com/questions/189943/how-can-i-quantify-difference-between-two-images) was asked a year ago and has numerous responses, including one regarding pixelizing the images, which I was going to suggest as at least a pre-qualification step (as it would exclude very non-similar images ... |
Are there functions in Python? | 1,819,372 | 8 | 2009-11-30T11:55:51Z | 1,819,395 | 31 | 2009-11-30T12:00:52Z | [
"python",
"computer-science"
] | Or is everything a method?
Since everything is an object, a
```
def whatever:
```
is just a method of that file.py, right? | Python has functions. As everything is an object [functions are objects too](http://www.diveintopython.org/getting%5Fto%5Fknow%5Fpython/everything%5Fis%5Fan%5Fobject.html).
So, to use your example:
```
>>> def whatever():
... pass
...
>>> whatever
<function whatever at 0x00AF5F30>
```
When we use `def` we have c... |
Cannot make cProfile work in IPython | 1,819,448 | 12 | 2009-11-30T12:12:25Z | 1,821,123 | 23 | 2009-11-30T17:13:48Z | [
"python",
"profiling",
"profiler",
"ipython"
] | I'm missing something very basic.
```
class C:
def __init__(self):
self.N = 100
pass
def f(self, param):
print 'C.f -- param'
for k in xrange(param):
for i in xrange(self.N):
for j in xrange(self.N):
a = float(i)/(1+float(j)) + fl... | While inside IPython, you can use the [%prun magic function](http://ipython.org/ipython-doc/stable/interactive/magics.html?highlight=prun#magic-prun):
```
In [9]: %prun c.f(3)
C.f -- param
3 function calls in 0.066 CPU seconds
Ordered by: internal time
ncalls tottime percall cumtime percall filena... |
Cannot make cProfile work in IPython | 1,819,448 | 12 | 2009-11-30T12:12:25Z | 3,305,654 | 14 | 2010-07-22T03:46:58Z | [
"python",
"profiling",
"profiler",
"ipython"
] | I'm missing something very basic.
```
class C:
def __init__(self):
self.N = 100
pass
def f(self, param):
print 'C.f -- param'
for k in xrange(param):
for i in xrange(self.N):
for j in xrange(self.N):
a = float(i)/(1+float(j)) + fl... | Not the original poster's problem, but you can also get this same error if you are invoking cProfile.run() in something other than the \_\_main\_\_ namespace (from within a function or an import). In that case you need to use the following instead of the run() method:
```
cProfile.runctx("your code", globals(), locals... |
Python - Exists a function that is called when an object does not implement a function? | 1,820,160 | 7 | 2009-11-30T14:31:48Z | 1,820,213 | 7 | 2009-11-30T14:41:48Z | [
"python",
"oop",
"function"
] | In Smalltalk there is a message `DoesNotUnderstand` that is called when an object does not understand a message (this is, when the object does not have the message sent implemented).
So, I like to know if in python there is a function that does the same thing.
In this example:
```
class MyObject:
def __init__(se... | Here is a proposition for what you want to do:
```
class callee:
def __init__(self, name):
self.name = name
def __call__(self):
print self.name, "has been called"
class A:
def __getattr__(self, attr):
return callee(attr)
a = A()
a.DoSomething()
>>> DoSomething has been called
`... |
tokenize a string keeping delimiters in Python | 1,820,336 | 17 | 2009-11-30T15:02:38Z | 1,820,371 | 19 | 2009-11-30T15:08:11Z | [
"python",
"string",
"split",
"tokenize"
] | Is there any equivalent to `str.split` in Python that also returns the delimiters?
I need to preserve the whitespace layout for my output after processing some of the tokens.
Example:
```
>>> s="\tthis is an example"
>>> print s.split()
['this', 'is', 'an', 'example']
>>> print what_I_want(s)
['\t', 'this', ' ', '... | How about
```
import re
splitter = re.compile(r'(\s+|\S+)')
splitter.findall(s)
``` |
Redirecting a user in a django template | 1,820,390 | 4 | 2009-11-30T15:10:34Z | 1,820,396 | 14 | 2009-11-30T15:14:58Z | [
"python",
"django"
] | I have a django website that is spilt depending on what user type you are, I need to redirect users that are not entitled to see certain aspects of the site,
in my template, I have
```
{% if user.get_profile.is_store %}
<!--DO SOME LOGIC-->
{%endif%}
```
how would I go about redirecting said store back to the in... | You will want to do this, I think, in a *view* not in the *template*. So, something like:
```
from django.http import HttpResponseRedirect
def myview(request):
if request.user.get_profile().is_store():
return HttpResponseRedirect("/path/")
# return regular view otherwise
```
You could also use a `@d... |
Redirecting a user in a django template | 1,820,390 | 4 | 2009-11-30T15:10:34Z | 5,583,185 | 9 | 2011-04-07T15:00:07Z | [
"python",
"django"
] | I have a django website that is spilt depending on what user type you are, I need to redirect users that are not entitled to see certain aspects of the site,
in my template, I have
```
{% if user.get_profile.is_store %}
<!--DO SOME LOGIC-->
{%endif%}
```
how would I go about redirecting said store back to the in... | Use the HTML's raw redirection.
```
{% if user.get_profile.is_store %}
<meta http-equiv="REFRESH" content="0;url=http://redirect-url">
{% endif %}
```
or provide the redirection url as a context variable
```
{% if user.get_profile.is_store %}
<meta http-equiv="REFRESH" content="0;url={{ user.get_profile.stor... |
Must Standard libraries for python beginner | 1,820,657 | 3 | 2009-11-30T15:55:14Z | 1,820,687 | 8 | 2009-11-30T15:59:36Z | [
"python"
] | Though there can be many but as i am very new to python so which modules or classes within standard libraries i should know when programming in python, especially when i am practicing programming challenges from a C++ book? Libraries which can make my life easier? Since there can be no single correct answer, i am makin... | The standard libraries, i.e. the ones considered more or less part of Python. Start with those, there is plenty to learn before starting on 3rd party stuff.
Things like:
* [os](http://docs.python.org/library/os.html)
* [re](http://docs.python.org/library/re.html)
* [subprocess](http://docs.python.org/library/subproce... |
Must Standard libraries for python beginner | 1,820,657 | 3 | 2009-11-30T15:55:14Z | 1,820,700 | 8 | 2009-11-30T16:01:07Z | [
"python"
] | Though there can be many but as i am very new to python so which modules or classes within standard libraries i should know when programming in python, especially when i am practicing programming challenges from a C++ book? Libraries which can make my life easier? Since there can be no single correct answer, i am makin... | Check out the excellent [Python Module of the Week](http://www.doughellmann.com/projects/PyMOTW/) blog series. |
Django: check whether an object already exists before adding | 1,821,176 | 21 | 2009-11-30T17:26:39Z | 1,821,247 | 32 | 2009-11-30T17:39:15Z | [
"python",
"django"
] | This is a pretty simple Django question, but I can't find the answer in the Django docs, despite lots of hunting!
How do I check whether an object already exists, and only add it if it does *not* already exist?
Here's the code - I don't want to add the follow\_role twice in the database if it already exists. How do I... | There's a helper function for this idiom called 'get\_or\_create' on your model manager:
```
role, created = UserToUserRole.objects.get_or_create(
from_user=current_user, to_user=user, role='follow')
```
It returns a tuple of (model, bool) where 'model' is the object you're interested in and 'bool' tells you whet... |
How to get unicode month name in Python? | 1,821,204 | 3 | 2009-11-30T17:31:20Z | 1,821,292 | 12 | 2009-11-30T17:48:29Z | [
"python",
"unicode"
] | I am trying to get a unicode version of `calendar.month_abbr[6]`. If I don't specify an encoding for the locale, I don't know how to convert the string to unicode. The example code below shows my problem:
```
>>> import locale
>>> import calendar
>>> locale.setlocale(locale.LC_ALL, ("ru_RU"))
'ru_RU'
>>> print repr(ca... | Change the last line in your code:
```
>>> print calendar.month_abbr[6].decode("utf8")
ÐÑн
```
Improperly used [`repr()`](http://docs.python.org/library/functions.html#repr) hides from you that you already get what you needed.
Also `getlocale()` can be used to get encoding for current locale:
```
>>> locale.setl... |
Python: Nested Loop | 1,821,471 | 2 | 2009-11-30T18:20:42Z | 1,821,511 | 7 | 2009-11-30T18:27:53Z | [
"python",
"loops",
"nested"
] | Consider this:
```
>>> a = [("one","two"), ("bad","good")]
>>> for i in a:
... for x in i:
... print x
...
one
two
bad
good
```
How can I write this code, but using a syntax like:
```
for i in a:
print [x for x in i]
```
Obviously, This does not work, it prints:
```
['one', 'two']
['bad', 'good']... | List comprehensions and generators are only designed to be used as expressions, while printing is a statement. While you can effect what you're trying to do by doing
```
from __future__ import print_function
for x in a:
[print(each) for each in x]
```
doing so is amazingly unpythonic, and results in the generatio... |
Python: Nested Loop | 1,821,471 | 2 | 2009-11-30T18:20:42Z | 1,821,532 | 7 | 2009-11-30T18:30:21Z | [
"python",
"loops",
"nested"
] | Consider this:
```
>>> a = [("one","two"), ("bad","good")]
>>> for i in a:
... for x in i:
... print x
...
one
two
bad
good
```
How can I write this code, but using a syntax like:
```
for i in a:
print [x for x in i]
```
Obviously, This does not work, it prints:
```
['one', 'two']
['bad', 'good']... | Given your example you could do something like this:
```
a = [("one","two"), ("bad","good")]
for x in sum(map(list, a), []):
print x
```
This can, however, become quite slow once the list gets big.
The better way to do it would be like [Tim Pietzcker](http://stackoverflow.com/users/20670/tim-pietzcker) suggeste... |
Is RLock a sensible default over Lock? | 1,822,541 | 11 | 2009-11-30T21:32:42Z | 1,977,542 | 10 | 2009-12-29T23:21:09Z | [
"python",
"multithreading"
] | the threading module in Python provides two kinds of locks: A common lock and a reentrant lock. It seems to me, that if I need a lock, I should always prefer the RLock over the Lock; mainly to prevent deadlock situations.
Besides that, I see two points, when to prefer a Lock over a RLock:
* RLock has a more complicat... | Two points:
* In officially released Python versions (2.4, 2.5... up to 3.1), an RLock is much slower than a Lock, because Locks are implemented in C and RLocks in Python (this will change in 3.2)
* A Lock can be released from any thread (not necessarily the thread which acquire()d it), while an RLock has to be releas... |
How to print number with commas as thousands separators? | 1,823,058 | 290 | 2009-11-30T23:11:43Z | 1,823,089 | 11 | 2009-11-30T23:19:53Z | [
"python",
"python-2.x"
] | I am trying to print an integer in *Python 2.6.1* with commas as thousands separators. For example, I want to show the number `1234567` as `1,234,567`. How would I go about doing this? I have seen many examples on Google, but I am looking for the simplest practical way.
It does not need to be locale-specific to decide... | I'm sure there must be a standard library function for this, but it was fun to try to write it myself using recursion so here's what I came up with:
```
def intToStringWithCommas(x):
if type(x) is not int and type(x) is not long:
raise TypeError("Not an integer!")
if x < 0:
return '-' + intToSt... |
How to print number with commas as thousands separators? | 1,823,058 | 290 | 2009-11-30T23:11:43Z | 1,823,101 | 198 | 2009-11-30T23:22:13Z | [
"python",
"python-2.x"
] | I am trying to print an integer in *Python 2.6.1* with commas as thousands separators. For example, I want to show the number `1234567` as `1,234,567`. How would I go about doing this? I have seen many examples on Google, but I am looking for the simplest practical way.
It does not need to be locale-specific to decide... | I got this to work:
```
>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'en_US')
'en_US'
>>> locale.format("%d", 1255000, grouping=True)
'1,255,000'
```
Sure, you don't *need* internationalization support, but it's clear, concise, and uses a built-in library.
P.S. That "%d" is the usual %-style formatter. You ... |
How to print number with commas as thousands separators? | 1,823,058 | 290 | 2009-11-30T23:11:43Z | 1,823,189 | 73 | 2009-11-30T23:42:26Z | [
"python",
"python-2.x"
] | I am trying to print an integer in *Python 2.6.1* with commas as thousands separators. For example, I want to show the number `1234567` as `1,234,567`. How would I go about doing this? I have seen many examples on Google, but I am looking for the simplest practical way.
It does not need to be locale-specific to decide... | Here is the locale grouping code after removing irrelevant parts and cleaning it up a little:
(The following only works for integers)
```
def group(number):
s = '%d' % number
groups = []
while s and s[-1].isdigit():
groups.append(s[-3:])
s = s[:-3]
return s + ','.join(reversed(groups))... |
How to print number with commas as thousands separators? | 1,823,058 | 290 | 2009-11-30T23:11:43Z | 4,205,875 | 8 | 2010-11-17T15:19:15Z | [
"python",
"python-2.x"
] | I am trying to print an integer in *Python 2.6.1* with commas as thousands separators. For example, I want to show the number `1234567` as `1,234,567`. How would I go about doing this? I have seen many examples on Google, but I am looking for the simplest practical way.
It does not need to be locale-specific to decide... | From the [comments](http://code.activestate.com/recipes/498181-add-thousands-separator-commas-to-formatted-number/#c3) to activestate recipe [498181](http://code.activestate.com/recipes/498181-add-thousands-separator-commas-to-formatted-number/) I reworked this:
```
import re
def thous(x, sep=',', dot='.'):
num, _... |
How to print number with commas as thousands separators? | 1,823,058 | 290 | 2009-11-30T23:11:43Z | 8,932,161 | 63 | 2012-01-19T19:35:28Z | [
"python",
"python-2.x"
] | I am trying to print an integer in *Python 2.6.1* with commas as thousands separators. For example, I want to show the number `1234567` as `1,234,567`. How would I go about doing this? I have seen many examples on Google, but I am looking for the simplest practical way.
It does not need to be locale-specific to decide... | For inefficiency and unreadability it's hard to beat:
```
>>> import itertools
>>> s = '-1234567'
>>> ','.join(["%s%s%s" % (x[0], x[1] or '', x[2] or '') for x in itertools.izip_longest(s[::-1][::3], s[::-1][1::3], s[::-1][2::3])])[::-1].replace('-,','-')
``` |
How to print number with commas as thousands separators? | 1,823,058 | 290 | 2009-11-30T23:11:43Z | 10,742,904 | 807 | 2012-05-24T18:02:17Z | [
"python",
"python-2.x"
] | I am trying to print an integer in *Python 2.6.1* with commas as thousands separators. For example, I want to show the number `1234567` as `1,234,567`. How would I go about doing this? I have seen many examples on Google, but I am looking for the simplest practical way.
It does not need to be locale-specific to decide... | I too, prefer the "simplest practical way". For >= 2.7:
```
"{:,}".format(value)
```
<http://docs.python.org/library/string.html#format-specification-mini-language> |
How to print number with commas as thousands separators? | 1,823,058 | 290 | 2009-11-30T23:11:43Z | 11,562,205 | 26 | 2012-07-19T13:42:46Z | [
"python",
"python-2.x"
] | I am trying to print an integer in *Python 2.6.1* with commas as thousands separators. For example, I want to show the number `1234567` as `1,234,567`. How would I go about doing this? I have seen many examples on Google, but I am looking for the simplest practical way.
It does not need to be locale-specific to decide... | Here's a one-line regex replacement:
```
re.sub("(\d)(?=(\d{3})+(?!\d))", r"\1,", "%d" % val)
```
Works only for inegral outputs:
```
import re
val = 1234567890
re.sub("(\d)(?=(\d{3})+(?!\d))", r"\1,", "%d" % val)
# Returns: '1,234,567,890'
val = 1234567890.1234567890
# Returns: '1,234,567,890'
```
Or for floats w... |
How to print number with commas as thousands separators? | 1,823,058 | 290 | 2009-11-30T23:11:43Z | 32,050,746 | 7 | 2015-08-17T12:43:14Z | [
"python",
"python-2.x"
] | I am trying to print an integer in *Python 2.6.1* with commas as thousands separators. For example, I want to show the number `1234567` as `1,234,567`. How would I go about doing this? I have seen many examples on Google, but I am looking for the simplest practical way.
It does not need to be locale-specific to decide... | You can also use `'{:n}'.format( value )` for a locale representation. I think this is the simpliest way for a locale solution.
For more information, search for `thousands` in [Python DOC](https://docs.python.org/3.5/library/string.html#format-specification-mini-language).
For currency, you can use `locale.currency`,... |
Optimized method for calculating cosine distance in Python | 1,823,293 | 9 | 2009-12-01T00:15:59Z | 1,823,365 | 8 | 2009-12-01T00:45:10Z | [
"python",
"arrays",
"optimization",
"distance"
] | I wrote a method to calculate the cosine distance between two arrays:
```
def cosine_distance(a, b):
if len(a) != len(b):
return False
numerator = 0
denoma = 0
denomb = 0
for i in range(len(a)):
numerator += a[i]*b[i]
denoma += abs(a[i])**2
denomb += abs(b[i])**2
result = 1 ... | If you can use SciPy, you can use `cosine` from `spatial.distance`:
<http://docs.scipy.org/doc/scipy/reference/spatial.distance.html>
If you can't use SciPy, you could try to obtain a small speedup by rewriting your Python (EDIT: but it didn't work out like I thought it would, see below).
```
from itertools import i... |
Optimized method for calculating cosine distance in Python | 1,823,293 | 9 | 2009-12-01T00:15:59Z | 1,823,442 | 8 | 2009-12-01T01:13:06Z | [
"python",
"arrays",
"optimization",
"distance"
] | I wrote a method to calculate the cosine distance between two arrays:
```
def cosine_distance(a, b):
if len(a) != len(b):
return False
numerator = 0
denoma = 0
denomb = 0
for i in range(len(a)):
numerator += a[i]*b[i]
denoma += abs(a[i])**2
denomb += abs(b[i])**2
result = 1 ... | (I originally thought) you're not going to speed it up a lot without breaking out to C (like numpy or scipy) or changing what you compute. But here's how I'd try that, anyway:
```
from itertools import imap
from math import sqrt
from operator import mul
def cosine_distance(a, b):
assert len(a) == len(b)
retur... |
What's the best way to divide large files in Python for multiprocessing? | 1,823,300 | 14 | 2009-12-01T00:23:25Z | 1,823,530 | 7 | 2009-12-01T01:45:05Z | [
"python",
"concurrency",
"multiprocessing",
"bioinformatics"
] | I run across a lot of "embarrassingly parallel" projects I'd like to parallelize with the `multiprocessing` module. However, they often involve reading in huge files (greater than 2gb), processing them line by line, running basic calculations, and then writing results. What's the best way to split a file and process it... | One of the best architectures is already part of Linux OS's. No special libraries required.
You want a "fan-out" design.
1. A "main" program creates a number of subprocesses connected by pipes.
2. The main program reads the file, writing lines to the pipes doing the minimum filtering required to deal the lines to app... |
Debugging Pyparsing Grammar | 1,823,427 | 14 | 2009-12-01T01:08:14Z | 1,823,558 | 27 | 2009-12-01T01:55:18Z | [
"python",
"pyparsing"
] | I'm building a parser for an imaginary programming language called C-- (not the actual C-- language). I've gotten to the stage where I need to translate the language's grammar into something Pyparsing can accept. Unfortunatly when I come to parse my input string (which is correct and should not cause Pyparsing to error... | 1) Change `Literal("if")` to `Keyword("if")` (and so on, down to `Literal("void")`), to prevent matching the leading "if" of a variable named `"ifactor"`.
2) `nums`, `alphas`, and `alphanums` are not expressions, they are strings, that can be used with the Word class to define some typical sets of characters when defi... |
which is a better language (C++ or Python) for complex problem solving exercises (ex. Graphs)? | 1,823,431 | 4 | 2009-12-01T01:08:54Z | 1,823,434 | 8 | 2009-12-01T01:10:10Z | [
"c++",
"python",
"algorithm",
"graph"
] | I am trying to work on some problems and algorithms. I know C++ but a friend told me that it would be better if done with Python.As it would be much **faster** *to develop* and less time is spent in programming details which does not actually earn anything solution wise.
**EDIT 2**: I plan to use *python-graph* lib fr... | A bit subjective, but I'd vote for python because it has good libraries and abstracts a lot of the low level 'detail' that you'd have to consider when using c++... |
which is a better language (C++ or Python) for complex problem solving exercises (ex. Graphs)? | 1,823,431 | 4 | 2009-12-01T01:08:54Z | 1,823,475 | 23 | 2009-12-01T01:22:37Z | [
"c++",
"python",
"algorithm",
"graph"
] | I am trying to work on some problems and algorithms. I know C++ but a friend told me that it would be better if done with Python.As it would be much **faster** *to develop* and less time is spent in programming details which does not actually earn anything solution wise.
**EDIT 2**: I plan to use *python-graph* lib fr... | I think you're looking for Python, because you can:
* Focus on the algorithms themselves and not have to worry about other detail like memory management.
* Do more with less code
* The syntax is almost like working with pseudo code.
* There is great built in language support for lists, tuples, list comprehensions, etc... |
which is a better language (C++ or Python) for complex problem solving exercises (ex. Graphs)? | 1,823,431 | 4 | 2009-12-01T01:08:54Z | 1,823,578 | 9 | 2009-12-01T02:03:06Z | [
"c++",
"python",
"algorithm",
"graph"
] | I am trying to work on some problems and algorithms. I know C++ but a friend told me that it would be better if done with Python.As it would be much **faster** *to develop* and less time is spent in programming details which does not actually earn anything solution wise.
**EDIT 2**: I plan to use *python-graph* lib fr... | Instead of focusing on the language, you should focus on the *libraries* available to you.
You shouldn't write your own graph library when there are already plenty (read, "too many") available, both in [C++](http://www.google.com/search?q=c%2B%2B+graph+library) and in [Python](http://wiki.python.org/moin/PythonGraphAp... |
Django, updating a user profile with a ModelForm | 1,823,588 | 7 | 2009-12-01T02:05:50Z | 1,823,636 | 8 | 2009-12-01T02:26:07Z | [
"python",
"django"
] | I'm trying to display a simple ModelForm for a user's profile and allow the user to update it. The problem here is that my logic is somehow flawed, and after a successful form.save() call, the old values show on the page. It isn't until a refresh that the appropriate value is shown. What is wrong here?
```
@login_requ... | Try this:
```
@login_required
def user_profile(request):
success = False
user = User.objects.get(pk=request.user.id)
if request.method == 'POST':
upform = UserProfileForm(request.POST, instance=user.get_profile())
if upform.is_valid():
up = upform.save(commit=False)
... |
SendKeys for Python 3.1 on Windows | 1,823,762 | 2 | 2009-12-01T03:12:07Z | 2,004,267 | 8 | 2010-01-05T05:03:38Z | [
"python",
"sendkeys"
] | The latest Python Sendkeys module is for Python 2.6. I can't upgrade it myself as it needs the C module to be recompiled.
Does anyone know of a fairly easy alternative way to send keys to a window?
Using win32ui.FindWindow() I can find the right window, then make it active with PyCWnd.SetActiveWindow(), so all that's... | Here is a working module that calls user32.SendInput().
Not perfect, but usable.
Edit:
Yesterday I did a version with a class, and am using it in a working tkinter app. Will put it here when i get time to clean it up.
Have added this in the doc string below:
[ It is OK if I work from a folder within my profile.
... |
Overload a method with a function at runtime | 1,823,898 | 4 | 2009-12-01T03:53:55Z | 1,823,925 | 8 | 2009-12-01T04:02:44Z | [
"python",
"metaprogramming"
] | OK, I'll admit upfront this is a mega kludge and that I could definately implement this better. It's only morbid curiosity that's driving me to find out how I could do this.
```
class SomeClass(object):
def __init__(self):
def __(self, arg):
self.doStuff(arg)
self.overLoaded = __
de... | Don't worry about the self parameter, the function already has that from local scope.
```
class SomeClass(object):
def __init__(self):
def __(arg):
self.bar(arg)
self.foo = __
def foo(self, arg):
print "foo", arg
def bar(self, arg):
print "bar", arg
SomeClass().... |
urllib2 not retrieving entire HTTP response | 1,824,069 | 12 | 2009-12-01T04:51:24Z | 1,824,147 | 17 | 2009-12-01T05:25:21Z | [
"python",
"http",
"urllib2"
] | I'm perplexed as to why I'm not able to download the entire contents of some JSON responses from [FriendFeed](http://friendfeed.com/) using [urllib2](http://docs.python.org/library/urllib2.html).
```
>>> import urllib2
>>> stream = urllib2.urlopen('http://friendfeed.com/api/room/the-life-scientists/profile?format=json... | Best way to get all of the data:
```
fp = urllib2.urlopen("http://www.example.com/index.cfm")
response = ""
while 1:
data = fp.read()
if not data: # This might need to be if data == "": -- can't remember
break
response += data
print response
```
The reason is that `.read()` isn't gu... |
major changes in python since version 2.2.3 | 1,824,417 | 3 | 2009-12-01T06:49:25Z | 1,824,435 | 8 | 2009-12-01T06:53:34Z | [
"python",
"changelog"
] | I've written a small python script to create a file and calculate times. I've tested it on Fedora 10, and Ubuntu 8.x and it worked well. the python versions were 2.5.x.
I tried to run it on my production server (an old red hat based linux server), the version of python is 2.2.3. the script does not work and raises a s... | I wrote a script a while ago to help answer this exact question: [pyqver](http://github.com/ghewgill/pyqver).
> This script attempts to identify the minimum version of Python that is required
> to execute a particular source file.
>
> When developing Python scripts for distribution, it is desirable to identify
> which... |
Infinity generated in python code | 1,824,751 | 6 | 2009-12-01T08:27:15Z | 1,824,777 | 12 | 2009-12-01T08:33:54Z | [
"python",
"infinity"
] | I'm looking over some complex Python 2.6 code which is occasionally resulting in an infinity being generated (at least an Infinity being serialized by the json library -- which checks w/ math.isinf).
What is especially baffling is that Python (as far as I can tell) shouldn't be able to ever produce computation results... | Somewhere between 1e308 and 1e309 the floats run out of precision, so if you are computing results above that range you will see inf
```
>>> 1e308
1e+308
>>> 1e309
inf
>>> json.dumps(1e308,allow_nan=False)
'1e+308'
>>> json.dumps(1e309,allow_nan=False)
Traceback (most recent call last):
File "<stdin>", line 1, in <... |
Mark string as safe in Mako | 1,825,343 | 11 | 2009-12-01T10:36:30Z | 1,859,850 | 10 | 2009-12-07T13:05:10Z | [
"python",
"pylons",
"mako"
] | I'm using Pylons with Mako templates and I want to avoid typing this all the time:
```
${ h.some_function_that_outputs_html() | n }
```
I want to somehow mark the function, or a variable as safe (you can do that in Django) so I don't have to pipe-en all the time. Any ideas? | I just found out that if you put a **html** method in your class, then Mako will just call that method and output whatever it returns in the template.
So I did:
```
def __html__(self):
return unicode(self)
```
That's basically what h.literal does. |
Using super() in nested classes | 1,825,384 | 17 | 2009-12-01T10:47:22Z | 1,825,470 | 15 | 2009-12-01T11:04:30Z | [
"python",
"super"
] | Imagine this:
```
class A(object):
class B(object):
def __init__(self):
super(B, self).__init__()
```
This creates an error:
```
NameError: global name B is not defined.
```
I've tried `A.B`, but then it says that `A` is not defined.
**Update:**
I've found the problem.
I've had a class li... | I'm not sure why A.B is not working correctly for you, as it should.. Here's some shell output that works:
```
>>> class A(object):
... class B(object):
... def __init__(self):
... super(A.B, self).__init__()
... def getB(self):
... return A.B()
...
>>> A().getB()
<__main__.B object at 0x100496410>
... |
Download html page and its content | 1,825,438 | 23 | 2009-12-01T10:58:09Z | 1,825,465 | 20 | 2009-12-01T11:02:16Z | [
"python",
"html"
] | Does python have any way of downloading entire html page and its contents (images, css) to local folder given a url. And updating local html file to pick content locally. | You can use the [`urllib`](http://docs.python.org/library/urllib.html) module to download individual URLs but this will just return the data. It will not parse the HTML and automatically download things like CSS files and images.
If you want to download the "whole" page you will need to parse the HTML and find the oth... |
Can python send text to the Mac clipboard | 1,825,692 | 20 | 2009-12-01T11:51:49Z | 1,825,723 | 8 | 2009-12-01T11:58:46Z | [
"python",
"osx",
"clipboard"
] | I'd like my python program to place some text in the Mac clipboard.
Is this possible? | **New answer:**
[This page](http://www.devx.com/opensource/Article/37233/0/page/3) suggests:
> **Implementation for All Mac OS X
> Versions**
>
> The other Mac module
> (MacSharedClipboard.py, in Listing 4)
> implements the clipboard interface on
> top of two command-line programs
> called pbcopy (which copies text i... |
Can python send text to the Mac clipboard | 1,825,692 | 20 | 2009-12-01T11:51:49Z | 3,555,675 | 14 | 2010-08-24T10:55:48Z | [
"python",
"osx",
"clipboard"
] | I'd like my python program to place some text in the Mac clipboard.
Is this possible? | The following code use PyObjC (http://pyobjc.sourceforge.net/)
```
from AppKit import NSPasteboard, NSArray
pb = NSPasteboard.generalPasteboard()
pb.clearContents()
a = NSArray.arrayWithObject_("hello world")
pb.writeObjects_(a)
```
As [explained in Cocoa documentation](http://developer.apple.com/mac/library/documen... |
Can python send text to the Mac clipboard | 1,825,692 | 20 | 2009-12-01T11:51:49Z | 9,346,957 | 11 | 2012-02-19T05:21:07Z | [
"python",
"osx",
"clipboard"
] | I'd like my python program to place some text in the Mac clipboard.
Is this possible? | A simple way:
```
cmd = 'echo %s | tr -d "\n" | pbcopy' % str
os.system(cmd)
```
A cross-platform way:
<http://stackoverflow.com/a/4203897/805627>
```
from Tkinter import Tk
r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append('i can has clipboardz?')
r.destroy()
``` |
Can python send text to the Mac clipboard | 1,825,692 | 20 | 2009-12-01T11:51:49Z | 25,802,742 | 30 | 2014-09-12T07:12:39Z | [
"python",
"osx",
"clipboard"
] | I'd like my python program to place some text in the Mac clipboard.
Is this possible? | How to write a Unicode string to the Mac clipboard:
```
import subprocess
def write_to_clipboard(output):
process = subprocess.Popen(
'pbcopy', env={'LANG': 'en_US.UTF-8'}, stdin=subprocess.PIPE)
process.communicate(output.encode('utf-8'))
```
How to read a Unicode string from the Mac clipboard:
```... |
How to pack and unpack using ctypes (Structure <-> str) | 1,825,715 | 28 | 2009-12-01T11:57:23Z | 1,827,666 | 19 | 2009-12-01T17:24:38Z | [
"python",
"struct",
"ctypes"
] | This might be a silly question but I couldn't find a good answer in the docs or anywhere.
If I use **struct** to define a binary structure, the struct has 2 symmetrical methods for serialization and deserialization (pack and unpack) but it seems **ctypes** doesn't have a straightforward way to do this. Here's my solut... | [The PythonInfo wiki](http://wiki.python.org/moin/ctypes) has a solution for this.
> FAQ: How do I copy bytes to Python from a ctypes.Structure?
>
> ```
> def send(self):
> return buffer(self)[:]
> ```
>
> FAQ: How do I copy bytes to a ctypes.Structure from Python?
>
> ```
> def receiveSome(self, bytes):
> fit... |
How to pack and unpack using ctypes (Structure <-> str) | 1,825,715 | 28 | 2009-12-01T11:57:23Z | 1,972,348 | 14 | 2009-12-29T00:40:59Z | [
"python",
"struct",
"ctypes"
] | This might be a silly question but I couldn't find a good answer in the docs or anywhere.
If I use **struct** to define a binary structure, the struct has 2 symmetrical methods for serialization and deserialization (pack and unpack) but it seems **ctypes** doesn't have a straightforward way to do this. Here's my solut... | Have a look at this link on binary i/o in python:
<http://www.dabeaz.com/blog/2009/08/python-binary-io-handling.html>
Based on this you can simply write the following to read from a buffer (not just files):
```
g = open("foo","rb")
q = Example()
g.readinto(q)
```
To write is simply:
```
g.write(q)
```
The same fo... |
How much of NumPy and SciPy is in C? | 1,825,857 | 7 | 2009-12-01T12:21:20Z | 1,825,950 | 11 | 2009-12-01T12:39:25Z | [
"python",
"performance",
"numpy",
"scipy",
"scientific-computing"
] | Are parts of NumPy and/or SciPy programmed in C/C++?
And how does the overhead of calling C from Python compare to the overhead of calling C from Java and/or C#?
I'm just wondering if Python is a better option than Java or C# for scientific apps.
If I look at the [shootouts](http://shootout.alioth.debian.org/u32/ben... | 1. ~~I would question any benchmark which doesn't show the source for each implementation (or did I miss something)? It's entirely possible that either or both of those solutions are coded badly which would result in an unfair appraisal of either or both language's performance.~~ **[Edit]** Oops, now I see the source. ... |
Numpy meshgrid in 3D | 1,827,489 | 26 | 2009-12-01T16:53:37Z | 1,830,192 | 23 | 2009-12-02T01:53:21Z | [
"python",
"numpy"
] | Numpy's meshgrid is very useful for converting two vectors to a coordinate grid. What is the easiest way to extend this to three dimensions? So given three vectors x, y, and z, construct 3x3D arrays (instead of 2x2D arrays) which can be used as coordinates. | Here is the source code of meshgrid:
```
def meshgrid(x,y):
"""
Return coordinate matrices from two coordinate vectors.
Parameters
----------
x, y : ndarray
Two 1-D arrays representing the x and y coordinates of a grid.
Returns
-------
X, Y : ndarray
For vectors `x`, `... |
Numpy meshgrid in 3D | 1,827,489 | 26 | 2009-12-01T16:53:37Z | 22,684,348 | 20 | 2014-03-27T10:11:38Z | [
"python",
"numpy"
] | Numpy's meshgrid is very useful for converting two vectors to a coordinate grid. What is the easiest way to extend this to three dimensions? So given three vectors x, y, and z, construct 3x3D arrays (instead of 2x2D arrays) which can be used as coordinates. | In case someone comes past this, numpy (as of 1.8 I think) support higher that 2D generation of position grids with [meshgrid](http://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html). One important addition which really helped me is the ability to chose the indexing order (either `xy` or `ij` for Carte... |
Django creating a form field that's read only using widgets | 1,827,526 | 12 | 2009-12-01T16:58:46Z | 1,827,587 | 36 | 2009-12-01T17:09:18Z | [
"python",
"django",
"forms",
"widget"
] | My form field looks something like the following:
```
class FooForm(ModelForm):
somefield = models.CharField(
widget=forms.TextInput(attrs={'readonly':'readonly'})
)
class Meta:
model = Foo
```
Geting an error like the following with the code above: **init**() got an unexpected keyword argument... | You should use a form field and not a model field:
```
somefield = models.CharField(
widget=forms.TextInput(attrs={'readonly':'readonly'})
)
```
replaced with
```
somefield = forms.CharField(
widget=forms.TextInput(attrs={'readonly':'readonly'})
)
```
Should fix it. |
Django creating a form field that's read only using widgets | 1,827,526 | 12 | 2009-12-01T16:58:46Z | 2,359,167 | 16 | 2010-03-01T21:23:17Z | [
"python",
"django",
"forms",
"widget"
] | My form field looks something like the following:
```
class FooForm(ModelForm):
somefield = models.CharField(
widget=forms.TextInput(attrs={'readonly':'readonly'})
)
class Meta:
model = Foo
```
Geting an error like the following with the code above: **init**() got an unexpected keyword argument... | Note that the `readonly` attribute does not keep Django from processing any value sent by the client. If it is important to you that the value doesn't change, no matter how creative your users are with [FireBug](http://getfirebug.com/), you need to use a more involved method, e.g. a `ReadOnlyField`/`ReadOnlyWidget` lik... |
reading mails using python | 1,827,848 | 4 | 2009-12-01T18:03:46Z | 1,828,673 | 13 | 2009-12-01T20:26:46Z | [
"python",
"email",
"gmail",
"imap"
] | how do i read mails from my mail box using python??
```
import getpass, imaplib
M = imaplib.IMAP4('IMAP4.gmail.com:993')
M.login(getpass.getuser(), getpass.getpass())
M.select()
typ, data = M.search(None, 'ALL')
for num in data[0].split():
typ, data = M.fetch(num, '(RFC822)')
print 'Message %s\n%s\n' % (num, d... | Three issues:
1. The hostname is `imap.gmail.com`, not `imap4.gmail.com`
2. The IMAP4 constructor takes two parameters: the host and port (not colon-separated)
3. Gmail expects you to be talking SSL
So:
```
import imaplib
M = imaplib.IMAP4_SSL("imap.gmail.com", 993)
``` |
how to reference python package when filename contains a period | 1,828,127 | 15 | 2009-12-01T18:53:48Z | 1,828,244 | 8 | 2009-12-01T19:15:56Z | [
"python",
"import",
"package"
] | I am using django and I have a file named models.admin.py and I want to do the following idea in models.py:
```
from "models.admin" import *
```
however, I get a syntax error for having double quotes. But if I just do
```
from models.admin import *
```
then I get "ImportError: No module named admin"
Is there any w... | If you *really* want to, you can import a module with an unusual filename (e.g., a filename containing a '.' before the '.py') using the imp module:
```
>>> import imp
>>> a_b = imp.load_source('a.b', 'a.b.py')
>>> a_b.x
"I was defined in a.b.py!"
```
However, that's generally a bad idea. It's more likely that you're... |
how to reference python package when filename contains a period | 1,828,127 | 15 | 2009-12-01T18:53:48Z | 1,828,249 | 16 | 2009-12-01T19:16:50Z | [
"python",
"import",
"package"
] | I am using django and I have a file named models.admin.py and I want to do the following idea in models.py:
```
from "models.admin" import *
```
however, I get a syntax error for having double quotes. But if I just do
```
from models.admin import *
```
then I get "ImportError: No module named admin"
Is there any w... | Actually, you *can* import a module with an invalid name. But you'll need to use [`imp`](http://docs.python.org/library/imp.html) for that, e.g. assuming file is named `models.admin.py`, you could do
```
import imp
with open('models.admin.py', 'rb') as fp:
models_admin = imp.load_module(
'models_admin', fp... |
Determine complete Django url configuration | 1,828,187 | 65 | 2009-12-01T19:05:15Z | 1,829,565 | 42 | 2009-12-01T23:02:21Z | [
"python",
"django",
"url"
] | Is there a way to get the **complete** django url configuration?
For example Django's debugging 404 page does not show included url configs, so this is not the complete configuration.
---
**Answer**: Thanks to Alasdair, here is an example script:
```
import urls
def show_urls(urllist, depth=0):
for entry in ur... | Django is Python, so introspection is your friend.
In the shell, import `urls`. By looping through `urls.urlpatterns`, and drilling down through as many layers of included url configurations as possible, you can build the complete url configuration.
```
import urls
urls.urlpatterns
```
The list `urls.urlpatterns` co... |
Determine complete Django url configuration | 1,828,187 | 65 | 2009-12-01T19:05:15Z | 19,868,961 | 44 | 2013-11-08T21:38:43Z | [
"python",
"django",
"url"
] | Is there a way to get the **complete** django url configuration?
For example Django's debugging 404 page does not show included url configs, so this is not the complete configuration.
---
**Answer**: Thanks to Alasdair, here is an example script:
```
import urls
def show_urls(urllist, depth=0):
for entry in ur... | Django extensions provides a utility to do this as a manage.py command.
```
pip install django-extensions
```
Then add `django_extensions` to your INSTALLED\_APPS in `settings.py`. then from the console just type the following
```
python manage.py show_urls
``` |
Any way to make nice antialiased round corners for images in python? | 1,828,345 | 13 | 2009-12-01T19:32:44Z | 1,828,426 | 16 | 2009-12-01T19:48:33Z | [
"python",
"image-processing",
"python-imaging-library",
"rounded-corners"
] | Is there any way to make nice round corners with python? Currently PIL and GD2 are used in my project. Both of them have an `arc()` method, that allows you to draw a quater-circle, but the quater-circle is not antialiased, so the image looks crispy.
Is there any neat way to make antialiased/smooth round corners? | What I usually do is use an image as a mask, like this one for example:
border.png

```
border = Image.open('border.png')
source = border.convert('RGB')
img.paste(source, mask=border)
```
The mask can be resized to fit the dimensions you w... |
How to share variables across scripts in python? | 1,829,116 | 8 | 2009-12-01T21:38:54Z | 1,829,270 | 13 | 2009-12-01T22:05:37Z | [
"python",
"variables",
"share"
] | The following does not work
one.py
```
import shared
shared.value = 'Hello'
raw_input('A cheap way to keep process alive..')
```
two.py
```
import shared
print shared.value
```
run on two command lines as:
```
>>python one.py
>>python two.py
```
(the second one gets an attribute error, rightly so).
Is there a w... | You're not going to be able to do what you want without storing the information somewhere external to the two instances of the interpreter.
If it's just simple variables you want, you can easily dump a python dict to a file with the pickle module in script one and then re-load it in script two.
Example:
one.py
```
... |
How to share variables across scripts in python? | 1,829,116 | 8 | 2009-12-01T21:38:54Z | 3,898,232 | 7 | 2010-10-09T22:54:13Z | [
"python",
"variables",
"share"
] | The following does not work
one.py
```
import shared
shared.value = 'Hello'
raw_input('A cheap way to keep process alive..')
```
two.py
```
import shared
print shared.value
```
run on two command lines as:
```
>>python one.py
>>python two.py
```
(the second one gets an attribute error, rightly so).
Is there a w... | sudo apt-get install memcached python-memcache
one.py
```
import memcache
shared = memcache.Client(['127.0.0.1:11211'], debug=0)
shared.set('Value', 'Hello')
```
two.py
```
import memcache
shared = memcache.Client(['127.0.0.1:11211'], debug=0)
print shared.get('Value')
``` |
How to share variables across scripts in python? | 1,829,116 | 8 | 2009-12-01T21:38:54Z | 14,700,365 | 12 | 2013-02-05T04:45:07Z | [
"python",
"variables",
"share"
] | The following does not work
one.py
```
import shared
shared.value = 'Hello'
raw_input('A cheap way to keep process alive..')
```
two.py
```
import shared
print shared.value
```
run on two command lines as:
```
>>python one.py
>>python two.py
```
(the second one gets an attribute error, rightly so).
Is there a w... | Hope it's OK to jot down my notes about this issue here.
First of all, I appreciate the example in the OP a lot, because that is where I started as well - although it made me think `shared` is some built-in Python module, until I found a complete example at [[Tutor] Global Variables between Modules ??](http://mail.pyt... |
python modify __metaclass__ for whole program | 1,829,205 | 2 | 2009-12-01T21:55:05Z | 1,830,067 | 7 | 2009-12-02T01:10:02Z | [
"python",
"metaprogramming",
"metaclass",
"python-2.x"
] | **EDIT:** Note that this is a REALLY BAD idea to do in production code. This was just an interesting thing for me. Don't do this at home!
Is it possible to modify \_\_metaclass\_\_ variable for whole program (interpreter) in Python?
This simple example is working:
```
class ChattyType(type):
def __init__(cls, na... | The "global `__metaclass__`" feature of Python 2 is designed to work per-module, only (just think what havoc it would wreak, otherwise, by forcing your own metaclass on all library and third-party modules that you imported from that point onwards -- shudder!). If it's very important to you to "secretly" alter the behav... |
How can I programmatically obtain the max_length of a Django model field? | 1,829,216 | 44 | 2009-12-01T21:56:14Z | 1,829,286 | 58 | 2009-12-01T22:08:19Z | [
"python",
"django",
"django-models",
"oop"
] | Say I have a Django class something like this:
```
class Person(models.Model):
name = models.CharField(max_length=50)
# ...
```
How can I programatically obtain the `max_length` value for the `name` field? | `Person._meta.get_field('name').max_length` will give you this value. ~~But having to use `_meta` suggests this is something you shouldn't do in normal usage.~~
Edit: as Carl pointed out, this naming is misleading and it does seem quite acceptable to use it: <http://www.b-list.org/weblog/2007/nov/04/working-models/> |
Solving a cubic equation | 1,829,330 | 8 | 2009-12-01T22:16:45Z | 1,829,469 | 22 | 2009-12-01T22:44:54Z | [
"python",
"algorithm",
"math",
"cubic"
] | As part of a program I'm writing, I need to solve a cubic equation exactly (rather than using a numerical root finder):
```
a*x**3 + b*x**2 + c*x + d = 0.
```
I'm trying to use the equations from [here](http://en.wikipedia.org/wiki/Cubic_function#Root-finding_formula). However, consider the following code (this is Py... | Wikipedia's notation `(rho^(1/3), theta/3)` does not mean that `rho^(1/3)` is the real part and `theta/3` is the imaginary part. Rather, this is in polar coordinates. Thus, if you want the real part, you would take `rho^(1/3) * cos(theta/3)`.
I made these changes to your code and it worked for me:
```
theta = arccos(... |
How to read datetime back from sqlite as a datetime instead of string in Python? | 1,829,872 | 41 | 2009-12-02T00:15:06Z | 1,830,011 | 12 | 2009-12-02T00:51:38Z | [
"python",
"datetime",
"sqlite",
"sqlite3"
] | I'm using the sqlite3 module in Python 2.6.4 to store a datetime in a SQLite database. Inserting it is very easy, because sqlite automatically converts the date to a string. The problem is, when reading it it comes back as a string, but I need to reconstruct the original datetime object. How do I do this? | It turns out that sqlite3 can do this and it's even [documented](http://docs.python.org/library/sqlite3.html#module-functions-and-constants), kind of - but it's pretty easy to miss or misunderstand.
What I had to do is:
* Pass the **sqlite3.PARSE\_COLNAMES** option in the .connect() call, eg.
> ```
> conn = sqlite3.... |
How to read datetime back from sqlite as a datetime instead of string in Python? | 1,829,872 | 41 | 2009-12-02T00:15:06Z | 1,830,499 | 68 | 2009-12-02T03:33:05Z | [
"python",
"datetime",
"sqlite",
"sqlite3"
] | I'm using the sqlite3 module in Python 2.6.4 to store a datetime in a SQLite database. Inserting it is very easy, because sqlite automatically converts the date to a string. The problem is, when reading it it comes back as a string, but I need to reconstruct the original datetime object. How do I do this? | If you declare your column with a type of timestamp, you're in clover:
```
>>> db = sqlite3.connect(':memory:', detect_types=sqlite3.PARSE_DECLTYPES)
>>> c = db.cursor()
>>> c.execute('create table foo (bar integer, baz timestamp)')
<sqlite3.Cursor object at 0x40fc50>
>>> c.execute('insert into foo values(?, ?)', (23,... |
TypeError: ListControl, must set a sequence (python error) | 1,830,262 | 5 | 2009-12-02T02:17:06Z | 1,830,294 | 8 | 2009-12-02T02:27:56Z | [
"python",
"http",
"url",
"mechanize"
] | I am using Python Mechanize to open a website, fill out a form, and submit that form.
It's actually pretty simple.
It works until I come across radio buttons and "select" input boxes.
```
br.open(url)
br.select_form(name="postmsg")
br.form['subject'] = "Is this good for the holidays? "
br.form['message'] = "I'm new to... | Radio buttons and Check-boxes can have different behavior then other elements. It depends on their name and id.
If the items have the same name, try doing this:
```
br.find_control(name="E").value = ["0"]
```
Another option is:
```
form.find_control(name="E", kind="list").value = ["0"]
```
and finally, this might ... |
How can I use pywin32 with a virtualenv without having to include the host environment's site-packages folder? | 1,830,304 | 46 | 2009-12-02T02:31:03Z | 2,500,528 | 69 | 2010-03-23T14:09:21Z | [
"python",
"winapi",
"virtualenv",
"pyinstaller"
] | I'm working with [PyInstaller](http://www.pyinstaller.org) under Python 2.6, which is only partially supported due to the mess MS have created with their manifest nonense which now affects Python since it is now MSVC8 compiled.
The problem is that the manifest embedding support relies on the [pywin32](http://sourcefor... | I found <http://old.nabble.com/Windows:-virtualenv-and-pywin32--td27658201.html> (now a dead link) which offered the following solution:
1. Browse <http://sourceforge.net/projects/pywin32/files/> for the URL of the exe you want
2. Activate your virtualenv
3. Run `easy_install http://PATH.TO/EXE/DOWNLOAD`
This works w... |
python locale strange error. what's going on here exactly? | 1,830,394 | 25 | 2009-12-02T02:57:27Z | 1,830,529 | 13 | 2009-12-02T03:44:31Z | [
"python",
"osx",
"osx-snow-leopard",
"locale"
] | So today I upgraded to bazaar 2.0.2, and I started receiving this message (I'm on snow leopard, btw):
```
bzr: warning: unknown locale: UTF-8
Could not determine what text encoding to use.
This error usually means your Python interpreter
doesn't support the locale set by $LANG (en_US.UTF-8)
Continuing with asc... | 2016 UPDATE: Turns out that [this is a Python bug](https://bugs.python.org/issue18378#msg215215) since at least 2013, very probably earlier too, consisting in Python not reacting well to non-GNU locales - like those found in Mac OS X and the BSDs. The bug is still open as of September 2016, and affects every Python ver... |
How to cleanly loop over two files in parallel in Python | 1,830,552 | 7 | 2009-12-02T03:53:53Z | 1,830,562 | 14 | 2009-12-02T03:56:45Z | [
"python"
] | I frequently write code like:
```
lines = open('wordprob.txt','r').readlines()
words = open('StdWord.txt','r').readlines()
i = 0
for line in lines:
v = [eval(s) for s in line.split()]
if v[0] > v[1]:
print words[i].strip(),
i += 1
```
Is it possible to avoid use variable i and make the program shorter?
Thanks. | You can try to use enumerate,
<http://docs.python.org/tutorial/datastructures.html#looping-techniques>
```
lines = open('wordprob.txt','r').readlines()
words = open('StdWord.txt','r').readlines()
for i,line in enumerate(lines):
v = [eval(s) for s in line.split()]
if v[0] > v[1]:
print ... |
How to cleanly loop over two files in parallel in Python | 1,830,552 | 7 | 2009-12-02T03:53:53Z | 1,830,663 | 15 | 2009-12-02T04:32:16Z | [
"python"
] | I frequently write code like:
```
lines = open('wordprob.txt','r').readlines()
words = open('StdWord.txt','r').readlines()
i = 0
for line in lines:
v = [eval(s) for s in line.split()]
if v[0] > v[1]:
print words[i].strip(),
i += 1
```
Is it possible to avoid use variable i and make the program shorter?
Thanks. | It looks like you don't care what the value of `i` is. You just are using it as a way to pair up the `lines` and the `words`. Therefore, I recommend you read one line at a time, and at the same time read one word. Then they will match.
Also, when you use `.readlines()` you read all the input at once into memory. For l... |
how to find the owner of a file or directory in python | 1,830,618 | 14 | 2009-12-02T04:19:36Z | 1,830,631 | 13 | 2009-12-02T04:25:33Z | [
"python",
"linux",
"file",
"permissions",
"ownership"
] | I need a function or method in Python to find the owner of a file or directory.
The function should be like:
```
>>> find_owner("/home/somedir/somefile")
owner3
``` | You want to use [`os.stat()`](http://docs.python.org/library/os.html):
```
os.stat(path)
Perform the equivalent of a stat() system call on the given path.
(This function follows symlinks; to stat a symlink use lstat().)
The return value is an object whose attributes correspond to the
members of the stat structure... |
how to find the owner of a file or directory in python | 1,830,618 | 14 | 2009-12-02T04:19:36Z | 1,830,635 | 40 | 2009-12-02T04:27:09Z | [
"python",
"linux",
"file",
"permissions",
"ownership"
] | I need a function or method in Python to find the owner of a file or directory.
The function should be like:
```
>>> find_owner("/home/somedir/somefile")
owner3
``` | I'm not really much of a python guy, but I was able to whip this up:
```
from os import stat
from pwd import getpwuid
def find_owner(filename):
return getpwuid(stat(filename).st_uid).pw_name
``` |
How to load compiled python modules from memory? | 1,830,727 | 6 | 2009-12-02T04:53:21Z | 1,830,807 | 30 | 2009-12-02T05:22:35Z | [
"python",
"module"
] | I need to read all modules (pre-compiled) from a zipfile (built by py2exe compressed) into memory and then load them all.
I know this can be done by loading direct from the zipfile but I need to load them from memory.
Any ideas? (I'm using python 2.5.2 on windows)
TIA Steve | It depends on what exactly you have as "the module (pre-compiled)". Let's assume it's exactly the contents of a `.pyc` file, e.g., `ciao.pyc` as built by:
```
$ cat>'ciao.py'
def ciao(): return 'Ciao!'
$ python -c'import ciao; print ciao.ciao()'
Ciao!
```
IOW, having thus built `ciao.pyc`, say that you now do:
```
... |
How to load compiled python modules from memory? | 1,830,727 | 6 | 2009-12-02T04:53:21Z | 1,830,820 | 8 | 2009-12-02T05:25:30Z | [
"python",
"module"
] | I need to read all modules (pre-compiled) from a zipfile (built by py2exe compressed) into memory and then load them all.
I know this can be done by loading direct from the zipfile but I need to load them from memory.
Any ideas? (I'm using python 2.5.2 on windows)
TIA Steve | Compiled Python file consist of
1. magic number (4 bytes) to determine type and version of Python,
2. timestamp (4 bytes) to check whether we have newer source,
3. marshaled code object.
To load module you have to create module object with `imp.new_module()`, execute unmashaled code in new module's namespace and put ... |
Does an entertaining guide exist? | 1,830,852 | 9 | 2009-12-02T05:38:19Z | 1,830,881 | 7 | 2009-12-02T05:44:10Z | [
"python"
] | I know of the few normally mentioned Python tutorial/guides/introductions, but I was wondering if there were any that were...more entertaining to go through, I guess.
For example, Ruby has [Why's (Poignant) Guide to Ruby](http://mislav.uniqpath.com/poignant-guide/), Haskell has [Learn You a Haskell for Great Good](htt... | [A Byte of Python](http://www.swaroopch.com/notes/Python "A Byte of Python")
For real entertainment, take [The Python Challenge](http://www.pythonchallenge.com/). |
Is there a tuple data structure in Python | 1,831,218 | 4 | 2009-12-02T07:36:01Z | 1,831,234 | 8 | 2009-12-02T07:38:45Z | [
"python",
"tuples"
] | I want to have an 3 item combination like tag, name, and list of values (array) what is the best possible data structure to store such things.
Current I am using dictionary, but it only allows 2 items, but easy traversal using
```
for k, v in dict.iteritems():
```
can we have something similar like:
```
for k, v, x... | [Python tutorial on data structutres](http://docs.python.org/tutorial/datastructures.html) see section 5.3 "Tuples and sequences"
however, if you want to use "name" to index the data, you probably want to use a dictionary that has the string name as key and values are tuple of (tag, [list, of, values]) e.g.
```
d =... |
Python time comparison | 1,831,410 | 42 | 2009-12-02T08:22:33Z | 1,831,422 | 7 | 2009-12-02T08:26:08Z | [
"python",
"time",
"comparison"
] | How do I compare times in python?
I see that date comparisons can be done and there's also "timedelta", but I'm struggling to find out how to check if the current time (from datetime.now()) is earlier, the same, or later than a specified time (e.g. 8am) regardless of the date. | You can compare datetime.datetime objects directly
E.g:
```
>>> a
datetime.datetime(2009, 12, 2, 10, 24, 34, 198130)
>>> b
datetime.datetime(2009, 12, 2, 10, 24, 36, 910128)
>>> a < b
True
>>> a > b
False
>>> a == a
True
>>> b == b
True
>>>
``` |
Python time comparison | 1,831,410 | 42 | 2009-12-02T08:22:33Z | 1,831,453 | 55 | 2009-12-02T08:32:21Z | [
"python",
"time",
"comparison"
] | How do I compare times in python?
I see that date comparisons can be done and there's also "timedelta", but I'm struggling to find out how to check if the current time (from datetime.now()) is earlier, the same, or later than a specified time (e.g. 8am) regardless of the date. | You *can't* compare a specific point in time (such as "right now") against an unfixed, recurring event (8am happens every day).
You can check if now is before or after *today's* 8am:
```
>>> import datetime
>>> now = datetime.datetime.now()
>>> today8am = now.replace(hour=8, minute=0, second=0, microsecond=0)
>>> now... |
Python time comparison | 1,831,410 | 42 | 2009-12-02T08:22:33Z | 1,831,479 | 38 | 2009-12-02T08:36:19Z | [
"python",
"time",
"comparison"
] | How do I compare times in python?
I see that date comparisons can be done and there's also "timedelta", but I'm struggling to find out how to check if the current time (from datetime.now()) is earlier, the same, or later than a specified time (e.g. 8am) regardless of the date. | You can use the `time()` method of `datetime` objects to get the time of day, which you can use for comparison without taking the date into account:
```
>>> this_morning = datetime.datetime(2009, 12, 2, 9, 30)
>>> last_night = datetime.datetime(2009, 12, 1, 20, 0)
>>> this_morning.time() < last_night.time()
True
``` |
How to refer to the local module in Python? | 1,832,626 | 3 | 2009-12-02T12:28:54Z | 1,832,635 | 10 | 2009-12-02T12:31:48Z | [
"python",
"import",
"module",
"packages"
] | Let's say we have a module `m`:
```
var = None
def get_var():
return var
def set_var(v):
var = v
```
This will not work as expected, because `set_var()` will not store `v` in the module-wide `var`. It will create a local variable `var` instead.
So I need a way of referring the module `m` from within `set_v... | ```
def set_var(v):
global var
var = v
```
The global keyword will allow you to change global variables from within in a function. |
How to refer to the local module in Python? | 1,832,626 | 3 | 2009-12-02T12:28:54Z | 1,832,678 | 9 | 2009-12-02T12:43:20Z | [
"python",
"import",
"module",
"packages"
] | Let's say we have a module `m`:
```
var = None
def get_var():
return var
def set_var(v):
var = v
```
This will not work as expected, because `set_var()` will not store `v` in the module-wide `var`. It will create a local variable `var` instead.
So I need a way of referring the module `m` from within `set_v... | As [Jeffrey Aylesworth's answer](http://stackoverflow.com/questions/1832626/how-to-refer-to-the-local-module-in-python/1832635#1832635) shows, you don't actually need a reference to the local module to achieve the OP's aim. The `global` keyword can achieve this aim.
However for the sake of answering the OP title, *How... |
Python regex matching Unicode properties | 1,832,893 | 41 | 2009-12-02T13:25:41Z | 1,836,283 | 22 | 2009-12-02T22:22:09Z | [
"python",
"regex",
"unicode",
"ucd",
"character-properties"
] | Perl and some other current regex engines support Unicode properties, such as the category, in a regex. E.g. in Perl you can use `\p{Ll}` to match an arbitrary lower-case letter, or `p{Zs}` for any space separator. I don't see support for this in either the 2.x nor 3.x lines of Python (with due regrets). Is anybody awa... | Have you tried [Ponyguruma](https://github.com/mitsuhiko/ponyguruma/), a Python binding to the [Oniguruma](http://www.geocities.jp/kosako3/oniguruma/) regular expression engine? In that engine you can simply say `\p{Armenian}` to match Armenian characters. `\p{Ll}` or `\p{Zs}` work too. |
Python regex matching Unicode properties | 1,832,893 | 41 | 2009-12-02T13:25:41Z | 4,316,097 | 42 | 2010-11-30T16:37:20Z | [
"python",
"regex",
"unicode",
"ucd",
"character-properties"
] | Perl and some other current regex engines support Unicode properties, such as the category, in a regex. E.g. in Perl you can use `\p{Ll}` to match an arbitrary lower-case letter, or `p{Zs}` for any space separator. I don't see support for this in either the 2.x nor 3.x lines of Python (with due regrets). Is anybody awa... | The [regex](http://pypi.python.org/pypi/regex) module (an alternative to the standard `re` module) supports Unicode codepoint properties with the `\p{}` syntax. |
Is using eval in Python a bad practice? | 1,832,940 | 41 | 2009-12-02T13:34:07Z | 1,832,957 | 104 | 2009-12-02T13:37:08Z | [
"python",
"eval"
] | I am using the following class to easily store data of my songs.
```
class Song:
"""The class to store the details of each song"""
attsToStore=('Name', 'Artist', 'Album', 'Genre', 'Location')
def __init__(self):
for att in self.attsToStore:
exec 'self.%s=None'%(att.lower()) in locals()
... | Yes, using eval is a bad practice. Just to name a few reasons:
1. There is almost always a better way to do it
2. Very dangerous and insecure
3. Makes debugging difficult
4. Slow
In your case you can use [setattr](http://docs.python.org/library/functions.html#setattr) instead:
```
class Song:
"""The class to sto... |
Is using eval in Python a bad practice? | 1,832,940 | 41 | 2009-12-02T13:34:07Z | 1,832,968 | 13 | 2009-12-02T13:38:31Z | [
"python",
"eval"
] | I am using the following class to easily store data of my songs.
```
class Song:
"""The class to store the details of each song"""
attsToStore=('Name', 'Artist', 'Album', 'Genre', 'Location')
def __init__(self):
for att in self.attsToStore:
exec 'self.%s=None'%(att.lower()) in locals()
... | In this case, yes. Instead of
```
exec 'self.Foo=val'
```
you should use the [builtin](http://docs.python.org/library/functions.html) function `setattr`:
```
setattr(self, 'Foo', val)
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.