title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
Python - Rotation of 3D vector | 6,802,577 | 28 | 2011-07-23T18:57:33Z | 12,261,243 | 14 | 2012-09-04T10:10:11Z | [
"python",
"vector",
"rotation"
] | I have two vectors as Python lists and an angle. E.g.:
```
v = [3,5,0]
axis = [4,4,1]
theta = 1.2 #radian
```
What is the best/easiest way to get the resulting vector when rotating the v vector around the axis?
The rotation should appear to be counter clockwise for an observer to whom the axis vector is pointing. Th... | I just wanted to mention that if speed is required, wrapping unutbu's code in scipy's weave.inline and passing an already existing matrix as a parameter yields a 20-fold decrease in the running time.
The code (in rotation\_matrix\_test.py):
```
import numpy as np
import timeit
from math import cos, sin, sqrt
import ... |
Python - Rotation of 3D vector | 6,802,577 | 28 | 2011-07-23T18:57:33Z | 25,709,323 | 20 | 2014-09-07T10:37:42Z | [
"python",
"vector",
"rotation"
] | I have two vectors as Python lists and an angle. E.g.:
```
v = [3,5,0]
axis = [4,4,1]
theta = 1.2 #radian
```
What is the best/easiest way to get the resulting vector when rotating the v vector around the axis?
The rotation should appear to be counter clockwise for an observer to whom the axis vector is pointing. Th... | A one-liner, with numpy/scipy functions.
We use the following:
> let *a* be the unit vector along *axis*, i.e. *a = axis/norm(axis)*
> and *A = I Ã a* be the skew-symmetric matrix associated to *a*, i.e. the cross product of the identity matrix with *a*
>
> then *M = exp(θ A)* is the rotation matrix.
```
from nu... |
Does my code prevent directory traversal? | 6,803,505 | 12 | 2011-07-23T21:45:37Z | 6,803,714 | 15 | 2011-07-23T22:26:46Z | [
"python",
"security",
"wsgi",
"directory-traversal"
] | Is the following code snippet from a Python WSGI app safe from directory traversal? It reads a file name passed as parameter and returns the named file.
```
file_name = request.path_params["file"]
file = open(file_name, "rb")
mime_type = mimetypes.guess_type(file_name)[0]
start_response(status.OK, [('Content-Type', mi... | Your code does not prevent directory traversal. You can guard against this with the [os.path](http://docs.python.org/library/os.path.html) module.
```
>>> import os.path
>>> os.curdir
'.'
>>> startdir = os.path.abspath(os.curdir)
>>> startdir
'/home/jterrace'
```
`startdir` is now an absolute path where you don't wan... |
Playing around with Devanagari characters | 6,805,311 | 23 | 2011-07-24T06:26:21Z | 6,805,416 | 13 | 2011-07-24T07:02:08Z | [
"python",
"unicode",
"indic"
] | I have something like
```
a = "बिà¤à¥à¤°à¤® मà¥à¤°à¥ नाम हà¥"
```
I want to achieve something like
```
a[0] = बि a[1] = à¤à¥à¤° a[3] = म
```
but as म takes 4 bytes while बि takes 8 bytes I am not able to get to that straight.
So what could be done to achieve that? In Python. | So, you want to achieve something like this
```
a[0] = बि a[1] = à¤à¥à¤° a[3] = म
```
My advice is to ditch the idea that string indexing corresponds to the characters you see on the screen. Devanagari, as well as several other scripts, do not play well with programmers who grew up with Latin characters. I su... |
Playing around with Devanagari characters | 6,805,311 | 23 | 2011-07-24T06:26:21Z | 6,806,203 | 16 | 2011-07-24T10:12:32Z | [
"python",
"unicode",
"indic"
] | I have something like
```
a = "बिà¤à¥à¤°à¤® मà¥à¤°à¥ नाम हà¥"
```
I want to achieve something like
```
a[0] = बि a[1] = à¤à¥à¤° a[3] = म
```
but as म takes 4 bytes while बि takes 8 bytes I am not able to get to that straight.
So what could be done to achieve that? In Python. | The algorithm for splitting text into grapheme clusters is given in [Unicode Annex 29](http://www.unicode.org/reports/tr29/tr29-17.html#Grapheme_Cluster_Boundaries), section 3.1. I'm not going to implement the full algorithm for you here, but I'll show you roughly how to handle the case of Devanagari, and then you can ... |
How to: django template pass array and use it in javascript? | 6,806,371 | 4 | 2011-07-24T10:56:04Z | 6,806,953 | 7 | 2011-07-24T13:06:19Z | [
"python",
"django",
"google-app-engine",
"templates"
] | Ok so here is a problem,
I have an html template which looks something like this:
```
<script>
$(function() {
var vCountries = {{ visitedCountriesList }};
});
</script>
<..>
{{ visitedCountriesList }}
```
from server I pass an list to this item, but after rendering it looks like this:
```
<script>
... | The problem is the string representation of the array isn't valid JavaScript. The `u'` at the start is no good. This:
```
[u'Afghanistan', u'Japan', u'United Arab Emirates']
```
should be this:
```
['Afghanistan', 'Japan', 'United Arab Emirates']
```
You have two options. In the view function, encode it as JSON the... |
Rounding time in Python | 6,806,467 | 19 | 2011-07-24T11:21:49Z | 6,806,689 | 10 | 2011-07-24T12:05:37Z | [
"python",
"datetime",
"time",
"modulo",
"rounding"
] | What would be an elegant, efficient and Pythonic way to perform a h/m/s rounding operation on time related types in Python with control over the rounding resolution?
My guess is that it would require a time modulo operation. Illustrative examples:
* 20:11:13 % (10 seconds) => (3 seconds)
* 20:11:13 % (10 minutes) => ... | How about use `datetime.timedelta`s:
```
import time
import datetime as dt
hms=dt.timedelta(hours=20,minutes=11,seconds=13)
resolution=dt.timedelta(seconds=10)
print(dt.timedelta(seconds=hms.seconds%resolution.seconds))
# 0:00:03
resolution=dt.timedelta(minutes=10)
print(dt.timedelta(seconds=hms.seconds%resolution.... |
Rounding time in Python | 6,806,467 | 19 | 2011-07-24T11:21:49Z | 10,854,294 | 9 | 2012-06-01T16:44:01Z | [
"python",
"datetime",
"time",
"modulo",
"rounding"
] | What would be an elegant, efficient and Pythonic way to perform a h/m/s rounding operation on time related types in Python with control over the rounding resolution?
My guess is that it would require a time modulo operation. Illustrative examples:
* 20:11:13 % (10 seconds) => (3 seconds)
* 20:11:13 % (10 minutes) => ... | For a datetime.datetime rounding, see this function:
<http://stackoverflow.com/a/10854034/1431079>
Sample of use:
```
print roundTime(datetime.datetime(2012,12,31,23,44,59,1234),roundTo=60*60)
2013-01-01 00:00:00
``` |
ubuntu 11.04 lxml import etree problem for custom python | 6,806,831 | 10 | 2011-07-24T12:37:36Z | 6,906,318 | 14 | 2011-08-02T01:19:29Z | [
"python",
"lxml"
] | ubuntu 11.04 has native python2.7 i build python2.5 from source to /usr/local/python2.5/bin, and try to install lxml for my custom python2.5 install. Also i use virtualenv. I switch to my env with python2.5. On import lxml i got an error.
```
from lxml import etree
ImportError: /home/se7en/.virtualenvs/e-py25/lib/pyth... | This problem is usually caused by building Python without using the `--enable-unicode=ucs4` option on the `./configure` command.
To make sure you do it right, delete the existing Python build directory and start building again by unzipping the Python tarball.
Also, delete the existing Python 2.5 install directory `/u... |
Mixing python with a faster language for optimization in GAE | 6,807,119 | 9 | 2011-07-24T13:43:44Z | 6,807,245 | 9 | 2011-07-24T14:02:25Z | [
"java",
"python",
"performance",
"google-app-engine",
"go"
] | I'm a newbie in the Python and GAE world and I have a question.
With Python the normal approach is to only optimize the code when needed, fixing the more urgent bottlenecks.
And one of the ways to achieve that is by rewriting the most critical parts of the program in C.
By using GAE are we losing this possibility fore... | See [Can I write parts of the Google App Engine code in Java, other parts in Python ?](http://stackoverflow.com/questions/2342059/can-i-write-parts-of-the-google-app-engine-code-in-java-other-parts-in-python) for how to use multiple languages.
Basically, each version of a given app can only use one runtime language.
... |
Highlighting and Selecting text with Python curses | 6,807,808 | 8 | 2011-07-24T15:44:49Z | 6,848,670 | 12 | 2011-07-27T17:32:11Z | [
"python",
"ncurses",
"tui"
] | This is my first post to stack overflow. I've been lurking this site for information for years, and it's always helpful, so I thought that I would post my first question.
I've been searching for some similar examples, but can't seem to find anything.
Ultimately, I'm trying to write a simple text ui for finding false ... | I would like to update this question in case anybody else is searching the web for this and stumbles upon this question.
Okay, so the answer was actually quite simple and required reading all the functions listed on the python curses documentation.
What I did was make a 3 state machine: State 1: Normal mode (displays... |
Parsing hh:mm in Python | 6,808,064 | 4 | 2011-07-24T16:26:05Z | 6,808,121 | 8 | 2011-07-24T16:34:08Z | [
"python",
"parsing",
"calendar"
] | Sometimes I get a string like "02:40" indicating 2 hours and 40 minutes. I'd like to parse that string into the number of minutes (160 in this case) using Python.
Sure, I can parse the string and multiply the hours by 60, but is there something in the standard lib that does this? | Other than the following, string parsing (or if you want to be even slower for something so simple, use the `re` module) is the only way I can think of if you rely on the standard library. TimeDelta doesn't seem to suit the task.
```
>>> import time
>>> x = "02:40"
>>> t = time.strptime(x, "%H:%M")
>>> minutes = t.tm_... |
Python: maximum recursion depth exceeded while calling a Python object | 6,809,402 | 11 | 2011-07-24T20:14:59Z | 6,809,450 | 7 | 2011-07-24T20:22:45Z | [
"python",
"algorithm",
"recursion",
"web-crawler",
"depth"
] | I've built a crawler that had to run on about 5M pages (by increasing the url ID) and then parses the pages which contain the info' I need.
after using an algorithm which run on the urls (200K) and saved the good and bad results I found that the I'm wasting a lot of time. I could see that there are a a few returning s... | this turns the recursion in to a loop:
```
def checkNextID(ID):
global numOfRuns, curRes, lastResult
while ID < lastResult:
try:
numOfRuns += 1
if numOfRuns % 10 == 0:
time.sleep(3) # sleep every 10 iterations
if isValid(ID + 8):
parse... |
Python: maximum recursion depth exceeded while calling a Python object | 6,809,402 | 11 | 2011-07-24T20:14:59Z | 6,809,586 | 18 | 2011-07-24T20:42:34Z | [
"python",
"algorithm",
"recursion",
"web-crawler",
"depth"
] | I've built a crawler that had to run on about 5M pages (by increasing the url ID) and then parses the pages which contain the info' I need.
after using an algorithm which run on the urls (200K) and saved the good and bad results I found that the I'm wasting a lot of time. I could see that there are a a few returning s... | Python don't have a great support for recursion because of it's lack of TRE ([Tail Recursion Elimination](http://neopythonic.blogspot.com/2009/04/tail-recursion-elimination.html)).
This means that each call to your recursive function will create a function call stack and because there is a limit of stack depth (by def... |
Merging a Python script's subprocess' stdout and stderr while keeping them distinguishable | 6,809,590 | 21 | 2011-07-24T20:43:09Z | 6,810,231 | 8 | 2011-07-24T22:41:25Z | [
"python",
"subprocess",
"stdout",
"stderr"
] | I would like to direct a python script's subprocess' stdout and stdin into the same file. What I don't know is how to make the lines from the two sources distinguishable? (For example prefix the lines from stderr with an exclamation mark.)
In my particular case there is no need for live monitoring of the subprocess, t... | If you want to interleave to get roughly the same order that you would if you ran the process interactively then you need to do what the shell does and poll stdin/stdout and write in the order that they poll.
Here's some code that does something along the lines of what you want - in this case sending the stdout/stderr... |
Merging a Python script's subprocess' stdout and stderr while keeping them distinguishable | 6,809,590 | 21 | 2011-07-24T20:43:09Z | 7,629,651 | 20 | 2011-10-02T22:28:04Z | [
"python",
"subprocess",
"stdout",
"stderr"
] | I would like to direct a python script's subprocess' stdout and stdin into the same file. What I don't know is how to make the lines from the two sources distinguishable? (For example prefix the lines from stderr with an exclamation mark.)
In my particular case there is no need for live monitoring of the subprocess, t... | ```
tsk = subprocess.Popen(args,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
```
[`subprocess.STDOUT`](http://docs.python.org/2/library/subprocess.html#subprocess.STDOUT) is a special flag that tells subprocess to route all stderr output to stdout, thus combining your two streams.
btw, select doesn't have a poll(... |
Merging a Python script's subprocess' stdout and stderr while keeping them distinguishable | 6,809,590 | 21 | 2011-07-24T20:43:09Z | 9,899,753 | 8 | 2012-03-28T00:52:40Z | [
"python",
"subprocess",
"stdout",
"stderr"
] | I would like to direct a python script's subprocess' stdout and stdin into the same file. What I don't know is how to make the lines from the two sources distinguishable? (For example prefix the lines from stderr with an exclamation mark.)
In my particular case there is no need for live monitoring of the subprocess, t... | I found myself having to tackle this problem recently, and it took a while to get something I felt worked correctly in most cases, so here it is! (It also has the nice side effect of processing the output via a python logger, which I've noticed is another common question here on Stackoverflow).
Here is the code:
```
... |
What's "better" the reverse method or the reversed built-in function? | 6,810,036 | 5 | 2011-07-24T22:00:56Z | 6,810,075 | 16 | 2011-07-24T22:06:59Z | [
"python",
"list",
"methods",
"reverse",
"built-in"
] | What is typically regarded as more Pythonic/better/faster to use, the reverse method or the reversed built-in function?
Both in action:
```
_list = list(xrange(4))
print _list
rlist = list(reversed(_list))
print rlist
_list.reverse()
print _list
``` | `foo.reverse()` actually reverses the elements in the container. `reversed()` doesn't actually reverse anything, it merely returns an object that can be used to iterate over the container's elements in reverse order. This is often faster than actually reversing the elements. |
Django import datetime | 6,810,632 | 3 | 2011-07-25T00:11:46Z | 6,810,721 | 7 | 2011-07-25T00:28:27Z | [
"python",
"django",
"import"
] | Using:
* Ubuntu 11.04
* Django 1.3
* Python 2.7
* Following the tutorial at
[Writing your first Django app, part 1](https://docs.djangoproject.com/en/dev/intro/tutorial01/)
Hi, I'm a python beginner, coming from a PHP background, so I apologize if this is a stupid question. I'm getting stuck when trying to call the... | Make sure you import datetime in your view. Add:
```
import datetime
```
to your Views.py page. There was a ticket that was once opened for this issue:
<https://code.djangoproject.com/ticket/5668> |
How to determine file, function and line number? | 6,810,999 | 31 | 2011-07-25T01:28:36Z | 6,811,020 | 46 | 2011-07-25T01:31:56Z | [
"python"
] | In C++, I can print debug output like this:
```
printf(
"FILE: %s, FUNC: %s, LINE: %d, LOG: %s\n",
__FILE__,
__FUNCTION__,
__LINE__,
logmessage
);
```
How can I do something similar in Python? | There is a module named [`inspect`](http://docs.python.org/library/inspect.html) which provides these information.
Example usage:
```
import inspect
def PrintFrame():
callerframerecord = inspect.stack()[1] # 0 represents this line
# 1 represents line at caller
frame... |
How to determine file, function and line number? | 6,810,999 | 31 | 2011-07-25T01:28:36Z | 6,811,030 | 8 | 2011-07-25T01:35:08Z | [
"python"
] | In C++, I can print debug output like this:
```
printf(
"FILE: %s, FUNC: %s, LINE: %d, LOG: %s\n",
__FILE__,
__FUNCTION__,
__LINE__,
logmessage
);
```
How can I do something similar in Python? | For example
```
import inspect
frame = inspect.currentframe()
# __FILE__
fileName = frame.f_code.co_filename
# __LINE__
fileNo = frame.f_lineno
```
There's more here <http://docs.python.org/library/inspect.html> |
Rolling window for 1D arrays in Numpy? | 6,811,183 | 12 | 2011-07-25T02:04:51Z | 6,811,241 | 23 | 2011-07-25T02:17:59Z | [
"python",
"numpy",
"window"
] | Is there a way to efficiently implement a rolling window for 1D arrays in Numpy?
For example, I have this pure Python code snippet to calculate the rolling standard deviations for a 1D list, where `observations` is the 1D list of values, and `n` is the window length for the standard deviation:
```
stdev = []
for i, d... | Just use the blog code, but apply your function to the result.
i.e.
```
numpy.std(rolling_window(observations, n), 1)
```
where you have (from the blog):
```
def rolling_window(a, window):
shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)
strides = a.strides + (a.strides[-1],)
return np.lib.stri... |
How can I include a python package with Hadoop streaming job? | 6,811,549 | 13 | 2011-07-25T03:33:58Z | 6,811,772 | 7 | 2011-07-25T04:26:10Z | [
"python",
"hadoop"
] | I am trying include a python package (NLTK) with a Hadoop streaming job, but am not sure how to do this without including every file manually via the CLI argument, "-file".
Edit: One solution would be to install this package on all the slaves, but I don't have that option currently. | I would zip up the package into a `.tar.gz` or a `.zip` and pass the entire tarball or archive in a `-file` option to your hadoop command. I've done this in the past with Perl but not Python.
That said, I would think this would still work for you if you use Python's `zipimport` at <http://docs.python.org/library/zipim... |
How can I include a python package with Hadoop streaming job? | 6,811,549 | 13 | 2011-07-25T03:33:58Z | 6,811,775 | 22 | 2011-07-25T04:26:25Z | [
"python",
"hadoop"
] | I am trying include a python package (NLTK) with a Hadoop streaming job, but am not sure how to do this without including every file manually via the CLI argument, "-file".
Edit: One solution would be to install this package on all the slaves, but I don't have that option currently. | Just came across this gem of a solution: <http://blog.cloudera.com/blog/2008/11/sending-files-to-remote-task-nodes-with-hadoop-mapreduce/>
```
# first create zip w/ the libraries desired
zip -r nltkandyaml.zip nltk yaml
mv ntlkandyaml.zip /path/to/where/your/mapper/will/be/nltkandyaml.mod
# next, include via Hadoop s... |
How to make unicode string with python3 | 6,812,031 | 35 | 2011-07-25T05:16:20Z | 6,812,069 | 48 | 2011-07-25T05:21:46Z | [
"python",
"unicode",
"python-3.x"
] | I used this :
```
u = unicode(text, 'utf-8')
```
But getting error with Python 3 (or... maybe I just forgot to include something) :
```
NameError: global name 'unicode' is not defined
```
Thank you. | Literal strings are unicode by default in Python3
Assuming that text is a `bytes` object, just use `text.decode('utf-8')`
`unicode` of Python2 is equivalent to `str` in Python3, so you can also write
```
str(text, 'utf-8')
```
if you prefer |
How can I correctly install multiple non-package Distribute/virtualenv/pip ecosystems on Ubuntu? | 6,812,207 | 8 | 2011-07-25T05:50:18Z | 6,875,127 | 7 | 2011-07-29T15:04:19Z | [
"python",
"ubuntu",
"virtualenv",
"pip",
"distribute"
] | I am developing Python applications in Ubuntu. I want to setup a [Distribute/virtualenv/pip ecosystem](http://guide.python-distribute.org/introduction.html#creating-a-micro-ecosystem-with-virtualenv) to manage my Python packages independently of any system Python packages (which I manage in Synaptic, or rather I let th... | Based on [Walker Hale IV's answer](http://stackoverflow.com/questions/4324558/whats-the-proper-way-to-install-pip-virtualenv-and-distribute-for-python/5177027#5177027) to a similar (but distinct! ;) ) question, there are two keys to doing this:
* you don't need to install distribute and pip because these are automatic... |
Python: Memory cost of importing a module | 6,812,571 | 4 | 2011-07-25T06:45:38Z | 6,812,809 | 7 | 2011-07-25T07:15:11Z | [
"python",
"memory-efficient"
] | The memory cost obviously depends on exactly how large a module is, but I'm only looking for a general answer: Is it generally expensive or cheap to import a module in Python? If I have a few tens of small scripts that potentially stay in memory for the whole duration of the application, how much will that hog the memo... | It sounds like you aren't worried about time cost (good; that would be silly, since modules are only imported once) but memory cost. I put it to you: if you need all the functionality in these modules, then how exactly do you plan to **avoid** having them all in memory? Might as well just `import` things in the most lo... |
A source file with unicode characters is making Django throw up a SyntaxError exception | 6,812,612 | 6 | 2011-07-25T06:50:17Z | 6,813,574 | 17 | 2011-07-25T08:45:22Z | [
"python",
"django",
"character-encoding"
] | A file in UTF-8 encoding has an `è` character (e with accent grave) embedded in comment delimiters for Python. Django complains about this character and will not render the page. How can I resolve this? | The SyntaxError Django is raising already points you in the right direction.
It is always a good thing to actually read exceptions. In your case, it will have said something along the lines of
> Non-ASCII character '\xc3' in file /home/zakx/../views.py on line 84, but no encoding declared; see <http://www.python.org/... |
What is better than Mechanize in Python? | 6,813,058 | 4 | 2011-07-25T07:44:30Z | 6,813,088 | 7 | 2011-07-25T07:48:28Z | [
"python",
"mechanize"
] | I want to submit a form, follow link, select some check boxes & Radio buttons and click on buttons through my Python Program. I have worked with Perl's Mechanize. I checked google and I found its available for Python too
```
http://wwwsearch.sourceforge.net/mechanize/
```
Unfortunately, that link is dead! So, where c... | Try this link:
<http://pypi.python.org/pypi/mechanize>
If not mechanize then webdriver driving webkit or webunit backend from Python is an option. Or just use the webkit bindings from Python directly. |
Python have dictionary with same-name keys? | 6,813,564 | 8 | 2011-07-25T08:44:33Z | 6,813,689 | 11 | 2011-07-25T08:54:52Z | [
"python",
"dictionary",
"key"
] | I need to have a dictionary which might have same names for some keys and return a list of values when referencing the key in that case.
For example
```
print mydict['key']
[1,2,3,4,5,6]
``` | For consistency, you should have the dictionary map keys to lists (or sets) of values, of which some can be empty. There is a nice idiom for this:
```
from collections import defaultdict
d = defaultdict(set)
d["key"].add(...)
```
(A `defaultdict` is like a normal dictionary, but if a key is missing it will call the ... |
Python have dictionary with same-name keys? | 6,813,564 | 8 | 2011-07-25T08:44:33Z | 6,815,061 | 9 | 2011-07-25T11:01:33Z | [
"python",
"dictionary",
"key"
] | I need to have a dictionary which might have same names for some keys and return a list of values when referencing the key in that case.
For example
```
print mydict['key']
[1,2,3,4,5,6]
``` | You can also try `paste.util.multidict.MultiDict`
```
$ easy_install Paste
```
Then:
```
from paste.util.multidict import MultiDict
d = MultiDict()
d.add('a', 1)
d.add('a', 2)
d.add('b', 3)
d.mixed()
>>> {'a': [1, 2], 'b': 3}
d.getall('a')
>>> [1, 2]
d.getall('b')
>>> [3]
```
Web frameworks like Pylons are using th... |
Append a new item to a list within a list | 6,814,727 | 5 | 2011-07-25T10:29:12Z | 6,814,768 | 11 | 2011-07-25T10:32:54Z | [
"python",
"list",
"append"
] | I'm trying to append a new float element to a list within another list, for example:
```
list = [[]]*2
list[1].append(2.5)
```
And I get the following:
```
print list
[[2.5], [2.5]]
```
When I'd like to get:
```
[[], [2.5]]
```
How can I do this?
Thanks in advance. | `lst = [[] for _ in xrange(2)]` (or just `[[], []]`). Don't use multiplication with mutable objects â you get the same one X times, not X different ones. |
Extract absolute links from a page using HTMLParser | 6,816,138 | 3 | 2011-07-25T12:30:24Z | 6,816,191 | 7 | 2011-07-25T12:34:39Z | [
"python",
"html",
"html-parsing"
] | I'm using the following snippet to extract all the links on a page using `HTMLParser`. I get quite a few relative URLs. How can I convert these to absolute URLs for a domain e.g. www.exmaple.com
```
import htmllib, formatter
import urllib, htmllib, formatter
class LinksExtractor(htmllib.HTMLParser):
def __init__(... | You want
```
urlparse.urljoin(base, url[, allow_fragments])
```
<http://docs.python.org/library/urlparse.html#urlparse.urljoin>
This allows you to give an absolute or base url, and join it with a relative url. Even if they have overlapping pieces, it should work. |
Catch any error in Python | 6,817,640 | 8 | 2011-07-25T14:26:11Z | 6,817,663 | 18 | 2011-07-25T14:28:13Z | [
"python",
"exception",
"exception-handling",
"try-catch",
"fallback"
] | Is it possible to catch *any* error in Python? I don't care what the specific exceptions will be, because all of them will have the same fallback. | Using `except` by itself will catch any exception short of a segfault.
```
try:
something()
except:
fallback()
```
You might want to handle KeyboardInterrupt separately in case you need to use it to exit your script:
```
try:
something()
except KeyboardInterrupt:
return
except:
fallback()
```
Th... |
Catch any error in Python | 6,817,640 | 8 | 2011-07-25T14:26:11Z | 6,817,677 | 10 | 2011-07-25T14:29:17Z | [
"python",
"exception",
"exception-handling",
"try-catch",
"fallback"
] | Is it possible to catch *any* error in Python? I don't care what the specific exceptions will be, because all of them will have the same fallback. | ```
try:
# do something
except Exception, e:
# handle it
``` |
Sqlite - how to use more memory and cache, and make it run faster | 6,818,136 | 6 | 2011-07-25T15:03:27Z | 6,818,217 | 8 | 2011-07-25T15:10:20Z | [
"python",
"sql",
"database",
"sqlite"
] | I'm inserting into a table in Sqlite around 220GB of data,
and I noticed it use a lot of Disk I/O, read and write,
but doesn't use the computer's memory in any significant way,
though there is a lot of free memory, and I don't use commit to often.
I think the disk I/O is my bottle neck not CPU nor Memory.
how can I a... | There is an old tutorial on optimizing SQLite for speed [here](http://web.utk.edu/~jplyon/sqlite/SQLite_optimization_FAQ.html). It should still be relevant, and get you started.
EDIT: That page no longer exists, but has been mirrored [here](http://www.codificar.com.br/blog/sqlite-optimization-faq/) |
Insert a tzinfo into datetime | 6,818,377 | 7 | 2011-07-25T15:22:19Z | 6,818,483 | 11 | 2011-07-25T15:29:06Z | [
"python",
"datetime",
"timezone",
"tzinfo"
] | I have the following `tzinfo` concrete subclass definition:
```
from datetime import datetime, timedelta, tzinfo
class ManilaTime(tzinfo):
def utcoffset(self, dt):
return timedelta(hours=8)
def tzname(self, dt):
return "Manila"
```
I obtain a date string and would like to transform it into a timezone-aw... | ```
def transform_date(date_string, tzinfo):
fmt = '%Y-%m-%d'
date = datetime.strptime(date_string, fmt).replace(tzinfo=tzinfo)
return date
``` |
Add text to existing PDF document in Python | 6,819,336 | 4 | 2011-07-25T16:30:45Z | 6,821,240 | 18 | 2011-07-25T19:28:15Z | [
"python",
"pdf-generation",
"imagemagick"
] | I'm trying to convert a pdf to the same size as my pdf which is an A4 page.
```
convert my_pdf.pdf -density 300x300 -page A4 my_png.png
```
The resulting png file, however, is 595px à 842px which should be the resolution at 72 dpi.
I was thinking of using PIL to write some text on some of the pdf fields and convert ... | After searching around some I finally found the solution:
It turns out that [this](http://stackoverflow.com/questions/1180115/add-text-to-existing-pdf-using-python) was the correct approach after all.
Yet, i feel that it wasn't verbose enough.
It appears that the poster probably took it from [here](http://language.dynd... |
Plotting points in python | 6,819,653 | 7 | 2011-07-25T16:55:59Z | 6,819,720 | 18 | 2011-07-25T17:01:05Z | [
"python",
"plot"
] | I want to plot some (x,y) points on the same graph and I don't need any special features at all short of support for polar coordinates which would be nice but not necessary. It's mostly for visualizing my data. Is there a simple way to do this? Matplotlib seems like way more than I need right now. Are there any more ba... | Go with [matplotlib](http://matplotlib.sourceforge.net/) Chance is that sometime in the future you might need to do more than just "simple" stuff and then you don't need to invest time learning a new plot-tool.
See this [link](http://wiki.python.org/moin/NumericAndScientific/Plotting) for list of plotting tools for py... |
Plotting points in python | 6,819,653 | 7 | 2011-07-25T16:55:59Z | 6,820,012 | 10 | 2011-07-25T17:31:00Z | [
"python",
"plot"
] | I want to plot some (x,y) points on the same graph and I don't need any special features at all short of support for polar coordinates which would be nice but not necessary. It's mostly for visualizing my data. Is there a simple way to do this? Matplotlib seems like way more than I need right now. Are there any more ba... | Absolutely. Matplotlib is the way to go.
The [pyplot module](http://matplotlib.sourceforge.net/users/pyplot_tutorial.html) provides a nice interface to get simple plots up and running fast, especially if you are familiar with MatLab's plotting environment. Here is a simple example using pyplot:
```
import matplotlib.... |
python location on mac osx | 6,819,661 | 27 | 2011-07-25T16:56:20Z | 6,819,708 | 22 | 2011-07-25T17:00:21Z | [
"python",
"osx"
] | I'm a little confused with the python on osx. I do not know if the previous owner of the laptop has installed macpython using macport. And I remembered that osx has an builtin version of python. I tried using `type -a python` and the result returned
```
python is /usr/bin/python
python is /usr/local/bin/python
```
Ho... | On Mac OS X, it's in the Python framework in `/System/Library/Frameworks/Python.framework/Resources`.
Full path is:
```
/System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python
```
Btw it's easy to find out where you can find a specific binary: `which Python` will show you ... |
python location on mac osx | 6,819,661 | 27 | 2011-07-25T16:56:20Z | 6,820,991 | 23 | 2011-07-25T19:02:22Z | [
"python",
"osx"
] | I'm a little confused with the python on osx. I do not know if the previous owner of the laptop has installed macpython using macport. And I remembered that osx has an builtin version of python. I tried using `type -a python` and the result returned
```
python is /usr/bin/python
python is /usr/local/bin/python
```
Ho... | `[GCC 4.2.1 (Apple Inc. build 5646)]` is the version of GCC that the Python(s) were built with, not the version of Python itself. That information should be on the previous line. For example:
```
# Apple-supplied Python 2.6 in OS X 10.6
$ /usr/bin/python
Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49)
[GCC 4.2.1 (Ap... |
How to find range overlap in python? | 6,821,156 | 17 | 2011-07-25T19:19:41Z | 6,821,193 | 31 | 2011-07-25T19:23:25Z | [
"python",
"range"
] | What is the best way in Python to determine what values in two ranges overlap?
For example:
```
x = range(1,10)
y = range(8,20)
(The answer I am looking for would be the integers 8 and 9.)
```
Given a range, x, what is the best way to iterate through another range, y and output all values that are shared by both ra... | Try with set intersection:
```
>>> x = range(1,10)
>>> y = range(8,20)
>>> xs = set(x)
>>> xs.intersection(y)
set([8, 9])
```
Note that `intersection` accepts any iterable as an argument (`y` is not required to be converted to a *set* for the operation).
There is an operator equivalent to the `intersection` method: `... |
How to find range overlap in python? | 6,821,156 | 17 | 2011-07-25T19:19:41Z | 6,821,196 | 9 | 2011-07-25T19:23:28Z | [
"python",
"range"
] | What is the best way in Python to determine what values in two ranges overlap?
For example:
```
x = range(1,10)
y = range(8,20)
(The answer I am looking for would be the integers 8 and 9.)
```
Given a range, x, what is the best way to iterate through another range, y and output all values that are shared by both ra... | One option is to just use list comprehension like:
```
x = range(1,10)
y = range(8,20)
z = [i for i in x if i in y]
print z
``` |
How to find range overlap in python? | 6,821,156 | 17 | 2011-07-25T19:19:41Z | 6,821,204 | 13 | 2011-07-25T19:24:07Z | [
"python",
"range"
] | What is the best way in Python to determine what values in two ranges overlap?
For example:
```
x = range(1,10)
y = range(8,20)
(The answer I am looking for would be the integers 8 and 9.)
```
Given a range, x, what is the best way to iterate through another range, y and output all values that are shared by both ra... | You can use [set](http://docs.python.org/tutorial/datastructures.html#sets)s for that, but be aware that `set(list)` removes all duplicate entries from the `list`:
```
>>> x = range(1,10)
>>> y = range(8,20)
>>> list(set(x) & set(y))
[8, 9]
``` |
How to find range overlap in python? | 6,821,156 | 17 | 2011-07-25T19:19:41Z | 6,821,298 | 27 | 2011-07-25T19:33:24Z | [
"python",
"range"
] | What is the best way in Python to determine what values in two ranges overlap?
For example:
```
x = range(1,10)
y = range(8,20)
(The answer I am looking for would be the integers 8 and 9.)
```
Given a range, x, what is the best way to iterate through another range, y and output all values that are shared by both ra... | If the step is always +1 (which is the default for range) the following should be more efficient than converting each list to a set or iterating over either list:
```
range(max(x[0], y[0]), min(x[-1], y[-1])+1)
``` |
Speed differences between intersection() and 'object for object in set if object in other_set' | 6,821,329 | 3 | 2011-07-25T19:36:04Z | 6,821,465 | 8 | 2011-07-25T19:47:06Z | [
"python",
"performance",
"data-structures",
"set",
"intersection"
] | Which one of these is faster? Is one "better"? Basically I'll have two sets and I want to eventually get *one* match from between the two lists. So really I suppose the for loop is more like:
```
for object in set:
if object in other_set:
return object
```
Like I said - I only need one match, but I'm not ... | ```
from timeit import timeit
setup = """
from random import sample, shuffle
a = range(100000)
b = sample(a, 1000)
a.reverse()
"""
forin = setup + """
def forin():
# a = set(a)
for obj in b:
if obj in a:
return obj
"""
setin = setup + """
def setin():
return tuple(set(a) & set(b))[0]
... |
Python code performance decreases with threading | 6,821,477 | 20 | 2011-07-25T19:47:49Z | 6,821,513 | 8 | 2011-07-25T19:51:00Z | [
"python",
"multithreading",
"performance",
"io"
] | I've written a working program in Python that basically parses a batch of binary files, extracting data into a data structure. Each file takes around a second to parse, which translates to hours for thousands of files. I've successfully implemented a threaded version of the batch parsing method with an adjustable numbe... | The threading library does not actually utilize multiple cores simultaneously for computation. You should use the [multiprocessing](http://docs.python.org/py3k/library/multiprocessing.html) library instead for computational threading. |
Python code performance decreases with threading | 6,821,477 | 20 | 2011-07-25T19:47:49Z | 6,821,529 | 29 | 2011-07-25T19:52:04Z | [
"python",
"multithreading",
"performance",
"io"
] | I've written a working program in Python that basically parses a batch of binary files, extracting data into a data structure. Each file takes around a second to parse, which translates to hours for thousands of files. I've successfully implemented a threaded version of the batch parsing method with an adjustable numbe... | This is sadly how things are in CPython, mainly due to the Global Interpreter Lock (GIL). Python code that's CPU-bound simply doesn't scale across threads (I/O-bound code, on the other hand, might scale to some extent).
There is a highly informative [presentation](http://www.dabeaz.com/python/UnderstandingGIL.pdf) by ... |
Read image XMP data in Python | 6,822,693 | 8 | 2011-07-25T21:39:54Z | 8,120,117 | 7 | 2011-11-14T10:20:21Z | [
"python",
"image",
"python-imaging-library",
"xmp"
] | Can I use PIL, like in [this example](http://stackoverflow.com/questions/4764932/in-python-how-do-i-read-the-exif-data-for-an-image/4765242#4765242)?
I only need to **read** the data, and I'm looking for the easiest simplest way to do it *(I can't install **pyexiv**)*.
**edit:** I don't want to believe that the only ... | Well, I was looking for something similar, then I came across the [PHP equivalent](http://stackoverflow.com/questions/1578169/how-can-i-read-xmp-data-from-a-jpg-with-php) question and I translated the anwer to Python:
```
f = 'example.jpg'
fd = open(f)
d= fd.read()
xmp_start = d.find('<x:xmpmeta')
xmp_end = d.find('</... |
Rolling or sliding window iterator in Python | 6,822,725 | 65 | 2011-07-25T21:41:58Z | 6,822,761 | 26 | 2011-07-25T21:46:19Z | [
"python",
"algorithm"
] | I need a rolling window (aka sliding window) iterable over a sequence/iterator/generator. Default Python iteration can be considered a special case, where the window length is 1. I'm currently using the following code. Does anyone have a more Pythonic, less verbose, or more efficient method for doing this?
```
def rol... | This seems tailor-made for a `collections.deque` since you essentially have a FIFO (add to one end, remove from the other). However, even if you use a `list` you shouldn't be slicing twice; instead, you should probably just `pop(0)` from the list and `append()` the new item.
Here is an optimized deque-based implementa... |
Rolling or sliding window iterator in Python | 6,822,725 | 65 | 2011-07-25T21:41:58Z | 6,822,773 | 62 | 2011-07-25T21:47:10Z | [
"python",
"algorithm"
] | I need a rolling window (aka sliding window) iterable over a sequence/iterator/generator. Default Python iteration can be considered a special case, where the window length is 1. I'm currently using the following code. Does anyone have a more Pythonic, less verbose, or more efficient method for doing this?
```
def rol... | There's one in an old version of the Python docs with [`itertools` examples](http://docs.python.org/release/2.3.5/lib/itertools-example.html):
```
from itertools import islice
def window(seq, n=2):
"Returns a sliding window (of width n) over data from the iterable"
" s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ... |
Rolling or sliding window iterator in Python | 6,822,725 | 65 | 2011-07-25T21:41:58Z | 6,822,907 | 21 | 2011-07-25T22:02:57Z | [
"python",
"algorithm"
] | I need a rolling window (aka sliding window) iterable over a sequence/iterator/generator. Default Python iteration can be considered a special case, where the window length is 1. I'm currently using the following code. Does anyone have a more Pythonic, less verbose, or more efficient method for doing this?
```
def rol... | I like `tee()`:
```
from itertools import tee, izip
def window(iterable, size):
iters = tee(iterable, size)
for i in xrange(1, size):
for each in iters[i:]:
next(each, None)
return izip(*iters)
for each in window(xrange(6), 3):
print list(each)
```
gives:
```
[0, 1, 2]
[1, 2, 3]... |
Python on IIS: how? | 6,823,316 | 40 | 2011-07-25T22:47:55Z | 9,745,836 | 84 | 2012-03-16T23:36:33Z | [
"python",
"iis"
] | I've got a background in PHP, dotNet and am charmed by Python. I want to transpose functionality from PHP to Python step by step, running bits and pieces side-by-side. During this transition, which could take 2 years since the app is enormous, I am bound to IIS. I've got 15 years background of web-programming, includin... | I just did this in 5 minutes.
1. Insure you have IIS. run: `%windir%\system32\OptionalFeatures.exe`. Or, via pointy-clicky: Start...Control Panel...Programs and Features... (and then on the left hand side) Turn Windows Features on or Off. Make sure CGI is installed, under the IIS node.
![enter image description he... |
Mapping a NumPy array in place | 6,824,122 | 39 | 2011-07-26T00:52:35Z | 6,824,389 | 38 | 2011-07-26T01:48:13Z | [
"python",
"arrays",
"multidimensional-array",
"mapping",
"numpy"
] | **Is it possible to map a NumPy array in place? If yes, how?**
Given `a_values` - 2D array - this is the bit of code that does the trick for me at the moment:
```
for row in range(len(a_values)):
for col in range(len(a_values[0])):
a_values[row][col] = dim(a_values[row][col])
```
But it's so ugly that I ... | It's only worth trying to do this in-place if you are under significant space constraints. If that's the case, it is possible to speed up your code a little bit by iterating over a flattened view of the array. Since `reshape` returns a new view [when possible](http://docs.scipy.org/doc/numpy/reference/generated/numpy.r... |
Mapping a NumPy array in place | 6,824,122 | 39 | 2011-07-26T00:52:35Z | 6,833,886 | 38 | 2011-07-26T17:12:02Z | [
"python",
"arrays",
"multidimensional-array",
"mapping",
"numpy"
] | **Is it possible to map a NumPy array in place? If yes, how?**
Given `a_values` - 2D array - this is the bit of code that does the trick for me at the moment:
```
for row in range(len(a_values)):
for col in range(len(a_values[0])):
a_values[row][col] = dim(a_values[row][col])
```
But it's so ugly that I ... | > *This is a write-up of contributions scattered in answers and
> comments, that I wrote after accepting the answer to the question.
> Upvotes are always welcome, but if you upvote this answer, please
> don't miss to upvote also those of **senderle** and (if (s)he writes
> one) **eryksun**, who suggested the methods be... |
Get a random boolean in python? | 6,824,681 | 92 | 2011-07-26T02:46:02Z | 6,824,692 | 82 | 2011-07-26T02:48:37Z | [
"python",
"random"
] | I am looking for the best way (fast and elegant) to get a random boolean in python (flip a coin).
For the moment I am using `random.randint(0, 1)` or `random.getrandbits(1)`.
Are there better choices that I am not aware of? | ```
random.choice([True, False])
```
would also work. |
Get a random boolean in python? | 6,824,681 | 92 | 2011-07-26T02:46:02Z | 6,824,868 | 130 | 2011-07-26T03:18:45Z | [
"python",
"random"
] | I am looking for the best way (fast and elegant) to get a random boolean in python (flip a coin).
For the moment I am using `random.randint(0, 1)` or `random.getrandbits(1)`.
Are there better choices that I am not aware of? | Adam's answer is quite fast, but I found that `random.getrandbits(1)` to be quite a lot faster. If you really want a boolean instead of a long then
```
bool(random.getrandbits(1))
```
is still about twice as fast as `random.choice([True, False])`
If utmost speed isn't to priority then `random.choice` definitely read... |
Get a random boolean in python? | 6,824,681 | 92 | 2011-07-26T02:46:02Z | 22,201,905 | 14 | 2014-03-05T15:23:23Z | [
"python",
"random"
] | I am looking for the best way (fast and elegant) to get a random boolean in python (flip a coin).
For the moment I am using `random.randint(0, 1)` or `random.getrandbits(1)`.
Are there better choices that I am not aware of? | Found a faster method:
```
$ python -m timeit -s "from random import getrandbits" "not getrandbits(1)"
10000000 loops, best of 3: 0.222 usec per loop
$ python -m timeit -s "from random import random" "True if random() > 0.5 else False"
10000000 loops, best of 3: 0.0786 usec per loop
$ python -m timeit -s "from random ... |
Data Type Recognition/Guessing of CSV data in python | 6,824,862 | 8 | 2011-07-26T03:17:37Z | 18,036,886 | 7 | 2013-08-03T20:15:22Z | [
"python",
"algorithm",
"csv",
"schema",
"heuristics"
] | My problem is in the context of processing data from large CSV files.
I'm looking for the most efficient way to determine (that is, guess) the data type of a column based on the values found in that column. I'm potentially dealing with very messy data. Therefore, the algorithm should be error-tolerant to some extent.
... | You may be interested in this python library which does exactly this kind of type guessing on CSVs and XLS files for you:
* <https://github.com/okfn/messytables>
* <https://messytables.readthedocs.org/> - docs
It happily scales to very large files, to streaming data off the internet etc.
There is also an even simple... |
how to run python scripts using tcl exec command | 6,825,546 | 6 | 2011-07-26T05:14:26Z | 6,825,675 | 10 | 2011-07-26T05:31:21Z | [
"python",
"exec",
"tcl"
] | I have a tcl driver script which in turn calls several other programs.
I want to invoke a python script from my tcl script.
lets say this is my python script "1.py"
```
#!/usr/bin/python2.4
import os
import sys
try:
fi = open('sample_+_file', 'w')
except IOError:
print 'Can\'t open file for writing.'
sys.e... | Your tcl script defines a procedure to execute a python script, but does not call the procedure. Add a call to your tcl script:
```
#! /usr/bin/tclsh
proc call_python {} {
set output [exec python helloWorld.py]
puts $output
}
call_python
```
Also, anything written to stdout by the process launched via `exec`... |
check if a file is open in Python | 6,825,994 | 28 | 2011-07-26T06:10:32Z | 6,826,099 | 25 | 2011-07-26T06:23:37Z | [
"python",
"excel"
] | In my app I write to an excel file. After writing, the user is able to view the file by opening it.
But if the user forgets to close the file before any further writing, a warning message should appear. So I need a way to check this file is open before writing process. Could you supply me with some python code to do th... | I assume that you're writing to the file, then close it (so the user can open it in Excel), and then, before re-opening it for append/write operations, you want to check that the file isn't still open in Excel?
This is how you should do that:
```
try:
myfile = open("myfile.csv", "r+") # or "a+", whatever you need... |
check if a file is open in Python | 6,825,994 | 28 | 2011-07-26T06:10:32Z | 18,924,955 | 12 | 2013-09-20T20:04:22Z | [
"python",
"excel"
] | In my app I write to an excel file. After writing, the user is able to view the file by opening it.
But if the user forgets to close the file before any further writing, a warning message should appear. So I need a way to check this file is open before writing process. Could you supply me with some python code to do th... | The easiest and fastest way is to use the file object attribute "closed"
```
f = open('file.py')
if f.closed:
print 'file is closed'
```
source: <http://docs.python.org/2.4/lib/bltin-file-objects.html> |
How to convert this particular json string into a python dictionary? | 6,826,495 | 4 | 2011-07-26T07:09:57Z | 6,826,511 | 15 | 2011-07-26T07:12:14Z | [
"python",
"json"
] | How do I convert this string ->
```
string = [{"name":"sam"}]
```
into a python dictionary like so ->
```
data = {
"name" : "sam"
}
``` | ```
In [1]: import json
In [2]: json.loads('[{"name":"sam"}]')
Out[2]: [{u'name': u'sam'}]
```
This returns a list, the first element of which is the desired dictionary. |
reverse() does not work on a Python literal? | 6,827,413 | 18 | 2011-07-26T08:44:28Z | 6,827,449 | 52 | 2011-07-26T08:47:34Z | [
"python"
] | Why doesn't this work in Python?
```
>>> print [0,1,0,1,1,0,1,1,1,0,1,1,1,1,0].reverse()
None
```
I expected to get back the list in reverse order. | ```
>>> a = [3, 4, 5]
>>> print a.reverse()
None
>>> a
[5, 4, 3]
>>>
```
It's because `reverse()` does not return the list, rather it reverses the list in place. So the return value of `a.reverse()` is `None` which is shown in the `print`. |
reverse() does not work on a Python literal? | 6,827,413 | 18 | 2011-07-26T08:44:28Z | 6,827,467 | 23 | 2011-07-26T08:49:02Z | [
"python"
] | Why doesn't this work in Python?
```
>>> print [0,1,0,1,1,0,1,1,1,0,1,1,1,1,0].reverse()
None
```
I expected to get back the list in reverse order. | If you want it to return a new list in reverse order, you can use `[::-1]`
```
>>> [0,1,0,1,1,0,1,1,1,0,1,1,1,1,0][::-1]
[0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0]
```
---
As I'm still trying to understand the downvote, if it doesn't matter that the original list gets changed, use [@taskinoor's answer](http://sta... |
reverse() does not work on a Python literal? | 6,827,413 | 18 | 2011-07-26T08:44:28Z | 6,827,512 | 22 | 2011-07-26T08:53:07Z | [
"python"
] | Why doesn't this work in Python?
```
>>> print [0,1,0,1,1,0,1,1,1,0,1,1,1,1,0].reverse()
None
```
I expected to get back the list in reverse order. | If you want reversed copy of a list, use [`reversed`](http://docs.python.org/library/functions.html#reversed):
```
>>> list(reversed([1,2,3,4]))
[4, 3, 2, 1]
```
p.s. `reversed` returns an iterator instead of copy of a list (as `[][::1]` does). So it is suitable then you need to iterate through a reversed iterable. A... |
Should a validate method throw an exception? | 6,828,160 | 6 | 2011-07-26T09:46:05Z | 6,828,204 | 8 | 2011-07-26T09:49:10Z | [
"python",
"validation",
"exception",
"error-handling"
] | I've implemented a little validation library which is used like this:
```
domain_object.validate()
# handle validation errors in some way ...
if domain_object.errors:
for error in domain_object.errors:
print(error)
```
`validate()` performs the checks and populates a list called `errors`.
I know from ot... | No, I wouldn't think that a validation method should throw an exception.
That would create a bit of an anti-pattern, as the client code calling the method would reasonably *expect* an exception to be thrown, and would then need to catch the exception. Since it's generally recommended that exceptions not be used for fl... |
Python set to list | 6,828,722 | 65 | 2011-07-26T10:35:07Z | 6,828,769 | 133 | 2011-07-26T10:38:41Z | [
"python",
"list",
"set"
] | How can I convert a set to a list in Python? Using
```
a = set(["Blah", "Hello"])
a = list(a)
```
doesn't work. It gives me:
```
TypeError: 'set' object is not callable
``` | Your code *does* work (tested with cpython 2.4, 2.5, 2.6, 2.7, 3.1 and 3.2):
```
>>> a = set(["Blah", "Hello"])
>>> a = list(a) # You probably wrote a = list(a()) here or list = set() above
>>> a
['Blah', 'Hello']
```
Check that you didn't overwrite `list` by accident:
```
>>> assert list == __builtins__.list
``` |
Python set to list | 6,828,722 | 65 | 2011-07-26T10:35:07Z | 6,829,300 | 54 | 2011-07-26T11:27:09Z | [
"python",
"list",
"set"
] | How can I convert a set to a list in Python? Using
```
a = set(["Blah", "Hello"])
a = list(a)
```
doesn't work. It gives me:
```
TypeError: 'set' object is not callable
``` | You've shadowed the builtin set by accidentally using it as a variable name, here is a simple way to replicate your error
```
>>> set=set()
>>> set=set()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'set' object is not callable
```
The first line rebinds set to an *instance* of ... |
the proper method for making a DB connection available across many python modules | 6,829,675 | 3 | 2011-07-26T11:59:41Z | 6,830,296 | 13 | 2011-07-26T12:52:05Z | [
"python",
"mysql"
] | I want to make a single database object available across many python modules.
For a *related* example, I create globl.py:
```
DOCS_ROOT="c:\docs" ## as an example
SOLR_BASE="http://localhost:8636/solr/"
```
Any other module which needs it can do a
```
from globl import DOCS_ROOT
```
Now this example aside, I want ... | Even if the import doesn't run the code multiple times, this is definitely not the correct way.
You should instead hide the process of obtaining a connection or cursor behind a function. You can then implement this function using either a [Singleton](http://en.wikipedia.org/wiki/Singleton_pattern) or [Object Pool](htt... |
Project Euler #25: Keep getting Overflow error (result to large) - is it to do with calculating fibonacci number? | 6,830,005 | 2 | 2011-07-26T12:28:35Z | 6,830,068 | 8 | 2011-07-26T12:34:13Z | [
"python",
"overflow",
"fibonacci"
] | I'm working on solving the Project Euler problem 25:
> What is the first term in the Fibonacci sequence to contain 1000
> digits?
My piece of code works for smaller digits, but when I try a 1000 digits, i get the error:
`OverflowError: (34, 'Result too large')`
I'm thinking it may be on how I compute the fibonacci ... | The problem here is that only integers in Python have unlimited length, floating point values are still calculated using normal IEEE types which has a maximum precision.
As such, since you're using an approximation, using floating point calculations, you will get that problem eventually.
Instead, try calculating the ... |
Optimizing Python for loop | 6,831,539 | 4 | 2011-07-26T14:23:31Z | 6,831,691 | 9 | 2011-07-26T14:33:10Z | [
"python",
"optimization"
] | I have a loop that is my biggest time suck for a particular function and I'd like to speed it up. Current, this single loop takes up about 400ms, while the execution for the rest of the function takes about 610ms.
The code is:
```
for ctr in xrange(N):
list1[ctr] = in1[ctr] - in1[0] - ctr * c1
list2[ctr] = in... | Assuming that `list1`, `list2`, etc, all are numerical, consider using numpy arrays instead of lists. For large sequences of integers or floats you'll see a huge speedup.
If you go that route, your loop above could be written like this:
```
ctr = np.arange(N)
list1 = n1 - n1[0] - ctr * c1
list2 = n2 - n2[0] - ctr * c... |
Python and closed variables | 6,831,950 | 4 | 2011-07-26T14:50:18Z | 6,832,000 | 15 | 2011-07-26T14:52:59Z | [
"python",
"closures",
"python-2.x"
] | Have a look at this code:
```
def closure():
value = False
def method_1():
value = True
def method_2():
print 'value is:', value
method_1()
method_2()
closure()
```
I would expect it to print 'Value is: True' but it doesn't. Why is this and what is the solution? | This happens because `method_1` gets its own local scope where it can declare variables. Python sees `value = True` and thinks you're creating a new variable named `value`, local to `method_1`.
The reason Python does this is to avoid polluting the outer scope's locals with variables from an inner function. (You wouldn... |
Python multiprocessing: How do I share a dict among multiple processes? | 6,832,554 | 42 | 2011-07-26T15:29:41Z | 6,832,689 | 13 | 2011-07-26T15:38:29Z | [
"python",
"multiprocessing"
] | A program that creates several processes that work on a join-able queue, `Q`, and may eventually manipulate a global dictionary `D` to store results. (so each child process may use `D` to store its result and also see what results the other child processes are producing)
If I print the dictionary D in a child process,... | multiprocessing is not like threading. Each child process will get a copy of the main process's memory. Generally state is shared via communication (pipes/sockets), signals, or shared memory.
Multiprocessing makes some abstractions available for your use case - shared state that's treated as local by use of proxies or... |
Python multiprocessing: How do I share a dict among multiple processes? | 6,832,554 | 42 | 2011-07-26T15:29:41Z | 6,832,693 | 59 | 2011-07-26T15:38:50Z | [
"python",
"multiprocessing"
] | A program that creates several processes that work on a join-able queue, `Q`, and may eventually manipulate a global dictionary `D` to store results. (so each child process may use `D` to store its result and also see what results the other child processes are producing)
If I print the dictionary D in a child process,... | A general answer involves using a [`Manager`](http://docs.python.org/library/multiprocessing.html#sharing-state-between-processes) object. Adapted from the docs:
```
from multiprocessing import Process, Manager
def f(d):
d[1] += '1'
d['2'] += 2
if __name__ == '__main__':
manager = Manager()
d = mana... |
Confusing change of scope - what's going on? | 6,832,836 | 3 | 2011-07-26T15:49:02Z | 6,832,931 | 8 | 2011-07-26T15:55:43Z | [
"python"
] | ```
def Test(value):
def innerFunc():
print value
innerFunc()
def TestWithAssignment(value):
def innerFunc():
print value
value = "Changed value"
innerFunc()
Test("Hello 1")
# Prints "Hello 1"
TestWithAssignment("Hello 2")
# Throws UnboundLocalError: local variable 'value' ref... | The issue is that Python wants you to be explicit and you want to be implicit. The [execution model](http://docs.python.org/reference/executionmodel.html) that Python uses binds names to the nearest available **enclosing** scope.
```
def Test(value):
# Local Scope #1
def innerFunc():
# Local Scope #2
... |
Checkbox input using python mechanize | 6,833,868 | 7 | 2011-07-26T17:10:01Z | 6,833,991 | 11 | 2011-07-26T17:22:27Z | [
"python",
"checkbox",
"mechanize"
] | I want to fill a form using python mechanize. form looks like:
```
<POST https://10.20.254.39/cloud_computing/vmuser/migrate_vm/cli multipart/form-data
<TextControl(vm=cli)>
<TextControl(chost=10.20.14.39)>
<SelectControl(dhost=[*, 28, 27])>
<CheckboxControl(live=[on])>
<CheckboxControl(undefinesource=[on])>... | One way that I have done it is
```
br.find_control("live").items[0].selected=True
``` |
for loops in python | 6,834,368 | 8 | 2011-07-26T17:57:25Z | 6,834,473 | 9 | 2011-07-26T18:07:06Z | [
"python"
] | Is there a pythonic way (I know I can loop using range(len(..)) and get an index) to do the following example:
```
for line in list_of_strings:
if line[0] == '$':
while line[-1] == '#':
# read in the Next line and do stuff
# after quitting out of the while loop, the next iteration of th... | One of the most basic challenges in python is getting clever when iterating over `list`s and `dict`s. If you actually need to *modify* the collection while iterating, you may need to work on a copy, or store changes to apply at the end of iteration.
In your case, though, you just need to skip items in the list. You ca... |
How do you create line segments between two points? | 6,834,483 | 11 | 2011-07-26T18:08:07Z | 6,834,693 | 12 | 2011-07-26T18:26:02Z | [
"python",
"matplotlib"
] | I have this bit of code that plots out the points:
```
import matplotlib.pyplot as plot
from matplotlib import pyplot
all_data = [[1,10],[2,10],[3,10],[4,10],[5,10],[3,1],[3,2],[3,3],[3,4],[3,5]]
x = []
y = []
for i in xrange(len(all_data)):
x.append(all_data[i][0])
y.append(all_data[i][1])
plot.scatter(x,y)
... | ```
import matplotlib.pyplot as plt
import itertools
fig=plt.figure()
ax=fig.add_subplot(111)
all_data = [[1,10],[2,10],[3,10],[4,10],[5,10],[3,1],[3,2],[3,3],[3,4],[3,5]]
plt.plot(
*zip(*itertools.chain.from_iterable(itertools.combinations(all_data, 2))),
color = 'brown', marker = 'o')
plt.show()
```
![ent... |
How do you create line segments between two points? | 6,834,483 | 11 | 2011-07-26T18:08:07Z | 6,834,750 | 12 | 2011-07-26T18:31:36Z | [
"python",
"matplotlib"
] | I have this bit of code that plots out the points:
```
import matplotlib.pyplot as plot
from matplotlib import pyplot
all_data = [[1,10],[2,10],[3,10],[4,10],[5,10],[3,1],[3,2],[3,3],[3,4],[3,5]]
x = []
y = []
for i in xrange(len(all_data)):
x.append(all_data[i][0])
y.append(all_data[i][1])
plot.scatter(x,y)
... | This can be optimized but it works:
```
for point in all_data:
for point2 in all_data:
pyplot.plot([point[0], point2[0]], [point[1], point2[1]])
```
 |
Python equivalent of unix cksum function | 6,835,381 | 15 | 2011-07-26T19:24:02Z | 6,835,786 | 8 | 2011-07-26T19:56:09Z | [
"python",
"unix",
"checksum",
"zlib",
"crc32"
] | I've been looking for the equivalent python method for the unix cksum command:
<http://pubs.opengroup.org/onlinepubs/7990989775/xcu/cksum.html>
```
$ cksum ./temp.bin
1605138151 712368 ./temp.bin
```
So far I have found the zlib.crc32() function
```
>>> import zlib
>>> f = open('./temp.bin','rb')
>>> data = f.read(... | Found a snippet [here](http://pastebin.com/cKATyGLb) that implements a compatible cksum in python:
```
"""
This module implements the cksum command found in most UNIXes in pure
python.
The constants and routine are cribbed from the POSIX man page
"""
import sys
crctab = [ 0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326... |
Sorting a python array/recarray by column | 6,835,531 | 17 | 2011-07-26T19:38:11Z | 6,835,646 | 8 | 2011-07-26T19:46:35Z | [
"python",
"arrays",
"sorting",
"numpy",
"recarray"
] | I have a fairly simple question about how to sort an entire array/recarray by a given column. For example, given the array:
```
import numpy as np
data = np.array([[5,2], [4,1], [3,6]])
```
I would like to sort data by the first column to return:
```
array([[3,6], [4,1], [5,2]])
``` | you are looking for `operator.itemgetter`
```
>>> from operator import itemgetter, attrgetter
>>> sorted(student_tuples, key=itemgetter(2))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
>>> sorted(student_objects, key=attrgetter('age'))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
```
i.e.
... |
Sorting a python array/recarray by column | 6,835,531 | 17 | 2011-07-26T19:38:11Z | 6,835,668 | 26 | 2011-07-26T19:48:09Z | [
"python",
"arrays",
"sorting",
"numpy",
"recarray"
] | I have a fairly simple question about how to sort an entire array/recarray by a given column. For example, given the array:
```
import numpy as np
data = np.array([[5,2], [4,1], [3,6]])
```
I would like to sort data by the first column to return:
```
array([[3,6], [4,1], [5,2]])
``` | Use `data[np.argsort(data[:, 0])]` where the `0` is the column index on which to sort:
```
In [27]: import numpy as np
In [28]: data = np.array([[5,2], [4,1], [3,6]])
In [29]: col = 0
In [30]: data[np.argsort(data[:,col])]
Out[30]:
array([[3, 6],
[4, 1],
[5, 2]])
``` |
How to use namespace returned by parse_known_args? | 6,835,692 | 3 | 2011-07-26T19:49:35Z | 6,835,917 | 7 | 2011-07-26T20:05:29Z | [
"python",
"parsing",
"replace"
] | I am currently writing a Python script and trying to dynamically generate some arguments. However, an error is being thrown for the following script, stating "'Namespace' object is not iterable." Any ideas on how to fix?
```
import argparse
from os import path
import re
replacements = {}
pattern = '<<([^>]*)>>'
def ... | [`ArgumentParser.parse_known_args`](http://docs.python.org/library/argparse.html#partial-parsing) returns a *namespace* and a list of the remaining arguments. Namespaces aren't iterable, so when you try to assign one to the tuple `(infile, outfile)` you get the "not iterable" error.
Instead, you should write something... |
Help improve my file upload method (Pyramid framework) | 6,836,029 | 14 | 2011-07-26T20:16:20Z | 6,836,506 | 13 | 2011-07-26T20:56:42Z | [
"python",
"pylons",
"multipart",
"pyramid"
] | Currently, I am using the following method for uploading files (via HTML form) in Pyramid.
```
if request.params.get('form.submitted'):
upload_directory = os.getcwd() + '/myapp/static/uploads/'
my_file = request.POST.get('thumbnail')
saved_file = str(upload_directory) + str(my_file.filename)
perm_fi... | You'll want to use something like werkzug's [`safe_join`](https://github.com/mitsuhiko/werkzeug/blob/master/werkzeug/security.py#L128) rather than just adding the upload directory to the given file name. An attacker could create a POST with a filename of `../../../some/important/path` and cause this script to overwrite... |
Comparing a string to multiple items in Python | 6,838,238 | 7 | 2011-07-27T00:35:43Z | 6,838,247 | 10 | 2011-07-27T00:37:37Z | [
"python",
"string",
"string-comparison"
] | I'm trying to compare a string called `facility` to multiple possible strings to test if it is valid. The valid strings are:
```
auth, authpriv, daemon, cron, ftp, lpr, kern, mail, news, syslog, user, uucp, local0, ... , local7
```
Is there an efficient way of doing this other than:
```
if facility == "auth" or faci... | Unless your list of strings gets hideously long, something like this is probably best:
```
accepted_strings = ['auth', 'authpriv', 'daemon'] # etc etc
if facility in accepted_strings:
do_stuff()
``` |
Comparing a string to multiple items in Python | 6,838,238 | 7 | 2011-07-27T00:35:43Z | 6,838,304 | 19 | 2011-07-27T00:49:35Z | [
"python",
"string",
"string-comparison"
] | I'm trying to compare a string called `facility` to multiple possible strings to test if it is valid. The valid strings are:
```
auth, authpriv, daemon, cron, ftp, lpr, kern, mail, news, syslog, user, uucp, local0, ... , local7
```
Is there an efficient way of doing this other than:
```
if facility == "auth" or faci... | If, OTOH, your list of strings is indeed hideously long, use a set:
```
accepted_strings = {'auth', 'authpriv', 'daemon'}
if facility in accepted_strings:
do_stuff()
```
Testing for containment in a set is O(1) on average. |
Python - is there an elegant way to avoid dozens try/except blocks while getting data out of a json object? | 6,838,681 | 3 | 2011-07-27T01:59:59Z | 6,838,714 | 8 | 2011-07-27T02:06:22Z | [
"python",
"json"
] | I'm looking for ways to write functions like `get_profile(js)` but without all the ugly try/excepts.
Each assignment is in a try/except because occasionally the json field doesn't exist. I'd be happy with an elegant solution which defaulted everything to `None` even though I'm setting some defaults to `[]` and such, i... | 1. Use `get(key[, default])` method of [dictionaries](http://docs.python.org/library/stdtypes.html#dict.get)
2. Code generate this boilerplate code and save yourself even more trouble. |
Python - is there an elegant way to avoid dozens try/except blocks while getting data out of a json object? | 6,838,681 | 3 | 2011-07-27T01:59:59Z | 6,838,785 | 8 | 2011-07-27T02:19:59Z | [
"python",
"json"
] | I'm looking for ways to write functions like `get_profile(js)` but without all the ugly try/excepts.
Each assignment is in a try/except because occasionally the json field doesn't exist. I'd be happy with an elegant solution which defaulted everything to `None` even though I'm setting some defaults to `[]` and such, i... | Replace each of your try catch blocks with chained calls to the dictionary get(key [,default]) method. All calls to get before the last call in the chain should have a default value of {} (empty dictionary) so that the later calls can be called on a valid object, Only the last call in the chain should have the default ... |
How to use more than one condition in Python for loop? | 6,839,542 | 6 | 2011-07-27T04:48:21Z | 6,839,573 | 12 | 2011-07-27T04:53:24Z | [
"python"
] | How to use more than one condition in Python for loop?
```
for example in java:
int[] n={1,2,3,4,6,7};
for(int i=0;i<n.length && i<5 ;i++){
//do sth
}
```
How dose the python for loop do this? | The Python `for` loop does not, itself, have any support for this. You can get the same effect using a `break` statement:
```
for i in range(1, 8):
if i >= 5:
break
# do something
```
In Python, a `for` is really a `foreach` that iterates over some "iterator" or some "iterable object". In Python 2.x, ... |
How to use more than one condition in Python for loop? | 6,839,542 | 6 | 2011-07-27T04:48:21Z | 6,839,586 | 7 | 2011-07-27T04:55:52Z | [
"python"
] | How to use more than one condition in Python for loop?
```
for example in java:
int[] n={1,2,3,4,6,7};
for(int i=0;i<n.length && i<5 ;i++){
//do sth
}
```
How dose the python for loop do this? | The *direct* equivalent of your Java code is a `while` loop:
```
n = [1, 2, 3, 4, 6, 7]
i = 0
while i < len(n) and i < 5:
# do sth
i += 1
```
You could also do:
```
n = [1, 2, 3, 4, 6, 7]
for x in n[:5]:
# do sth
``` |
Python - Rewrite multiple lines in the Console | 6,840,420 | 11 | 2011-07-27T06:47:05Z | 6,840,469 | 21 | 2011-07-27T06:51:59Z | [
"python",
"printing",
"console",
"rewrite"
] | I know it is possible to consistently rewrite the last line displayed in the terminal with "\r", but I am having trouble figuring out if there is a way to go back and edit previous lines printed in the console.
What I would like to do is reprint multiple lines for a text-based RPG, however a friend was also wondering ... | On Unix, use the [curses](http://docs.python.org/howto/curses.html) module.
On Windows, there are several options:
* PDCurses: <http://www.lfd.uci.edu/~gohlke/pythonlibs/>
* The HOWTO linked above recommends the [Console](http://effbot.org/zone/console-index.htm) module
* <http://newcenturycomputers.net/projects/wcon... |
What is "\00" in Python? | 6,840,876 | 5 | 2011-07-27T07:30:57Z | 6,840,920 | 8 | 2011-07-27T07:35:08Z | [
"python",
"syntax",
null,
"escaping"
] | What does "\00" mean in Python? To learn more about this, I tried following:
* When I assign `d="\00"` and call `print d`, nothing displays on the screen.
* I also tried assigning `d` to a string with extra spacing between and at the end and then called `d.replace("\00", "")`, but no result was evident.
What does `d.... | The backslash followed by a number is used to represent the character with that octal value. So your `\00` represents [ASCII NUL](http://www.columbia.edu/kermit/ascii.html). |
What is "\00" in Python? | 6,840,876 | 5 | 2011-07-27T07:30:57Z | 6,840,947 | 16 | 2011-07-27T07:37:27Z | [
"python",
"syntax",
null,
"escaping"
] | What does "\00" mean in Python? To learn more about this, I tried following:
* When I assign `d="\00"` and call `print d`, nothing displays on the screen.
* I also tried assigning `d` to a string with extra spacing between and at the end and then called `d.replace("\00", "")`, but no result was evident.
What does `d.... | In Python 2, when a number starts with a leading zero, it means it's in octal (base 8). In Python 3 octal literals start with `0o` instead. `00` specifically is 0.
The leading `\` in `\00` is a way of specifying a byte value, a number between 0-255. It's normally used to represent a character that isn't on your keyboa... |
Python: accessing "module scope" vars | 6,841,853 | 12 | 2011-07-27T09:05:31Z | 6,842,138 | 15 | 2011-07-27T09:32:33Z | [
"python",
"variables",
"coding-style",
"module"
] | I'm currently learning Python, and I have to work on a Python 2.7 project.
Accessing "module scope" variables in functions of the module itself is a bit confusing for me, and I didn't succeed in finding a satisfying way.
My attempts so far:
**Way 1:**
my\_module.py
```
my_global_var = None
def my_func():
glob... | You probably want to read up on [Python's namespaces](http://docs.python.org/tutorial/classes.html#python-scopes-and-namespaces). Way 1 is correct but generally unnecessary, never use 2. An easier approach is to just use a dict (or class or some other object):
```
my_globals = {'var': None}
def my_func():
my_glob... |
Django: only blank page | 6,842,049 | 3 | 2011-07-27T09:24:33Z | 6,843,164 | 7 | 2011-07-27T10:55:01Z | [
"python",
"django",
"apache",
"response",
"wsgi"
] | I have a server with Apache and I would like to start website written in Django. I user mod\_wsgi. Now I have it prepared. But the respond of a server is empty. And in error log, there is nothing. Do you know what is the reason why?
If some file could help (\*.wsgi, settings.py) I will append it.
**Prochazky.wsgi**
... | Trying getting a hello world program working first and not Django. Watch:
<http://code.google.com/p/modwsgi/wiki/WhereToGetHelp?tm=6#Conference_Presentations>
and read:
<http://code.google.com/p/modwsgi/wiki/QuickConfigurationGuide>
At a guess though, are you perhaps loading mod\_python into the same Apache. An inc... |
How to find sqlalchemy remote side object's class or class name without db queries? | 6,843,144 | 5 | 2011-07-27T10:53:35Z | 6,850,178 | 13 | 2011-07-27T19:32:56Z | [
"python",
"class",
"sqlalchemy",
"relationship",
"relation"
] | Let's have a classes X and Y and relations between them x2y and y2x.
From class\_mapper(Class).iterate\_properties iterator we can get all class's properties.
So x2y and y2x are RelationshipProperty and what I hope to get from is a class or a class name of objects on remote side of relation.
I've already tried to make... | X.x2y.property.mapper.class\_
relatonshipproperty will eventually get class-level attribute documentation the same as mapper does now.
edit. Here is a test which illustrates the above returning "Y" from "X", and no reflection doesn't create relationships so should have no effect:
```
from sqlalchemy import Column, I... |
Using dictionaries in Mako templates | 6,843,428 | 6 | 2011-07-27T11:17:49Z | 6,843,489 | 7 | 2011-07-27T11:23:51Z | [
"python",
"mako"
] | Instead of passing variables to a template like so:
```
template.render(var1='hello', var2='world')
```
How can I pass a dictionary to the template and have it render in the same manner
```
vars = {'var1': 'hello', 'var2': 'world'}
```
so in the template I can display the variables as normal:
```
${var1} ${var2}
`... | I don't know mako, but to use a dict as [keyword arguments](http://docs.python.org/tutorial/controlflow.html#keyword-arguments) (or kwargs), you have to prepend two `*`:
```
template.render(**vars)
``` |
Are there any benefits from using a @staticmethod? | 6,843,549 | 7 | 2011-07-27T11:29:16Z | 6,843,638 | 22 | 2011-07-27T11:35:08Z | [
"python"
] | I was wondering if you use @staticmethod decorator in your code.
Personally I don't use it, since it takes more letters to write @staticmethod then self.
The only benefit (which comes to me) from using it may be a better clarity of a code, but since I usually write a method description for sphinx, I always state whet... | Whether to use `@staticmethod` or not depends on what you want to achieve. Ignoring the decorator because there is more to type is a rather silly reason (no offense!) and indicates that you have not understood the concept of a *static method* in Python!
Static methods are independent of the class and any class instanc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.