title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
How do I write a single-file Django application? | 1,297,873 | 11 | 2009-08-19T04:58:30Z | 1,297,931 | 11 | 2009-08-19T05:27:30Z | [
"python",
"django",
"web-applications"
] | I want to write a very small Django application in a single file, requiring all the appropriate modules and stuff, and then be able to run that as a normal Python script, like this:
```
$ python myapp.py
```
You can assume I won't render HTML, so I don't need templates (I'll return [JSON](http://en.wikipedia.org/wiki... | You might want to consider Simon Willison's library:
* [djngâa Django powered microframework](http://blog.simonwillison.net/post/57956850422/djng)
From the [readme](http://github.com/simonw/djng/tree/master):
> djng is a micro-framework that depends on a macro-framework (Django).
>
> My definition of a micro-frame... |
How do I write a single-file Django application? | 1,297,873 | 11 | 2009-08-19T04:58:30Z | 2,709,778 | 9 | 2010-04-25T20:11:01Z | [
"python",
"django",
"web-applications"
] | I want to write a very small Django application in a single file, requiring all the appropriate modules and stuff, and then be able to run that as a normal Python script, like this:
```
$ python myapp.py
```
You can assume I won't render HTML, so I don't need templates (I'll return [JSON](http://en.wikipedia.org/wiki... | Getting started with Django can be pretty easy too. Here's a 10-line single-file Django webapp:
```
import os
from django.conf.urls.defaults import patterns
from django.http import HttpResponse
filepath, extension = os.path.splitext(__file__)
ROOT_URLCONF = os.path.basename(filepath)
def yoohoo(request):
return H... |
How to set initial size for a dictionary in Python? | 1,298,636 | 12 | 2009-08-19T09:06:30Z | 1,298,739 | 7 | 2009-08-19T09:24:25Z | [
"python",
"performance",
"dictionary"
] | I'm putting around 4 million different keys into a Python dictionary.
Creating this dictionary takes about 15 minutes and consumes about 4GB of memory on my machine. After the dictionary is fully created, querying the dictionary is fast.
I suspect that dictionary creation is so resource consuming as the dictionary is ... | I tried :
```
a = dict.fromkeys((range(4000000)))
```
It creates a dictionary with 4 000 000 entries in about 3 seconds. After that, setting values are really fast. So I guess dict.fromkey is definitly the way to go. |
How to set initial size for a dictionary in Python? | 1,298,636 | 12 | 2009-08-19T09:06:30Z | 1,298,905 | 21 | 2009-08-19T10:05:42Z | [
"python",
"performance",
"dictionary"
] | I'm putting around 4 million different keys into a Python dictionary.
Creating this dictionary takes about 15 minutes and consumes about 4GB of memory on my machine. After the dictionary is fully created, querying the dictionary is fast.
I suspect that dictionary creation is so resource consuming as the dictionary is ... | With performance issues it's always best to measure. Here are some timings:
```
d = {}
for i in xrange(4000000):
d[i] = None
# 722ms
d = dict(itertools.izip(xrange(4000000), itertools.repeat(None)))
# 634ms
dict.fromkeys(xrange(4000000))
# 558ms
s = set(xrange(4000000))
dict.fromkeys(s)
# Not includi... |
Handling international dates in python | 1,299,377 | 4 | 2009-08-19T11:37:46Z | 1,299,387 | 7 | 2009-08-19T11:40:23Z | [
"python",
"datetime",
"internationalization"
] | I have a date that is either formatted in German for e.g,
```
2. Okt. 2009
```
and also perhaps as
```
2. Oct. 2009
```
How do I parse this into an ISO datetime (or python `datetime`)?
Solved by using this snippet:
```
for l in locale.locale_alias:
worked = False
try:
locale.setlocale(locale.LC_TI... | <http://docs.python.org/library/locale.html>
The `datetime` module is already locale aware.
It's something like the following
```
# German locale
loc= locale.setlocale(locale.LC_TIME,("de","de"))
try:
date= datetime.date.strptime( input, "%d. %b. %Y" )
except:
# English locale
loc= locale.setlocale(lo... |
upload file with Python Mechanize | 1,299,855 | 6 | 2009-08-19T13:15:20Z | 1,305,860 | 11 | 2009-08-20T12:30:32Z | [
"python",
"file",
"forms",
"upload",
"mechanize"
] | When I run the following script:
```
from mechanize import Browser
br = Browser()
br.open(url)
br.select_form(name="edit_form")
br['file'] = 'file.txt'
br.submit()
```
I get: *ValueError: value attribute is readonly*
And I still get the same error when I add:
```
br.form.set_all_readonly(False)
```
So, how can I u... | This is how to do it properly with Mechanize:
```
br.form.add_file(open(filename), 'text/plain', filename)
``` |
How to map one class against multiple tables with SQLAlchemy? | 1,300,433 | 9 | 2009-08-19T14:42:39Z | 1,300,603 | 8 | 2009-08-19T15:13:25Z | [
"python",
"database",
"database-design",
"sqlalchemy"
] | Lets say that I have a database structure with three tables that look like this:
```
items
- item_id
- item_handle
attributes
- attribute_id
- attribute_name
item_attributes
- item_attribute_id
- item_id
- attribute_id
- attribute_value
```
I would like to be able to do this in SQLAlchemy:
```
item = Item(... | This is called the [entity-attribute-value](http://en.wikipedia.org/wiki/Entity-attribute-value_model) pattern. There is an example about this under the SQLAlchemy examples directory: [vertical/](http://www.sqlalchemy.org/trac/browser/examples/vertical/).
If you are using PostgreSQL, then there is also the `hstore` co... |
How to sort digits in a number? | 1,301,156 | 2 | 2009-08-19T16:39:13Z | 1,301,246 | 10 | 2009-08-19T16:55:37Z | [
"python",
"numbers"
] | I'm trying to make an easy script in Python which takes a number and saves in a variable, sorting the digits in ascending and descending orders and saving both in separate variables. Implementing [Kaprekar's constant](http://en.wikipedia.org/wiki/6174).
It's probably a pretty noobish question. But I'm new to this and ... | Sort the digits in ascending and descending orders:
```
ascending = "".join(sorted(str(number)))
descending = "".join(sorted(str(number), reverse=True))
```
Like this:
```
>>> number = 5896
>>> ascending = "".join(sorted(str(number)))
>>>
>>> descending = "".join(sorted(str(number), reverse=True))
>>> ascending
'56... |
C# equivalent of rotating a list using python slice operation | 1,301,316 | 33 | 2009-08-19T17:08:16Z | 1,301,347 | 18 | 2009-08-19T17:11:57Z | [
"c#",
"python",
"algorithm"
] | In python, I can take a list my\_list and rotate the contents:
```
>>> my_list = list(range(10))
>>> my_list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> new_list = my_list[1:] + my_list[:1]
>>> new_list
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
```
What's the equivalent way in C# to create a new list that is a made up of two slices of a... | You can easily use LINQ to do this:
```
// Create the list
int[] my_list = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
IEnumerable<int> new_list =
my_list.Skip(1).Concat(my_list.Take(1));
```
You could even add this as an extension method like so:
```
public static IEnumerable<T> Slice<T>(this IEnumerable<T> e, int count)
... |
C# equivalent of rotating a list using python slice operation | 1,301,316 | 33 | 2009-08-19T17:08:16Z | 1,301,351 | 9 | 2009-08-19T17:12:27Z | [
"c#",
"python",
"algorithm"
] | In python, I can take a list my\_list and rotate the contents:
```
>>> my_list = list(range(10))
>>> my_list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> new_list = my_list[1:] + my_list[:1]
>>> new_list
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
```
What's the equivalent way in C# to create a new list that is a made up of two slices of a... | The closest thing in C# would be to use the [Enumerable.Skip](http://msdn.microsoft.com/en-us/library/bb358985.aspx) and [Enumerable.Take](http://msdn.microsoft.com/en-us/library/bb503062.aspx) extension methods. You could use these to build your new list. |
C# equivalent of rotating a list using python slice operation | 1,301,316 | 33 | 2009-08-19T17:08:16Z | 1,301,362 | 39 | 2009-08-19T17:14:13Z | [
"c#",
"python",
"algorithm"
] | In python, I can take a list my\_list and rotate the contents:
```
>>> my_list = list(range(10))
>>> my_list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> new_list = my_list[1:] + my_list[:1]
>>> new_list
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
```
What's the equivalent way in C# to create a new list that is a made up of two slices of a... | ```
var newlist = oldlist.Skip(1).Concat(oldlist.Take(1));
``` |
The meaning of a single- and a double-underscore before an object name in Python | 1,301,346 | 668 | 2009-08-19T17:11:57Z | 1,301,369 | 635 | 2009-08-19T17:15:53Z | [
"python",
"naming-conventions",
"private",
"underscores",
"double-underscore"
] | I want to clear this up once and for all. Can someone please explain the exact meaning of having leading underscores before an object's name in Python? Also explain the difference between a single and a double leading underscore. Also, does that meaning stay the same whether the object in question is a variable, a func... | ## Single Underscore
Names, in a class, with a leading underscore are simply to indicate to other programmers that the attribute or method is intended to be private. However, nothing special is done with the name itself.
To quote [PEP-8](http://www.python.org/dev/peps/pep-0008/):
> \_single\_leading\_underscore: wea... |
The meaning of a single- and a double-underscore before an object name in Python | 1,301,346 | 668 | 2009-08-19T17:11:57Z | 1,301,409 | 171 | 2009-08-19T17:21:29Z | [
"python",
"naming-conventions",
"private",
"underscores",
"double-underscore"
] | I want to clear this up once and for all. Can someone please explain the exact meaning of having leading underscores before an object's name in Python? Also explain the difference between a single and a double leading underscore. Also, does that meaning stay the same whether the object in question is a variable, a func... | `__foo__`: this is just a convention, a way for the Python system to use names that won't conflict with user names.
`_foo`: this is just a convention, a way for the programmer to indicate that the variable is private (whatever that means in Python).
`__foo`: this has real meaning: the interpreter replaces this name w... |
The meaning of a single- and a double-underscore before an object name in Python | 1,301,346 | 668 | 2009-08-19T17:11:57Z | 1,301,557 | 225 | 2009-08-19T17:52:36Z | [
"python",
"naming-conventions",
"private",
"underscores",
"double-underscore"
] | I want to clear this up once and for all. Can someone please explain the exact meaning of having leading underscores before an object's name in Python? Also explain the difference between a single and a double leading underscore. Also, does that meaning stay the same whether the object in question is a variable, a func... | Excellent answers so far but some tidbits are missing. A single leading underscore isn't exactly *just* a convention: if you use `from foobar import *`, and module `foobar` does not define an `__all__` list, the names imported from the module **do not** include those with a leading underscore. Let's say it's *mostly* a... |
The meaning of a single- and a double-underscore before an object name in Python | 1,301,346 | 668 | 2009-08-19T17:11:57Z | 8,822,881 | 15 | 2012-01-11T16:28:22Z | [
"python",
"naming-conventions",
"private",
"underscores",
"double-underscore"
] | I want to clear this up once and for all. Can someone please explain the exact meaning of having leading underscores before an object's name in Python? Also explain the difference between a single and a double leading underscore. Also, does that meaning stay the same whether the object in question is a variable, a func... | Sometimes you have what appears to be a tuple with a leading underscore as in
```
def foo(bar):
return _('my_' + bar)
```
In this case, what's going on is that \_() is an alias for a localization function that operates on text to put it into the proper language, etc. based on the locale. For example, Sphinx does ... |
The meaning of a single- and a double-underscore before an object name in Python | 1,301,346 | 668 | 2009-08-19T17:11:57Z | 12,629,901 | 82 | 2012-09-27T20:56:44Z | [
"python",
"naming-conventions",
"private",
"underscores",
"double-underscore"
] | I want to clear this up once and for all. Can someone please explain the exact meaning of having leading underscores before an object's name in Python? Also explain the difference between a single and a double leading underscore. Also, does that meaning stay the same whether the object in question is a variable, a func... | `._variable` is semiprivate and meant just for convention
`.__variable` is often incorrectly considered superprivate, while it's actual meaning is just to namemangle to **prevent accidental access**[[1]](https://www.youtube.com/watch?v=HTLu2DFOdTg&t=33m8s)
`.__variable__` is typically reserved for builtin methods or ... |
The meaning of a single- and a double-underscore before an object name in Python | 1,301,346 | 668 | 2009-08-19T17:11:57Z | 27,481,645 | 47 | 2014-12-15T10:10:20Z | [
"python",
"naming-conventions",
"private",
"underscores",
"double-underscore"
] | I want to clear this up once and for all. Can someone please explain the exact meaning of having leading underscores before an object's name in Python? Also explain the difference between a single and a double leading underscore. Also, does that meaning stay the same whether the object in question is a variable, a func... | **Single underscore at the beginning:**
Python doesn't have real private methods, so one underscore at the start of a method or attribute name means you shouldn't access this method, because it's not part of the API.
```
class BaseForm(StrAndUnicode):
def _get_errors(self):
"Returns an ErrorDict for the ... |
Python IDE on Linux Console | 1,301,352 | 10 | 2009-08-19T17:12:36Z | 1,301,370 | 9 | 2009-08-19T17:16:14Z | [
"python",
"shell",
"vi"
] | This may sound strange, but I need a better way to build python scripts than opening a file with nano/vi, change something, quit the editor, and type in `python script.py`, over and over again.
I need to build the script on a webserver without any gui. Any ideas how can I improve my workflow? | You should give the [screen](http://www.gnu.org/software/screen/screen.html) utility a look. While it's not an IDE it is some kind of window manager on the terminal -- i.e. you can have multiple windows and switch between them, which makes especially tasks like this much easier. |
Python IDE on Linux Console | 1,301,352 | 10 | 2009-08-19T17:12:36Z | 1,301,423 | 18 | 2009-08-19T17:24:01Z | [
"python",
"shell",
"vi"
] | This may sound strange, but I need a better way to build python scripts than opening a file with nano/vi, change something, quit the editor, and type in `python script.py`, over and over again.
I need to build the script on a webserver without any gui. Any ideas how can I improve my workflow? | put this line in your .vimrc file:
```
:map <F2> :w\|!python %<CR>
```
now hitting `<F2>` will save and run your python script |
Python: Why are some of Queue.queue's method "unreliable"? | 1,301,416 | 6 | 2009-08-19T17:22:43Z | 1,301,463 | 9 | 2009-08-19T17:31:55Z | [
"python",
"multithreading",
"queue"
] | In the `queue` class from the `Queue` module, there are a few methods, namely, `qsize`, `empty` and `full`, whose documentation claims they are "not reliable".
What exactly is not reliable about them?
I did notice that [on the Python docs](http://docs.python.org/library/queue.html) site, the following is said about `... | Yes, the docs use "unreliable" here to convey exactly this meaning: for example, in a sense, `qsize` doesn't tell you how many entries there are "right now", a concept that is not necessarily very meaningful in a multithreaded world (except at specific points where synchronization precautions are being taken) -- it tel... |
Setting timezone in Python | 1,301,493 | 21 | 2009-08-19T17:38:31Z | 1,301,528 | 38 | 2009-08-19T17:46:03Z | [
"python",
"timezone"
] | Is it possible with Python to set the timezone just like this in PHP:
```
date_default_timezone_set("Europe/London");
$Year = date('y');
$Month = date('m');
$Day = date('d');
$Hour = date('H');
$Minute = date('i');
```
I can't really install any other modules etc as I'm using shared web hosting.
Any ideas? | ```
>>> import os, time
>>> time.strftime('%X %x %Z')
'12:45:20 08/19/09 CDT'
>>> os.environ['TZ'] = 'Europe/London'
>>> time.tzset()
>>> time.strftime('%X %x %Z')
'18:45:39 08/19/09 BST'
```
To get the specific values you've listed:
```
>>> year = time.strftime('%Y')
>>> month = time.strftime('%m')
>>> day = time.st... |
Counting python method calls within another method | 1,301,735 | 7 | 2009-08-19T18:19:20Z | 1,301,926 | 13 | 2009-08-19T18:52:56Z | [
"python",
"profiling"
] | I'm actually trying doing this in Java, but I'm in the process of teaching myself python and it made me wonder if there was an easy/clever way to do this with wrappers or something.
I want to know how many times a specific method was called inside another method. For example:
```
def foo(z):
#do something
ret... | Sounds like almost the textbook example for decorators!
```
def counted(fn):
def wrapper(*args, **kwargs):
wrapper.called+= 1
return fn(*args, **kwargs)
wrapper.called= 0
wrapper.__name__= fn.__name__
return wrapper
@counted
def foo():
return
>>> foo()
>>> foo.called
1
```
You co... |
Why is Standard Input is not displayed as I type in Mac OS X Terminal application? | 1,301,887 | 10 | 2009-08-19T18:44:56Z | 2,623,452 | 19 | 2010-04-12T16:03:17Z | [
"python",
"django",
"osx",
"shell",
"terminal"
] | I'm confused by some behavior of my Mac OS X Terminal and my Django `manage.py` shell and pdb.
When I start a new terminal, the Standard Input is displayed as I type. However, if there is an error, suddenly Standard Input does not appear on the screen. This error continues until I shut down that terminal window.
The ... | Maybe this is because there was an error while running Django. Sometimes it happens that the std input disappears because `stty` was used. You can manually hide your input by typing:
`$ stty -echo`
Now you won't see what you typed. To restore this and solve your problem just type
`$ stty echo`
This could help. |
cutdown uuid further to make short string | 1,302,057 | 5 | 2009-08-19T19:13:04Z | 1,302,076 | 9 | 2009-08-19T19:17:50Z | [
"c#",
"python",
"string",
"uniqueidentifier",
"uuid"
] | I need to generate unique record id for the given unique string.
I tried using uuid format which seems to be good.
But we feel that is lengthly.
so we need to cutdown the uuid string 9f218a38-12cd-5942-b877-80adc0589315 to smaller. By removing '-' we can save 4 chars. What is the safest part to remove from uuid? We ... | Why not instead just convert it to a base 64 string? You can cut it down to 22 characters that way.
<http://stackoverflow.com/questions/772802/storing-uuid-as-base64-string> |
How do I parse timezones with UTC offsets in Python? | 1,302,161 | 6 | 2009-08-19T19:30:17Z | 2,496,144 | 21 | 2010-03-22T22:10:47Z | [
"python",
"datetime"
] | Let's say I have a timezone like "2009-08-18 13:52:54-04". I can parse most of it using a line like this:
```
datetime.strptime(time_string, "%Y-%m-%d %H:%M:%S")
```
However, I can't get the timezone to work. There's a %Z that handles textual timezones ("EST", "UTC", etc) but I don't see anything that can parse "-04"... | Maybe you could use [dateutil.parser.parse](http://labix.org/python-dateutil)? That method is also mentioned on [wiki.python.org/WorkingWithTime](http://wiki.python.org/moin/WorkingWithTime#ParsingISO8601withpython-dateutil).
```
>>> from dateutil.parser import parse
>>> parse("2009-08-18 13:52:54-04")
datetime.dateti... |
Python PEP8 printing wrapped strings without indent | 1,302,364 | 11 | 2009-08-19T20:10:40Z | 1,302,381 | 28 | 2009-08-19T20:13:19Z | [
"python",
"wrapping",
"pep8"
] | There is probably an easy answer for this, just not sure how to tease it out of my searches.
I adhere to [PEP8](http://www.python.org/dev/peps/pep-0008/) in my python code, and I'm currently using OptionParser for a script I'm writing. To prevent lines from going beyond a with of 80, I use the backslash where needed.
... | Use [automatic string concatenation](http://docs.python.org/tutorial/introduction.html#strings) + [implicit line continuation](http://docs.python.org/reference/lexical%5Fanalysis.html#implicit-line-joining):
```
long_string = ("Line 1 "
"Line 2 "
"Line 3 ")
>>> long_string
'Line 1 Line ... |
python for firefox extensions? | 1,302,567 | 23 | 2009-08-19T20:50:25Z | 1,302,574 | 23 | 2009-08-19T20:51:38Z | [
"python",
"firefox",
"plugins",
"firefox-addon"
] | Can I use python in firefox extensions? Does it work? | **Yes**, through an extension for mozilla, Python Extension (pythonext).
Originally hosted in [mozdev](http://pyxpcomext.mozdev.org/), PythonExt project have move to Google code, **you can see it in [PythonExt in Google code](http://code.google.com/p/pythonext/)**. |
How can I convert a URL query string into a list of tuples using Python? | 1,302,688 | 8 | 2009-08-19T21:23:16Z | 1,302,696 | 26 | 2009-08-19T21:25:00Z | [
"python",
"url",
"parsing"
] | I am struggling to convert a url to a nested tuple.
```
# Convert this string
str = 'http://somesite.com/?foo=bar&key=val'
# to a tuple like this:
[(u'foo', u'bar'), (u'key', u'val')]
```
I assume I need to be doing something like:
```
url = 'http://somesite.com/?foo=bar&key=val'
url = url.split('?')
get = ()
f... | I believe you are looking for the [`urlparse`](http://docs.python.org/library/urlparse.html) module.
> This module defines a standard
> interface to break Uniform Resource
> Locator (URL) strings up in components
> (addressing scheme, network location,
> path etc.), to combine the components
> back into a URL string, ... |
What possible values does datetime.strptime() accept for %Z? | 1,302,701 | 10 | 2009-08-19T21:26:21Z | 1,302,793 | 9 | 2009-08-19T21:44:04Z | [
"python",
"datetime"
] | Python's datetime.strptime() is documented as supporting a timezone in the %Z field. So, for example:
```
In [1]: datetime.strptime('2009-08-19 14:20:36 UTC', "%Y-%m-%d %H:%M:%S %Z")
Out[1]: datetime.datetime(2009, 8, 19, 14, 20, 36)
```
However, "UTC" seems to be the only timezone I can get it to support:
```
In [2... | I gather they are GMT, UTC, and whatever is listed in time.tzname.
```
>>> for t in time.tzname:
... print t
...
Eastern Standard Time
Eastern Daylight Time
>>> datetime.strptime('2009-08-19 14:20:36 Eastern Standard Time', "%Y-%m-%d %H:%M:%S %Z")
datetime.datetime(2009, 8, 19, 14, 20, 36)
>>> datetime.strptime('2... |
Shortest hash in python to name cache files | 1,303,021 | 15 | 2009-08-19T22:43:51Z | 1,303,050 | 26 | 2009-08-19T22:49:21Z | [
"python",
"hash"
] | What is the shortest hash (in filename-usable form, like a hexdigest) available in python? My application wants to save *cache files* for some objects. The objects must have unique repr() so they are used to 'seed' the filename. I want to produce a possibly unique filename for each object (not that many). They should n... | The builtin hash function of strings is fairly collision free, and also fairly short. It has `2**32` values, so it is fairly unlikely that you encounter collisions (if you use its abs value, it will have only `2**31` values).
You have been asking for the shortest hash function. That would certainly be
```
def hash(s)... |
Shortest hash in python to name cache files | 1,303,021 | 15 | 2009-08-19T22:43:51Z | 1,303,063 | 7 | 2009-08-19T22:53:53Z | [
"python",
"hash"
] | What is the shortest hash (in filename-usable form, like a hexdigest) available in python? My application wants to save *cache files* for some objects. The objects must have unique repr() so they are used to 'seed' the filename. I want to produce a possibly unique filename for each object (not that many). They should n... | You can make any hash you like shorter by simply truncating it. md5 is always 32 hex digits, but an arbitrary substring of it (or any other hash) has the proper qualities of a hash: equal values produce equal hashes, and the values are spread around a bunch. |
Shortest hash in python to name cache files | 1,303,021 | 15 | 2009-08-19T22:43:51Z | 1,303,619 | 33 | 2009-08-20T02:12:31Z | [
"python",
"hash"
] | What is the shortest hash (in filename-usable form, like a hexdigest) available in python? My application wants to save *cache files* for some objects. The objects must have unique repr() so they are used to 'seed' the filename. I want to produce a possibly unique filename for each object (not that many). They should n... | The [birthday paradox](http://en.wikipedia.org/wiki/Birthday%5Fparadox#Cast%5Fas%5Fa%5Fcollision%5Fproblem) applies: given a good hash function, the expected number of hashes before a collision occurs is about sqrt(N), where N is the number of different values that the hash function can take. (The wikipedia entry I've ... |
How to find out if a Python object is a string? | 1,303,243 | 195 | 2009-08-19T23:50:58Z | 1,303,252 | 181 | 2009-08-19T23:53:12Z | [
"python",
"string",
"types",
"compatibility"
] | How can I check if a Python object is a string (either regular or Unicode)? | # Python 2
Use `isinstance(obj, basestring)` for an object-to-test `obj`.
[Docs](http://docs.python.org/library/functions.html#basestring). |
How to find out if a Python object is a string? | 1,303,243 | 195 | 2009-08-19T23:50:58Z | 1,303,266 | 92 | 2009-08-19T23:58:15Z | [
"python",
"string",
"types",
"compatibility"
] | How can I check if a Python object is a string (either regular or Unicode)? | To check if an object `o` is a string type of a subclass of a string type:
```
isinstance(o, basestring)
```
because both `str` and `unicode` are subclasses of `basestring`.
To check if the type of `o` is exactly `str`:
```
type(o) is str
```
To check if `o` is an instance of `str` or any subclass of `str`:
```
i... |
How to find out if a Python object is a string? | 1,303,243 | 195 | 2009-08-19T23:50:58Z | 23,692,403 | 37 | 2014-05-16T03:57:49Z | [
"python",
"string",
"types",
"compatibility"
] | How can I check if a Python object is a string (either regular or Unicode)? | # Python 2 and 3
### (cross-compatible)
If you want to check with no regard for Python version (2.x vs 3.x), use [**`six`**](http://pythonhosted.org/six/) ([PyPI](https://pypi.python.org/pypi/six/)) and it's `string_types` attribute:
```
import six
if isinstance(obj, six.string_types):
print('obj is a string!')... |
How to find out if a Python object is a string? | 1,303,243 | 195 | 2009-08-19T23:50:58Z | 26,535,728 | 36 | 2014-10-23T19:19:58Z | [
"python",
"string",
"types",
"compatibility"
] | How can I check if a Python object is a string (either regular or Unicode)? | # Python 3
In Python 3.x `basestring` is not available anymore, as `str` is the sole string type (with the semantics of Python 2.x's `unicode`).
So the check in Python 3.x is just:
```
isinstance(obj_to_test, str)
```
This follows [the fix](https://docs.python.org/2/library/2to3.html#2to3fixer-basestring) of the of... |
FFT for Spectrograms in Python | 1,303,307 | 24 | 2009-08-20T00:14:03Z | 1,303,325 | 23 | 2009-08-20T00:19:31Z | [
"python",
"image",
"graphics",
"audio",
"fft"
] | How would I go about using Python to read the frequency peaks from a WAV PCM file and then be able to generate an image of it, for spectogram analysis?
I'm trying to make a program that allows you to read any audio file, converting it to WAV PCM, and then finding the peaks and frequency cutoffs. | [Python's wave library](http://docs.python.org/library/wave.html) will let you import the audio. After that, you can [use numpy to take an FFT](http://docs.scipy.org/doc/numpy/reference/routines.fft.html) of the audio.
Then, [matplotlib](http://matplotlib.sourceforge.net/index.html) makes very nice charts and graphs -... |
FFT for Spectrograms in Python | 1,303,307 | 24 | 2009-08-20T00:14:03Z | 1,368,688 | 13 | 2009-09-02T16:15:24Z | [
"python",
"image",
"graphics",
"audio",
"fft"
] | How would I go about using Python to read the frequency peaks from a WAV PCM file and then be able to generate an image of it, for spectogram analysis?
I'm trying to make a program that allows you to read any audio file, converting it to WAV PCM, and then finding the peaks and frequency cutoffs. | Loading WAV files is easy using [audiolab](http://cournape.github.com/audiolab/):
```
from audiolab import wavread
signal, fs, enc = wavread('test.wav')
```
or for reading any general audio format and converting to WAV:
```
from audiolab import Sndfile
sound_file = Sndfile('test.w64', 'r')
signal = wave_file.read_fr... |
Getting a map() to return a list in Python 3.x | 1,303,347 | 155 | 2009-08-20T00:27:26Z | 1,303,353 | 50 | 2009-08-20T00:28:19Z | [
"python",
"list",
"python-3.x",
"map-function"
] | I'm trying to map a list into hex, and then use the list elsewhere. In python 2.6, this was easy:
**A:** Python 2.6:
```
>>> map(chr, [66, 53, 0, 94])
['B', '5', '\x00', '^']
```
However, on Python 3.1, the above returns a map object.
**B:** Python 3.1:
```
>>> map(chr, [66, 53, 0, 94])
<map object at 0x00AF5570>
... | Why aren't you doing this:
```
[chr(x) for x in [66,53,0,94]]
```
It's called a list comprehension. You can find plenty of information on Google, but [here's the link to the Python (2.6) documentation on list comprehensions](http://docs.python.org/tutorial/datastructures.html#list-comprehensions). You might be more i... |
Getting a map() to return a list in Python 3.x | 1,303,347 | 155 | 2009-08-20T00:27:26Z | 1,303,354 | 256 | 2009-08-20T00:28:40Z | [
"python",
"list",
"python-3.x",
"map-function"
] | I'm trying to map a list into hex, and then use the list elsewhere. In python 2.6, this was easy:
**A:** Python 2.6:
```
>>> map(chr, [66, 53, 0, 94])
['B', '5', '\x00', '^']
```
However, on Python 3.1, the above returns a map object.
**B:** Python 3.1:
```
>>> map(chr, [66, 53, 0, 94])
<map object at 0x00AF5570>
... | Do this:
```
list(map(chr,[66,53,0,94]))
```
In Python 3+, many processes that iterate over iterables return iterators themselves. In most cases, this ends up saving memory, and should make things go faster.
If all you're going to do is iterate over this list eventually, there's no need to even convert it to a list,... |
Getting a map() to return a list in Python 3.x | 1,303,347 | 155 | 2009-08-20T00:27:26Z | 1,303,355 | 9 | 2009-08-20T00:28:44Z | [
"python",
"list",
"python-3.x",
"map-function"
] | I'm trying to map a list into hex, and then use the list elsewhere. In python 2.6, this was easy:
**A:** Python 2.6:
```
>>> map(chr, [66, 53, 0, 94])
['B', '5', '\x00', '^']
```
However, on Python 3.1, the above returns a map object.
**B:** Python 3.1:
```
>>> map(chr, [66, 53, 0, 94])
<map object at 0x00AF5570>
... | I'm not familiar with Python 3.1, but will this work?
```
[chr(x) for x in [66, 53, 0, 94]]
``` |
Getting a map() to return a list in Python 3.x | 1,303,347 | 155 | 2009-08-20T00:27:26Z | 24,507,069 | 13 | 2014-07-01T09:41:21Z | [
"python",
"list",
"python-3.x",
"map-function"
] | I'm trying to map a list into hex, and then use the list elsewhere. In python 2.6, this was easy:
**A:** Python 2.6:
```
>>> map(chr, [66, 53, 0, 94])
['B', '5', '\x00', '^']
```
However, on Python 3.1, the above returns a map object.
**B:** Python 3.1:
```
>>> map(chr, [66, 53, 0, 94])
<map object at 0x00AF5570>
... | List-returning map function has the advantage of saving typing, especially during interactive sessions. You can define `lmap` function (on the analogy of python2's `imap`) that returns list:
```
lmap = lambda func, *iterable: list(map(func, *iterable)
```
Then calling `lmap` instead of `map` will do the job:
`lmap(st... |
Threaded Django task doesn't automatically handle transactions or db connections? | 1,303,654 | 50 | 2009-08-20T02:26:48Z | 1,346,401 | 85 | 2009-08-28T11:22:05Z | [
"python",
"database",
"django",
"multithreading",
"transactions"
] | I've got Django set up to run some recurring tasks in their own threads, and I noticed that they were always leaving behind unfinished database connection processes (pgsql "Idle In Transaction").
I looked through the Postgres logs and found that the transactions weren't being completed (no ROLLBACK). I tried using the... | After weeks of testing and reading the Django source code, I've found the answer to my own question:
**Transactions**
Django's default autocommit behavior still holds true for my threaded function. However, it states in the Django docs:
> As soon as you perform an action that needs to write to the database, Django p... |
Python string interpolation using dictionary and strings | 1,304,025 | 17 | 2009-08-20T04:54:16Z | 1,304,050 | 10 | 2009-08-20T05:03:33Z | [
"python",
"string",
"interpolation"
] | Given:
```
dict = {"path": "/var/blah"}
curr = "1.1"
prev = "1.0"
```
What's the best/shortest way to interpolate the string to generate the following:
> path: /var/blah curr: 1.1 prev: 1.0
I know this works:
```
str = "path: %(path)s curr: %(curr)s prev: %(prev)s" % {"path": dict["path"],"curr": curr, "prev": pre... | Maybe:
```
path = dict['path']
str = "path: %(path)s curr: %(curr)s prev: %(prev)s" % locals()
```
I mean it works:
```
>>> dict = {"path": "/var/blah"}
>>> curr = "1.1"
>>> prev = "1.0"
>>> path = dict['path']
>>> str = "path: %(path)s curr: %(curr)s prev: %(prev)s" % locals()
>>> str
'path: /var/blah curr: 1.1 pre... |
Python string interpolation using dictionary and strings | 1,304,025 | 17 | 2009-08-20T04:54:16Z | 1,304,088 | 10 | 2009-08-20T05:16:38Z | [
"python",
"string",
"interpolation"
] | Given:
```
dict = {"path": "/var/blah"}
curr = "1.1"
prev = "1.0"
```
What's the best/shortest way to interpolate the string to generate the following:
> path: /var/blah curr: 1.1 prev: 1.0
I know this works:
```
str = "path: %(path)s curr: %(curr)s prev: %(prev)s" % {"path": dict["path"],"curr": curr, "prev": pre... | Why not:
```
mystr = "path: %s curr: %s prev: %s" % (mydict[path], curr, prev)
```
BTW, I've changed a couple names you were using that trample upon builtin names -- don't do that, it's never needed and once in a while will waste a lot of your time tracking down a misbehavior it causes (where something's using the bu... |
Python string interpolation using dictionary and strings | 1,304,025 | 17 | 2009-08-20T04:54:16Z | 1,304,098 | 38 | 2009-08-20T05:20:28Z | [
"python",
"string",
"interpolation"
] | Given:
```
dict = {"path": "/var/blah"}
curr = "1.1"
prev = "1.0"
```
What's the best/shortest way to interpolate the string to generate the following:
> path: /var/blah curr: 1.1 prev: 1.0
I know this works:
```
str = "path: %(path)s curr: %(curr)s prev: %(prev)s" % {"path": dict["path"],"curr": curr, "prev": pre... | You can try this:
```
data = {"path": "/var/blah",
"curr": "1.1",
"prev": "1.0"}
s = "path: %(path)s curr: %(curr)s prev: %(prev)s" % data
``` |
Python string interpolation using dictionary and strings | 1,304,025 | 17 | 2009-08-20T04:54:16Z | 1,304,483 | 17 | 2009-08-20T07:17:00Z | [
"python",
"string",
"interpolation"
] | Given:
```
dict = {"path": "/var/blah"}
curr = "1.1"
prev = "1.0"
```
What's the best/shortest way to interpolate the string to generate the following:
> path: /var/blah curr: 1.1 prev: 1.0
I know this works:
```
str = "path: %(path)s curr: %(curr)s prev: %(prev)s" % {"path": dict["path"],"curr": curr, "prev": pre... | And of course you could use the newer (from 2.6) [**.format**](http://docs.python.org/library/string.html#format-string-syntax) string method:
```
>>> mydict = {"path": "/var/blah"}
>>> curr = "1.1"
>>> prev = "1.0"
>>>
>>> s = "path: {0} curr: {1} prev: {2}".format(mydict['path'], curr, prev)
>>> s
'path: /var/blah c... |
Python socket error occured | 1,305,050 | 4 | 2009-08-20T09:36:41Z | 1,305,381 | 8 | 2009-08-20T10:54:41Z | [
"python",
"sockets"
] | I wrote this code.
```
import socket
host = 'localhost'
port = 3794
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.bind((host, port))
while 1:
print 'Type message you want to send...'
... | This means that you already have a socket bound to 3794 port.
It may be another application or it means that port didn't got released yet after the previous run of your own script (it happens, if script terminated improperly).
Simply try to use another port number - I believe everything will work fine. |
python 3.1 with pydev | 1,305,218 | 5 | 2009-08-20T10:22:37Z | 1,305,253 | 10 | 2009-08-20T10:31:19Z | [
"python",
"eclipse",
"python-3.x",
"pydev"
] | I am now moving to eclipse for my python development. I have pydev installed but it is showing grammar support up to python version 3.0. My question is can I use python 3.1 with 3.0 grammar? Has the grammar changed from version 3.0 to 3.1?
I am using eclipse 3.4.2 and pydev 1.4.7 | grammar hasn't changed, some [modules have](http://docs.python.org/3.1/whatsnew/3.1.html). |
Convert Python dict to object? | 1,305,532 | 322 | 2009-08-20T11:28:18Z | 1,305,547 | 47 | 2009-08-20T11:31:34Z | [
"python",
"object",
"dictionary"
] | I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.
For example:
```
>>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}
```
Should be accessible in this way:
```
>>> x = dict2obj(d)
>>> x.a
1
>>> x.b.c
2
>>> x.d[1].foo
bar
```
I think, this is not possibl... | ```
x = type('new_dict', (object,), d)
```
then add recursion to this and you're done.
**edit** this is how I'd implement it:
```
>>> d
{'a': 1, 'b': {'c': 2}, 'd': ['hi', {'foo': 'bar'}]}
>>> def obj_dic(d):
top = type('new', (object,), d)
seqs = tuple, list, set, frozenset
for i, j in d.items():
i... |
Convert Python dict to object? | 1,305,532 | 322 | 2009-08-20T11:28:18Z | 1,305,548 | 7 | 2009-08-20T11:31:59Z | [
"python",
"object",
"dictionary"
] | I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.
For example:
```
>>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}
```
Should be accessible in this way:
```
>>> x = dict2obj(d)
>>> x.a
1
>>> x.b.c
2
>>> x.d[1].foo
bar
```
I think, this is not possibl... | `x.__dict__.update(d)` should do fine. |
Convert Python dict to object? | 1,305,532 | 322 | 2009-08-20T11:28:18Z | 1,305,643 | 10 | 2009-08-20T11:50:56Z | [
"python",
"object",
"dictionary"
] | I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.
For example:
```
>>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}
```
Should be accessible in this way:
```
>>> x = dict2obj(d)
>>> x.a
1
>>> x.b.c
2
>>> x.d[1].foo
bar
```
I think, this is not possibl... | ```
>>> def dict2obj(d):
if isinstance(d, list):
d = [dict2obj(x) for x in d]
if not isinstance(d, dict):
return d
class C(object):
pass
o = C()
for k in d:
o.__dict__[k] = dict2obj(d[k])
return o
>>> d = {'a': 1, 'b': {'c': 2},... |
Convert Python dict to object? | 1,305,532 | 322 | 2009-08-20T11:28:18Z | 1,305,663 | 495 | 2009-08-20T11:55:39Z | [
"python",
"object",
"dictionary"
] | I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.
For example:
```
>>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}
```
Should be accessible in this way:
```
>>> x = dict2obj(d)
>>> x.a
1
>>> x.b.c
2
>>> x.d[1].foo
bar
```
I think, this is not possibl... | **Update:** In Python 2.6 and onwards, consider whether the [`namedtuple`](https://docs.python.org/2/library/collections.html#collections.namedtuple) data structure suits your needs:
```
>>> from collections import namedtuple
>>> MyStruct = namedtuple('MyStruct', 'a b d')
>>> s = MyStruct(a=1, b={'c': 2}, d=['hi'])
>>... |
Convert Python dict to object? | 1,305,532 | 322 | 2009-08-20T11:28:18Z | 1,305,682 | 67 | 2009-08-20T11:58:36Z | [
"python",
"object",
"dictionary"
] | I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.
For example:
```
>>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}
```
Should be accessible in this way:
```
>>> x = dict2obj(d)
>>> x.a
1
>>> x.b.c
2
>>> x.d[1].foo
bar
```
I think, this is not possibl... | ```
class obj(object):
def __init__(self, d):
for a, b in d.items():
if isinstance(b, (list, tuple)):
setattr(self, a, [obj(x) if isinstance(x, dict) else x for x in b])
else:
setattr(self, a, obj(b) if isinstance(b, dict) else b)
>>> d = {'a': 1, 'b': ... |
Convert Python dict to object? | 1,305,532 | 322 | 2009-08-20T11:28:18Z | 6,573,827 | 27 | 2011-07-04T16:12:02Z | [
"python",
"object",
"dictionary"
] | I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.
For example:
```
>>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}
```
Should be accessible in this way:
```
>>> x = dict2obj(d)
>>> x.a
1
>>> x.b.c
2
>>> x.d[1].foo
bar
```
I think, this is not possibl... | Taking what I feel are the best aspects of the previous examples, here's what I came up with:
```
class Struct:
'''The recursive class for building and representing objects with.'''
def __init__(self, obj):
for k, v in obj.iteritems():
if isinstance(v, dict):
setattr(self, k, Struct(v))
els... |
Convert Python dict to object? | 1,305,532 | 322 | 2009-08-20T11:28:18Z | 6,993,694 | 17 | 2011-08-09T08:58:27Z | [
"python",
"object",
"dictionary"
] | I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.
For example:
```
>>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}
```
Should be accessible in this way:
```
>>> x = dict2obj(d)
>>> x.a
1
>>> x.b.c
2
>>> x.d[1].foo
bar
```
I think, this is not possibl... | ```
class Struct(object):
"""Comment removed"""
def __init__(self, data):
for name, value in data.iteritems():
setattr(self, name, self._wrap(value))
def _wrap(self, value):
if isinstance(value, (tuple, list, set, frozenset)):
return type(value)([self._wrap(v) for v... |
Convert Python dict to object? | 1,305,532 | 322 | 2009-08-20T11:28:18Z | 9,413,295 | 33 | 2012-02-23T12:43:16Z | [
"python",
"object",
"dictionary"
] | I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.
For example:
```
>>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}
```
Should be accessible in this way:
```
>>> x = dict2obj(d)
>>> x.a
1
>>> x.b.c
2
>>> x.d[1].foo
bar
```
I think, this is not possibl... | For anyone who happens to stumble upon this question nowadays. In Python 2.6+ there's a
collection helper called [`namedtuple`](http://docs.python.org/library/collections.html?highlight=collections#namedtuple-factory-function-for-tuples-with-named-fields), that can do this for you:
```
from collections import namedtup... |
Convert Python dict to object? | 1,305,532 | 322 | 2009-08-20T11:28:18Z | 15,589,291 | 10 | 2013-03-23T16:41:48Z | [
"python",
"object",
"dictionary"
] | I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.
For example:
```
>>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}
```
Should be accessible in this way:
```
>>> x = dict2obj(d)
>>> x.a
1
>>> x.b.c
2
>>> x.d[1].foo
bar
```
I think, this is not possibl... | If you want to access dict keys as an object (or as a dict for difficult keys), do it recursively, and also be able to update the original dict, you could do:
```
class Dictate(object):
"""Object view of a dict, updating the passed in dict when values are set
or deleted. "Dictate" the contents of a dict...: ""... |
Convert Python dict to object? | 1,305,532 | 322 | 2009-08-20T11:28:18Z | 15,882,327 | 15 | 2013-04-08T14:53:46Z | [
"python",
"object",
"dictionary"
] | I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.
For example:
```
>>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}
```
Should be accessible in this way:
```
>>> x = dict2obj(d)
>>> x.a
1
>>> x.b.c
2
>>> x.d[1].foo
bar
```
I think, this is not possibl... | If your dict is coming from `json.loads()`, you can turn it into an object instead (rather than a dict) in one line:
```
import json
from collections import namedtuple
json.loads(data, object_hook=lambda d: namedtuple('X', d.keys())(*d.values()))
```
See also [How to convert JSON data into a Python object](http://st... |
Convert Python dict to object? | 1,305,532 | 322 | 2009-08-20T11:28:18Z | 24,852,544 | 37 | 2014-07-20T16:30:31Z | [
"python",
"object",
"dictionary"
] | I'm searching for an elegant way to convert a normal Python dict with some nested dicts to an object.
For example:
```
>>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}
```
Should be accessible in this way:
```
>>> x = dict2obj(d)
>>> x.a
1
>>> x.b.c
2
>>> x.d[1].foo
bar
```
I think, this is not possibl... | Surprisingly no one has mentioned [Bunch](https://github.com/dsc/bunch). This library is exclusively meant to provide attribute style access to dict objects and does exactly what the OP wants. A demonstration:
```
>>> from bunch import bunchify
>>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}
>>> x = bunch... |
How to do Obj-C Categories in Python? | 1,305,632 | 8 | 2009-08-20T11:48:56Z | 1,305,868 | 8 | 2009-08-20T12:31:41Z | [
"python"
] | Obj-C (which I have not used for a long time) has something called [categories](http://macdevelopertips.com/objective-c/objective-c-categories.html) to extend classes. Declaring a category with new methods and compiling it into your program, all instances of the class suddenly have the new methods.
Python has mixin po... | Why not just add methods dynamically ?
```
>>> class Foo(object):
>>> pass
>>> def newmethod(instance):
>>> print 'Called:', instance
...
>>> Foo.newmethod = newmethod
>>> f = Foo()
>>> f.newmethod()
Called: <__main__.Foo object at 0xb7c54e0c>
```
I know Objective-C and this looks just like categories. The on... |
ImportError: DLL load failed : - when trying to import psycopg2 library | 1,306,367 | 12 | 2009-08-20T13:54:40Z | 1,306,396 | 11 | 2009-08-20T14:00:08Z | [
"python",
"django",
"postgresql",
"psycopg2"
] | ```
>>> import psycopg2
Traceback (most recent call last):
File "", line 1, in
File "C:\Python26\lib\site-packages\psycopg2\__init__.py", line 60, in
from _psycopg import BINARY, NUMBER, STRING, DATETIME, ROWID
ImportError: DLL load failed: The application has failed to start because its si
de-by-side configu... | According to this [thread](http://groups.google.com/group/django-users/browse%5Fthread/thread/e1b628f0f75896f0) you need to install an earlier version since there were problems with the latest build.
> Simply install an earlier version, (2.0.10 works great), even with
> PostgreSQL 8.4.x series. |
ImportError: DLL load failed : - when trying to import psycopg2 library | 1,306,367 | 12 | 2009-08-20T13:54:40Z | 5,789,963 | 7 | 2011-04-26T11:59:55Z | [
"python",
"django",
"postgresql",
"psycopg2"
] | ```
>>> import psycopg2
Traceback (most recent call last):
File "", line 1, in
File "C:\Python26\lib\site-packages\psycopg2\__init__.py", line 60, in
from _psycopg import BINARY, NUMBER, STRING, DATETIME, ROWID
ImportError: DLL load failed: The application has failed to start because its si
de-by-side configu... | You can also try installing win-psycopg from [here](http://www.stickpeople.com/projects/python/win-psycopg/) |
ImportError: DLL load failed : - when trying to import psycopg2 library | 1,306,367 | 12 | 2009-08-20T13:54:40Z | 20,821,686 | 11 | 2013-12-29T02:58:20Z | [
"python",
"django",
"postgresql",
"psycopg2"
] | ```
>>> import psycopg2
Traceback (most recent call last):
File "", line 1, in
File "C:\Python26\lib\site-packages\psycopg2\__init__.py", line 60, in
from _psycopg import BINARY, NUMBER, STRING, DATETIME, ROWID
ImportError: DLL load failed: The application has failed to start because its si
de-by-side configu... | On Windows, make sure your path includes the Postgres bin directory. In my machine it's c:\Programs\PostgreSQL\9.3\bin. |
Calculating a SHA hash with a string + secret key in python | 1,306,550 | 26 | 2009-08-20T14:23:36Z | 1,306,575 | 54 | 2009-08-20T14:27:33Z | [
"python",
"hash",
"sha256"
] | Amazon Product API now requires a signature with every request which I'm trying to generate ushing Python.
The step I get hung up on is this one:
"Calculate an RFC 2104-compliant HMAC with the SHA256 hash algorithm using the string above with our "dummy" Secret Access Key: 1234567890. For more information about this ... | ```
import hmac
import hashlib
import base64
dig = hmac.new(b'1234567890', msg=your_bytes_string, digestmod=hashlib.sha256).digest()
base64.b64encode(dig).decode() # py3k-mode
'Nace+U3Az4OhN7tISqgs1vdLBHBEijWcBeCqL5xN9xg='
``` |
Calculating a SHA hash with a string + secret key in python | 1,306,550 | 26 | 2009-08-20T14:23:36Z | 1,307,439 | 9 | 2009-08-20T16:41:26Z | [
"python",
"hash",
"sha256"
] | Amazon Product API now requires a signature with every request which I'm trying to generate ushing Python.
The step I get hung up on is this one:
"Calculate an RFC 2104-compliant HMAC with the SHA256 hash algorithm using the string above with our "dummy" Secret Access Key: 1234567890. For more information about this ... | ```
>>> import hmac
>>> import hashlib
>>> import base64
>>> s = """GET
... webservices.amazon.com
... /onca/xml
... AWSAccessKeyId=00000000000000000000&ItemId=0679722769&Operation=ItemLookup&ResponseGroup=ItemAttributes%2COffers%2CImages%2CReviews&Service=AWSECommerceService&Timestamp=2009-01-01T12%3A00%3A00Z&Version=... |
Python: Add list to set? | 1,306,631 | 99 | 2009-08-20T14:35:42Z | 1,306,653 | 100 | 2009-08-20T14:39:51Z | [
"python",
"list",
"set"
] | Tested on Python 2.6 interpreter:
```
>>> a=set('abcde')
>>> a
set(['a', 'c', 'b', 'e', 'd'])
>>> l=['f','g']
>>> l
['f', 'g']
>>> a.add(l)
Traceback (most recent call last):
File "<pyshell#35>", line 1, in <module>
a.add(l)
TypeError: list objects are unhashable
```
I think that I can't add the list to the set... | You can't add a list to a set because lists are mutable, meaning that you can change the contents of the list after adding it to the set.
You can however add tuples to the set, because you cannot change the contents of a tuple:
```
>>> a.add(('f', 'g'))
>>> print a
set(['a', 'c', 'b', 'e', 'd', ('f', 'g')])
```
---
... |
Python: Add list to set? | 1,306,631 | 99 | 2009-08-20T14:35:42Z | 1,306,663 | 246 | 2009-08-20T14:41:46Z | [
"python",
"list",
"set"
] | Tested on Python 2.6 interpreter:
```
>>> a=set('abcde')
>>> a
set(['a', 'c', 'b', 'e', 'd'])
>>> l=['f','g']
>>> l
['f', 'g']
>>> a.add(l)
Traceback (most recent call last):
File "<pyshell#35>", line 1, in <module>
a.add(l)
TypeError: list objects are unhashable
```
I think that I can't add the list to the set... | ```
>>> a = set('abcde')
>>> l = ['f', 'g']
>>> a |= set(l)
>>> a
set(['a', 'c', 'b', 'e', 'd', 'g', 'f'])
```
The union operator is much faster than add anyway.
edit: If you want the list itself and not its members, then you must use a tuple, unfortunately. Set members must be hashable. |
Python: Add list to set? | 1,306,631 | 99 | 2009-08-20T14:35:42Z | 1,306,673 | 7 | 2009-08-20T14:43:17Z | [
"python",
"list",
"set"
] | Tested on Python 2.6 interpreter:
```
>>> a=set('abcde')
>>> a
set(['a', 'c', 'b', 'e', 'd'])
>>> l=['f','g']
>>> l
['f', 'g']
>>> a.add(l)
Traceback (most recent call last):
File "<pyshell#35>", line 1, in <module>
a.add(l)
TypeError: list objects are unhashable
```
I think that I can't add the list to the set... | **list objects are unhashable**. you might want to turn them in to tuples though. |
Python: Add list to set? | 1,306,631 | 99 | 2009-08-20T14:35:42Z | 10,461,650 | 7 | 2012-05-05T12:01:53Z | [
"python",
"list",
"set"
] | Tested on Python 2.6 interpreter:
```
>>> a=set('abcde')
>>> a
set(['a', 'c', 'b', 'e', 'd'])
>>> l=['f','g']
>>> l
['f', 'g']
>>> a.add(l)
Traceback (most recent call last):
File "<pyshell#35>", line 1, in <module>
a.add(l)
TypeError: list objects are unhashable
```
I think that I can't add the list to the set... | Please notice the function `set.update()`. The documentation says:
> Update a set with the union of itself and others. |
Python: Add list to set? | 1,306,631 | 99 | 2009-08-20T14:35:42Z | 18,399,318 | 25 | 2013-08-23T09:24:30Z | [
"python",
"list",
"set"
] | Tested on Python 2.6 interpreter:
```
>>> a=set('abcde')
>>> a
set(['a', 'c', 'b', 'e', 'd'])
>>> l=['f','g']
>>> l
['f', 'g']
>>> a.add(l)
Traceback (most recent call last):
File "<pyshell#35>", line 1, in <module>
a.add(l)
TypeError: list objects are unhashable
```
I think that I can't add the list to the set... | Hopefully this helps:
```
>>> seta = set('1234')
>>> listb = ['a','b','c']
>>> seta.union(listb)
set(['a', 'c', 'b', '1', '3', '2', '4'])
>>> seta
set(['1', '3', '2', '4'])
>>> seta = seta.union(listb)
>>> seta
set(['a', 'c', 'b', '1', '3', '2', '4'])
``` |
Mapping a nested list with List Comprehension in Python? | 1,306,670 | 7 | 2009-08-20T14:42:39Z | 1,306,682 | 7 | 2009-08-20T14:45:39Z | [
"python",
"list",
"list-comprehension",
"nested-lists",
"map-function"
] | I have the following code which I use to map a nested list in Python to produce a list with the same structure.
```
>>> nested_list = [['Hello', 'World'], ['Goodbye', 'World']]
>>> [map(str.upper, x) for x in nested_list]
[['HELLO', 'WORLD'], ['GOODBYE', 'WORLD']]
```
Can this be done with list comprehension alone (w... | For nested lists you can use nested list comprehensions:
```
nested_list = [[s.upper() for s in xs] for xs in nested_list]
```
Personally I find `map` to be cleaner in this situation, even though I almost always prefer list comprehensions. So it's really your call, since either will work. |
Python __str__ versus __unicode__ | 1,307,014 | 148 | 2009-08-20T15:34:07Z | 1,307,177 | 8 | 2009-08-20T16:00:08Z | [
"python",
"string",
"unicode",
"conventions"
] | Is there a python convention for when you should implement `__str__()` versus `__unicode__()`. I've seen classes override `__unicode__()` more frequently than `__str__()` but it doesn't appear to be consistent. Are there specific rules when it is better to implement one versus the other? Is it necessary/good practice t... | With the world getting smaller, chances are that any string you encounter will contain Unicode eventually. So for any new apps, you should at least provide `__unicode__()`. Whether you also override `__str__()` is then just a matter of taste. |
Python __str__ versus __unicode__ | 1,307,014 | 148 | 2009-08-20T15:34:07Z | 1,307,209 | 14 | 2009-08-20T16:04:22Z | [
"python",
"string",
"unicode",
"conventions"
] | Is there a python convention for when you should implement `__str__()` versus `__unicode__()`. I've seen classes override `__unicode__()` more frequently than `__str__()` but it doesn't appear to be consistent. Are there specific rules when it is better to implement one versus the other? Is it necessary/good practice t... | If I didn't especially care about micro-optimizing stringification for a given class I'd always implement `__unicode__` only, as it's more general. When I do care about such minute performance issues (which is the exception, not the rule), having `__str__` only (when I can prove there never will be non-ASCII characters... |
Python __str__ versus __unicode__ | 1,307,014 | 148 | 2009-08-20T15:34:07Z | 1,307,210 | 186 | 2009-08-20T16:04:34Z | [
"python",
"string",
"unicode",
"conventions"
] | Is there a python convention for when you should implement `__str__()` versus `__unicode__()`. I've seen classes override `__unicode__()` more frequently than `__str__()` but it doesn't appear to be consistent. Are there specific rules when it is better to implement one versus the other? Is it necessary/good practice t... | `__str__()` is the old method -- it returns bytes. `__unicode__()` is the new, preferred method -- it returns characters. The names are a bit confusing, but in 2.x we're stuck with them for compatibility reasons. Generally, you should put all your string formatting in `__unicode__()`, and create a stub `__str__()` meth... |
Python MYSQL update statement | 1,307,378 | 19 | 2009-08-20T16:30:31Z | 1,307,400 | 41 | 2009-08-20T16:33:46Z | [
"python",
"mysql",
"mysql-python",
"sql-parametrized-query"
] | I'm trying to get this Python MYSQL update statement correct(With Variables):
```
cursor.execute ("UPDATE tblTableName SET Year=%s" % Year ", Month=%s" % Month ", Day=%s" % Day ", Hour=%s" % Hour ", Minute=%s" Minute "WHERE Server=%s " % ServerID)
```
Any ideas where I'm going wrong? | It [should be](http://mysql-python.sourceforge.net/MySQLdb.html):
```
cursor.execute ("""
UPDATE tblTableName
SET Year=%s, Month=%s, Day=%s, Hour=%s, Minute=%s
WHERE Server=%s
""", (Year, Month, Day, Hour, Minute, ServerID))
```
You can **also** do it with basic string manipulation,
```
cursor.execute ("UPD... |
Python MYSQL update statement | 1,307,378 | 19 | 2009-08-20T16:30:31Z | 1,307,413 | 32 | 2009-08-20T16:35:46Z | [
"python",
"mysql",
"mysql-python",
"sql-parametrized-query"
] | I'm trying to get this Python MYSQL update statement correct(With Variables):
```
cursor.execute ("UPDATE tblTableName SET Year=%s" % Year ", Month=%s" % Month ", Day=%s" % Day ", Hour=%s" % Hour ", Minute=%s" Minute "WHERE Server=%s " % ServerID)
```
Any ideas where I'm going wrong? | You've got the syntax all wrong:
```
cursor.execute ("""
UPDATE tblTableName
SET Year=%s, Month=%s, Day=%s, Hour=%s, Minute=%s
WHERE Server=%s
""", (Year, Month, Day, Hour, Minute, ServerID))
```
For more, [read the documentation](http://mysql-python.sourceforge.net/MySQLdb.html). |
Django many-to-many relations, and through | 1,307,548 | 10 | 2009-08-20T17:01:55Z | 1,307,689 | 8 | 2009-08-20T17:27:49Z | [
"python",
"django",
"foreign-keys",
"many-to-many"
] | I want to store which user invited another user to a group... but django is telling me this is ambigous and against the rules (which makes sense).
> groups.group: Intermediary model
> Group\_to\_Member has more than one
> foreign key to User, which is
> ambiguous and is not permitted.
So how do I do this correctly? M... | You have to manage it yourself:
```
class MyGroup(models.Model):
name = models.CharField(max_length=100)
class Membership(models.Model):
group = models.ForeignKey(MyGroup)
member = models.ForeignKey(User)
invited_by = models.ForeignKey(User, related_name='invited_set')
```
Then instead of `group.mem... |
Calling Python from Objective-C | 1,308,079 | 8 | 2009-08-20T18:42:48Z | 1,308,469 | 17 | 2009-08-20T19:58:17Z | [
"python",
"objective-c",
"cocoa"
] | I'm developing a Python/ObjC application and I need to call some methods in my Python classes from ObjC.
I've tried several stuffs with no success.
* How can I call a Python method from Objective-C?
* My Python classes are being instantiated in Interface Builder. How can I call a method from that instance? | Use PyObjC.
It is included with Leopard & later.
```
>>> from Foundation import *
>>> a = NSArray.arrayWithObjects_("a", "b", "c", None)
>>> a
(
a,
b,
c
)
>>> a[1]
'b'
>>> a.objectAtIndex_(1)
'b'
>>> type(a)
<objective-c class NSCFArray at 0x7fff708bc178>
```
It even works with iPython:
```
In [1]... |
Do any Python ORMs (SQLAlchemy?) work with Google App Engine? | 1,308,376 | 10 | 2009-08-20T19:39:35Z | 1,309,598 | 7 | 2009-08-21T00:55:34Z | [
"python",
"google-app-engine",
"sqlalchemy",
"orm"
] | I'd like to use the Python version of App Engine but rather than write my code specifically for the Google Data Store, I'd like to create my models with a generic Python ORM that could be attached to Big Table, or, if I prefer, a regular database at some later time. Is there any Python ORM such as SQLAlchemy that would... | Technically this wouldn't be called an ORM (Object Relational Mapper) but a DAL (Database Abstraction Layer). The ORM part is not really interesting for AppEngine as the API already takes care of the object mapping and does some simple relational mapping (see RelationProperty).
Also realize that a DAL will never let y... |
Programmatically saving image to Django ImageField | 1,308,386 | 139 | 2009-08-20T19:42:39Z | 1,309,682 | 121 | 2009-08-21T01:32:50Z | [
"python",
"django",
"django-models"
] | Ok, I've tried about near everything and I cannot get this to work.
* I have a Django model with an ImageField on it
* I have code that downloads an image via HTTP (tested and works)
* The image is saved directly into the 'upload\_to' folder (the upload\_to being the one that is set on the ImageField)
* All I need to ... | I have some code that fetches an image off the web and stores it in a model. The important bits are:
```
from django.core.files import File # you need this somewhere
import urllib
# The following actually resides in a method of my model
result = urllib.urlretrieve(image_url) # image_url is a URL to an image
# sel... |
Programmatically saving image to Django ImageField | 1,308,386 | 139 | 2009-08-20T19:42:39Z | 3,323,465 | 30 | 2010-07-24T01:37:20Z | [
"python",
"django",
"django-models"
] | Ok, I've tried about near everything and I cannot get this to work.
* I have a Django model with an ImageField on it
* I have code that downloads an image via HTTP (tested and works)
* The image is saved directly into the 'upload\_to' folder (the upload\_to being the one that is set on the ImageField)
* All I need to ... | Just a little remark. tvon answer works but, if you're working on windows, you probably want to open() the file with 'rb'. Like this:
```
class CachedImage(models.Model):
url = models.CharField(max_length=255, unique=True)
photo = models.ImageField(upload_to=photo_path, blank=True)
def cache(self):
... |
Programmatically saving image to Django ImageField | 1,308,386 | 139 | 2009-08-20T19:42:39Z | 4,230,210 | 8 | 2010-11-19T23:08:23Z | [
"python",
"django",
"django-models"
] | Ok, I've tried about near everything and I cannot get this to work.
* I have a Django model with an ImageField on it
* I have code that downloads an image via HTTP (tested and works)
* The image is saved directly into the 'upload\_to' folder (the upload\_to being the one that is set on the ImageField)
* All I need to ... | What I did was to create my own storage that will just not save the file to the disk:
```
from django.core.files.storage import FileSystemStorage
class CustomStorage(FileSystemStorage):
def _open(self, name, mode='rb'):
return File(open(self.path(name), mode))
def _save(self, name, content):
... |
Programmatically saving image to Django ImageField | 1,308,386 | 139 | 2009-08-20T19:42:39Z | 6,566,011 | 10 | 2011-07-03T22:47:20Z | [
"python",
"django",
"django-models"
] | Ok, I've tried about near everything and I cannot get this to work.
* I have a Django model with an ImageField on it
* I have code that downloads an image via HTTP (tested and works)
* The image is saved directly into the 'upload\_to' folder (the upload\_to being the one that is set on the ImageField)
* All I need to ... | Here is a method that works well and allows you to convert the file to a certain format as well (to avoid "cannot write mode P as JPEG" error):
```
import urllib2
from django.core.files.base import ContentFile
from StringIO import StringIO
def download_image(name, image, url):
input_file = StringIO(urllib2.urlope... |
Programmatically saving image to Django ImageField | 1,308,386 | 139 | 2009-08-20T19:42:39Z | 12,917,845 | 47 | 2012-10-16T15:11:28Z | [
"python",
"django",
"django-models"
] | Ok, I've tried about near everything and I cannot get this to work.
* I have a Django model with an ImageField on it
* I have code that downloads an image via HTTP (tested and works)
* The image is saved directly into the 'upload\_to' folder (the upload\_to being the one that is set on the ImageField)
* All I need to ... | Super easy if model hasn't been created yet:
**First**, copy your image file to the upload path (assumed = **'path/'** in following snippet).
**Second**, use something like:
```
class Layout(models.Model):
image = models.ImageField('img', upload_to='path/')
layout = Layout()
layout.image = "path/image.png"
layo... |
How to catch 404 error in urllib.urlretrieve | 1,308,542 | 21 | 2009-08-20T20:14:39Z | 1,308,846 | 27 | 2009-08-20T21:11:37Z | [
"python",
"http",
"url",
"urllib"
] | Background: I am using [`urllib.urlretrieve`](http://docs.activestate.com/activepython/2.6/python/library/urllib.html), as opposed to any other function in the `urllib*` modules, because of the hook function support (see `reporthook` below) .. which is used to display a textual progress bar. This is Python >=2.6.
```
... | Check out `urllib.urlretrieve`'s complete code:
```
def urlretrieve(url, filename=None, reporthook=None, data=None):
global _urlopener
if not _urlopener:
_urlopener = FancyURLopener()
return _urlopener.retrieve(url, filename, reporthook, data)
```
In other words, you can use [urllib.FancyURLopener](http://d... |
How to catch 404 error in urllib.urlretrieve | 1,308,542 | 21 | 2009-08-20T20:14:39Z | 2,202,866 | 14 | 2010-02-04T20:17:57Z | [
"python",
"http",
"url",
"urllib"
] | Background: I am using [`urllib.urlretrieve`](http://docs.activestate.com/activepython/2.6/python/library/urllib.html), as opposed to any other function in the `urllib*` modules, because of the hook function support (see `reporthook` below) .. which is used to display a textual progress bar. This is Python >=2.6.
```
... | You should use:
```
import urllib2
try:
resp = urllib2.urlopen("http://www.google.com/this-gives-a-404/")
except urllib2.URLError, e:
if not hasattr(e, "code"):
raise
resp = e
print "Gave", resp.code, resp.msg
print "=" * 80
print resp.read(80)
```
*Edit:* The rationale here is that unless you e... |
Python assert -- improved introspection of failure? | 1,308,607 | 10 | 2009-08-20T20:25:23Z | 1,309,039 | 7 | 2009-08-20T21:49:36Z | [
"python",
"debugging",
"assert",
"syntactic-sugar"
] | This is a rather useless assertion error; it does not tell the values of the expression involved (assume constants used are actually variable names):
```
$ python -c "assert 6-(3*2)"
[...]
AssertionError
```
Is there a better `assert` implementation in Python that is more fancy? It must not introduce additional overh... | As [@Mark Rushakoff said](http://stackoverflow.com/questions/1308607/python-assert-improved-introspection-of-failure/1308835#1308835) `nose` can evaluate failed asserts. It works on the standard `assert` too.
```
# test_error_reporting.py
def test():
a,b,c = 6, 2, 3
assert a - b*c
```
`nosetests`' help:
```
... |
Python assert -- improved introspection of failure? | 1,308,607 | 10 | 2009-08-20T20:25:23Z | 1,309,812 | 10 | 2009-08-21T02:25:37Z | [
"python",
"debugging",
"assert",
"syntactic-sugar"
] | This is a rather useless assertion error; it does not tell the values of the expression involved (assume constants used are actually variable names):
```
$ python -c "assert 6-(3*2)"
[...]
AssertionError
```
Is there a better `assert` implementation in Python that is more fancy? It must not introduce additional overh... | Install your of function as `sys.excepthook` -- see [the docs](http://docs.python.org/library/sys.html#sys.excepthook). Your function, if the second argument is `AssertionError`, can introspect to your heart's contents; in particular, through the third argument, the traceback, it can get the frame and exact spot in whi... |
Transparency in PNGs with reportlab 2.3 | 1,308,710 | 15 | 2009-08-20T20:45:23Z | 1,625,350 | 36 | 2009-10-26T15:01:40Z | [
"python",
"python-imaging-library",
"reportlab"
] | I have two PNGs that I am trying to combine into a PDF using ReportLab 2.3 on Python 2.5. When I use canvas.drawImage(ImageReader) to write either PNG onto the canvas and save, the transparency comes out black. If I use PIL (1.1.6) to generate a new Image, then paste() either PNG onto the PIL Image, it composits just f... | Passing the **mask parameter** with a value of 'auto' to `drawImage` fixes this for me.
```
drawImage(......., mask='auto')
```
[More information on the drawImage-function](http://www.reportlab.com/apis/reportlab/dev/pdfgen.html#reportlab.pdfgen.canvas.Canvas.drawImage) |
Running function 5 seconds after pygtk widget is shown | 1,309,006 | 11 | 2009-08-20T21:39:46Z | 1,309,257 | 14 | 2009-08-20T22:49:06Z | [
"python",
"function",
"time",
"pygtk"
] | How to run function 5 seconds after pygtk widget is shown? | You can use **[glib.timeout\_add(*interval*, *callback*, *...*)](http://library.gnome.org/devel/pygobject/stable/glib-functions.html#function-glib--timeout-add)** to periodically call a function.
If the function returns *True* then it will be called again after the interval; if the function return *False* then it will... |
Running function 5 seconds after pygtk widget is shown | 1,309,006 | 11 | 2009-08-20T21:39:46Z | 1,309,404 | 9 | 2009-08-20T23:30:22Z | [
"python",
"function",
"time",
"pygtk"
] | How to run function 5 seconds after pygtk widget is shown? | If the time is not critical to be exact to the tenth of a second, use
```
glib.timeout_add_seconds(5, ..)
```
else as above.
\*timeout\_add\_seconds\* allows the system to align timeouts to other events, in the long run reducing CPU wakeups (especially if the timeout is reocurring) and [save energy for the planet](h... |
Python String Formatting And String Multiplication Oddity | 1,309,737 | 4 | 2009-08-21T01:55:41Z | 1,309,759 | 12 | 2009-08-21T02:02:41Z | [
"python",
"string",
"formatting",
"order-of-operations"
] | Python is doing string multiplication where I would expect it to do numeric multiplication, and I don't know why.
```
>>> print('%d' % 2 * 4)
2222
>>> print('%d' % (2 * 4))
8
```
Even forcing the type to integer does nothing. (I realize this is redundant, but it's an idiot-check for me:
```
>>> print('%d' % int(2) ... | You are experiencing *operator precedence*.
In python `%` has the same precedence as `*` so they group left to right.
So,
```
print('%d' % 2 * 4)
```
is the same as,
```
print( ('%d' % 2) * 4)
```
Here is the python [operator precedence table](http://docs.python.org/reference/expressions.html#summary).
Since it ... |
Parameter substitution for a SQLite "IN" clause | 1,309,989 | 26 | 2009-08-21T03:41:15Z | 1,309,993 | 8 | 2009-08-21T03:45:41Z | [
"python",
"sqlite"
] | I am trying to use parameter substitution with [SQLite within Python](http://docs.python.org/library/sqlite3.html) for an IN clause. Here is a complete running example that demonstrates:
```
import sqlite3
c = sqlite3.connect(":memory:")
c.execute('CREATE TABLE distro (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)... | Update: this works:
```
import sqlite3
c = sqlite3.connect(":memory:")
c.execute('CREATE TABLE distro (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)')
for name in 'Ubuntu Fedora Puppy DSL SuSE'.split():
c.execute('INSERT INTO distro (name) VALUES (?)', ( name,) )
desired_ids = ["1", "2", "5", "47"]
result_set ... |
Parameter substitution for a SQLite "IN" clause | 1,309,989 | 26 | 2009-08-21T03:41:15Z | 1,310,001 | 40 | 2009-08-21T03:52:20Z | [
"python",
"sqlite"
] | I am trying to use parameter substitution with [SQLite within Python](http://docs.python.org/library/sqlite3.html) for an IN clause. Here is a complete running example that demonstrates:
```
import sqlite3
c = sqlite3.connect(":memory:")
c.execute('CREATE TABLE distro (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)... | You do need the right number of `?`s, but that doesn't pose a sql injection risk:
```
>>> result_set = c.execute('SELECT * FROM distro WHERE id IN (%s)' %
','.join('?'*len(desired_ids)), desired_ids)
>>> print result_set.fetchall()
[(1, u'Ubuntu'), (2, u'Fedora'), (5, u'SuSE')]
``` |
Parameter substitution for a SQLite "IN" clause | 1,309,989 | 26 | 2009-08-21T03:41:15Z | 3,498,634 | 13 | 2010-08-17T01:18:51Z | [
"python",
"sqlite"
] | I am trying to use parameter substitution with [SQLite within Python](http://docs.python.org/library/sqlite3.html) for an IN clause. Here is a complete running example that demonstrates:
```
import sqlite3
c = sqlite3.connect(":memory:")
c.execute('CREATE TABLE distro (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)... | According to <http://www.sqlite.org/limits.html> (item 9), SQLite can't (by default) handle more than 999 parameters to a query, so the solutions here (generating the required list of placeholders) will fail if you have thousands of items that you're looking `IN`. If that's the case, you're going to need to break up th... |
What is the best way to create a Python object when you have the class implementaion stored in a string? | 1,310,254 | 2 | 2009-08-21T05:50:00Z | 1,310,297 | 9 | 2009-08-21T06:11:48Z | [
"python"
] | What is the best way to dynamically create a Python object instance when all you have is the Python class saved as a string?
For background, I am working in the Google Application Engine environment and I want to be able to load classes dynamically from a string version of the class.
```
problem = â1,2,3,4,5â
so... | Alas, `exec` is your only choice, but at least do it right to avert disaster: pass an explicit dictionary (with an `in` clause, of course)! E.g.:
```
>>> class X(object): pass
...
>>> x=X()
>>> exec 'a=23' in vars(x)
>>> x.a
23
```
this way you KNOW the `exec` won't pollute general namespaces, and whatever classes a... |
Running a Python script outside of Django | 1,310,495 | 33 | 2009-08-21T07:33:37Z | 1,310,547 | 20 | 2009-08-21T07:44:19Z | [
"python",
"django"
] | I have a script which uses the Django ORM features, amongst other external libraries, that I want to run outside of Django (that is, executed from the command-line).
Edit: At the moment, I can launch it by navigating to a URL...
How do I setup the environment for this? | ```
from <Project path> import settings #your project settings file
from django.core.management import setup_environ #environment setup function
setup_environ(settings)
#Rest of your django imports and code go here
``` |
Running a Python script outside of Django | 1,310,495 | 33 | 2009-08-21T07:33:37Z | 1,310,607 | 12 | 2009-08-21T08:00:02Z | [
"python",
"django"
] | I have a script which uses the Django ORM features, amongst other external libraries, that I want to run outside of Django (that is, executed from the command-line).
Edit: At the moment, I can launch it by navigating to a URL...
How do I setup the environment for this? | All you need is importable settings and properly set python path. In the most raw form this can be done by setting up appropriate environment variables, like:
```
$ DJANGO_SETTINGS_MODULE=myproject.settings PYTHONPATH=$HOME/djangoprojects python myscript.py
```
There are other ways, like calling `settings.configure()... |
Running a Python script outside of Django | 1,310,495 | 33 | 2009-08-21T07:33:37Z | 1,310,642 | 37 | 2009-08-21T08:11:29Z | [
"python",
"django"
] | I have a script which uses the Django ORM features, amongst other external libraries, that I want to run outside of Django (that is, executed from the command-line).
Edit: At the moment, I can launch it by navigating to a URL...
How do I setup the environment for this? | The easiest way to do this is to set up your script as a `manage.py` subcommand. It's quite easy to do:
```
from django.core.management.base import NoArgsCommand, make_option
class Command(NoArgsCommand):
help = "Whatever you want to print here"
option_list = NoArgsCommand.option_list + (
make_optio... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.