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 |
|---|---|---|---|---|---|---|---|---|---|
Running a Python script outside of Django | 1,310,495 | 33 | 2009-08-21T07:33:37Z | 12,130,739 | 10 | 2012-08-26T14:02: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? | **Note** that the suggestions around importing settings and using setup\_environ have been deprecated with Django 1.4.
There's a thread on the Django Github describing [why this was done](https://github.com/django/django/commit/38f1fe3b35).
There are still some other options out there but many of them seem hackish to... |
Running a Python script outside of Django | 1,310,495 | 33 | 2009-08-21T07:33:37Z | 17,980,230 | 9 | 2013-07-31T20:23:04Z | [
"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? | Use `runscript` from [django-extensions](http://django-extensions.readthedocs.org/en/latest/runscript.html): `python manage.py runscript <my_script>`
In order to do this, you need to:
1. `pip install django-extensions`
2. Create a directory called `scripts`. This can be located in your root directory, or in a specifi... |
What is the oldest time that can be represented in python? | 1,310,740 | 10 | 2009-08-21T08:37:28Z | 1,310,772 | 11 | 2009-08-21T08:43:53Z | [
"python",
"python-3.x"
] | I have written a function comp(time1, time2) which will return true when time1 is lesser than time2. I have a scenario where time1 should always be lesser than time2. I need time1 to have the least possible value(date). How to find this time and how to form the corresponding object. | In python, the datetime object exports the following constants
```
datetime.MINYEAR
The smallest year number allowed in a date or datetime object. MINYEAR is 1.
datetime.MAXYEAR
The largest year number allowed in a date or datetime object. MAXYEAR is 9999.
```
<http://docs.python.org/library/datetime.html> |
What is the oldest time that can be represented in python? | 1,310,740 | 10 | 2009-08-21T08:37:28Z | 31,972,447 | 13 | 2015-08-12T18:09:56Z | [
"python",
"python-3.x"
] | I have written a function comp(time1, time2) which will return true when time1 is lesser than time2. I have a scenario where time1 should always be lesser than time2. I need time1 to have the least possible value(date). How to find this time and how to form the corresponding object. | If using the [datetime](https://docs.python.org/2/library/datetime.html) module, [date](https://docs.python.org/2/library/datetime.html#date-objects), [time](https://docs.python.org/2/library/datetime.html#time-objects), and [datetime](https://docs.python.org/2/library/datetime.html#datetime-objects) objects all have a... |
How to execute asynchronous post-processing in CherryPy? | 1,310,959 | 4 | 2009-08-21T09:33:12Z | 1,313,032 | 7 | 2009-08-21T16:48:03Z | [
"python",
"asynchronous",
"cherrypy"
] | **Context:**
Imagine that you have a standard CherryPy hello word app:
```
def index(self):
return "Hello world!"
index.exposed = True
```
and you would like to do some post-processing, i.e. record request processing or just log the fact that we were called from specific IP. What you would do is probably:... | The "global threading aware queue" is called Queue.Queue. I just added a recipe for this at <http://tools.cherrypy.org/wiki/BackgroundTaskQueue> |
How nicely does Python 'flow' with HTML as compared to PHP? | 1,311,789 | 11 | 2009-08-21T13:00:30Z | 1,311,980 | 23 | 2009-08-21T13:34:14Z | [
"php",
"python",
"html"
] | I'm thinking of switching from using PHP to Python for web applications, but I was wondering if Python is as adept as weaving in and out of HTML as PHP is. Essentially, I find it very easy/intuitive to use `<? and ?>` to put PHP where I want, and am then free to arrange/organize my HTML however I want. Is it just as ea... | You can't easily compare PHP and Python.
PHP is a web processing framework that is designed specifically as an Apache plug-in. It includes HTTP protocol handling as well as a programming language.
Python is "just" a programming language. There are many Python web frameworks to plug Python into Apache. There's [mod\_w... |
Using a global dictionary with threads in Python | 1,312,331 | 13 | 2009-08-21T14:33:32Z | 1,312,389 | 19 | 2009-08-21T14:44:38Z | [
"python",
"multithreading"
] | Is accessing/changing dictionary values thread-safe?
I have a global dictionary `foo` and multiple threads with ids `id1`, `id2`, ... , `idn`. Is it OK to access and change `foo`'s values without allocating a lock for it if it's known that each thread will only work with its id-related value, say thread with `id1` wil... | Assuming CPython: Yes and no. It is actually safe to fetch/store values from a shared dictionary in the sense that multiple concurrent read/write requests won't corrupt the dictionary. This is due to the global interpreter lock ("GIL") maintained by the implementation. That is:
Thread A running:
```
a = global_dict["... |
Using a global dictionary with threads in Python | 1,312,331 | 13 | 2009-08-21T14:33:32Z | 1,312,704 | 16 | 2009-08-21T15:36:10Z | [
"python",
"multithreading"
] | Is accessing/changing dictionary values thread-safe?
I have a global dictionary `foo` and multiple threads with ids `id1`, `id2`, ... , `idn`. Is it OK to access and change `foo`'s values without allocating a lock for it if it's known that each thread will only work with its id-related value, say thread with `id1` wil... | The best, safest, portable way to have each thread work with independent data is:
```
import threading
tloc = threading.local()
```
Now each thread works with a totally independent `tloc` object even though it's a global name. The thread can get and set attributes on `tloc`, use `tloc.__dict__` if it specifically nee... |
Using a global dictionary with threads in Python | 1,312,331 | 13 | 2009-08-21T14:33:32Z | 29,532,297 | 7 | 2015-04-09T07:24:00Z | [
"python",
"multithreading"
] | Is accessing/changing dictionary values thread-safe?
I have a global dictionary `foo` and multiple threads with ids `id1`, `id2`, ... , `idn`. Is it OK to access and change `foo`'s values without allocating a lock for it if it's known that each thread will only work with its id-related value, say thread with `id1` wil... | Since I needed something similar, I landed here. I sum up your answers in this short snippet :
```
#!/usr/bin/env python3
import threading
class ThreadSafeDict(dict) :
def __init__(self, * p_arg, ** n_arg) :
dict.__init__(self, * p_arg, ** n_arg)
self._lock = threading.Lock()
def __enter__(s... |
Python: what kind of literal delimiter is "better" to use? | 1,312,940 | 2 | 2009-08-21T16:26:42Z | 1,312,949 | 9 | 2009-08-21T16:28:53Z | [
"python",
"string"
] | What is the best literal delimiter in Python and why? Single ' or double "? And most important, why?
I'm a beginner in Python and I'm trying to stick with just one. I know that in PHP, for example " is preferred, because PHP does not try to search for the 'string' variable. Is the same case in Python? | ' because it's one keystroke less than ". Save your wrists!
They're otherwise identical (except you have to escape whichever you choose to use, if they appear inside the string). |
Python: what kind of literal delimiter is "better" to use? | 1,312,940 | 2 | 2009-08-21T16:26:42Z | 1,312,959 | 9 | 2009-08-21T16:30:11Z | [
"python",
"string"
] | What is the best literal delimiter in Python and why? Single ' or double "? And most important, why?
I'm a beginner in Python and I'm trying to stick with just one. I know that in PHP, for example " is preferred, because PHP does not try to search for the 'string' variable. Is the same case in Python? | Consider these strings:
```
"Don't do that."
'I said, "okay".'
"""She said, "That won't work"."""
```
Which quote is "best"? |
What is this construct called in python: ( x, y ) | 1,313,805 | 5 | 2009-08-21T19:27:03Z | 1,313,809 | 14 | 2009-08-21T19:28:11Z | [
"python"
] | What is this called in python:
```
[('/', MainPage)]
```
Is that an array .. of ... erhm one dictionary?
Is that
```
()
```
A tuple? ( or whatever they call it? ) | Its a list with a single tuple. |
Raise exception vs. return None in Python functions | 1,313,812 | 44 | 2009-08-21T19:28:19Z | 1,313,837 | 53 | 2009-08-21T19:34:06Z | [
"python",
"exception-handling"
] | What's better practice in a user-defined function in Python: raise an exception or return None? For example, I have a function that finds the most recent file in a folder.
```
def latestpdf(folder):
# list the files and sort them
try:
latest = files[-1]
except IndexError:
# Folder is empty.... | It's really a matter of semantics. What does `foo = latestpdf(d)` *mean*?
Is it perfectly reasonable that there's no latest file? Then sure, just return None.
Are you expecting to always find a latest file? Raise an exception. And yes, re-raising a more appropriate exception is fine.
If this is just a general functi... |
If I have the contents of a zipfile in a Python string, can I decompress it without writing it to a file? | 1,313,845 | 12 | 2009-08-21T19:35:05Z | 1,313,868 | 23 | 2009-08-21T19:37:45Z | [
"python"
] | I've written some Python code that fetches a zip file from the web and into a string:
```
In [1]: zip_contents[0:5]
Out[1]: 'PK\x03\x04\x14'
```
I see there's a zipfile library, but I'm having trouble finding a function in it that I can just pass a bunch of raw zip data. It seems to want to read it from a file.
Do I... | `zipfile.ZipFile` accepts any file-like object, so you can use `StringIO` (2.x) or `BytesIO` (3.x):
```
try:
from cStringIO import StringIO
except:
from StringIO import StringIO
import zipfile
fp = StringIO('PK\x03\x04\x14')
zfp = zipfile.ZipFile(fp, "r")
``` |
How can I scrape this frame? | 1,314,052 | 2 | 2009-08-21T20:28:36Z | 1,314,138 | 8 | 2009-08-21T20:46:55Z | [
"python",
"vbscript",
"screen-scraping",
"mechanize"
] | If you visit [this link](http://cad.chp.ca.gov/iiqr.asp?Center=RDCC&LogNumber=0197D0820&t=Traffic%20Hazard&l=3358%20MYRTLE&b=) right now, you will probably get a VBScript error.
On the other hand, if you visit [this link first](http://cad.chp.ca.gov/) and *then* the above link (in the same session), the page comes thr... | It always comes down to the request/response model. You just have to craft a series of http requests such that you get the desired responses. In this case, you also need the server to treat each request as part of the same session. To do that, you need to figure out how the server is tracking sessions. It could be a nu... |
Is there any way to get vim to auto wrap python strings at 79 chars? | 1,314,174 | 32 | 2009-08-21T20:54:01Z | 1,315,419 | 12 | 2009-08-22T07:46:39Z | [
"python",
"vim",
"string",
"wrapping",
"textwrapping"
] | I found this [answer](http://stackoverflow.com/questions/1302364/python-pep8-printing-wrapped-strings-without-indent/1302381#1302381) about wrapping strings using parens extremely useful, but is there a way in Vim to make this happen automatically? I want to be within a string, typing away, and have Vim just put parens... | More a direction than a solution.
Use `'formatexpr'` or `'formatprg'`. When a line exceeds `'textwidth'` and passes the criteria set by the `'formatoptions'` these are used (if set) to break the line. The only real difference is that `'formatexpr'` is a vimscript expression, while `'formatprg'` filters the line throug... |
How can I filter items from a list in Python? | 1,314,314 | 7 | 2009-08-21T21:27:30Z | 1,314,352 | 18 | 2009-08-21T21:40:28Z | [
"python"
] | I have data naively collected from package dependency lists.
Depends: foo bar baz >= 5.2
I end up with
```
d = set(['foo','bar','baz','>=','5.2'])
```
I don't want the numerics and the operands.
In Perl I would
```
@new = grep {/^[a-z]+$/} @old
```
but I can't find a way to e.g. pass remove() a lambda, or somet... | No need for regular expressions here. Use [`str.isalpha`](http://docs.python.org/library/stdtypes.html#str.isalpha). With and without list comprehensions:
```
my_list = ['foo','bar','baz','>=','5.2']
# With
only_words = [token for token in my_list if token.isalpha()]
# Without
only_words = filter(str.isalpha, my_lis... |
How can I specify that some command line arguments are mandatory in Python? | 1,315,425 | 5 | 2009-08-22T07:49:17Z | 1,315,462 | 10 | 2009-08-22T08:10:24Z | [
"python",
"command-line"
] | I'm writing a program in Python that accepts command line arguments. I am parsing them with `getopt` (though my choice of `getopt` is no Catholic marriage. I'm more than willing to use any other library). Is there any way to specify that certain arguments *must* be given, or do I have to manually make sure that all the... | As for me I prefer using [optparse module](http://docs.python.org/library/optparse.html), it is quite powerful, for exapmle it can automatically generate -h message by given options:
```
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
help... |
How good is startswith? | 1,315,559 | 11 | 2009-08-22T09:02:23Z | 1,315,568 | 25 | 2009-08-22T09:04:25Z | [
"python"
] | Is
```
text.startswith('a')
```
better than
```
text[0]=='a'
```
?
Knowing text is not empty and we are only interested in the first character of it. | `text[0]` fails if `text` is an empty string:
```
IronPython 2.6 Alpha (2.6.0.1) on .NET 4.0.20506.1
Type "help", "copyright", "credits" or "license" for more information.
>>> text = ""
>>> print(text.startswith("a"))
False
>>> print(text[0]=='a')
Traceback (most recent call last):
File "<stdin>", line 1, in <module... |
How good is startswith? | 1,315,559 | 11 | 2009-08-22T09:02:23Z | 1,315,570 | 9 | 2009-08-22T09:05:48Z | [
"python"
] | Is
```
text.startswith('a')
```
better than
```
text[0]=='a'
```
?
Knowing text is not empty and we are only interested in the first character of it. | Personally I would say `startswith` is more readable.
Also, from Python 2.5 `startwith` can take a tuple of prefixes to look for:
```
>>> "hello world".startswith(("hello","goodbye"))
True
``` |
How good is startswith? | 1,315,559 | 11 | 2009-08-22T09:02:23Z | 1,315,577 | 10 | 2009-08-22T09:07:49Z | [
"python"
] | Is
```
text.startswith('a')
```
better than
```
text[0]=='a'
```
?
Knowing text is not empty and we are only interested in the first character of it. | Yes: itâs easier to use and easier to read. When you are testing for more than one letter, when using slicing, youâll have to know how long the target text is:
```
haystack = 'Hello, World!'
needle = 'Hello'
# The easy way
result = haystack.startswith(needle)
# The slightly harder way
result = haystack[:len(need... |
How good is startswith? | 1,315,559 | 11 | 2009-08-22T09:02:23Z | 1,315,580 | 7 | 2009-08-22T09:09:46Z | [
"python"
] | Is
```
text.startswith('a')
```
better than
```
text[0]=='a'
```
?
Knowing text is not empty and we are only interested in the first character of it. | The stock phrase for the questiom is: "Premature optimization is the root of all evil". |
How good is startswith? | 1,315,559 | 11 | 2009-08-22T09:02:23Z | 1,316,245 | 18 | 2009-08-22T15:44:09Z | [
"python"
] | Is
```
text.startswith('a')
```
better than
```
text[0]=='a'
```
?
Knowing text is not empty and we are only interested in the first character of it. | I'd agree with the others that startswith is more readable, and you should use that. That said, if performance is a big issue for such a special case, benchmark it:
```
$ python -m timeit -s 'text="foo"' 'text.startswith("a")'
1000000 loops, best of 3: 0.537 usec per loop
$ python -m timeit -s 'text="foo"' 'text[0]==... |
Is there an way to programatically read a file from a TrueCrypt disk into memory? | 1,315,677 | 10 | 2009-08-22T10:06:06Z | 1,315,722 | 12 | 2009-08-22T10:38:11Z | [
"c#",
"python",
"perl",
"readfile",
"truecrypt"
] | I need to load a file from an umounted TrueCrypt disk into memory. Is there any way to do this programatically? Does TrueCrypt offer an API?
The way I believe is best for attempting this would be to mount the volume (prompting the user for a password, of course), open the file, and then unmount the volume. Is there a ... | Can you not use the [true crypt command line](http://www.truecrypt.org/docs/?s=command-line-usage) from say System.Diagnostics.Process?
```
using System;
using System.Diagnostics;
namespace Test {
class TrueCrypeStart
{
static void Main(string[] args)
{
string password = getPassw... |
when is it necessary to add an `else` clause to a try..except in Python? | 1,316,002 | 4 | 2009-08-22T13:41:42Z | 1,316,011 | 9 | 2009-08-22T13:46:00Z | [
"python",
"exception"
] | When I write code in Python with exception handling I can write code like:
```
try:
some_code_that_can_cause_an_exception()
except:
some_code_to_handle_exceptions()
else:
code_that_needs_to_run_when_there_are_no_exceptions()
```
How does this differ from:
```
try:
some_code_that_can_cause_an_exceptio... | In the second example, `code_that_needs_to_run_when_there_are_no_exceptions()` will be ran when you **do** have an exception and then you handle it, continuing after the except.
so ...
In both cases code\_that\_needs\_to\_run\_when\_there\_are\_no\_exceptions() will execute when there are no exceptions, but in the la... |
Pythonic way of iterating over 3D array | 1,316,068 | 5 | 2009-08-22T14:16:04Z | 1,316,087 | 7 | 2009-08-22T14:29:59Z | [
"python",
"arrays",
"loops"
] | I have a 3D array in Python and I need to iterate over all the cubes in the array. That is, for all `(x,y,z)` in the array's dimensions I need to access the cube:
```
array[(x + 0, y + 0, z + 0)]
array[(x + 1, y + 0, z + 0)]
array[(x + 0, y + 1, z + 0)]
array[(x + 1, y + 1, z + 0)]
array[(x + 0, y + 0, z + 1)]
array[(... | ```
import itertools
for x, y, z in itertools.product(xrange(x_size),
xrange(y_size),
xrange(z_size)):
work_with_cube(array[x, y, z])
``` |
Pythonic way of iterating over 3D array | 1,316,068 | 5 | 2009-08-22T14:16:04Z | 1,316,104 | 13 | 2009-08-22T14:38:12Z | [
"python",
"arrays",
"loops"
] | I have a 3D array in Python and I need to iterate over all the cubes in the array. That is, for all `(x,y,z)` in the array's dimensions I need to access the cube:
```
array[(x + 0, y + 0, z + 0)]
array[(x + 1, y + 0, z + 0)]
array[(x + 0, y + 1, z + 0)]
array[(x + 1, y + 1, z + 0)]
array[(x + 0, y + 0, z + 1)]
array[(... | Have a look at [itertools](http://docs.python.org/library/itertools.html), especially [itertools.product](http://docs.python.org/library/itertools.html#itertools.product). You can compress the three loops into one with
```
import itertools
for x, y, z in itertools.product(*map(xrange, (x_dim, y_dim, z_dim)):
...
... |
pylint not recognizing some of the standard library | 1,316,334 | 9 | 2009-08-22T16:19:08Z | 1,316,693 | 9 | 2009-08-22T18:40:45Z | [
"python",
"email",
"import",
"pydev",
"pylint"
] | I'm using pylint + pydev, with python 2.6.
I have a module with just this line of code
```
from email import Message
```
Now when I try to run this module it runs fine. But pylint reports an error:
```
ID: E0611 No name 'Message' in module 'email'
```
Although it exists...
Any idea why? | I like pylint, but I do find I have to use a lot of `# pylint: disable-msg=E0611` and the like to make it shut up in cases that are perfectly correct but confuse it (for example, like in this case, due to `email`'s playing with import tricks). |
pylint not recognizing some of the standard library | 1,316,334 | 9 | 2009-08-22T16:19:08Z | 6,261,591 | 10 | 2011-06-07T06:53:58Z | [
"python",
"email",
"import",
"pydev",
"pylint"
] | I'm using pylint + pydev, with python 2.6.
I have a module with just this line of code
```
from email import Message
```
Now when I try to run this module it runs fine. But pylint reports an error:
```
ID: E0611 No name 'Message' in module 'email'
```
Although it exists...
Any idea why? | realise this is an old question, but the correct answer is that the older ways of invoking what you need, which use the "import hackery" that Richie describes, have long been deprecated (despite still appearing in many tutorials). If you use the new ways, you'll be writing better code and `pylint` won't complain.
e.g.... |
zlib decompression in python | 1,316,357 | 4 | 2009-08-22T16:24:56Z | 1,317,267 | 22 | 2009-08-22T23:06:12Z | [
"python",
"compression",
"zlib",
"corruption"
] | Okay so I have some data streams compressed by python's (2.6) zlib.compress() function. When I try to decompress them, some of them won't decompress (zlib error -5, which seems to be a "buffer error", no idea what to make of that). At first, I thought I was done, but I realized that all the ones I couldn't decompress s... | According to [RFC 1950](http://www.ietf.org/rfc/rfc1950.txt) , the difference between the "OK" 0x789C and the "bad" 0x78DA is in the FLEVEL bit-field:
```
FLEVEL (Compression level)
These flags are available for use by specific compression
methods. The "deflate" method (CM = 8) sets these flags as
fo... |
Django URL.py and the index | 1,316,682 | 9 | 2009-08-22T18:35:01Z | 1,316,696 | 23 | 2009-08-22T18:41:43Z | [
"python",
"django",
"django-urls"
] | I want to know what is the best way to write in the `URL.py`. I am trying to get the index in this way: `www.example.com` with `(r'',index)`. But when I try `r''`, all pages in the website are going to the home page.
Part of my `url.py`:
```
(r'^index',homepages),
(r'',homepages),
```
Thanks :) | Like this:
```
#...
(r'^$', index),
#...
``` |
How can I explicitly free memory in Python? | 1,316,767 | 123 | 2009-08-22T19:10:35Z | 1,316,779 | 11 | 2009-08-22T19:14:30Z | [
"python",
"memory",
"memory-management"
] | I wrote a Python program that acts on a large input file to create a few million objects representing triangles. The algorithm is:
1. read an input file
2. process the file and create a list of triangles, represented by their vertices
3. output the vertices in the OFF format: a list of vertices followed by a list of t... | Python is garbage-collected, so if you reduce the size of your list, it will reclaim memory. You can also use the "del" statement to get rid of a variable completely:
```
biglist = [blah,blah,blah]
#...
del biglist
``` |
How can I explicitly free memory in Python? | 1,316,767 | 123 | 2009-08-22T19:10:35Z | 1,316,788 | 13 | 2009-08-22T19:16:12Z | [
"python",
"memory",
"memory-management"
] | I wrote a Python program that acts on a large input file to create a few million objects representing triangles. The algorithm is:
1. read an input file
2. process the file and create a list of triangles, represented by their vertices
3. output the vertices in the OFF format: a list of vertices followed by a list of t... | The `del` statement might be of use, but IIRC **it isn't guaranteed to free the memory**. The [docs are here](http://docs.python.org/reference/simple%5Fstmts.html) ... and a [why it isn't released is here](http://effbot.org/pyfaq/why-doesnt-python-release-the-memory-when-i-delete-a-large-object.htm).
I have heard peop... |
How can I explicitly free memory in Python? | 1,316,767 | 123 | 2009-08-22T19:10:35Z | 1,316,790 | 13 | 2009-08-22T19:16:44Z | [
"python",
"memory",
"memory-management"
] | I wrote a Python program that acts on a large input file to create a few million objects representing triangles. The algorithm is:
1. read an input file
2. process the file and create a list of triangles, represented by their vertices
3. output the vertices in the OFF format: a list of vertices followed by a list of t... | You can't explicitly free memory. What you need to do is to make sure you don't keep references to objects. They will then be garbage collected, freeing the memory.
In your case, when you need large lists, you typically need to reorganize the code, typically using generators/iterators instead. That way you don't need ... |
How can I explicitly free memory in Python? | 1,316,767 | 123 | 2009-08-22T19:10:35Z | 1,316,793 | 108 | 2009-08-22T19:18:27Z | [
"python",
"memory",
"memory-management"
] | I wrote a Python program that acts on a large input file to create a few million objects representing triangles. The algorithm is:
1. read an input file
2. process the file and create a list of triangles, represented by their vertices
3. output the vertices in the OFF format: a list of vertices followed by a list of t... | According to [Python Official Documentation](http://docs.python.org/library/gc.html), you can force the Garbage Collector to release unreferenced memory with `gc.collect()` |
How can I explicitly free memory in Python? | 1,316,767 | 123 | 2009-08-22T19:10:35Z | 1,316,799 | 68 | 2009-08-22T19:21:21Z | [
"python",
"memory",
"memory-management"
] | I wrote a Python program that acts on a large input file to create a few million objects representing triangles. The algorithm is:
1. read an input file
2. process the file and create a list of triangles, represented by their vertices
3. output the vertices in the OFF format: a list of vertices followed by a list of t... | Unfortunately (depending on your version and release of Python) some types of objects use "free lists" which are a neat local optimization but may cause memory fragmentation, specifically by making more and more memory "earmarked" for only objects of a certain type and thereby unavailable to the "general fund".
The on... |
How can I explicitly free memory in Python? | 1,316,767 | 123 | 2009-08-22T19:10:35Z | 1,317,085 | 7 | 2009-08-22T21:29:57Z | [
"python",
"memory",
"memory-management"
] | I wrote a Python program that acts on a large input file to create a few million objects representing triangles. The algorithm is:
1. read an input file
2. process the file and create a list of triangles, represented by their vertices
3. output the vertices in the OFF format: a list of vertices followed by a list of t... | Lists of numbers are much less memory-efficient than the format used by the standard array module or the third-party Numpy module. You would save memory by putting your vertices in a Numpy 3xN array and your triangles in an N-element array. |
What is the most efficient string concatenation method in python? | 1,316,887 | 75 | 2009-08-22T19:53:41Z | 1,316,891 | 42 | 2009-08-22T19:55:58Z | [
"python",
"string"
] | Is there any efficient mass string concatenation method in Python (like *StringBuilder* in C# or *StringBuffer* in Java)? I found following methods [here](http://skymind.com/~ocrow/python_string/):
* Simple concatenation using `+`
* Using string list and `join` method
* Using `UserString` from `MutableString` module
*... | `''.join(sequenceofstrings)` is what usually works best -- simplest and fastest. |
What is the most efficient string concatenation method in python? | 1,316,887 | 75 | 2009-08-22T19:53:41Z | 1,316,959 | 72 | 2009-08-22T20:26:59Z | [
"python",
"string"
] | Is there any efficient mass string concatenation method in Python (like *StringBuilder* in C# or *StringBuffer* in Java)? I found following methods [here](http://skymind.com/~ocrow/python_string/):
* Simple concatenation using `+`
* Using string list and `join` method
* Using `UserString` from `MutableString` module
*... | You may be interested in this: [An optimization anecdote](http://www.python.org/doc/essays/list2str/) by Guido. Although it is worth remembering also that this is an old article and it predates the existence of things like `''.join` (although I guess `string.joinfields` is more-or-less the same)
On the strength of tha... |
What is the most efficient string concatenation method in python? | 1,316,887 | 75 | 2009-08-22T19:53:41Z | 1,316,982 | 23 | 2009-08-22T20:36:58Z | [
"python",
"string"
] | Is there any efficient mass string concatenation method in Python (like *StringBuilder* in C# or *StringBuffer* in Java)? I found following methods [here](http://skymind.com/~ocrow/python_string/):
* Simple concatenation using `+`
* Using string list and `join` method
* Using `UserString` from `MutableString` module
*... | It depends on what you're doing.
After Python 2.5, string concatenation with the + operator is pretty fast. If you're just concatenating a couple of values, using the + operator works best:
```
>>> x = timeit.Timer(stmt="'a' + 'b'")
>>> x.timeit()
0.039999961853027344
>>> x = timeit.Timer(stmt="''.join(['a', 'b'])")... |
What is the most efficient string concatenation method in python? | 1,316,887 | 75 | 2009-08-22T19:53:41Z | 38,362,140 | 9 | 2016-07-13T21:38:41Z | [
"python",
"string"
] | Is there any efficient mass string concatenation method in Python (like *StringBuilder* in C# or *StringBuffer* in Java)? I found following methods [here](http://skymind.com/~ocrow/python_string/):
* Simple concatenation using `+`
* Using string list and `join` method
* Using `UserString` from `MutableString` module
*... | Python 3.6 is going to change this for strings that have known components with [Literal String Interpolation](https://www.python.org/dev/peps/pep-0498/).
Given the test case from [mkoistinen's answer](http://stackoverflow.com/a/24718551/918959), having strings
```
domain = 'some_really_long_example.com'
lang = 'en'
p... |
sqlalchemy flush() and get inserted id? | 1,316,952 | 40 | 2009-08-22T20:21:42Z | 1,325,560 | 26 | 2009-08-25T01:06:33Z | [
"python",
"sqlalchemy"
] | I want to do something like this:
```
f = Foo(bar='x')
session.add(f)
session.flush()
# do additional queries using f.id before commit()
print f.id # should be not None
session.commit()
```
But f.id is None when I try it. How can I get this to work?
-Dan | your sample code should be providing a value for `f.id`, assuming its an autogenerating primary key column. primary key attributes are populated immediately within the flush() process as they are generated and no call to commit() should be required. So the answer here lies in the details of your mapping, if there are a... |
sqlalchemy flush() and get inserted id? | 1,316,952 | 40 | 2009-08-22T20:21:42Z | 5,083,472 | 72 | 2011-02-22T20:21:13Z | [
"python",
"sqlalchemy"
] | I want to do something like this:
```
f = Foo(bar='x')
session.add(f)
session.flush()
# do additional queries using f.id before commit()
print f.id # should be not None
session.commit()
```
But f.id is None when I try it. How can I get this to work?
-Dan | I've just run across the same problem, and after testing I have found that NONE of these answers are sufficient.
Currently, or as of sqlalchemy .6+, there is a very simple solution (I don't know if this exists in prior version, though I imagine it does):
**session.refresh()**
So, your code would look something like ... |
Finding matching keys in two large dictionaries and doing it fast | 1,317,410 | 10 | 2009-08-23T00:27:34Z | 1,317,411 | 33 | 2009-08-23T00:30:01Z | [
"python",
"bioinformatics"
] | I am trying to find corresponding keys in two different dictionaries. Each has about 600k entries.
Say for example:
```
myRDP = { 'Actinobacter': 'GATCGA...TCA', 'subtilus sp.': 'ATCGATT...ACT' }
myNames = { 'Actinobacter': '8924342' }
```
I want to print out the value for Actinobacter (8924342) since it mat... | You could do this:
```
for key in myRDP:
if key in myNames:
print key, myNames[key]
```
Your first attempt was slow because you were comparing *every* key in myRDP with *every* key in myNames. In algorithmic jargon, if myRDP has **n** elements and myNames has **m** elements, then that algorithm would take... |
Finding matching keys in two large dictionaries and doing it fast | 1,317,410 | 10 | 2009-08-23T00:27:34Z | 1,317,412 | 8 | 2009-08-23T00:30:47Z | [
"python",
"bioinformatics"
] | I am trying to find corresponding keys in two different dictionaries. Each has about 600k entries.
Say for example:
```
myRDP = { 'Actinobacter': 'GATCGA...TCA', 'subtilus sp.': 'ATCGATT...ACT' }
myNames = { 'Actinobacter': '8924342' }
```
I want to print out the value for Actinobacter (8924342) since it mat... | ```
for key in myRDP:
name = myNames.get(key, None)
if name:
print key, name
```
`dict.get` returns the default value you give it (in this case, `None`) if the key doesn't exist. |
Finding matching keys in two large dictionaries and doing it fast | 1,317,410 | 10 | 2009-08-23T00:27:34Z | 1,317,416 | 21 | 2009-08-23T00:32:07Z | [
"python",
"bioinformatics"
] | I am trying to find corresponding keys in two different dictionaries. Each has about 600k entries.
Say for example:
```
myRDP = { 'Actinobacter': 'GATCGA...TCA', 'subtilus sp.': 'ATCGATT...ACT' }
myNames = { 'Actinobacter': '8924342' }
```
I want to print out the value for Actinobacter (8924342) since it mat... | Use sets, because they have a built-in `intersection` method which ought to be quick:
```
myRDP = { 'Actinobacter': 'GATCGA...TCA', 'subtilus sp.': 'ATCGATT...ACT' }
myNames = { 'Actinobacter': '8924342' }
rdpSet = set(myRDP)
namesSet = set(myNames)
for name in rdpSet.intersection(namesSet):
print name, myNames[... |
Converting a float to a string without rounding it | 1,317,558 | 39 | 2009-08-23T02:03:07Z | 1,317,563 | 8 | 2009-08-23T02:05:19Z | [
"python",
"string",
"floating-point",
"rounding"
] | I'm making a program that, for reasons not needed to be explained, requires a float to be converted into a string to be counted with len(). However, str(float(x)) results in x being rounded when converted to a string, which throws the entire thing off. Does anyone know of a fix for it?
Here's the code being used if you... | ```
len(repr(float(x)/3))
```
However I must say that this isn't as reliable as you think.
Floats are entered/displayed as decimal numbers, but your computer (in fact, your standard C library) stores them as binary. You get some side effects from this transition:
```
>>> print len(repr(0.1))
19
>>> print repr(0.1)
0... |
Converting a float to a string without rounding it | 1,317,558 | 39 | 2009-08-23T02:03:07Z | 1,317,578 | 63 | 2009-08-23T02:10:13Z | [
"python",
"string",
"floating-point",
"rounding"
] | I'm making a program that, for reasons not needed to be explained, requires a float to be converted into a string to be counted with len(). However, str(float(x)) results in x being rounded when converted to a string, which throws the entire thing off. Does anyone know of a fix for it?
Here's the code being used if you... | Some form of rounding is often unavoidable when dealing with floating point numbers. This is because numbers that you can express exactly in base 10 cannot always be expressed exactly in base 2 (which your computer uses).
For example:
```
>>> .1
0.10000000000000001
```
In this case, you're seeing .1 converted to a s... |
Should I use "from package import utils, settings" or "from . import utils, settings" | 1,317,624 | 4 | 2009-08-23T02:43:54Z | 1,317,642 | 10 | 2009-08-23T02:57:34Z | [
"python"
] | I'm developing a Python application; it has all its code in one package and runs inside this of course. The application's Python package is of no interest from the interpreter to the user, it's simply a GUI application.
The question is, which style is preferred when importing modules inside the application package
``... | The [Python Style Guide](http://www.python.org/dev/peps/pep-0008/) recommends explicitly against relative imports (the . style):
> Relative imports for intra-package imports are highly discouraged.
> Always use the absolute package path for all imports.
> Even now that PEP 328 [7] is fully implemented in Python 2.5,
>... |
How can I filter a date of a DateTimeField in Django? | 1,317,714 | 112 | 2009-08-23T03:52:07Z | 1,317,725 | 67 | 2009-08-23T04:02:35Z | [
"python",
"django",
"datetime",
"filter",
"django-queryset"
] | I am trying to filter a `DateTimeField` comparing with a date. I mean:
```
MyObject.objects.filter(datetime_attr=datetime.date(2009,8,22))
```
I get an empty queryset list as an answer because (I think) I am not considering time, but I want "any time".
Is there an easy way in Django for doing this?
I have the time ... | ```
YourModel.objects.filter(datetime_published__year='2008',
datetime_published__month='03',
datetime_published__day='27')
```
// edit after comments
```
YourModel.objects.filter(datetime_published=datetime(2008, 03, 27))
```
doest not work because it creates a da... |
How can I filter a date of a DateTimeField in Django? | 1,317,714 | 112 | 2009-08-23T03:52:07Z | 1,973,917 | 90 | 2009-12-29T10:23:03Z | [
"python",
"django",
"datetime",
"filter",
"django-queryset"
] | I am trying to filter a `DateTimeField` comparing with a date. I mean:
```
MyObject.objects.filter(datetime_attr=datetime.date(2009,8,22))
```
I get an empty queryset list as an answer because (I think) I am not considering time, but I want "any time".
Is there an easy way in Django for doing this?
I have the time ... | Such lookups are implemented in `django.views.generic.date_based` as follows:
```
{'date_time_field__range': (datetime.datetime.combine(date, datetime.time.min),
datetime.datetime.combine(date, datetime.time.max))}
```
Because it is quite verbose there are plans to improve the syntax using... |
How can I filter a date of a DateTimeField in Django? | 1,317,714 | 112 | 2009-08-23T03:52:07Z | 2,262,766 | 22 | 2010-02-14T21:05:12Z | [
"python",
"django",
"datetime",
"filter",
"django-queryset"
] | I am trying to filter a `DateTimeField` comparing with a date. I mean:
```
MyObject.objects.filter(datetime_attr=datetime.date(2009,8,22))
```
I get an empty queryset list as an answer because (I think) I am not considering time, but I want "any time".
Is there an easy way in Django for doing this?
I have the time ... | This produces the same results as using \_\_year, \_\_month, and \_\_day and seems to work for me:
```
YourModel.objects.filter(your_datetime_field__startswith=datetime.date(2009,8,22))
``` |
How can I filter a date of a DateTimeField in Django? | 1,317,714 | 112 | 2009-08-23T03:52:07Z | 9,414,681 | 22 | 2012-02-23T14:11:08Z | [
"python",
"django",
"datetime",
"filter",
"django-queryset"
] | I am trying to filter a `DateTimeField` comparing with a date. I mean:
```
MyObject.objects.filter(datetime_attr=datetime.date(2009,8,22))
```
I get an empty queryset list as an answer because (I think) I am not considering time, but I want "any time".
Is there an easy way in Django for doing this?
I have the time ... | ```
Mymodel.objects.filter(date_time_field__contains=datetime.date(1986, 7, 28))
```
the above is what I've used. Not only does it work, it also has some inherent logical backing. |
How can I filter a date of a DateTimeField in Django? | 1,317,714 | 112 | 2009-08-23T03:52:07Z | 11,174,559 | 51 | 2012-06-24T02:31:03Z | [
"python",
"django",
"datetime",
"filter",
"django-queryset"
] | I am trying to filter a `DateTimeField` comparing with a date. I mean:
```
MyObject.objects.filter(datetime_attr=datetime.date(2009,8,22))
```
I get an empty queryset list as an answer because (I think) I am not considering time, but I want "any time".
Is there an easy way in Django for doing this?
I have the time ... | Here are the results I got with ipython's timeit function:
```
from datetime import date
today = date.today()
timeit[Model.objects.filter(date_created__year=today.year, date_created__month=today.month, date_created__day=today.day)]
1000 loops, best of 3: 652 us per loop
timeit[Model.objects.filter(date_created__gte=... |
How can I filter a date of a DateTimeField in Django? | 1,317,714 | 112 | 2009-08-23T03:52:07Z | 32,271,398 | 7 | 2015-08-28T12:44:37Z | [
"python",
"django",
"datetime",
"filter",
"django-queryset"
] | I am trying to filter a `DateTimeField` comparing with a date. I mean:
```
MyObject.objects.filter(datetime_attr=datetime.date(2009,8,22))
```
I get an empty queryset list as an answer because (I think) I am not considering time, but I want "any time".
Is there an easy way in Django for doing this?
I have the time ... | Now Django has [\_\_date](https://docs.djangoproject.com/en/dev/ref/models/querysets/#date) queryset filter to query datetime objects against dates in development version. Thus, it will be available in 1.9 soon. |
How can I hide incompatible code from older Python versions? | 1,317,946 | 3 | 2009-08-23T06:59:55Z | 1,317,965 | 11 | 2009-08-23T07:09:44Z | [
"python",
"unit-testing"
] | I'm writing unit tests for a function that takes both an `*args` and a `**kwargs` argument. A reasonable use-case for this function is using keyword arguments after the `*args` argment, i.e. of the form
```
def f(a, *b, **c):
print a, b, c
f(1, *(2, 3, 4), keyword=13)
```
Now this only [became legal in Python 2.... | I don't think you should be testing whether Python works correctly; instead, focus on testing your own code. In doing so, it is perfectly possible to write the specific invocation in a way that works for all Python versions, namely:
```
f(1, *(2,3,4), **{'keyword':13})
``` |
Why is the Borg pattern better than the Singleton pattern in Python | 1,318,406 | 50 | 2009-08-23T12:01:43Z | 1,318,426 | 10 | 2009-08-23T12:13:06Z | [
"python",
"singleton"
] | Why is the [Borg pattern](http://code.activestate.com/recipes/66531/) better than the [Singleton pattern](http://stackoverflow.com/questions/31875/is-there-a-simple-elegant-way-to-define-singletons-in-python)?
I ask because I don't see them resulting in anything different.
Borg:
```
class Borg:
__shared_state = {}... | It is not. What is generally not recommended is a pattern like this in python:
```
class Singleton(object):
_instance = None
def __init__(self, ...):
...
@classmethod
def instance(cls):
if cls._instance is None:
cls._instance = cls(...)
return cls._instance
```
where you use a class method to get the ... |
Why is the Borg pattern better than the Singleton pattern in Python | 1,318,406 | 50 | 2009-08-23T12:01:43Z | 1,318,444 | 40 | 2009-08-23T12:22:22Z | [
"python",
"singleton"
] | Why is the [Borg pattern](http://code.activestate.com/recipes/66531/) better than the [Singleton pattern](http://stackoverflow.com/questions/31875/is-there-a-simple-elegant-way-to-define-singletons-in-python)?
I ask because I don't see them resulting in anything different.
Borg:
```
class Borg:
__shared_state = {}... | The real reason that borg is different comes down to subclassing.
If you subclass a borg, the subclass' objects have the same state as their parents classes objects, unless you explicitly override the shared state in that subclass. Each subclass of the singleton pattern has its own state and therefore will produce dif... |
Why is the Borg pattern better than the Singleton pattern in Python | 1,318,406 | 50 | 2009-08-23T12:01:43Z | 20,809,695 | 11 | 2013-12-28T00:30:55Z | [
"python",
"singleton"
] | Why is the [Borg pattern](http://code.activestate.com/recipes/66531/) better than the [Singleton pattern](http://stackoverflow.com/questions/31875/is-there-a-simple-elegant-way-to-define-singletons-in-python)?
I ask because I don't see them resulting in anything different.
Borg:
```
class Borg:
__shared_state = {}... | In python if you want a unique "object" that you can access from anywhere just create a class `Unique` that only contains static attributes, `@staticmethod`s, and `@classmethod`s; you could call it the Unique Pattern. Here I implement and compare the 3 patterns:
Unique
```
#Unique Pattern
class Unique:
#Define some s... |
In pdb how do you reset the list (l) command line count? | 1,318,676 | 22 | 2009-08-23T14:13:40Z | 11,848,010 | 13 | 2012-08-07T14:18:25Z | [
"python",
"pdb"
] | From PDB
```
(Pdb) help l
l(ist) [first [,last]]
List source code for the current file.
Without arguments, list 11 lines around the current line
or continue the previous listing.
With one argument, list 11 lines starting at that line.
With two arguments, list the given range;
if the second argument is less... | Late but hopefully still helpful. In pdb, make the following alias (which you can add to your .pdbrc file so it's always available):
```
alias ll u;;d;;l
```
Then whenever you type `ll`, pdb will list from the current position. It works by going up the stack and then down the stack, which resets 'l' to show from the ... |
Ctypes pro and con | 1,318,736 | 7 | 2009-08-23T14:45:21Z | 1,319,150 | 13 | 2009-08-23T18:00:05Z | [
"python",
"winapi",
"ctypes"
] | I have heard that Ctypes can cause crashes (or stop errors) in Python and windows. Should I stay away from their use? Where did I hear? It was back when I tried to control various aspects of windows, automation, that sort of thing.
I hear of swig, but I see Ctypes more often than not. Any danger here? If so, what shou... | In terms of robustness, I still think swig is somewhat superior to ctypes, because it's possible to have a C compiler check things more thoroughly for you; however, this is pretty moot by now (while it loomed larger in earlier ctypes versons), thanks to the `argtypes` feature @Mark already mentioned. However, there is ... |
Python/GAE web request error handling | 1,318,960 | 4 | 2009-08-23T16:35:41Z | 1,319,433 | 9 | 2009-08-23T20:12:58Z | [
"python",
"google-app-engine",
"error-handling",
"design-patterns"
] | I am developing an application on the Google App Engine using Python.
I have a handler that can return a variety of outputs (html and json at the moment), I am testing for obvious errors in the system based on invalid parameters sent to the request handler.
However what I am doing feels dirty (see below):
```
class ... | There's a couple of handy methods here. The first is self.[error](http://code.google.com/p/googleappengine/source/browse/trunk/python/google/appengine/ext/webapp/%5F%5Finit%5F%5F.py#353)(code). By default this method simply sets the status code and clears the output buffer, but you can override it to output custom erro... |
Parallel Python: What is a callback? | 1,319,074 | 20 | 2009-08-23T17:30:50Z | 1,319,108 | 13 | 2009-08-23T17:42:35Z | [
"python",
"callback",
"parallel-python"
] | In [Parallel Python](http://www.parallelpython.com/) it has something in the *submit* function called a *callback* ([documentation](http://www.parallelpython.com/content/view/15/30/)) however it doesn't seem to explain it too well. I've posted on their forum a couple days ago and I've not received a response. Would som... | The relevant spot in the docs:
```
callback - callback function which will be called with argument
list equal to callbackargs+(result,)
as soon as calculation is done
callbackargs - additional arguments for callback function
```
So, if you want some code to be executed as soon as the result is ready... |
Parallel Python: What is a callback? | 1,319,074 | 20 | 2009-08-23T17:30:50Z | 1,319,135 | 83 | 2009-08-23T17:52:53Z | [
"python",
"callback",
"parallel-python"
] | In [Parallel Python](http://www.parallelpython.com/) it has something in the *submit* function called a *callback* ([documentation](http://www.parallelpython.com/content/view/15/30/)) however it doesn't seem to explain it too well. I've posted on their forum a couple days ago and I've not received a response. Would som... | A callback is a function provided by the consumer of an API that the API can then turn around and invoke (calling you back). If I setup a Dr.'s appointment, I can give them my phone number, so they can call me the day before to confirm the appointment. A callback is like that, except instead of just being a phone numbe... |
Shorter, more pythonic way of writing an if statement | 1,319,214 | 38 | 2009-08-23T18:33:08Z | 1,319,219 | 80 | 2009-08-23T18:34:47Z | [
"python",
"if-statement"
] | I have this
```
bc = 'off'
if c.page == 'blog':
bc = 'on'
print bc
```
Is there a more pythonic (and/or shorter) way of writing this in python? | Shortest one should be:
```
bc = 'on' if c.page=='blog' else 'off'
```
Generally this might look a bit confusing, so you should only use it when it is clear what it means. Don't use it for big boolean clauses, since it begins to look ugly fast. |
Shorter, more pythonic way of writing an if statement | 1,319,214 | 38 | 2009-08-23T18:33:08Z | 1,319,223 | 13 | 2009-08-23T18:35:56Z | [
"python",
"if-statement"
] | I have this
```
bc = 'off'
if c.page == 'blog':
bc = 'on'
print bc
```
Is there a more pythonic (and/or shorter) way of writing this in python? | Or you could use an inline if statement:
```
>>> cpage = 'blog'
>>> bc = 'on' if cpage == 'blog' else 'off'
>>> bc
'on'
>>> cpage = 'asdf'
>>> bc = 'on' if cpage == 'blog' else 'off'
>>> bc
'off'
```
There's a bit of a writeup on that feature at [this blog](http://www.siafoo.net/article/52#id34), and the relevant PEP... |
Shorter, more pythonic way of writing an if statement | 1,319,214 | 38 | 2009-08-23T18:33:08Z | 1,319,289 | 25 | 2009-08-23T19:03:25Z | [
"python",
"if-statement"
] | I have this
```
bc = 'off'
if c.page == 'blog':
bc = 'on'
print bc
```
Is there a more pythonic (and/or shorter) way of writing this in python? | Well, not being a python guy please take this with a huge grain of salt, but having written (and, with more difficulty, *read*) a lot of clever code over the years, I find myself with a strong preference now for readable code. I got the gist of what your original code was doing even though I'm a nobody as a Python guy.... |
Shorter, more pythonic way of writing an if statement | 1,319,214 | 38 | 2009-08-23T18:33:08Z | 1,319,479 | 58 | 2009-08-23T20:33:02Z | [
"python",
"if-statement"
] | I have this
```
bc = 'off'
if c.page == 'blog':
bc = 'on'
print bc
```
Is there a more pythonic (and/or shorter) way of writing this in python? | This is:
1. definitely shorter
2. arguably Pythonic (pre-Python 2.5, which introduced the controversial `X if Z else Y` syntax)
3. questionably readable. With those caveats in mind, here it goes:
```
bc = ("off","on")[c.page=="blog"]
```
EDIT: As per request, the generalized form is:
```
result = (on_fa... |
What is the most efficient way to add an element to a list only if isn't there yet? | 1,319,254 | 7 | 2009-08-23T18:50:41Z | 1,319,272 | 8 | 2009-08-23T18:55:27Z | [
"python",
"list",
"optimization"
] | I have the following code in Python:
```
def point_to_index(point):
if point not in points:
points.append(point)
return points.index(point)
```
This code is awfully inefficient, especially since I expect `points` to grow to hold a few million elements.
If the point isn't in the list, I traverse the l... | You want to use a [set](http://docs.python.org/library/stdtypes.html#set):
```
>>> x = set()
>>> x
set([])
>>> x.add(1)
>>> x
set([1])
>>> x.add(1)
>>> x
set([1])
```
A set contains only one instance of any item you add, and it will be a lot more efficient than iterating a list manually.
[This wikibooks page](http:/... |
What is the most efficient way to add an element to a list only if isn't there yet? | 1,319,254 | 7 | 2009-08-23T18:50:41Z | 1,319,287 | 10 | 2009-08-23T19:02:13Z | [
"python",
"list",
"optimization"
] | I have the following code in Python:
```
def point_to_index(point):
if point not in points:
points.append(point)
return points.index(point)
```
This code is awfully inefficient, especially since I expect `points` to grow to hold a few million elements.
If the point isn't in the list, I traverse the l... | This will traverse at most once:
```
def point_to_index(point):
try:
return points.index(point)
except ValueError:
points.append(point)
return len(points)-1
```
You may also want to try this version, which takes into account that matches are likely to be near the end of the list. Note... |
Combining two lists and removing duplicates, without removing duplicates in original list | 1,319,338 | 31 | 2009-08-23T19:27:58Z | 1,319,353 | 59 | 2009-08-23T19:32:09Z | [
"python",
"list"
] | I have two lists that i need to combine where the second list has any duplicates of the first list ignored. .. A bit hard to explain, so let me show an example of what the code looks like, and what i want as a result.
```
first_list = [1, 2, 2, 5]
second_list = [2, 5, 7, 9]
# The result of combining the two lists sh... | You need to append to the first list those elements of the second list that aren't in the first - sets are the easiest way of determining which elements they are, like this:
```
first_list = [1, 2, 2, 5]
second_list = [2, 5, 7, 9]
in_first = set(first_list)
in_second = set(second_list)
in_second_but_not_in_first = i... |
Combining two lists and removing duplicates, without removing duplicates in original list | 1,319,338 | 31 | 2009-08-23T19:27:58Z | 1,319,355 | 19 | 2009-08-23T19:32:42Z | [
"python",
"list"
] | I have two lists that i need to combine where the second list has any duplicates of the first list ignored. .. A bit hard to explain, so let me show an example of what the code looks like, and what i want as a result.
```
first_list = [1, 2, 2, 5]
second_list = [2, 5, 7, 9]
# The result of combining the two lists sh... | ```
resulting_list = list(first_list)
resulting_list.extend(x for x in second_list if x not in resulting_list)
``` |
Need Help using XPath in ElementTree | 1,319,385 | 26 | 2009-08-23T19:48:21Z | 1,319,417 | 47 | 2009-08-23T20:02:48Z | [
"python",
"xml",
"xpath",
"elementtree"
] | I am having a heck of a time using ElementTree 1.3 in Python. Essentially, ElementTree does absolutely nothing.
My XML file looks like the following:
```
<?xml version="1.0"?>
<ItemSearchResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2008-08-19">
<Items>
<Item>
<ItemAttributes>
... | There are 2 problems that you have.
1) `element` contains only the root element, not recursively the whole document. It is of type Element not ElementTree.
2) Your search string needs to use namespaces if you keep the namespace in the XML.
**To fix problem #1:**
You need to change:
```
element = ET.parse(fp).getro... |
Is this a good approach to avoid using SQLAlchemy/SQLObject? | 1,319,585 | 3 | 2009-08-23T21:15:05Z | 1,319,598 | 8 | 2009-08-23T21:23:54Z | [
"python",
"sqlalchemy",
"sqlobject"
] | Rather than use an ORM, I am considering the following approach in Python and MySQL with no ORM (SQLObject/SQLAlchemy). I would like to get some feedback on whether this seems likely to have any negative long-term consequences since in the short-term view it seems fine from what I can tell.
Rather than translate a row... | That doesn't do away with the need for an ORM. That **is** an ORM. In which case, why reinvent the wheel?
Is there a compelling reason you're trying to avoid using an established ORM? |
Proper way to declare custom exceptions in modern Python? | 1,319,615 | 595 | 2009-08-23T21:29:29Z | 1,319,660 | 10 | 2009-08-23T21:46:54Z | [
"python",
"exception"
] | What's the proper way to declare custom exception classes in modern Python? My primary goal is to follow whatever standard other exception classes have, so that (for instance) any extra string I include in the exception is printed out by whatever tool caught the exception.
By "modern Python" I mean something that will... | You should override `__repr__` or `__unicode__` methods instead of using message, the args you provide when you construct the exception will be in `args` member variable when you need. |
Proper way to declare custom exceptions in modern Python? | 1,319,615 | 595 | 2009-08-23T21:29:29Z | 1,319,675 | 578 | 2009-08-23T21:55:23Z | [
"python",
"exception"
] | What's the proper way to declare custom exception classes in modern Python? My primary goal is to follow whatever standard other exception classes have, so that (for instance) any extra string I include in the exception is printed out by whatever tool caught the exception.
By "modern Python" I mean something that will... | Maybe I missed the question, but why not:
```
class MyException(Exception):
pass
```
**Edit:** to override something (or pass extra args), do this:
```
class ValidationError(Exception):
def __init__(self, message, errors):
# Call the base class constructor with the parameters it needs
super(... |
Proper way to declare custom exceptions in modern Python? | 1,319,615 | 595 | 2009-08-23T21:29:29Z | 10,270,732 | 223 | 2012-04-22T18:18:17Z | [
"python",
"exception"
] | What's the proper way to declare custom exception classes in modern Python? My primary goal is to follow whatever standard other exception classes have, so that (for instance) any extra string I include in the exception is printed out by whatever tool caught the exception.
By "modern Python" I mean something that will... | With modern Python Exceptions, you don't need to abuse `.message`, or override `.__str__()` or `.__repr__()` or any of it. If all you want is an informative message when your exception is raised, do this:
```
class MyException(Exception):
pass
raise MyException("My hovercraft is full of eels")
```
That will give... |
Proper way to declare custom exceptions in modern Python? | 1,319,615 | 595 | 2009-08-23T21:29:29Z | 18,108,623 | 21 | 2013-08-07T16:23:56Z | [
"python",
"exception"
] | What's the proper way to declare custom exception classes in modern Python? My primary goal is to follow whatever standard other exception classes have, so that (for instance) any extra string I include in the exception is printed out by whatever tool caught the exception.
By "modern Python" I mean something that will... | see how exceptions work by default if one *vs* more attributes are used (tracebacks omitted):
```
>>> raise Exception('bad thing happened')
Exception: bad thing happened
>>> raise Exception('bad thing happened', 'code is broken')
Exception: ('bad thing happened', 'code is broken')
```
so you might want to have a sor... |
Proper way to declare custom exceptions in modern Python? | 1,319,615 | 595 | 2009-08-23T21:29:29Z | 26,938,914 | 53 | 2014-11-14T21:09:22Z | [
"python",
"exception"
] | What's the proper way to declare custom exception classes in modern Python? My primary goal is to follow whatever standard other exception classes have, so that (for instance) any extra string I include in the exception is printed out by whatever tool caught the exception.
By "modern Python" I mean something that will... | > # "Proper way to declare custom exceptions in modern Python?"
This is fine, unless your exception is really a type of a more specific exception:
```
class MyException(Exception):
pass
```
Or better (maybe perfect), instead of `pass` give a docstring:
```
class MyException(Exception):
"""Raise for my speci... |
Key-ordered dict in Python | 1,319,763 | 24 | 2009-08-23T22:33:49Z | 1,320,202 | 27 | 2009-08-24T02:20:48Z | [
"python",
"data-structures",
"collections",
"dictionary"
] | I am looking for a solid implementation of an ordered associative array, that is, an ordered dictionary. I want the ordering in terms of keys, not of insertion order.
More precisely, I am looking for a space-efficent implementation of a int-to-float (or string-to-float for another use case) mapping structure for which... | "Random access O(1)" is an extremely exacting requirement which basically imposes an underlying hash table -- and I hope you do mean random READS only, because I think it can be mathematically proven than it's impossible in the general case to have O(1) writes as well as O(N) ordered iteration.
I don't think you will ... |
urlopen, BeautifulSoup and UTF-8 Issue | 1,320,591 | 2 | 2009-08-24T05:17:24Z | 1,320,669 | 11 | 2009-08-24T05:58:34Z | [
"python",
"utf-8",
"urllib2",
"beautifulsoup"
] | I am just trying to retrieve a web page, but somehow a foreign character is embedded in the HTML file. This character is not visible when I use "View Source."
```
isbn = 9780141187983
url = "http://search.barnesandnoble.com/booksearch/isbninquiry.asp?ean=%s" % isbn
opener = urllib2.build_opener()
url_opener = opener.o... | This error is probably actually happening when you try to *print* the representation of the BeautifulSoup file, which will happen automatically if, as I suspect, you are working in the interactive console.
```
# This code will work fine, note we are assigning the result
# of the BeautifulSoup object to prevent it fro... |
Good graph traversal algorithm | 1,320,688 | 11 | 2009-08-24T06:05:32Z | 1,320,716 | 7 | 2009-08-24T06:15:54Z | [
"python",
"performance",
"algorithm",
"language-agnostic",
"graph-traversal"
] | Abstract problem : I have a graph of about 250,000 nodes and the average connectivity is around 10. Finding a node's connections is a long process (10 seconds lets say). Saving a node to the database also takes about 10 seconds. I can check if a node is already present in the db very quickly. Allowing concurrency, but ... | To remember IDs of the users you've already visited, you need a map of a length of 250,000 integers. That's far from "too much". Just maintain such a map and only traverse through the edges that lead to the already undiscovered users, adding them to that map at the point of finding such edge.
As far I can see, you're ... |
Count number of files with certain extension in Python | 1,320,731 | 16 | 2009-08-24T06:20:54Z | 1,320,744 | 23 | 2009-08-24T06:26:35Z | [
"python",
"file",
"count"
] | I am fairly new to Python and I am trying to figure out the most efficient way to count the number of .TIF files in a particular sub-directory.
Doing some searching, I found one example (I have not tested), which claimed to count all of the files in a directory:
```
file_count = sum((len(f) for _, _, f in os.walk(myP... | Something has to iterate over all files in the directory, and look at every single file name - whether that's your code or a library routine. So no matter what the specific solution, they will all have roughly the same cost.
If you think it's too much code, and if you don't actually need to search subdirectories recur... |
How to extend distutils with a simple post install script? | 1,321,270 | 33 | 2009-08-24T09:11:33Z | 1,321,345 | 28 | 2009-08-24T09:27:59Z | [
"python",
"distutils"
] | I need to run a simple script after the modules and programs have been installed.
I'm having a little trouble finding straight-forward documentation on how to do this. It looks like I need to inherit from distutils.command.install, override some methods and add this object to the setup script. The specifics are a bit h... | I dug through distutils source for a day to learn enough about it to make a bunch of custom commands. It's not pretty, but it does work.
```
import distutils.core
from distutils.command.install import install
...
class my_install(install):
def run(self):
install.run(self)
# Custom stuff here
... |
How to extend distutils with a simple post install script? | 1,321,270 | 33 | 2009-08-24T09:11:33Z | 1,321,356 | 12 | 2009-08-24T09:31:05Z | [
"python",
"distutils"
] | I need to run a simple script after the modules and programs have been installed.
I'm having a little trouble finding straight-forward documentation on how to do this. It looks like I need to inherit from distutils.command.install, override some methods and add this object to the setup script. The specifics are a bit h... | OK, I figured it out. The idea is basically to extend one of the distutils commands and overwrite the run method. To tell distutils to use the new class you can use the cmdclass variable.
```
from distutils.core import setup
from distutils.command.install_data import install_data
class post_install(install_data):
... |
What are the required functionnalities of ETL frameworks? | 1,321,396 | 11 | 2009-08-24T09:41:16Z | 1,321,585 | 16 | 2009-08-24T10:26:51Z | [
"python",
"mongodb",
"etl"
] | I am writing an ETL (in python with a mongodb backend) and was wondering : what kind of standard functions and tools an ETL should have to be called an ETL ?
This ETL will be as general purpose as possible, with a scriptable and modular approach. Mostly it will be used to keep different databases in sync, and to impor... | Let's think of the ETL use cases for a moment.
1. Extract.
* Read databases through a generic DB-API adapter.
* Read flat files through a similar adapter.
* Read spreadsheets through a similar adapter.
2. Cleanse.
* Arbitrary rules
* Filter and reject
* Replace
* Add columns of data
3. Profile Dat... |
Determine if Python variable is an instance of a built-in type | 1,322,068 | 11 | 2009-08-24T12:27:22Z | 1,322,152 | 10 | 2009-08-24T12:42:49Z | [
"python",
"variables",
"instance"
] | I need to determine if a given Python variable is an instance of native type: `str`, `int`, `float`, `bool`, `list`, `dict` and so on. Is there elegant way to doing it?
Or is this the only way:
```
if myvar in (str, int, float, bool):
# do something
``` | The best way to achieve this is to collect the types in a list of tuple called `primitiveTypes` and:
```
if isinstance(myvar, primitiveTypes): ...
```
The [`types` module](http://docs.python.org/library/types.html) contains collections of all important types which can help to build the list/tuple.
[Works since Pytho... |
gotchas where Numpy differs from straight python? | 1,322,380 | 23 | 2009-08-24T13:21:37Z | 1,322,468 | 12 | 2009-08-24T13:36:41Z | [
"python",
"numpy"
] | Folks,
is there a collection of gotchas where Numpy differs from python,
points that have puzzled and cost time ?
> "The horror of that moment I shall
> never never forget !"
> "You will, though," the Queen said, "if you don't
> make a memorandum of it."
For example, NaNs are always trouble, anywhere.
If you can e... | `NaN` is not a singleton like `None`, so you can't really use the is check on it. What makes it a bit tricky is that `NaN == NaN` is `False` as IEEE-754 requires. That's why you need to use the `numpy.isnan()` function to check if a float is not a number. Or the standard library `math.isnan()` if you're using Python 2.... |
gotchas where Numpy differs from straight python? | 1,322,380 | 23 | 2009-08-24T13:21:37Z | 1,323,233 | 20 | 2009-08-24T15:58:42Z | [
"python",
"numpy"
] | Folks,
is there a collection of gotchas where Numpy differs from python,
points that have puzzled and cost time ?
> "The horror of that moment I shall
> never never forget !"
> "You will, though," the Queen said, "if you don't
> make a memorandum of it."
For example, NaNs are always trouble, anywhere.
If you can e... | I think this one is funny:
```
>>> import numpy as n
>>> a = n.array([[1,2],[3,4]])
>>> a[1], a[0] = a[0], a[1]
>>> a
array([[1, 2],
[1, 2]])
```
For Python lists on the other hand this works as intended:
```
>>> b = [[1,2],[3,4]]
>>> b[1], b[0] = b[0], b[1]
>>> b
[[3, 4], [1, 2]]
```
Funny side note: numpy ... |
gotchas where Numpy differs from straight python? | 1,322,380 | 23 | 2009-08-24T13:21:37Z | 1,324,939 | 19 | 2009-08-24T21:44:02Z | [
"python",
"numpy"
] | Folks,
is there a collection of gotchas where Numpy differs from python,
points that have puzzled and cost time ?
> "The horror of that moment I shall
> never never forget !"
> "You will, though," the Queen said, "if you don't
> make a memorandum of it."
For example, NaNs are always trouble, anywhere.
If you can e... | The biggest gotcha for me was that almost every standard operator is overloaded to distribute across the array.
Define a list and an array
```
>>> l = range(10)
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> import numpy
>>> a = numpy.array(l)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
```
Multiplication duplicates the p... |
gotchas where Numpy differs from straight python? | 1,322,380 | 23 | 2009-08-24T13:21:37Z | 1,414,038 | 7 | 2009-09-12T02:19:46Z | [
"python",
"numpy"
] | Folks,
is there a collection of gotchas where Numpy differs from python,
points that have puzzled and cost time ?
> "The horror of that moment I shall
> never never forget !"
> "You will, though," the Queen said, "if you don't
> make a memorandum of it."
For example, NaNs are always trouble, anywhere.
If you can e... | Slicing creates views, not copies.
```
>>> l = [1, 2, 3, 4]
>>> s = l[2:3]
>>> s[0] = 5
>>> l
[1, 2, 3, 4]
>>> a = array([1, 2, 3, 4])
>>> s = a[2:3]
>>> s[0] = 5
>>> a
array([1, 2, 5, 4])
``` |
gotchas where Numpy differs from straight python? | 1,322,380 | 23 | 2009-08-24T13:21:37Z | 6,065,203 | 23 | 2011-05-19T21:43:35Z | [
"python",
"numpy"
] | Folks,
is there a collection of gotchas where Numpy differs from python,
points that have puzzled and cost time ?
> "The horror of that moment I shall
> never never forget !"
> "You will, though," the Queen said, "if you don't
> make a memorandum of it."
For example, NaNs are always trouble, anywhere.
If you can e... | Because `__eq__` does not return a bool, using numpy arrays in any kind of containers prevents equality testing without a container-specific work around.
Example:
```
>>> import numpy
>>> a = numpy.array(range(3))
>>> b = numpy.array(range(3))
>>> a == b
array([ True, True, True], dtype=bool)
>>> x = (a, 'banana')
... |
Django Admin - Bulk editing data? | 1,322,425 | 3 | 2009-08-24T13:30:04Z | 1,322,459 | 8 | 2009-08-24T13:34:59Z | [
"python",
"django",
"django-models",
"django-admin"
] | Are there any admin extensions to let bulk editing data in Django Admin? (ie. Changing the *picture* fields of all *product* models at once. Note that this is needed for a users POV so scripting doesn't count.) Any thoughts on subject welcome. | With Django 1.1, you can create admin actions which can be applied to multiple entries at once. See [the documentation](http://docs.djangoproject.com/en/dev/ref/contrib/admin/actions/#ref-contrib-admin-actions) on this subject. |
python time format check | 1,322,464 | 5 | 2009-08-24T13:36:10Z | 1,322,524 | 14 | 2009-08-24T13:45:51Z | [
"python",
"regex"
] | I want to check if the input string is in "HH:MM" such as 01:16 or 23:16 or 24:00. Giving true or false by the result.
How can I achieve this by using regular expression ? | You can achieve this without regular expressions:
```
import time
def isTimeFormat(input):
try:
time.strptime(input, '%H:%M')
return True
except ValueError:
return False
>>>isTimeFormat('12:12')
True
>>>isTimeFormat('012:12')
False
``` |
Python - How to edit hexadecimal file byte by byte | 1,322,508 | 5 | 2009-08-24T13:42:53Z | 1,322,570 | 7 | 2009-08-24T13:50:13Z | [
"python",
"byte",
"hex",
"filereader"
] | I want to be able to open up an image file and extra the hexadecimal values byte-by-byte. I have no idea how to do this and googling "python byte editing" and "python byte array" didn't come up with anything, surprisingly. Can someone point me towards the library i need to use, specific methods i can google, or tutoria... | Python standard library has mmap module, which can be used to do exactly this. Take a look on [the documentation](http://docs.python.org/library/mmap.html) for further information. |
Python - How to edit hexadecimal file byte by byte | 1,322,508 | 5 | 2009-08-24T13:42:53Z | 1,322,579 | 9 | 2009-08-24T13:51:39Z | [
"python",
"byte",
"hex",
"filereader"
] | I want to be able to open up an image file and extra the hexadecimal values byte-by-byte. I have no idea how to do this and googling "python byte editing" and "python byte array" didn't come up with anything, surprisingly. Can someone point me towards the library i need to use, specific methods i can google, or tutoria... | Depending on what you want to do it might be enough to [open the file in binary mode](http://docs.python.org/library/functions.html#open) and read the data with the normal [file](http://docs.python.org/library/stdtypes.html#bltin-file-objects) functions:
```
# load it
f = open("somefile", 'rb')
data = f.read()
f.close... |
What numbers can you pass as verbosity in running Python Unit Test Suites? | 1,322,575 | 26 | 2009-08-24T13:51:20Z | 1,322,648 | 43 | 2009-08-24T14:08:36Z | [
"python",
"unit-testing",
"verbosity"
] | The Python unittest framework has a concept of verbosity that I can't seem to find defined anywhere. For instance, I'm running test cases like this ([like in the documentation](http://docs.python.org/library/unittest.html#basic-example)):
```
suite = unittest.TestLoader().loadTestsFromTestCase(MyAwesomeTest)
unittest.... | You only have 3 different levels:
* 0 ***(quiet)***: you just get the total numbers of tests executed and the global result
* 1 ***(default)***: you get the same plus a dot for every successful test or a F for every failure
* 2 ***(verbose)***: you get the help string of every test and the result
You can use command ... |
Finding "closest" strings in a Python list (alphabetically) | 1,322,934 | 2 | 2009-08-24T15:04:06Z | 1,323,025 | 15 | 2009-08-24T15:21:21Z | [
"python",
"string"
] | I have a Python list of strings, e.g. initialized as follows:
```
l = ['aardvark', 'cat', 'dog', 'fish', 'tiger', 'zebra']
```
I would like to test an input string against this list, and find the "closest string below it" and the "closest string above it", alphabetically and case-insensitively (i.e. no phonetics, jus... | This is exactly what the bisect module is for. It will be much faster than just iterating through large lists.
```
import bisect
def closest(haystack, needle):
if len(haystack) == 0: return None, None
index = bisect.bisect_left(haystack, needle)
if index == 0:
return None, haystack[0]
if inde... |
In Python, how to check if a string only contains certain characters? | 1,323,364 | 26 | 2009-08-24T16:22:05Z | 1,323,374 | 37 | 2009-08-24T16:24:38Z | [
"python",
"regex",
"search",
"character"
] | In Python, how to check if a string only contains certain characters?
I need to check a string containing only a..z, 0..9, and . (period) and no other character.
I could iterate over each character and check the character is a..z or 0..9, or . but that would be slow.
I am not clear now how to do it with a regular ex... | Here's a simple, pure-Python implementation. It should be used when performance is not critical (included for future Googlers).
```
import string
allowed = set(string.ascii_lowercase + string.digits + '.')
def check(test_str):
set(test_str) <= allowed
```
---
Regarding performance, iteration will probably be th... |
In Python, how to check if a string only contains certain characters? | 1,323,364 | 26 | 2009-08-24T16:22:05Z | 1,323,385 | 14 | 2009-08-24T16:26:21Z | [
"python",
"regex",
"search",
"character"
] | In Python, how to check if a string only contains certain characters?
I need to check a string containing only a..z, 0..9, and . (period) and no other character.
I could iterate over each character and check the character is a..z or 0..9, or . but that would be slow.
I am not clear now how to do it with a regular ex... | Simpler approach? A little more Pythonic?
```
>>> ok = "0123456789abcdef"
>>> all(c in ok for c in "123456abc")
True
>>> all(c in ok for c in "hello world")
False
```
It certainly isn't the most efficient, but it's sure readable. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.