title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
sequence |
---|---|---|---|---|---|---|---|---|---|
What is the simplest way to find the difference between 2 times in python? | 51,010 | <p>I have 2 time values which have the type <code>datetime.time</code>. I want to find their difference. The obvious thing to do is t1 - t2, but this doesn't work. It works for objects of type <code>datetime.datetime</code> but not for <code>datetime.time</code>. So what is the best way to do this?</p>
| 9 | 2008-09-09T00:28:58Z | 263,451 | <p>Environment.TickCount seems to work well if you need something quick.</p>
<p>int start = Environment.TickCount</p>
<p>...DoSomething()</p>
<p>int elapsedtime = Environment.TickCount - start</p>
<p>Jon</p>
| -3 | 2008-11-04T21:05:21Z | [
"python",
"datetime",
"time"
] |
How to write a download progress indicator in Python? | 51,212 | <p>I am writing a little application to download files over http (as, for example, described <a href="http://stackoverflow.com/questions/22676/how-do-i-download-a-file-over-http-using-python#22776" rel="nofollow">here</a>).</p>
<p>I also want to include a little download progress indicator showing the percentage of the download progress.</p>
<p>Here is what I came up with:</p>
<pre>
sys.stdout.write(rem_file + "...")
urllib.urlretrieve(rem_file, loc_file, reporthook=dlProgress)
def dlProgress(count, blockSize, totalSize):
percent = int(count*blockSize*100/totalSize)
sys.stdout.write("%2d%%" % percent)
sys.stdout.write("\b\b\b")
sys.stdout.flush()
</pre>
<p>Output: MyFileName... 9%</p>
<p>Any other ideas or recommendations to do this? </p>
<p>One thing that's somewhat annoying is the blinking cursor in the terminal on the first digit of the percentage. Is there a way to prevent this? Is there a way to hide the cursor?</p>
<p><strong>EDIT:</strong></p>
<p>Here a better alternative using a global variable for the filename in dlProgress and the '\r' code:</p>
<pre>
global rem_file # global variable to be used in dlProgress
urllib.urlretrieve(rem_file, loc_file, reporthook=dlProgress)
def dlProgress(count, blockSize, totalSize):
percent = int(count*blockSize*100/totalSize)
sys.stdout.write("\r" + rem_file + "...%d%%" % percent)
sys.stdout.flush()
</pre>
<p>Output: MyFileName...9% </p>
<p>And the cursor shows up at the END of the line. Much better.</p>
| 41 | 2008-09-09T04:09:15Z | 51,214 | <p>If you use the <code>curses</code> package, you have much greater control of the console. It also comes at a higher cost in code complexity and is probably unnecessary unless you are developing a large console-based app.</p>
<p>For a simple solution, you can always put the spinning wheel at the end of the status messge (the sequence of characters <code>|, \, -, /</code> which actually looks nice under blinking cursor.</p>
| 4 | 2008-09-09T04:14:37Z | [
"python",
"http"
] |
How to write a download progress indicator in Python? | 51,212 | <p>I am writing a little application to download files over http (as, for example, described <a href="http://stackoverflow.com/questions/22676/how-do-i-download-a-file-over-http-using-python#22776" rel="nofollow">here</a>).</p>
<p>I also want to include a little download progress indicator showing the percentage of the download progress.</p>
<p>Here is what I came up with:</p>
<pre>
sys.stdout.write(rem_file + "...")
urllib.urlretrieve(rem_file, loc_file, reporthook=dlProgress)
def dlProgress(count, blockSize, totalSize):
percent = int(count*blockSize*100/totalSize)
sys.stdout.write("%2d%%" % percent)
sys.stdout.write("\b\b\b")
sys.stdout.flush()
</pre>
<p>Output: MyFileName... 9%</p>
<p>Any other ideas or recommendations to do this? </p>
<p>One thing that's somewhat annoying is the blinking cursor in the terminal on the first digit of the percentage. Is there a way to prevent this? Is there a way to hide the cursor?</p>
<p><strong>EDIT:</strong></p>
<p>Here a better alternative using a global variable for the filename in dlProgress and the '\r' code:</p>
<pre>
global rem_file # global variable to be used in dlProgress
urllib.urlretrieve(rem_file, loc_file, reporthook=dlProgress)
def dlProgress(count, blockSize, totalSize):
percent = int(count*blockSize*100/totalSize)
sys.stdout.write("\r" + rem_file + "...%d%%" % percent)
sys.stdout.flush()
</pre>
<p>Output: MyFileName...9% </p>
<p>And the cursor shows up at the END of the line. Much better.</p>
| 41 | 2008-09-09T04:09:15Z | 51,218 | <p>You might also try:</p>
<pre><code>sys.stdout.write("\r%2d%%" % percent)
sys.stdout.flush()
</code></pre>
<p>Using a single carriage return at the beginning of your string rather than several backspaces. Your cursor will still blink, but it'll blink after the percent sign rather than under the first digit, and with one control character instead of three you may get less flicker.</p>
| 13 | 2008-09-09T04:21:09Z | [
"python",
"http"
] |
How to write a download progress indicator in Python? | 51,212 | <p>I am writing a little application to download files over http (as, for example, described <a href="http://stackoverflow.com/questions/22676/how-do-i-download-a-file-over-http-using-python#22776" rel="nofollow">here</a>).</p>
<p>I also want to include a little download progress indicator showing the percentage of the download progress.</p>
<p>Here is what I came up with:</p>
<pre>
sys.stdout.write(rem_file + "...")
urllib.urlretrieve(rem_file, loc_file, reporthook=dlProgress)
def dlProgress(count, blockSize, totalSize):
percent = int(count*blockSize*100/totalSize)
sys.stdout.write("%2d%%" % percent)
sys.stdout.write("\b\b\b")
sys.stdout.flush()
</pre>
<p>Output: MyFileName... 9%</p>
<p>Any other ideas or recommendations to do this? </p>
<p>One thing that's somewhat annoying is the blinking cursor in the terminal on the first digit of the percentage. Is there a way to prevent this? Is there a way to hide the cursor?</p>
<p><strong>EDIT:</strong></p>
<p>Here a better alternative using a global variable for the filename in dlProgress and the '\r' code:</p>
<pre>
global rem_file # global variable to be used in dlProgress
urllib.urlretrieve(rem_file, loc_file, reporthook=dlProgress)
def dlProgress(count, blockSize, totalSize):
percent = int(count*blockSize*100/totalSize)
sys.stdout.write("\r" + rem_file + "...%d%%" % percent)
sys.stdout.flush()
</pre>
<p>Output: MyFileName...9% </p>
<p>And the cursor shows up at the END of the line. Much better.</p>
| 41 | 2008-09-09T04:09:15Z | 51,239 | <p>There's a text progress bar library for python at <a href="http://pypi.python.org/pypi/progressbar/2.2">http://pypi.python.org/pypi/progressbar/2.2</a> that you might find useful: </p>
<blockquote>
<p>This library provides a text mode progressbar. This is tipically used to display the progress of a long running operation, providing a visual clue that processing is underway.</p>
<p>The ProgressBar class manages the progress, and the format of the line is given by a number of widgets. A widget is an object that may display diferently depending on the state of the progress. There are three types of widget: - a string, which always shows itself; - a ProgressBarWidget, which may return a diferent value every time it's update method is called; and - a ProgressBarWidgetHFill, which is like ProgressBarWidget, except it expands to fill the remaining width of the line.</p>
<p>The progressbar module is very easy to use, yet very powerful. And automatically supports features like auto-resizing when available.</p>
</blockquote>
| 16 | 2008-09-09T04:48:28Z | [
"python",
"http"
] |
How to write a download progress indicator in Python? | 51,212 | <p>I am writing a little application to download files over http (as, for example, described <a href="http://stackoverflow.com/questions/22676/how-do-i-download-a-file-over-http-using-python#22776" rel="nofollow">here</a>).</p>
<p>I also want to include a little download progress indicator showing the percentage of the download progress.</p>
<p>Here is what I came up with:</p>
<pre>
sys.stdout.write(rem_file + "...")
urllib.urlretrieve(rem_file, loc_file, reporthook=dlProgress)
def dlProgress(count, blockSize, totalSize):
percent = int(count*blockSize*100/totalSize)
sys.stdout.write("%2d%%" % percent)
sys.stdout.write("\b\b\b")
sys.stdout.flush()
</pre>
<p>Output: MyFileName... 9%</p>
<p>Any other ideas or recommendations to do this? </p>
<p>One thing that's somewhat annoying is the blinking cursor in the terminal on the first digit of the percentage. Is there a way to prevent this? Is there a way to hide the cursor?</p>
<p><strong>EDIT:</strong></p>
<p>Here a better alternative using a global variable for the filename in dlProgress and the '\r' code:</p>
<pre>
global rem_file # global variable to be used in dlProgress
urllib.urlretrieve(rem_file, loc_file, reporthook=dlProgress)
def dlProgress(count, blockSize, totalSize):
percent = int(count*blockSize*100/totalSize)
sys.stdout.write("\r" + rem_file + "...%d%%" % percent)
sys.stdout.flush()
</pre>
<p>Output: MyFileName...9% </p>
<p>And the cursor shows up at the END of the line. Much better.</p>
| 41 | 2008-09-09T04:09:15Z | 704,865 | <p>For small files you may need to had this lines in order to avoid crazy percentages:</p>
<p>sys.stdout.write("\r%2d%%" % percent)</p>
<p>sys.stdout.flush()</p>
<p>Cheers</p>
| 0 | 2009-04-01T10:04:19Z | [
"python",
"http"
] |
How to write a download progress indicator in Python? | 51,212 | <p>I am writing a little application to download files over http (as, for example, described <a href="http://stackoverflow.com/questions/22676/how-do-i-download-a-file-over-http-using-python#22776" rel="nofollow">here</a>).</p>
<p>I also want to include a little download progress indicator showing the percentage of the download progress.</p>
<p>Here is what I came up with:</p>
<pre>
sys.stdout.write(rem_file + "...")
urllib.urlretrieve(rem_file, loc_file, reporthook=dlProgress)
def dlProgress(count, blockSize, totalSize):
percent = int(count*blockSize*100/totalSize)
sys.stdout.write("%2d%%" % percent)
sys.stdout.write("\b\b\b")
sys.stdout.flush()
</pre>
<p>Output: MyFileName... 9%</p>
<p>Any other ideas or recommendations to do this? </p>
<p>One thing that's somewhat annoying is the blinking cursor in the terminal on the first digit of the percentage. Is there a way to prevent this? Is there a way to hide the cursor?</p>
<p><strong>EDIT:</strong></p>
<p>Here a better alternative using a global variable for the filename in dlProgress and the '\r' code:</p>
<pre>
global rem_file # global variable to be used in dlProgress
urllib.urlretrieve(rem_file, loc_file, reporthook=dlProgress)
def dlProgress(count, blockSize, totalSize):
percent = int(count*blockSize*100/totalSize)
sys.stdout.write("\r" + rem_file + "...%d%%" % percent)
sys.stdout.flush()
</pre>
<p>Output: MyFileName...9% </p>
<p>And the cursor shows up at the END of the line. Much better.</p>
| 41 | 2008-09-09T04:09:15Z | 12,880,543 | <p>Thats how I did this could help you:
<a href="https://github.com/mouuff/MouDownloader/blob/master/api/download.py" rel="nofollow">https://github.com/mouuff/MouDownloader/blob/master/api/download.py</a></p>
| 0 | 2012-10-14T08:31:23Z | [
"python",
"http"
] |
How to write a download progress indicator in Python? | 51,212 | <p>I am writing a little application to download files over http (as, for example, described <a href="http://stackoverflow.com/questions/22676/how-do-i-download-a-file-over-http-using-python#22776" rel="nofollow">here</a>).</p>
<p>I also want to include a little download progress indicator showing the percentage of the download progress.</p>
<p>Here is what I came up with:</p>
<pre>
sys.stdout.write(rem_file + "...")
urllib.urlretrieve(rem_file, loc_file, reporthook=dlProgress)
def dlProgress(count, blockSize, totalSize):
percent = int(count*blockSize*100/totalSize)
sys.stdout.write("%2d%%" % percent)
sys.stdout.write("\b\b\b")
sys.stdout.flush()
</pre>
<p>Output: MyFileName... 9%</p>
<p>Any other ideas or recommendations to do this? </p>
<p>One thing that's somewhat annoying is the blinking cursor in the terminal on the first digit of the percentage. Is there a way to prevent this? Is there a way to hide the cursor?</p>
<p><strong>EDIT:</strong></p>
<p>Here a better alternative using a global variable for the filename in dlProgress and the '\r' code:</p>
<pre>
global rem_file # global variable to be used in dlProgress
urllib.urlretrieve(rem_file, loc_file, reporthook=dlProgress)
def dlProgress(count, blockSize, totalSize):
percent = int(count*blockSize*100/totalSize)
sys.stdout.write("\r" + rem_file + "...%d%%" % percent)
sys.stdout.flush()
</pre>
<p>Output: MyFileName...9% </p>
<p>And the cursor shows up at the END of the line. Much better.</p>
| 41 | 2008-09-09T04:09:15Z | 14,123,416 | <p>I used this code:</p>
<pre><code>url = (<file location>)
file_name = url.split('/')[-1]
u = urllib2.urlopen(url)
f = open(file_name, 'wb')
meta = u.info()
file_size = int(meta.getheaders("Content-Length")[0])
print "Downloading: %s Bytes: %s" % (file_name, file_size)
file_size_dl = 0
block_sz = 8192
while True:
buffer = u.read(block_sz)
if not buffer:
break
file_size_dl += len(buffer)
f.write(buffer)
status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
status = status + chr(8)*(len(status)+1)
print status,
f.close()
</code></pre>
| 1 | 2013-01-02T14:01:43Z | [
"python",
"http"
] |
How to write a download progress indicator in Python? | 51,212 | <p>I am writing a little application to download files over http (as, for example, described <a href="http://stackoverflow.com/questions/22676/how-do-i-download-a-file-over-http-using-python#22776" rel="nofollow">here</a>).</p>
<p>I also want to include a little download progress indicator showing the percentage of the download progress.</p>
<p>Here is what I came up with:</p>
<pre>
sys.stdout.write(rem_file + "...")
urllib.urlretrieve(rem_file, loc_file, reporthook=dlProgress)
def dlProgress(count, blockSize, totalSize):
percent = int(count*blockSize*100/totalSize)
sys.stdout.write("%2d%%" % percent)
sys.stdout.write("\b\b\b")
sys.stdout.flush()
</pre>
<p>Output: MyFileName... 9%</p>
<p>Any other ideas or recommendations to do this? </p>
<p>One thing that's somewhat annoying is the blinking cursor in the terminal on the first digit of the percentage. Is there a way to prevent this? Is there a way to hide the cursor?</p>
<p><strong>EDIT:</strong></p>
<p>Here a better alternative using a global variable for the filename in dlProgress and the '\r' code:</p>
<pre>
global rem_file # global variable to be used in dlProgress
urllib.urlretrieve(rem_file, loc_file, reporthook=dlProgress)
def dlProgress(count, blockSize, totalSize):
percent = int(count*blockSize*100/totalSize)
sys.stdout.write("\r" + rem_file + "...%d%%" % percent)
sys.stdout.flush()
</pre>
<p>Output: MyFileName...9% </p>
<p>And the cursor shows up at the END of the line. Much better.</p>
| 41 | 2008-09-09T04:09:15Z | 28,424,236 | <p>Late to the party, as usual. Here's an implementation that supports reporting progress, like the core <code>urlretrieve</code>:</p>
<pre><code>import urllib2
def urlretrieve(urllib2_request, filepath, reporthook=None, chunk_size=4096):
req = urllib2.urlopen(urllib2_request)
if reporthook:
# ensure progress method is callable
if hasattr(reporthook, '__call__'):
reporthook = None
try:
# get response length
total_size = req.info().getheaders('Content-Length')[0]
except KeyError:
reporthook = None
data = ''
num_blocks = 0
with open(filepath, 'w') as f:
while True:
data = req.read(chunk_size)
num_blocks += 1
if reporthook:
# report progress
reporthook(num_blocks, chunk_size, total_size)
if not data:
break
f.write(data)
# return downloaded length
return len(data)
</code></pre>
| 0 | 2015-02-10T04:38:33Z | [
"python",
"http"
] |
How to write a download progress indicator in Python? | 51,212 | <p>I am writing a little application to download files over http (as, for example, described <a href="http://stackoverflow.com/questions/22676/how-do-i-download-a-file-over-http-using-python#22776" rel="nofollow">here</a>).</p>
<p>I also want to include a little download progress indicator showing the percentage of the download progress.</p>
<p>Here is what I came up with:</p>
<pre>
sys.stdout.write(rem_file + "...")
urllib.urlretrieve(rem_file, loc_file, reporthook=dlProgress)
def dlProgress(count, blockSize, totalSize):
percent = int(count*blockSize*100/totalSize)
sys.stdout.write("%2d%%" % percent)
sys.stdout.write("\b\b\b")
sys.stdout.flush()
</pre>
<p>Output: MyFileName... 9%</p>
<p>Any other ideas or recommendations to do this? </p>
<p>One thing that's somewhat annoying is the blinking cursor in the terminal on the first digit of the percentage. Is there a way to prevent this? Is there a way to hide the cursor?</p>
<p><strong>EDIT:</strong></p>
<p>Here a better alternative using a global variable for the filename in dlProgress and the '\r' code:</p>
<pre>
global rem_file # global variable to be used in dlProgress
urllib.urlretrieve(rem_file, loc_file, reporthook=dlProgress)
def dlProgress(count, blockSize, totalSize):
percent = int(count*blockSize*100/totalSize)
sys.stdout.write("\r" + rem_file + "...%d%%" % percent)
sys.stdout.flush()
</pre>
<p>Output: MyFileName...9% </p>
<p>And the cursor shows up at the END of the line. Much better.</p>
| 41 | 2008-09-09T04:09:15Z | 36,022,923 | <p>For what it's worth, here's the code I used to get it working:</p>
<pre><code>from urllib import urlretrieve
from progressbar import ProgressBar, Percentage, Bar
url = "http://......."
fileName = "file"
pbar = ProgressBar(widgets=[Percentage(), Bar()])
urlretrieve(url, fileName, reporthook=dlProgress)
def dlProgress(count, blockSize, totalSize):
pbar.update( int(count * blockSize * 100 / totalSize) )
</code></pre>
| 2 | 2016-03-15T21:52:32Z | [
"python",
"http"
] |
How can I retrieve the page title of a webpage using Python? | 51,233 | <p>How can I retrieve the page title of a webpage (title html tag) using Python?</p>
| 44 | 2008-09-09T04:38:55Z | 51,240 | <p>I'll always use <a href="http://lxml.de/">lxml</a> for such tasks. You could use <a href="http://www.crummy.com/software/BeautifulSoup/">beautifulsoup</a> as well.</p>
<pre><code>import lxml.html
t = lxml.html.parse(url)
print t.find(".//title").text
</code></pre>
| 44 | 2008-09-09T04:49:38Z | [
"python",
"html"
] |
How can I retrieve the page title of a webpage using Python? | 51,233 | <p>How can I retrieve the page title of a webpage (title html tag) using Python?</p>
| 44 | 2008-09-09T04:38:55Z | 51,242 | <p>This is probably overkill for such a simple task, but if you plan to do more than that, then it's saner to start from these tools (mechanize, BeautifulSoup) because they are much easier to use than the alternatives (urllib to get content and regexen or some other parser to parse html)</p>
<p>Links:
<a href="http://crummy.com/software/BeautifulSoup" rel="nofollow">BeautifulSoup</a>
<a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow">mechanize</a></p>
<pre><code>#!/usr/bin/env python
#coding:utf-8
from BeautifulSoup import BeautifulSoup
from mechanize import Browser
#This retrieves the webpage content
br = Browser()
res = br.open("https://www.google.com/")
data = res.get_data()
#This parses the content
soup = BeautifulSoup(data)
title = soup.find('title')
#This outputs the content :)
print title.renderContents()
</code></pre>
| 5 | 2008-09-09T04:51:09Z | [
"python",
"html"
] |
How can I retrieve the page title of a webpage using Python? | 51,233 | <p>How can I retrieve the page title of a webpage (title html tag) using Python?</p>
| 44 | 2008-09-09T04:38:55Z | 51,263 | <p>The mechanize Browser object has a title() method. So the code from <a href="http://stackoverflow.com/questions/51233/how-can-i-retrieve-the-page-title-of-a-webpage-using-python#51242" rel="nofollow">this post</a> can be rewritten as:</p>
<pre><code>from mechanize import Browser
br = Browser()
br.open("http://www.google.com/")
print br.title()
</code></pre>
| 10 | 2008-09-09T05:45:39Z | [
"python",
"html"
] |
How can I retrieve the page title of a webpage using Python? | 51,233 | <p>How can I retrieve the page title of a webpage (title html tag) using Python?</p>
| 44 | 2008-09-09T04:38:55Z | 51,550 | <p>Here's a simplified version of <a href="http://stackoverflow.com/a/51242/4279">@Vinko Vrsalovic's answer</a>:</p>
<pre><code>import urllib2
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(urllib2.urlopen("https://www.google.com"))
print soup.title.string
</code></pre>
<p>NOTE:</p>
<ul>
<li><p><em>soup.title</em> finds the first <em>title</em> element <strong>anywhere</strong> in the html document</p></li>
<li><p><em>title.string</em> assumes it has only <strong>one</strong> child node, and that child node is a <strong>string</strong></p></li>
</ul>
<p>For <a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/">beautifulsoup 4.x</a>, use different import:</p>
<pre><code>from bs4 import BeautifulSoup
</code></pre>
| 54 | 2008-09-09T10:32:54Z | [
"python",
"html"
] |
How can I retrieve the page title of a webpage using Python? | 51,233 | <p>How can I retrieve the page title of a webpage (title html tag) using Python?</p>
| 44 | 2008-09-09T04:38:55Z | 17,123,979 | <p><code>soup.title.string</code> actually returns a unicode string.
To convert that into normal string, you need to do
<code>string=string.encode('ascii','ignore')</code></p>
| 1 | 2013-06-15T13:05:59Z | [
"python",
"html"
] |
How can I retrieve the page title of a webpage using Python? | 51,233 | <p>How can I retrieve the page title of a webpage (title html tag) using Python?</p>
| 44 | 2008-09-09T04:38:55Z | 36,650,753 | <p>Using <a href="https://docs.python.org/3.4/library/html.parser.html" rel="nofollow">HTMLParser</a>:</p>
<pre><code>from urllib.request import urlopen
from html.parser import HTMLParser
class TitleParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.match = False
self.title = ''
def handle_starttag(self, tag, attributes):
self.match = True if tag == 'title' else False
def handle_data(self, data):
if self.match:
self.title = data
self.match = False
url = "http://example.com/"
html_string = str(urlopen(url).read())
parser = TitleParser()
parser.feed(html_string)
print(parser.title) # prints: Example Domain
</code></pre>
| 0 | 2016-04-15T15:07:10Z | [
"python",
"html"
] |
Passing on named variable arguments in python | 51,412 | <p>Say I have the following methods:</p>
<pre><code>def methodA(arg, **kwargs):
pass
def methodB(arg, *args, **kwargs):
pass
</code></pre>
<p>In methodA I wish to call methodB, passing on the kwargs. However, it seems that if I define <code>methodA</code> as follows, the second argument will be passed on as positional rather than named variable arguments.</p>
<pre><code>def methodA(arg, **kwargs):
methodB("argvalue", kwargs)
</code></pre>
<p>How do I make sure that the **kwargs in methodA gets passed as **kwargs to methodB?</p>
| 11 | 2008-09-09T08:46:51Z | 51,414 | <p>Some experimentation and I figured this one out:</p>
<p>def methodA(arg, **kwargs):
methodB("argvalue", **kwargs)</p>
<p>Seems obvious now...</p>
| 1 | 2008-09-09T08:49:02Z | [
"python",
"varargs"
] |
Passing on named variable arguments in python | 51,412 | <p>Say I have the following methods:</p>
<pre><code>def methodA(arg, **kwargs):
pass
def methodB(arg, *args, **kwargs):
pass
</code></pre>
<p>In methodA I wish to call methodB, passing on the kwargs. However, it seems that if I define <code>methodA</code> as follows, the second argument will be passed on as positional rather than named variable arguments.</p>
<pre><code>def methodA(arg, **kwargs):
methodB("argvalue", kwargs)
</code></pre>
<p>How do I make sure that the **kwargs in methodA gets passed as **kwargs to methodB?</p>
| 11 | 2008-09-09T08:46:51Z | 51,415 | <p>Put the asterisks before the kwargs variable. This makes Python pass the variable (which is assumed to be a dictionary) as keyword arguments.</p>
<pre><code>methodB("argvalue", **kwargs)
</code></pre>
| 32 | 2008-09-09T08:50:34Z | [
"python",
"varargs"
] |
Passing on named variable arguments in python | 51,412 | <p>Say I have the following methods:</p>
<pre><code>def methodA(arg, **kwargs):
pass
def methodB(arg, *args, **kwargs):
pass
</code></pre>
<p>In methodA I wish to call methodB, passing on the kwargs. However, it seems that if I define <code>methodA</code> as follows, the second argument will be passed on as positional rather than named variable arguments.</p>
<pre><code>def methodA(arg, **kwargs):
methodB("argvalue", kwargs)
</code></pre>
<p>How do I make sure that the **kwargs in methodA gets passed as **kwargs to methodB?</p>
| 11 | 2008-09-09T08:46:51Z | 63,943 | <p>As an aside: When using functions instead of methods, you could also use functools.partial:</p>
<pre><code>import functools
def foo(arg, **kwargs):
...
bar = functools.partial(foo, "argvalue")
</code></pre>
<p>The last line will define a function "bar" that, when called, will call foo with the first argument set to "argvalue" and all other functions just passed on:</p>
<pre><code>bar(5, myarg="value")
</code></pre>
<p>will call</p>
<pre><code>foo("argvalue", 5, myarg="value")
</code></pre>
<p>Unfortunately that will not work with methods.</p>
| 2 | 2008-09-15T15:28:30Z | [
"python",
"varargs"
] |
Improving Python readability? | 51,502 | <p>I've been really enjoying Python programming lately. I come from a background of a strong love for C-based coding, where everything is perhaps more complicated than it should be (but puts hair on your chest, at least). So switching from C to Python for more complex things that don't require tons of speed has been more of a boon than a bane in writing projects.</p>
<p>However, coming from this land of brackets and parentheses and structs as far as the naked eye can see, I come across a small problem: I find Python difficult to read.</p>
<p>For example, the following block of text is hard for me to decipher unless I stare at it (which I dislike doing):</p>
<pre><code>if foo:
bar = baz
while bar not biz:
bar = i_am_going_to_find_you_biz_i_swear_on_my_life()
did_i_not_warn_you_biz()
my_father_is_avenged()
</code></pre>
<p>The problem occurs at the end of that if block: all the tabbing and then suddenly returning to a jarring block feels almost disturbing. As a solution, I've started coding my Python like this:</p>
<pre><code>if foo:
bar = baz
while bar not biz:
bar = i_am_going_to_find_you_biz_i_swear_on_my_life()
#-- while --
#-- if --
did_i_not_warn_you_biz()
my_father_is_avenged()
</code></pre>
<p>And this, for some odd reason, makes me more able to read my own code. But I'm curious: has anyone else with my strange problem found easier ways to make their tabbed-out code more readable? I'd love to find out if there's a better way to do this before this becomes a huge habit for me.</p>
| 2 | 2008-09-09T10:05:36Z | 51,505 | <p>You could try increasing the indent size, but in general I would just say, relax, it will come with time. I don't think trying to make Python look like C is a very good idea.</p>
| 8 | 2008-09-09T10:08:28Z | [
"python",
"readability"
] |
Improving Python readability? | 51,502 | <p>I've been really enjoying Python programming lately. I come from a background of a strong love for C-based coding, where everything is perhaps more complicated than it should be (but puts hair on your chest, at least). So switching from C to Python for more complex things that don't require tons of speed has been more of a boon than a bane in writing projects.</p>
<p>However, coming from this land of brackets and parentheses and structs as far as the naked eye can see, I come across a small problem: I find Python difficult to read.</p>
<p>For example, the following block of text is hard for me to decipher unless I stare at it (which I dislike doing):</p>
<pre><code>if foo:
bar = baz
while bar not biz:
bar = i_am_going_to_find_you_biz_i_swear_on_my_life()
did_i_not_warn_you_biz()
my_father_is_avenged()
</code></pre>
<p>The problem occurs at the end of that if block: all the tabbing and then suddenly returning to a jarring block feels almost disturbing. As a solution, I've started coding my Python like this:</p>
<pre><code>if foo:
bar = baz
while bar not biz:
bar = i_am_going_to_find_you_biz_i_swear_on_my_life()
#-- while --
#-- if --
did_i_not_warn_you_biz()
my_father_is_avenged()
</code></pre>
<p>And this, for some odd reason, makes me more able to read my own code. But I'm curious: has anyone else with my strange problem found easier ways to make their tabbed-out code more readable? I'd love to find out if there's a better way to do this before this becomes a huge habit for me.</p>
| 2 | 2008-09-09T10:05:36Z | 51,531 | <p>Perhaps the best thing would be to turn on "show whitespace" in your editor. Then you would have a visual indication of how far in each line is tabbed (usually a bunch of dots), and it will be more apparent when that changes.</p>
| 3 | 2008-09-09T10:24:46Z | [
"python",
"readability"
] |
Improving Python readability? | 51,502 | <p>I've been really enjoying Python programming lately. I come from a background of a strong love for C-based coding, where everything is perhaps more complicated than it should be (but puts hair on your chest, at least). So switching from C to Python for more complex things that don't require tons of speed has been more of a boon than a bane in writing projects.</p>
<p>However, coming from this land of brackets and parentheses and structs as far as the naked eye can see, I come across a small problem: I find Python difficult to read.</p>
<p>For example, the following block of text is hard for me to decipher unless I stare at it (which I dislike doing):</p>
<pre><code>if foo:
bar = baz
while bar not biz:
bar = i_am_going_to_find_you_biz_i_swear_on_my_life()
did_i_not_warn_you_biz()
my_father_is_avenged()
</code></pre>
<p>The problem occurs at the end of that if block: all the tabbing and then suddenly returning to a jarring block feels almost disturbing. As a solution, I've started coding my Python like this:</p>
<pre><code>if foo:
bar = baz
while bar not biz:
bar = i_am_going_to_find_you_biz_i_swear_on_my_life()
#-- while --
#-- if --
did_i_not_warn_you_biz()
my_father_is_avenged()
</code></pre>
<p>And this, for some odd reason, makes me more able to read my own code. But I'm curious: has anyone else with my strange problem found easier ways to make their tabbed-out code more readable? I'd love to find out if there's a better way to do this before this becomes a huge habit for me.</p>
| 2 | 2008-09-09T10:05:36Z | 51,551 | <p>I like to put blank lines around blocks to make control flow more obvious. For example:</p>
<pre><code>if foo:
bar = baz
while bar not biz:
bar = i_am_going_to_find_you_biz_i_swear_on_my_life()
did_i_not_warn_you_biz()
my_father_is_avenged()
</code></pre>
| 15 | 2008-09-09T10:33:05Z | [
"python",
"readability"
] |
Improving Python readability? | 51,502 | <p>I've been really enjoying Python programming lately. I come from a background of a strong love for C-based coding, where everything is perhaps more complicated than it should be (but puts hair on your chest, at least). So switching from C to Python for more complex things that don't require tons of speed has been more of a boon than a bane in writing projects.</p>
<p>However, coming from this land of brackets and parentheses and structs as far as the naked eye can see, I come across a small problem: I find Python difficult to read.</p>
<p>For example, the following block of text is hard for me to decipher unless I stare at it (which I dislike doing):</p>
<pre><code>if foo:
bar = baz
while bar not biz:
bar = i_am_going_to_find_you_biz_i_swear_on_my_life()
did_i_not_warn_you_biz()
my_father_is_avenged()
</code></pre>
<p>The problem occurs at the end of that if block: all the tabbing and then suddenly returning to a jarring block feels almost disturbing. As a solution, I've started coding my Python like this:</p>
<pre><code>if foo:
bar = baz
while bar not biz:
bar = i_am_going_to_find_you_biz_i_swear_on_my_life()
#-- while --
#-- if --
did_i_not_warn_you_biz()
my_father_is_avenged()
</code></pre>
<p>And this, for some odd reason, makes me more able to read my own code. But I'm curious: has anyone else with my strange problem found easier ways to make their tabbed-out code more readable? I'd love to find out if there's a better way to do this before this becomes a huge habit for me.</p>
| 2 | 2008-09-09T10:05:36Z | 51,570 | <p>Rather than focusing on making your existing structures more readable, you should focus on making more logical structures. Make smaller blocks, try not to nest blocks excessively, make smaller functions, and try to think through your code flow more.</p>
<p>If you come to a point where you can't quickly determine the structure of your code, you should probably consider refactoring and adding some comments. Code flow should always be immediately apparent -- the more you have to think about it, the less maintainable your code becomes.</p>
| 7 | 2008-09-09T10:43:27Z | [
"python",
"readability"
] |
Improving Python readability? | 51,502 | <p>I've been really enjoying Python programming lately. I come from a background of a strong love for C-based coding, where everything is perhaps more complicated than it should be (but puts hair on your chest, at least). So switching from C to Python for more complex things that don't require tons of speed has been more of a boon than a bane in writing projects.</p>
<p>However, coming from this land of brackets and parentheses and structs as far as the naked eye can see, I come across a small problem: I find Python difficult to read.</p>
<p>For example, the following block of text is hard for me to decipher unless I stare at it (which I dislike doing):</p>
<pre><code>if foo:
bar = baz
while bar not biz:
bar = i_am_going_to_find_you_biz_i_swear_on_my_life()
did_i_not_warn_you_biz()
my_father_is_avenged()
</code></pre>
<p>The problem occurs at the end of that if block: all the tabbing and then suddenly returning to a jarring block feels almost disturbing. As a solution, I've started coding my Python like this:</p>
<pre><code>if foo:
bar = baz
while bar not biz:
bar = i_am_going_to_find_you_biz_i_swear_on_my_life()
#-- while --
#-- if --
did_i_not_warn_you_biz()
my_father_is_avenged()
</code></pre>
<p>And this, for some odd reason, makes me more able to read my own code. But I'm curious: has anyone else with my strange problem found easier ways to make their tabbed-out code more readable? I'd love to find out if there's a better way to do this before this becomes a huge habit for me.</p>
| 2 | 2008-09-09T10:05:36Z | 52,090 | <p>Part of learning a new programming language is learning to read code in that language. A crutch like this may make it easier to read your own code, but it's going to impede the process of learning how to read anyone else's Python code. I really think you'd be better off getting rid of the end of block comments and getting used to normal Python.</p>
| 23 | 2008-09-09T14:58:52Z | [
"python",
"readability"
] |
Improving Python readability? | 51,502 | <p>I've been really enjoying Python programming lately. I come from a background of a strong love for C-based coding, where everything is perhaps more complicated than it should be (but puts hair on your chest, at least). So switching from C to Python for more complex things that don't require tons of speed has been more of a boon than a bane in writing projects.</p>
<p>However, coming from this land of brackets and parentheses and structs as far as the naked eye can see, I come across a small problem: I find Python difficult to read.</p>
<p>For example, the following block of text is hard for me to decipher unless I stare at it (which I dislike doing):</p>
<pre><code>if foo:
bar = baz
while bar not biz:
bar = i_am_going_to_find_you_biz_i_swear_on_my_life()
did_i_not_warn_you_biz()
my_father_is_avenged()
</code></pre>
<p>The problem occurs at the end of that if block: all the tabbing and then suddenly returning to a jarring block feels almost disturbing. As a solution, I've started coding my Python like this:</p>
<pre><code>if foo:
bar = baz
while bar not biz:
bar = i_am_going_to_find_you_biz_i_swear_on_my_life()
#-- while --
#-- if --
did_i_not_warn_you_biz()
my_father_is_avenged()
</code></pre>
<p>And this, for some odd reason, makes me more able to read my own code. But I'm curious: has anyone else with my strange problem found easier ways to make their tabbed-out code more readable? I'd love to find out if there's a better way to do this before this becomes a huge habit for me.</p>
| 2 | 2008-09-09T10:05:36Z | 52,111 | <p>I would look in to understanding more details about Python syntax. Often times if a piece of code looks odd, there usually is a better way to write it. For example, in the above example:</p>
<pre><code>bar = foo if baz else None
while bar not biz:
bar = i_am_going_to_find_you_biz_i_swear_on_my_life()
did_i_not_warn_you_biz()
my_father_is_avenged()
</code></pre>
<p>While it is a small change, it might help the readability. Also, in all honesty, I've never used a while loop, so there is a good change you would end up with a nice concise list comprehension or for loop instead. ;)</p>
| -1 | 2008-09-09T15:09:04Z | [
"python",
"readability"
] |
Improving Python readability? | 51,502 | <p>I've been really enjoying Python programming lately. I come from a background of a strong love for C-based coding, where everything is perhaps more complicated than it should be (but puts hair on your chest, at least). So switching from C to Python for more complex things that don't require tons of speed has been more of a boon than a bane in writing projects.</p>
<p>However, coming from this land of brackets and parentheses and structs as far as the naked eye can see, I come across a small problem: I find Python difficult to read.</p>
<p>For example, the following block of text is hard for me to decipher unless I stare at it (which I dislike doing):</p>
<pre><code>if foo:
bar = baz
while bar not biz:
bar = i_am_going_to_find_you_biz_i_swear_on_my_life()
did_i_not_warn_you_biz()
my_father_is_avenged()
</code></pre>
<p>The problem occurs at the end of that if block: all the tabbing and then suddenly returning to a jarring block feels almost disturbing. As a solution, I've started coding my Python like this:</p>
<pre><code>if foo:
bar = baz
while bar not biz:
bar = i_am_going_to_find_you_biz_i_swear_on_my_life()
#-- while --
#-- if --
did_i_not_warn_you_biz()
my_father_is_avenged()
</code></pre>
<p>And this, for some odd reason, makes me more able to read my own code. But I'm curious: has anyone else with my strange problem found easier ways to make their tabbed-out code more readable? I'd love to find out if there's a better way to do this before this becomes a huge habit for me.</p>
| 2 | 2008-09-09T10:05:36Z | 3,054,853 | <pre><code>from __future__ import braces
</code></pre>
<p>Need I say more? :)</p>
<p>Seriously, <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP 8</a>, 'Blank lines', §4 is the official way to do it.</p>
| 0 | 2010-06-16T15:40:49Z | [
"python",
"readability"
] |
How to get an absolute file path in Python | 51,520 | <p>Given a path such as <code>"mydir/myfile.txt"</code>, how do I find the absolute filepath relative to the current working directory in Python? E.g. on Windows, I might end up with:</p>
<pre><code>"C:/example/cwd/mydir/myfile.txt"
</code></pre>
| 308 | 2008-09-09T10:19:32Z | 51,523 | <pre><code>>>> import os
>>> os.path.abspath("mydir/myfile.txt")
</code></pre>
| 424 | 2008-09-09T10:21:03Z | [
"python",
"path",
"relative-path",
"absolute-path"
] |
How to get an absolute file path in Python | 51,520 | <p>Given a path such as <code>"mydir/myfile.txt"</code>, how do I find the absolute filepath relative to the current working directory in Python? E.g. on Windows, I might end up with:</p>
<pre><code>"C:/example/cwd/mydir/myfile.txt"
</code></pre>
| 308 | 2008-09-09T10:19:32Z | 51,539 | <pre><code>>>> import os
>>> os.path.abspath('mydir/myfile.txt')
'C:\\example\\cwd\\mydir\\myfile.txt'
>>>
</code></pre>
| 32 | 2008-09-09T10:28:26Z | [
"python",
"path",
"relative-path",
"absolute-path"
] |
How to get an absolute file path in Python | 51,520 | <p>Given a path such as <code>"mydir/myfile.txt"</code>, how do I find the absolute filepath relative to the current working directory in Python? E.g. on Windows, I might end up with:</p>
<pre><code>"C:/example/cwd/mydir/myfile.txt"
</code></pre>
| 308 | 2008-09-09T10:19:32Z | 58,417 | <p>Better still, install the <a href="http://pypi.python.org/pypi/path.py/2.2"><code>path.py</code></a> module, it wraps all the <code>os.path</code> functions and other related functions into methods on an object that can be used wherever strings are used:</p>
<pre><code>>>> from path import path
>>> path('mydir/myfile.txt').abspath()
'C:\\example\\cwd\\mydir\\myfile.txt'
>>>
</code></pre>
| 13 | 2008-09-12T06:53:25Z | [
"python",
"path",
"relative-path",
"absolute-path"
] |
How to get an absolute file path in Python | 51,520 | <p>Given a path such as <code>"mydir/myfile.txt"</code>, how do I find the absolute filepath relative to the current working directory in Python? E.g. on Windows, I might end up with:</p>
<pre><code>"C:/example/cwd/mydir/myfile.txt"
</code></pre>
| 308 | 2008-09-09T10:19:32Z | 15,325,066 | <p>Today you can also use the <code>unipath</code> package which was based on <code>path.py</code>: <a href="http://sluggo.scrapping.cc/python/unipath/">http://sluggo.scrapping.cc/python/unipath/</a></p>
<pre><code>>>> from unipath import Path
>>> absolute_path = Path('mydir/myfile.txt').absolute()
Path('C:\\example\\cwd\\mydir\\myfile.txt')
>>> str(absolute_path)
C:\\example\\cwd\\mydir\\myfile.txt
>>>
</code></pre>
<p>I would recommend using this package as it offers <a href="http://sluggo.scrapping.cc/python/unipath/Unipath-current/README.html">a clean interface to common os.path utilities</a>.</p>
| 7 | 2013-03-10T17:11:57Z | [
"python",
"path",
"relative-path",
"absolute-path"
] |
How to get an absolute file path in Python | 51,520 | <p>Given a path such as <code>"mydir/myfile.txt"</code>, how do I find the absolute filepath relative to the current working directory in Python? E.g. on Windows, I might end up with:</p>
<pre><code>"C:/example/cwd/mydir/myfile.txt"
</code></pre>
| 308 | 2008-09-09T10:19:32Z | 26,539,947 | <p>You could use the new Python 3.4 library <code>pathlib</code>. (You can also get it for Python 2.6 or 2.7 using <code>pip install pathlib</code>.) The authors <a href="http://www.python.org/dev/peps/pep-0428/#abstract" rel="nofollow">wrote</a>: "The aim of this library is to provide a simple hierarchy of classes to handle filesystem paths and the common operations users do over them."</p>
<p>To get an absolute path in Windows:</p>
<pre><code>>>> from pathlib import Path
>>> p = Path("pythonw.exe").resolve()
>>> p
WindowsPath('C:/Python27/pythonw.exe')
>>> str(p)
'C:\\Python27\\pythonw.exe'
</code></pre>
<p>Or on UNIX:</p>
<pre><code>>>> from pathlib import Path
>>> p = Path("python3.4").resolve()
>>> p
PosixPath('/opt/python3/bin/python3.4')
>>> str(p)
'/opt/python3/bin/python3.4'
</code></pre>
<p>Docs are here: <a href="https://docs.python.org/3/library/pathlib.html" rel="nofollow">https://docs.python.org/3/library/pathlib.html</a></p>
| 29 | 2014-10-24T01:05:02Z | [
"python",
"path",
"relative-path",
"absolute-path"
] |
How to get an absolute file path in Python | 51,520 | <p>Given a path such as <code>"mydir/myfile.txt"</code>, how do I find the absolute filepath relative to the current working directory in Python? E.g. on Windows, I might end up with:</p>
<pre><code>"C:/example/cwd/mydir/myfile.txt"
</code></pre>
| 308 | 2008-09-09T10:19:32Z | 38,813,098 | <p>I prefer to use glob</p>
<p>here is how to list all file types in your current folder:</p>
<pre><code>import glob
for x in glob.glob():
print(x)
</code></pre>
<p>here is how to list all (for example) .txt files in your current folder:</p>
<pre><code>import glob
for x in glob.glob('*.txt'):
print(x)
</code></pre>
<p>here is how to list all file types in a chose directory:</p>
<pre><code>import glob
for x in glob.glob('C:/example/hi/hello/'):
print(x)
</code></pre>
<p>hope this helped you</p>
| 2 | 2016-08-07T10:14:40Z | [
"python",
"path",
"relative-path",
"absolute-path"
] |
Why are SQL aggregate functions so much slower than Python and Java (or Poor Man's OLAP) | 51,553 | <p>I need a real DBA's opinion. Postgres 8.3 takes 200 ms to execute this query on my Macbook Pro while Java and Python perform the same calculation in under 20 ms (350,000 rows):</p>
<pre><code>SELECT count(id), avg(a), avg(b), avg(c), avg(d) FROM tuples;
</code></pre>
<p>Is this normal behaviour when using a SQL database?</p>
<p>The schema (the table holds responses to a survey):</p>
<pre><code>CREATE TABLE tuples (id integer primary key, a integer, b integer, c integer, d integer);
\copy tuples from '350,000 responses.csv' delimiter as ','
</code></pre>
<p>I wrote some tests in Java and Python for context and they crush SQL (except for pure python):</p>
<pre><code>java 1.5 threads ~ 7 ms
java 1.5 ~ 10 ms
python 2.5 numpy ~ 18 ms
python 2.5 ~ 370 ms
</code></pre>
<p>Even sqlite3 is competitive with Postgres despite it assumping all columns are strings (for contrast: even using just switching to numeric columns instead of integers in Postgres results in 10x slowdown)</p>
<p>Tunings i've tried without success include (blindly following some web advice):</p>
<pre><code>increased the shared memory available to Postgres to 256MB
increased the working memory to 2MB
disabled connection and statement logging
used a stored procedure via CREATE FUNCTION ... LANGUAGE SQL
</code></pre>
<p>So my question is, is my experience here normal, and this is what I can expect when using a SQL database? I can understand that ACID must come with costs, but this is kind of crazy in my opinion. I'm not asking for realtime game speed, but since Java can process millions of doubles in under 20 ms, I feel a bit jealous. </p>
<p>Is there a better way to do simple OLAP on the cheap (both in terms of money and server complexity)? I've looked into Mondrian and Pig + Hadoop but not super excited about maintaining yet another server application and not sure if they would even help.</p>
<hr>
<p>No the Python code and Java code do all the work in house so to speak. I just generate 4 arrays with 350,000 random values each, then take the average. I don't include the generation in the timings, only the averaging step. The java threads timing uses 4 threads (one per array average), overkill but it's definitely the fastest.</p>
<p>The sqlite3 timing is driven by the Python program and is running from disk (not :memory:)</p>
<p>I realize Postgres is doing much more behind the scenes, but most of that work doesn't matter to me since this is read only data.</p>
<p>The Postgres query doesn't change timing on subsequent runs.</p>
<p>I've rerun the Python tests to include spooling it off the disk. The timing slows down considerably to nearly 4 secs. But I'm guessing that Python's file handling code is pretty much in C (though maybe not the csv lib?) so this indicates to me that Postgres isn't streaming from the disk either (or that you are correct and I should bow down before whoever wrote their storage layer!)</p>
| 11 | 2008-09-09T10:33:39Z | 51,668 | <p>I don't think that your results are all that surprising -- if anything it is that Postgres is so fast.</p>
<p>Does the Postgres query run faster a second time once it has had a chance to cache the data? To be a little fairer your test for Java and Python should cover the cost of acquiring the data in the first place (ideally loading it off disk).</p>
<p>If this performance level is a problem for your application in practice but you need a RDBMS for other reasons then you could look at <a href="http://www.danga.com/memcached/" rel="nofollow">memcached</a>. You would then have faster cached access to raw data and could do the calculations in code.</p>
| 0 | 2008-09-09T11:43:10Z | [
"python",
"sql",
"optimization",
"aggregate",
"olap"
] |
Why are SQL aggregate functions so much slower than Python and Java (or Poor Man's OLAP) | 51,553 | <p>I need a real DBA's opinion. Postgres 8.3 takes 200 ms to execute this query on my Macbook Pro while Java and Python perform the same calculation in under 20 ms (350,000 rows):</p>
<pre><code>SELECT count(id), avg(a), avg(b), avg(c), avg(d) FROM tuples;
</code></pre>
<p>Is this normal behaviour when using a SQL database?</p>
<p>The schema (the table holds responses to a survey):</p>
<pre><code>CREATE TABLE tuples (id integer primary key, a integer, b integer, c integer, d integer);
\copy tuples from '350,000 responses.csv' delimiter as ','
</code></pre>
<p>I wrote some tests in Java and Python for context and they crush SQL (except for pure python):</p>
<pre><code>java 1.5 threads ~ 7 ms
java 1.5 ~ 10 ms
python 2.5 numpy ~ 18 ms
python 2.5 ~ 370 ms
</code></pre>
<p>Even sqlite3 is competitive with Postgres despite it assumping all columns are strings (for contrast: even using just switching to numeric columns instead of integers in Postgres results in 10x slowdown)</p>
<p>Tunings i've tried without success include (blindly following some web advice):</p>
<pre><code>increased the shared memory available to Postgres to 256MB
increased the working memory to 2MB
disabled connection and statement logging
used a stored procedure via CREATE FUNCTION ... LANGUAGE SQL
</code></pre>
<p>So my question is, is my experience here normal, and this is what I can expect when using a SQL database? I can understand that ACID must come with costs, but this is kind of crazy in my opinion. I'm not asking for realtime game speed, but since Java can process millions of doubles in under 20 ms, I feel a bit jealous. </p>
<p>Is there a better way to do simple OLAP on the cheap (both in terms of money and server complexity)? I've looked into Mondrian and Pig + Hadoop but not super excited about maintaining yet another server application and not sure if they would even help.</p>
<hr>
<p>No the Python code and Java code do all the work in house so to speak. I just generate 4 arrays with 350,000 random values each, then take the average. I don't include the generation in the timings, only the averaging step. The java threads timing uses 4 threads (one per array average), overkill but it's definitely the fastest.</p>
<p>The sqlite3 timing is driven by the Python program and is running from disk (not :memory:)</p>
<p>I realize Postgres is doing much more behind the scenes, but most of that work doesn't matter to me since this is read only data.</p>
<p>The Postgres query doesn't change timing on subsequent runs.</p>
<p>I've rerun the Python tests to include spooling it off the disk. The timing slows down considerably to nearly 4 secs. But I'm guessing that Python's file handling code is pretty much in C (though maybe not the csv lib?) so this indicates to me that Postgres isn't streaming from the disk either (or that you are correct and I should bow down before whoever wrote their storage layer!)</p>
| 11 | 2008-09-09T10:33:39Z | 51,745 | <p>I would say your test scheme is not really useful. To fulfill the db query, the db server goes through several steps:</p>
<ol>
<li>parse the SQL</li>
<li>work up a query plan, i. e. decide on which indices to use (if any), optimize etc.</li>
<li>if an index is used, search it for the pointers to the actual data, then go to the appropriate location in the data or</li>
<li>if no index is used, scan <i>the whole table</i> to determine which rows are needed</li>
<li>load the data from disk into a temporary location (hopefully, but not necessarily, memory)</li>
<li>perform the count() and avg() calculations</li>
</ol>
<p>So, creating an array in Python and getting the average basically skips all these steps save the last one. As disk I/O is among the most expensive operations a program has to perform, this is a major flaw in the test (see also the answers to <a href="http://stackoverflow.com/questions/26021/how-is-data-compression-more-effective-than-indexing-for-search-performance">this question</a> I asked here before). Even if you read the data from disk in your other test, the process is completely different and it's hard to tell how relevant the results are.</p>
<p>To obtain more information about where Postgres spends its time, I would suggest the following tests:</p>
<ul>
<li>Compare the execution time of your query to a SELECT without the aggregating functions (i. e. cut step 5)</li>
<li>If you find that the aggregation leads to a significant slowdown, try if Python does it faster, obtaining the raw data through the plain SELECT from the comparison.</li>
</ul>
<p>To speed up your query, reduce disk access first. I doubt very much that it's the aggregation that takes the time.</p>
<p>There's several ways to do that:</p>
<ul>
<li>Cache data (in memory!) for subsequent access, either via the db engine's own capabilities or with tools like memcached</li>
<li>Reduce the size of your stored data</li>
<li>Optimize the use of indices. Sometimes this can mean to skip index use altogether (after all, it's disk access, too). For MySQL, I seem to remember that it's recommended to skip indices if you assume that the query fetches more than 10% of all the data in the table.</li>
<li>If your query makes good use of indices, I know that for MySQL databases it helps to put indices and data on separate physical disks. However, I don't know whether that's applicable for Postgres.</li>
<li>There also might be more sophisticated problems such as swapping rows to disk if for some reason the result set can't be completely processed in memory. But I would leave that kind of research until I run into serious performance problems that I can't find another way to fix, as it requires knowledge about a lot of little under-the-hood details in your process.</li>
</ul>
<p><b>Update:</b></p>
<p><i>I just realized that you seem to have no use for indices for the above query and most likely aren't using any, too, so my advice on indices probably wasn't helpful. Sorry. Still, I'd say that the aggregation is not the problem but disk access is. I'll leave the index stuff in, anyway, it might still have some use.</i></p>
| 13 | 2008-09-09T12:31:26Z | [
"python",
"sql",
"optimization",
"aggregate",
"olap"
] |
Why are SQL aggregate functions so much slower than Python and Java (or Poor Man's OLAP) | 51,553 | <p>I need a real DBA's opinion. Postgres 8.3 takes 200 ms to execute this query on my Macbook Pro while Java and Python perform the same calculation in under 20 ms (350,000 rows):</p>
<pre><code>SELECT count(id), avg(a), avg(b), avg(c), avg(d) FROM tuples;
</code></pre>
<p>Is this normal behaviour when using a SQL database?</p>
<p>The schema (the table holds responses to a survey):</p>
<pre><code>CREATE TABLE tuples (id integer primary key, a integer, b integer, c integer, d integer);
\copy tuples from '350,000 responses.csv' delimiter as ','
</code></pre>
<p>I wrote some tests in Java and Python for context and they crush SQL (except for pure python):</p>
<pre><code>java 1.5 threads ~ 7 ms
java 1.5 ~ 10 ms
python 2.5 numpy ~ 18 ms
python 2.5 ~ 370 ms
</code></pre>
<p>Even sqlite3 is competitive with Postgres despite it assumping all columns are strings (for contrast: even using just switching to numeric columns instead of integers in Postgres results in 10x slowdown)</p>
<p>Tunings i've tried without success include (blindly following some web advice):</p>
<pre><code>increased the shared memory available to Postgres to 256MB
increased the working memory to 2MB
disabled connection and statement logging
used a stored procedure via CREATE FUNCTION ... LANGUAGE SQL
</code></pre>
<p>So my question is, is my experience here normal, and this is what I can expect when using a SQL database? I can understand that ACID must come with costs, but this is kind of crazy in my opinion. I'm not asking for realtime game speed, but since Java can process millions of doubles in under 20 ms, I feel a bit jealous. </p>
<p>Is there a better way to do simple OLAP on the cheap (both in terms of money and server complexity)? I've looked into Mondrian and Pig + Hadoop but not super excited about maintaining yet another server application and not sure if they would even help.</p>
<hr>
<p>No the Python code and Java code do all the work in house so to speak. I just generate 4 arrays with 350,000 random values each, then take the average. I don't include the generation in the timings, only the averaging step. The java threads timing uses 4 threads (one per array average), overkill but it's definitely the fastest.</p>
<p>The sqlite3 timing is driven by the Python program and is running from disk (not :memory:)</p>
<p>I realize Postgres is doing much more behind the scenes, but most of that work doesn't matter to me since this is read only data.</p>
<p>The Postgres query doesn't change timing on subsequent runs.</p>
<p>I've rerun the Python tests to include spooling it off the disk. The timing slows down considerably to nearly 4 secs. But I'm guessing that Python's file handling code is pretty much in C (though maybe not the csv lib?) so this indicates to me that Postgres isn't streaming from the disk either (or that you are correct and I should bow down before whoever wrote their storage layer!)</p>
| 11 | 2008-09-09T10:33:39Z | 51,817 | <p>One other thing that an RDBMS generally does for you is to provide concurrency by protecting you from simultaneous access by another process. This is done by placing locks, and there's some overhead from that.</p>
<p>If you're dealing with entirely static data that never changes, and especially if you're in a basically "single user" scenario, then using a relational database doesn't necessarily gain you much benefit.</p>
| 0 | 2008-09-09T13:04:15Z | [
"python",
"sql",
"optimization",
"aggregate",
"olap"
] |
Why are SQL aggregate functions so much slower than Python and Java (or Poor Man's OLAP) | 51,553 | <p>I need a real DBA's opinion. Postgres 8.3 takes 200 ms to execute this query on my Macbook Pro while Java and Python perform the same calculation in under 20 ms (350,000 rows):</p>
<pre><code>SELECT count(id), avg(a), avg(b), avg(c), avg(d) FROM tuples;
</code></pre>
<p>Is this normal behaviour when using a SQL database?</p>
<p>The schema (the table holds responses to a survey):</p>
<pre><code>CREATE TABLE tuples (id integer primary key, a integer, b integer, c integer, d integer);
\copy tuples from '350,000 responses.csv' delimiter as ','
</code></pre>
<p>I wrote some tests in Java and Python for context and they crush SQL (except for pure python):</p>
<pre><code>java 1.5 threads ~ 7 ms
java 1.5 ~ 10 ms
python 2.5 numpy ~ 18 ms
python 2.5 ~ 370 ms
</code></pre>
<p>Even sqlite3 is competitive with Postgres despite it assumping all columns are strings (for contrast: even using just switching to numeric columns instead of integers in Postgres results in 10x slowdown)</p>
<p>Tunings i've tried without success include (blindly following some web advice):</p>
<pre><code>increased the shared memory available to Postgres to 256MB
increased the working memory to 2MB
disabled connection and statement logging
used a stored procedure via CREATE FUNCTION ... LANGUAGE SQL
</code></pre>
<p>So my question is, is my experience here normal, and this is what I can expect when using a SQL database? I can understand that ACID must come with costs, but this is kind of crazy in my opinion. I'm not asking for realtime game speed, but since Java can process millions of doubles in under 20 ms, I feel a bit jealous. </p>
<p>Is there a better way to do simple OLAP on the cheap (both in terms of money and server complexity)? I've looked into Mondrian and Pig + Hadoop but not super excited about maintaining yet another server application and not sure if they would even help.</p>
<hr>
<p>No the Python code and Java code do all the work in house so to speak. I just generate 4 arrays with 350,000 random values each, then take the average. I don't include the generation in the timings, only the averaging step. The java threads timing uses 4 threads (one per array average), overkill but it's definitely the fastest.</p>
<p>The sqlite3 timing is driven by the Python program and is running from disk (not :memory:)</p>
<p>I realize Postgres is doing much more behind the scenes, but most of that work doesn't matter to me since this is read only data.</p>
<p>The Postgres query doesn't change timing on subsequent runs.</p>
<p>I've rerun the Python tests to include spooling it off the disk. The timing slows down considerably to nearly 4 secs. But I'm guessing that Python's file handling code is pretty much in C (though maybe not the csv lib?) so this indicates to me that Postgres isn't streaming from the disk either (or that you are correct and I should bow down before whoever wrote their storage layer!)</p>
| 11 | 2008-09-09T10:33:39Z | 51,933 | <p>Those are very detailed answers, but they mostly beg the question, how do I get these benefits without leaving Postgres given that the data easily fits into memory, requires concurrent reads but no writes and is queried with the same query over and over again.</p>
<p>Is it possible to precompile the query and optimization plan? I would have thought the stored procedure would do this, but it doesn't really help.</p>
<p>To avoid disk access it's necessary to cache the whole table in memory, can I force Postgres to do that? I think it's already doing this though, since the query executes in just 200 ms after repeated runs.</p>
<p>Can I tell Postgres that the table is read only, so it can optimize any locking code?</p>
<p>I think it's possible to estimate the query construction costs with an empty table (timings range from 20-60 ms) </p>
<p>I still can't see why the Java/Python tests are invalid. Postgres just isn't doing that much more work (though I still haven't addressed the concurrency aspect, just the caching and query construction)</p>
<p>UPDATE:
I don't think it's fair to compare the SELECTS as suggested by pulling 350,000 through the driver and serialization steps into Python to run the aggregation, nor even to omit the aggregation as the overhead in formatting and displaying is hard to separate from the timing. If both engines are operating on in memory data, it should be an apples to apples comparison, I'm not sure how to guarantee that's already happening though.</p>
<p>I can't figure out how to add comments, maybe i don't have enough reputation?</p>
| 3 | 2008-09-09T13:50:18Z | [
"python",
"sql",
"optimization",
"aggregate",
"olap"
] |
Why are SQL aggregate functions so much slower than Python and Java (or Poor Man's OLAP) | 51,553 | <p>I need a real DBA's opinion. Postgres 8.3 takes 200 ms to execute this query on my Macbook Pro while Java and Python perform the same calculation in under 20 ms (350,000 rows):</p>
<pre><code>SELECT count(id), avg(a), avg(b), avg(c), avg(d) FROM tuples;
</code></pre>
<p>Is this normal behaviour when using a SQL database?</p>
<p>The schema (the table holds responses to a survey):</p>
<pre><code>CREATE TABLE tuples (id integer primary key, a integer, b integer, c integer, d integer);
\copy tuples from '350,000 responses.csv' delimiter as ','
</code></pre>
<p>I wrote some tests in Java and Python for context and they crush SQL (except for pure python):</p>
<pre><code>java 1.5 threads ~ 7 ms
java 1.5 ~ 10 ms
python 2.5 numpy ~ 18 ms
python 2.5 ~ 370 ms
</code></pre>
<p>Even sqlite3 is competitive with Postgres despite it assumping all columns are strings (for contrast: even using just switching to numeric columns instead of integers in Postgres results in 10x slowdown)</p>
<p>Tunings i've tried without success include (blindly following some web advice):</p>
<pre><code>increased the shared memory available to Postgres to 256MB
increased the working memory to 2MB
disabled connection and statement logging
used a stored procedure via CREATE FUNCTION ... LANGUAGE SQL
</code></pre>
<p>So my question is, is my experience here normal, and this is what I can expect when using a SQL database? I can understand that ACID must come with costs, but this is kind of crazy in my opinion. I'm not asking for realtime game speed, but since Java can process millions of doubles in under 20 ms, I feel a bit jealous. </p>
<p>Is there a better way to do simple OLAP on the cheap (both in terms of money and server complexity)? I've looked into Mondrian and Pig + Hadoop but not super excited about maintaining yet another server application and not sure if they would even help.</p>
<hr>
<p>No the Python code and Java code do all the work in house so to speak. I just generate 4 arrays with 350,000 random values each, then take the average. I don't include the generation in the timings, only the averaging step. The java threads timing uses 4 threads (one per array average), overkill but it's definitely the fastest.</p>
<p>The sqlite3 timing is driven by the Python program and is running from disk (not :memory:)</p>
<p>I realize Postgres is doing much more behind the scenes, but most of that work doesn't matter to me since this is read only data.</p>
<p>The Postgres query doesn't change timing on subsequent runs.</p>
<p>I've rerun the Python tests to include spooling it off the disk. The timing slows down considerably to nearly 4 secs. But I'm guessing that Python's file handling code is pretty much in C (though maybe not the csv lib?) so this indicates to me that Postgres isn't streaming from the disk either (or that you are correct and I should bow down before whoever wrote their storage layer!)</p>
| 11 | 2008-09-09T10:33:39Z | 51,976 | <p>You need to increase postgres' caches to the point where the whole working set fits into memory before you can expect to see perfomance comparable to doing it in-memory with a program.</p>
| 0 | 2008-09-09T14:10:06Z | [
"python",
"sql",
"optimization",
"aggregate",
"olap"
] |
Why are SQL aggregate functions so much slower than Python and Java (or Poor Man's OLAP) | 51,553 | <p>I need a real DBA's opinion. Postgres 8.3 takes 200 ms to execute this query on my Macbook Pro while Java and Python perform the same calculation in under 20 ms (350,000 rows):</p>
<pre><code>SELECT count(id), avg(a), avg(b), avg(c), avg(d) FROM tuples;
</code></pre>
<p>Is this normal behaviour when using a SQL database?</p>
<p>The schema (the table holds responses to a survey):</p>
<pre><code>CREATE TABLE tuples (id integer primary key, a integer, b integer, c integer, d integer);
\copy tuples from '350,000 responses.csv' delimiter as ','
</code></pre>
<p>I wrote some tests in Java and Python for context and they crush SQL (except for pure python):</p>
<pre><code>java 1.5 threads ~ 7 ms
java 1.5 ~ 10 ms
python 2.5 numpy ~ 18 ms
python 2.5 ~ 370 ms
</code></pre>
<p>Even sqlite3 is competitive with Postgres despite it assumping all columns are strings (for contrast: even using just switching to numeric columns instead of integers in Postgres results in 10x slowdown)</p>
<p>Tunings i've tried without success include (blindly following some web advice):</p>
<pre><code>increased the shared memory available to Postgres to 256MB
increased the working memory to 2MB
disabled connection and statement logging
used a stored procedure via CREATE FUNCTION ... LANGUAGE SQL
</code></pre>
<p>So my question is, is my experience here normal, and this is what I can expect when using a SQL database? I can understand that ACID must come with costs, but this is kind of crazy in my opinion. I'm not asking for realtime game speed, but since Java can process millions of doubles in under 20 ms, I feel a bit jealous. </p>
<p>Is there a better way to do simple OLAP on the cheap (both in terms of money and server complexity)? I've looked into Mondrian and Pig + Hadoop but not super excited about maintaining yet another server application and not sure if they would even help.</p>
<hr>
<p>No the Python code and Java code do all the work in house so to speak. I just generate 4 arrays with 350,000 random values each, then take the average. I don't include the generation in the timings, only the averaging step. The java threads timing uses 4 threads (one per array average), overkill but it's definitely the fastest.</p>
<p>The sqlite3 timing is driven by the Python program and is running from disk (not :memory:)</p>
<p>I realize Postgres is doing much more behind the scenes, but most of that work doesn't matter to me since this is read only data.</p>
<p>The Postgres query doesn't change timing on subsequent runs.</p>
<p>I've rerun the Python tests to include spooling it off the disk. The timing slows down considerably to nearly 4 secs. But I'm guessing that Python's file handling code is pretty much in C (though maybe not the csv lib?) so this indicates to me that Postgres isn't streaming from the disk either (or that you are correct and I should bow down before whoever wrote their storage layer!)</p>
| 11 | 2008-09-09T10:33:39Z | 52,006 | <p>Postgres is doing a lot more than it looks like (maintaining data consistency for a start!)</p>
<p>If the values don't have to be 100% spot on, or if the table is updated rarely, but you are running this calculation often, you might want to look into Materialized Views to speed it up.</p>
<p>(Note, I have not used materialized views in Postgres, they look at little hacky, but might suite your situation).</p>
<p><a href="http://jonathangardner.net/tech/w/PostgreSQL/Materialized_Views">Materialized Views</a></p>
<p>Also consider the overhead of actually connecting to the server and the round trip required to send the request to the server and back.</p>
<p>I'd consider 200ms for something like this to be pretty good, A quick test on my oracle server, the same table structure with about 500k rows and no indexes, takes about 1 - 1.5 seconds, which is almost all just oracle sucking the data off disk.</p>
<p>The real question is, is 200ms fast enough?</p>
<p>-------------- More --------------------</p>
<p>I was interested in solving this using materialized views, since I've never really played with them. This is in oracle.</p>
<p>First I created a MV which refreshes every minute.</p>
<pre><code>create materialized view mv_so_x
build immediate
refresh complete
START WITH SYSDATE NEXT SYSDATE + 1/24/60
as select count(*),avg(a),avg(b),avg(c),avg(d) from so_x;
</code></pre>
<p>While its refreshing, there is no rows returned</p>
<pre><code>SQL> select * from mv_so_x;
no rows selected
Elapsed: 00:00:00.00
</code></pre>
<p>Once it refreshes, its MUCH faster than doing the raw query</p>
<pre><code>SQL> select count(*),avg(a),avg(b),avg(c),avg(d) from so_x;
COUNT(*) AVG(A) AVG(B) AVG(C) AVG(D)
---------- ---------- ---------- ---------- ----------
1899459 7495.38839 22.2905454 5.00276131 2.13432836
Elapsed: 00:00:05.74
SQL> select * from mv_so_x;
COUNT(*) AVG(A) AVG(B) AVG(C) AVG(D)
---------- ---------- ---------- ---------- ----------
1899459 7495.38839 22.2905454 5.00276131 2.13432836
Elapsed: 00:00:00.00
SQL>
</code></pre>
<p>If we insert into the base table, the result is not immediately viewable view the MV.</p>
<pre><code>SQL> insert into so_x values (1,2,3,4,5);
1 row created.
Elapsed: 00:00:00.00
SQL> commit;
Commit complete.
Elapsed: 00:00:00.00
SQL> select * from mv_so_x;
COUNT(*) AVG(A) AVG(B) AVG(C) AVG(D)
---------- ---------- ---------- ---------- ----------
1899459 7495.38839 22.2905454 5.00276131 2.13432836
Elapsed: 00:00:00.00
SQL>
</code></pre>
<p>But wait a minute or so, and the MV will update behind the scenes, and the result is returned fast as you could want.</p>
<pre><code>SQL> /
COUNT(*) AVG(A) AVG(B) AVG(C) AVG(D)
---------- ---------- ---------- ---------- ----------
1899460 7495.35823 22.2905352 5.00276078 2.17647059
Elapsed: 00:00:00.00
SQL>
</code></pre>
<p>This isn't ideal. for a start, its not realtime, inserts/updates will not be immediately visible. Also, you've got a query running to update the MV whether you need it or not (this can be tune to whatever time frame, or on demand). But, this does show how much faster an MV can make it seem to the end user, if you can live with values which aren't quite upto the second accurate.</p>
| 8 | 2008-09-09T14:26:28Z | [
"python",
"sql",
"optimization",
"aggregate",
"olap"
] |
Why are SQL aggregate functions so much slower than Python and Java (or Poor Man's OLAP) | 51,553 | <p>I need a real DBA's opinion. Postgres 8.3 takes 200 ms to execute this query on my Macbook Pro while Java and Python perform the same calculation in under 20 ms (350,000 rows):</p>
<pre><code>SELECT count(id), avg(a), avg(b), avg(c), avg(d) FROM tuples;
</code></pre>
<p>Is this normal behaviour when using a SQL database?</p>
<p>The schema (the table holds responses to a survey):</p>
<pre><code>CREATE TABLE tuples (id integer primary key, a integer, b integer, c integer, d integer);
\copy tuples from '350,000 responses.csv' delimiter as ','
</code></pre>
<p>I wrote some tests in Java and Python for context and they crush SQL (except for pure python):</p>
<pre><code>java 1.5 threads ~ 7 ms
java 1.5 ~ 10 ms
python 2.5 numpy ~ 18 ms
python 2.5 ~ 370 ms
</code></pre>
<p>Even sqlite3 is competitive with Postgres despite it assumping all columns are strings (for contrast: even using just switching to numeric columns instead of integers in Postgres results in 10x slowdown)</p>
<p>Tunings i've tried without success include (blindly following some web advice):</p>
<pre><code>increased the shared memory available to Postgres to 256MB
increased the working memory to 2MB
disabled connection and statement logging
used a stored procedure via CREATE FUNCTION ... LANGUAGE SQL
</code></pre>
<p>So my question is, is my experience here normal, and this is what I can expect when using a SQL database? I can understand that ACID must come with costs, but this is kind of crazy in my opinion. I'm not asking for realtime game speed, but since Java can process millions of doubles in under 20 ms, I feel a bit jealous. </p>
<p>Is there a better way to do simple OLAP on the cheap (both in terms of money and server complexity)? I've looked into Mondrian and Pig + Hadoop but not super excited about maintaining yet another server application and not sure if they would even help.</p>
<hr>
<p>No the Python code and Java code do all the work in house so to speak. I just generate 4 arrays with 350,000 random values each, then take the average. I don't include the generation in the timings, only the averaging step. The java threads timing uses 4 threads (one per array average), overkill but it's definitely the fastest.</p>
<p>The sqlite3 timing is driven by the Python program and is running from disk (not :memory:)</p>
<p>I realize Postgres is doing much more behind the scenes, but most of that work doesn't matter to me since this is read only data.</p>
<p>The Postgres query doesn't change timing on subsequent runs.</p>
<p>I've rerun the Python tests to include spooling it off the disk. The timing slows down considerably to nearly 4 secs. But I'm guessing that Python's file handling code is pretty much in C (though maybe not the csv lib?) so this indicates to me that Postgres isn't streaming from the disk either (or that you are correct and I should bow down before whoever wrote their storage layer!)</p>
| 11 | 2008-09-09T10:33:39Z | 52,179 | <p>Thanks for the Oracle timings, that's the kind of stuff I'm looking for (disappointing though :-)</p>
<p>Materialized views are probably worth considering as I think I can precompute the most interesting forms of this query for most users.</p>
<p>I don't think query round trip time should be very high as i'm running the the queries on the same machine that runs Postgres, so it can't add much latency?</p>
<p>I've also done some checking into the cache sizes, and it seems Postgres relies on the OS to handle caching, they specifically mention BSD as the ideal OS for this, so I thinking Mac OS ought to be pretty smart about bringing the table into memory. Unless someone has more specific params in mind I think more specific caching is out of my control.</p>
<p>In the end I can probably put up with 200 ms response times, but knowing that 7 ms is a possible target makes me feel unsatisfied, as even 20-50 ms times would enable more users to have more up to date queries and get rid of a lots of caching and precomputed hacks.</p>
<p>I just checked the timings using MySQL 5 and they are slightly worse than Postgres. So barring some major caching breakthroughs, I guess this is what I can expect going the relational db route.</p>
<p>I wish I could up vote some of your answers, but I don't have enough points yet.</p>
| 0 | 2008-09-09T15:34:19Z | [
"python",
"sql",
"optimization",
"aggregate",
"olap"
] |
Why are SQL aggregate functions so much slower than Python and Java (or Poor Man's OLAP) | 51,553 | <p>I need a real DBA's opinion. Postgres 8.3 takes 200 ms to execute this query on my Macbook Pro while Java and Python perform the same calculation in under 20 ms (350,000 rows):</p>
<pre><code>SELECT count(id), avg(a), avg(b), avg(c), avg(d) FROM tuples;
</code></pre>
<p>Is this normal behaviour when using a SQL database?</p>
<p>The schema (the table holds responses to a survey):</p>
<pre><code>CREATE TABLE tuples (id integer primary key, a integer, b integer, c integer, d integer);
\copy tuples from '350,000 responses.csv' delimiter as ','
</code></pre>
<p>I wrote some tests in Java and Python for context and they crush SQL (except for pure python):</p>
<pre><code>java 1.5 threads ~ 7 ms
java 1.5 ~ 10 ms
python 2.5 numpy ~ 18 ms
python 2.5 ~ 370 ms
</code></pre>
<p>Even sqlite3 is competitive with Postgres despite it assumping all columns are strings (for contrast: even using just switching to numeric columns instead of integers in Postgres results in 10x slowdown)</p>
<p>Tunings i've tried without success include (blindly following some web advice):</p>
<pre><code>increased the shared memory available to Postgres to 256MB
increased the working memory to 2MB
disabled connection and statement logging
used a stored procedure via CREATE FUNCTION ... LANGUAGE SQL
</code></pre>
<p>So my question is, is my experience here normal, and this is what I can expect when using a SQL database? I can understand that ACID must come with costs, but this is kind of crazy in my opinion. I'm not asking for realtime game speed, but since Java can process millions of doubles in under 20 ms, I feel a bit jealous. </p>
<p>Is there a better way to do simple OLAP on the cheap (both in terms of money and server complexity)? I've looked into Mondrian and Pig + Hadoop but not super excited about maintaining yet another server application and not sure if they would even help.</p>
<hr>
<p>No the Python code and Java code do all the work in house so to speak. I just generate 4 arrays with 350,000 random values each, then take the average. I don't include the generation in the timings, only the averaging step. The java threads timing uses 4 threads (one per array average), overkill but it's definitely the fastest.</p>
<p>The sqlite3 timing is driven by the Python program and is running from disk (not :memory:)</p>
<p>I realize Postgres is doing much more behind the scenes, but most of that work doesn't matter to me since this is read only data.</p>
<p>The Postgres query doesn't change timing on subsequent runs.</p>
<p>I've rerun the Python tests to include spooling it off the disk. The timing slows down considerably to nearly 4 secs. But I'm guessing that Python's file handling code is pretty much in C (though maybe not the csv lib?) so this indicates to me that Postgres isn't streaming from the disk either (or that you are correct and I should bow down before whoever wrote their storage layer!)</p>
| 11 | 2008-09-09T10:33:39Z | 53,303 | <p>I'm a MS-SQL guy myself, and we'd use <a href="http://msdn.microsoft.com/en-us/library/ms178015.aspx" rel="nofollow">DBCC PINTABLE</a> to keep a table cached, and <a href="http://msdn.microsoft.com/en-us/library/ms184361.aspx" rel="nofollow">SET STATISTICS IO</a> to see that it's reading from cache, and not disk. </p>
<p>I can't find anything on Postgres to mimic PINTABLE, but <a href="http://www.postgresql.org/docs/current/static/pgbuffercache.html" rel="nofollow">pg_buffercache</a> seems to give details on what is in the cache - you may want to check that, and see if your table is actually being cached.</p>
<p>A quick back of the envelope calculation makes me suspect that you're paging from disk. Assuming Postgres uses 4-byte integers, you have (6 * 4) bytes per row, so your table is a minimum of (24 * 350,000) bytes ~ 8.4MB. Assuming 40 MB/s sustained throughput on your HDD, you're looking at right around 200ms to read the data (which, <a href="http://stackoverflow.com/questions/51553/why-are-sql-aggregate-functions-so-much-slower-than-python-and-java-or-poor-man#51668" rel="nofollow">as pointed out</a>, should be where almost all of the time is being spent). </p>
<p>Unless I screwed up my math somewhere, I don't see how it's possible that you are able to read 8MB into your Java app and process it in the times you're showing - unless that file is already cached by either the drive or your OS.</p>
| 2 | 2008-09-10T01:47:32Z | [
"python",
"sql",
"optimization",
"aggregate",
"olap"
] |
Why are SQL aggregate functions so much slower than Python and Java (or Poor Man's OLAP) | 51,553 | <p>I need a real DBA's opinion. Postgres 8.3 takes 200 ms to execute this query on my Macbook Pro while Java and Python perform the same calculation in under 20 ms (350,000 rows):</p>
<pre><code>SELECT count(id), avg(a), avg(b), avg(c), avg(d) FROM tuples;
</code></pre>
<p>Is this normal behaviour when using a SQL database?</p>
<p>The schema (the table holds responses to a survey):</p>
<pre><code>CREATE TABLE tuples (id integer primary key, a integer, b integer, c integer, d integer);
\copy tuples from '350,000 responses.csv' delimiter as ','
</code></pre>
<p>I wrote some tests in Java and Python for context and they crush SQL (except for pure python):</p>
<pre><code>java 1.5 threads ~ 7 ms
java 1.5 ~ 10 ms
python 2.5 numpy ~ 18 ms
python 2.5 ~ 370 ms
</code></pre>
<p>Even sqlite3 is competitive with Postgres despite it assumping all columns are strings (for contrast: even using just switching to numeric columns instead of integers in Postgres results in 10x slowdown)</p>
<p>Tunings i've tried without success include (blindly following some web advice):</p>
<pre><code>increased the shared memory available to Postgres to 256MB
increased the working memory to 2MB
disabled connection and statement logging
used a stored procedure via CREATE FUNCTION ... LANGUAGE SQL
</code></pre>
<p>So my question is, is my experience here normal, and this is what I can expect when using a SQL database? I can understand that ACID must come with costs, but this is kind of crazy in my opinion. I'm not asking for realtime game speed, but since Java can process millions of doubles in under 20 ms, I feel a bit jealous. </p>
<p>Is there a better way to do simple OLAP on the cheap (both in terms of money and server complexity)? I've looked into Mondrian and Pig + Hadoop but not super excited about maintaining yet another server application and not sure if they would even help.</p>
<hr>
<p>No the Python code and Java code do all the work in house so to speak. I just generate 4 arrays with 350,000 random values each, then take the average. I don't include the generation in the timings, only the averaging step. The java threads timing uses 4 threads (one per array average), overkill but it's definitely the fastest.</p>
<p>The sqlite3 timing is driven by the Python program and is running from disk (not :memory:)</p>
<p>I realize Postgres is doing much more behind the scenes, but most of that work doesn't matter to me since this is read only data.</p>
<p>The Postgres query doesn't change timing on subsequent runs.</p>
<p>I've rerun the Python tests to include spooling it off the disk. The timing slows down considerably to nearly 4 secs. But I'm guessing that Python's file handling code is pretty much in C (though maybe not the csv lib?) so this indicates to me that Postgres isn't streaming from the disk either (or that you are correct and I should bow down before whoever wrote their storage layer!)</p>
| 11 | 2008-09-09T10:33:39Z | 53,333 | <p>I retested with MySQL specifying ENGINE = MEMORY and it doesn't change a thing (still 200 ms). Sqlite3 using an in-memory db gives similar timings as well (250 ms).</p>
<p>The math <a href="http://stackoverflow.com/questions/51553/why-are-sql-aggregate-functions-so-much-slower-than-python-and-java-or-poor-man#53303" rel="nofollow">here</a> looks correct (at least the size, as that's how big the sqlite db is :-)</p>
<p>I'm just not buying the disk-causes-slowness argument as there is every indication the tables are in memory (the postgres guys all warn against trying too hard to pin tables to memory as they swear the OS will do it better than the programmer)</p>
<p>To clarify the timings, the Java code is not reading from disk, making it a totally unfair comparison if Postgres is reading from the disk and calculating a complicated query, but that's really besides the point, the DB should be smart enough to bring a small table into memory and precompile a stored procedure IMHO.</p>
<p>UPDATE (in response to the first comment below):</p>
<p><em>I'm not sure how I'd test the query without using an aggregation function in a way that would be fair, since if i select all of the rows it'll spend tons of time serializing and formatting everything. I'm not saying that the slowness is due to the aggregation function, it could still be just overhead from concurrency, integrity, and friends. I just don't know how to isolate the aggregation as the sole independent variable.</em></p>
| 5 | 2008-09-10T02:29:45Z | [
"python",
"sql",
"optimization",
"aggregate",
"olap"
] |
Why are SQL aggregate functions so much slower than Python and Java (or Poor Man's OLAP) | 51,553 | <p>I need a real DBA's opinion. Postgres 8.3 takes 200 ms to execute this query on my Macbook Pro while Java and Python perform the same calculation in under 20 ms (350,000 rows):</p>
<pre><code>SELECT count(id), avg(a), avg(b), avg(c), avg(d) FROM tuples;
</code></pre>
<p>Is this normal behaviour when using a SQL database?</p>
<p>The schema (the table holds responses to a survey):</p>
<pre><code>CREATE TABLE tuples (id integer primary key, a integer, b integer, c integer, d integer);
\copy tuples from '350,000 responses.csv' delimiter as ','
</code></pre>
<p>I wrote some tests in Java and Python for context and they crush SQL (except for pure python):</p>
<pre><code>java 1.5 threads ~ 7 ms
java 1.5 ~ 10 ms
python 2.5 numpy ~ 18 ms
python 2.5 ~ 370 ms
</code></pre>
<p>Even sqlite3 is competitive with Postgres despite it assumping all columns are strings (for contrast: even using just switching to numeric columns instead of integers in Postgres results in 10x slowdown)</p>
<p>Tunings i've tried without success include (blindly following some web advice):</p>
<pre><code>increased the shared memory available to Postgres to 256MB
increased the working memory to 2MB
disabled connection and statement logging
used a stored procedure via CREATE FUNCTION ... LANGUAGE SQL
</code></pre>
<p>So my question is, is my experience here normal, and this is what I can expect when using a SQL database? I can understand that ACID must come with costs, but this is kind of crazy in my opinion. I'm not asking for realtime game speed, but since Java can process millions of doubles in under 20 ms, I feel a bit jealous. </p>
<p>Is there a better way to do simple OLAP on the cheap (both in terms of money and server complexity)? I've looked into Mondrian and Pig + Hadoop but not super excited about maintaining yet another server application and not sure if they would even help.</p>
<hr>
<p>No the Python code and Java code do all the work in house so to speak. I just generate 4 arrays with 350,000 random values each, then take the average. I don't include the generation in the timings, only the averaging step. The java threads timing uses 4 threads (one per array average), overkill but it's definitely the fastest.</p>
<p>The sqlite3 timing is driven by the Python program and is running from disk (not :memory:)</p>
<p>I realize Postgres is doing much more behind the scenes, but most of that work doesn't matter to me since this is read only data.</p>
<p>The Postgres query doesn't change timing on subsequent runs.</p>
<p>I've rerun the Python tests to include spooling it off the disk. The timing slows down considerably to nearly 4 secs. But I'm guessing that Python's file handling code is pretty much in C (though maybe not the csv lib?) so this indicates to me that Postgres isn't streaming from the disk either (or that you are correct and I should bow down before whoever wrote their storage layer!)</p>
| 11 | 2008-09-09T10:33:39Z | 53,713 | <p>Are you using TCP to access the Postgres? In that case Nagle is messing with your timing.</p>
| 1 | 2008-09-10T09:45:20Z | [
"python",
"sql",
"optimization",
"aggregate",
"olap"
] |
Cross-platform space remaining on volume using python | 51,658 | <p>I need a way to determine the space remaining on a disk volume using python on linux, Windows and OS X. I'm currently parsing the output of the various system calls (df, dir) to accomplish this - is there a better way?</p>
| 56 | 2008-09-09T11:36:39Z | 51,663 | <p>The <a href="https://docs.python.org/2.7/library/os.html" rel="nofollow">os.statvfs()</a> function is a better way to get that information for Unix-like platforms (including OS X). The Python documentation says "Availability: Unix" but it's worth checking whether it works on Windows too in your build of Python (ie. the docs might not be up to date).</p>
<p>Otherwise, you can use the <a href="http://sourceforge.net/projects/pywin32/" rel="nofollow">pywin32</a> library to directly call the <a href="http://msdn.microsoft.com/en-us/library/aa364937(VS.85).aspx" rel="nofollow">GetDiskFreeSpaceEx</a> function.</p>
| 1 | 2008-09-09T11:40:26Z | [
"python",
"windows",
"linux",
"osx",
"diskspace"
] |
Cross-platform space remaining on volume using python | 51,658 | <p>I need a way to determine the space remaining on a disk volume using python on linux, Windows and OS X. I'm currently parsing the output of the various system calls (df, dir) to accomplish this - is there a better way?</p>
| 56 | 2008-09-09T11:36:39Z | 51,675 | <p>I Don't know of any cross-platform way to achieve this, but maybe a good workaround for you would be to write a wrapper class that checks the operating system and uses the best method for each.</p>
<p>For Windows, there's the <a href="http://aspn.activestate.com/ASPN/docs/ActivePython/2.2/PyWin32/win32api__GetDiskFreeSpaceEx_meth.html" rel="nofollow">GetDiskFreeSpaceEx</a> method in the win32 extensions.</p>
| 0 | 2008-09-09T11:47:20Z | [
"python",
"windows",
"linux",
"osx",
"diskspace"
] |
Cross-platform space remaining on volume using python | 51,658 | <p>I need a way to determine the space remaining on a disk volume using python on linux, Windows and OS X. I'm currently parsing the output of the various system calls (df, dir) to accomplish this - is there a better way?</p>
| 56 | 2008-09-09T11:36:39Z | 53,170 | <p>You can use <a href="http://man.he.net/?section=all&topic=df" rel="nofollow">df</a> as a cross-platform way. It is a part of <a href="http://www.gnu.org/software/coreutils/" rel="nofollow">GNU core utilities</a>. These are the core utilities which are expected to exist on every operating system. However, they are not installed on Windows by default (Here, <a href="http://getgnuwin32.sourceforge.net/" rel="nofollow">GetGnuWin32</a> comes in handy).</p>
<p><em>df</em> is a command-line utility, therefore a wrapper required for scripting purposes.
For example: </p>
<pre><code>from subprocess import PIPE, Popen
def free_volume(filename):
"""Find amount of disk space available to the current user (in bytes)
on the file system containing filename."""
stats = Popen(["df", "-Pk", filename], stdout=PIPE).communicate()[0]
return int(stats.splitlines()[1].split()[3]) * 1024
</code></pre>
| -2 | 2008-09-09T23:48:07Z | [
"python",
"windows",
"linux",
"osx",
"diskspace"
] |
Cross-platform space remaining on volume using python | 51,658 | <p>I need a way to determine the space remaining on a disk volume using python on linux, Windows and OS X. I'm currently parsing the output of the various system calls (df, dir) to accomplish this - is there a better way?</p>
| 56 | 2008-09-09T11:36:39Z | 1,728,106 | <p>If you dont like to add another dependency you can for windows use ctypes to call the win32 function call directly. </p>
<pre><code>import ctypes
free_bytes = ctypes.c_ulonglong(0)
ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(u'c:\\'), None, None, ctypes.pointer(free_bytes))
if free_bytes.value == 0:
print 'dont panic'
</code></pre>
| 5 | 2009-11-13T09:22:14Z | [
"python",
"windows",
"linux",
"osx",
"diskspace"
] |
Cross-platform space remaining on volume using python | 51,658 | <p>I need a way to determine the space remaining on a disk volume using python on linux, Windows and OS X. I'm currently parsing the output of the various system calls (df, dir) to accomplish this - is there a better way?</p>
| 56 | 2008-09-09T11:36:39Z | 2,372,171 | <pre><code>import ctypes
import os
import platform
import sys
def get_free_space_mb(dirname):
"""Return folder/drive free space (in megabytes)."""
if platform.system() == 'Windows':
free_bytes = ctypes.c_ulonglong(0)
ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(dirname), None, None, ctypes.pointer(free_bytes))
return free_bytes.value / 1024 / 1024
else:
st = os.statvfs(dirname)
return st.f_bavail * st.f_frsize / 1024 / 1024
</code></pre>
<p>Note that you <em>must</em> pass a directory name for <code>GetDiskFreeSpaceEx()</code> to work
(<code>statvfs()</code> works on both files and directories). You can get a directory name
from a file with <code>os.path.dirname()</code>.</p>
<p>Also see the documentation for <a href="https://docs.python.org/3/library/os.html#os.fstatvfs"><code>os.statvfs()</code></a> and <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa364937(v=vs.85).aspx"><code>GetDiskFreeSpaceEx</code></a>.</p>
| 58 | 2010-03-03T14:45:23Z | [
"python",
"windows",
"linux",
"osx",
"diskspace"
] |
Cross-platform space remaining on volume using python | 51,658 | <p>I need a way to determine the space remaining on a disk volume using python on linux, Windows and OS X. I'm currently parsing the output of the various system calls (df, dir) to accomplish this - is there a better way?</p>
| 56 | 2008-09-09T11:36:39Z | 6,773,639 | <p>A good cross-platform way is using psutil: <a href="http://pythonhosted.org/psutil/#disks" rel="nofollow">http://pythonhosted.org/psutil/#disks</a>
(Note that you'll need psutil 0.3.0 or above).</p>
| 5 | 2011-07-21T09:02:48Z | [
"python",
"windows",
"linux",
"osx",
"diskspace"
] |
Cross-platform space remaining on volume using python | 51,658 | <p>I need a way to determine the space remaining on a disk volume using python on linux, Windows and OS X. I'm currently parsing the output of the various system calls (df, dir) to accomplish this - is there a better way?</p>
| 56 | 2008-09-09T11:36:39Z | 19,332,602 | <p>You could use the <a href="https://pypi.python.org/pypi/WMI/">wmi</a> module for windows and os.statvfs for unix</p>
<p>for window</p>
<pre><code>import wmi
c = wmi.WMI ()
for d in c.Win32_LogicalDisk():
print( d.Caption, d.FreeSpace, d.Size, d.DriveType)
</code></pre>
<p>for unix or linux</p>
<pre><code>from os import statvfs
statvfs(path)
</code></pre>
| 13 | 2013-10-12T09:20:42Z | [
"python",
"windows",
"linux",
"osx",
"diskspace"
] |
Cross-platform space remaining on volume using python | 51,658 | <p>I need a way to determine the space remaining on a disk volume using python on linux, Windows and OS X. I'm currently parsing the output of the various system calls (df, dir) to accomplish this - is there a better way?</p>
| 56 | 2008-09-09T11:36:39Z | 29,944,093 | <p>Install <a href="http://pythonhosted.org/psutil/">psutil</a> using <code>pip install psutil</code>. Then you can get the amount of free space in bytes using:</p>
<pre class="lang-python prettyprint-override"><code>import psutil
print(psutil.disk_usage(".").free)
</code></pre>
| 7 | 2015-04-29T12:43:17Z | [
"python",
"windows",
"linux",
"osx",
"diskspace"
] |
Cross-platform space remaining on volume using python | 51,658 | <p>I need a way to determine the space remaining on a disk volume using python on linux, Windows and OS X. I'm currently parsing the output of the various system calls (df, dir) to accomplish this - is there a better way?</p>
| 56 | 2008-09-09T11:36:39Z | 35,860,878 | <p>Below code returns correct value on windows</p>
<pre><code>import win32file
def get_free_space(dirname):
secsPerClus, bytesPerSec, nFreeClus, totClus = win32file.GetDiskFreeSpace(dirname)
return secsPerClus * bytesPerSec * nFreeClus
</code></pre>
| 0 | 2016-03-08T06:53:17Z | [
"python",
"windows",
"linux",
"osx",
"diskspace"
] |
Cross-platform space remaining on volume using python | 51,658 | <p>I need a way to determine the space remaining on a disk volume using python on linux, Windows and OS X. I'm currently parsing the output of the various system calls (df, dir) to accomplish this - is there a better way?</p>
| 56 | 2008-09-09T11:36:39Z | 38,889,608 | <p>From Python 3.3 you can use <a href="https://docs.python.org/3/library/shutil.html#shutil.disk_usage" rel="nofollow">shutil.disk_usage("/").free</a> from standard library for both Windows and UNIX :)</p>
| 2 | 2016-08-11T07:11:52Z | [
"python",
"windows",
"linux",
"osx",
"diskspace"
] |
Large Python Includes | 53,027 | <p>I have a file that I want to include in Python but the included file is fairly long and it'd be much neater to be able to split them into several files but then I have to use several include statements.</p>
<p>Is there some way to group together several files and include them all at once?</p>
| 3 | 2008-09-09T22:15:09Z | 53,036 | <p>Yes, take a look at the "6.4 Packages" section in <a href="http://docs.python.org/tut/node8.html" rel="nofollow">http://docs.python.org/tut/node8.html</a>:</p>
<p>Basically, you can place a bunch of files into a directory and add an __init__.py file to the directory. If the directory is in your PYTHONPATH or sys.path, you can do "import directoryname" to import everything in the directory or "import directoryname.some_file_in_directory" to import a specific file that is in the directory.</p>
<blockquote>
<p>The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as "string", from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later. </p>
</blockquote>
| 6 | 2008-09-09T22:19:25Z | [
"python"
] |
Large Python Includes | 53,027 | <p>I have a file that I want to include in Python but the included file is fairly long and it'd be much neater to be able to split them into several files but then I have to use several include statements.</p>
<p>Is there some way to group together several files and include them all at once?</p>
| 3 | 2008-09-09T22:15:09Z | 53,037 | <ol>
<li>Put files in one folder. </li>
<li>Add __init__.py file to the folder. Do necessary imports in __init__.py</li>
<li><p>Replace multiple imports by one:</p>
<p>import folder_name </p></li>
</ol>
<p>See <a href="http://docs.python.org/tut/node8.html#SECTION008400000000000000000" rel="nofollow">Python Package Management</a></p>
| 8 | 2008-09-09T22:21:04Z | [
"python"
] |
How can I do a line break (line continuation) in Python? | 53,162 | <p>I have a long line of code that I want to break up among multiple lines. What do I use and what is the syntax?</p>
<p>For example, adding a bunch of strings,</p>
<pre><code>e = 'a' + 'b' + 'c' + 'd'
</code></pre>
<p>and have it like this:</p>
<pre><code>e = 'a' + 'b' +
'c' + 'd'
</code></pre>
| 535 | 2008-09-09T23:45:30Z | 53,173 | <p>Put a <code>\</code> at the end of your line or enclose the statement in parens <code>( .. )</code>. From <a href="http://www.ibm.com/developerworks/opensource/library/os-python5/">IBM</a>:</p>
<pre><code>b = ((i1 < 20) and
(i2 < 30) and
(i3 < 40))
</code></pre>
<p>or</p>
<pre><code>b = (i1 < 20) and \
(i2 < 30) and \
(i3 < 40)
</code></pre>
| 12 | 2008-09-09T23:48:30Z | [
"python",
"syntax",
"line-breaks",
"long-lines"
] |
How can I do a line break (line continuation) in Python? | 53,162 | <p>I have a long line of code that I want to break up among multiple lines. What do I use and what is the syntax?</p>
<p>For example, adding a bunch of strings,</p>
<pre><code>e = 'a' + 'b' + 'c' + 'd'
</code></pre>
<p>and have it like this:</p>
<pre><code>e = 'a' + 'b' +
'c' + 'd'
</code></pre>
| 535 | 2008-09-09T23:45:30Z | 53,180 | <p>What is the line? You can just have arguments on the next line without any problems:</p>
<pre><code>a = dostuff(blahblah1, blahblah2, blahblah3, blahblah4, blahblah5,
blahblah6, blahblah7)
</code></pre>
<p>Otherwise you can do something like this:</p>
<pre><code>if a == True and \
b == False
</code></pre>
<p>Check the <a href="http://www.python.org/dev/peps/pep-0008/">style guide</a> for more information.</p>
<p>From your example line:</p>
<pre><code>a = '1' + '2' + '3' + \
'4' + '5'
</code></pre>
<p>Or:</p>
<pre><code>a = ('1' + '2' + '3' +
'4' + '5')
</code></pre>
<p>Note that the style guide says that using the implicit continuation with parentheses is preferred, but in this particular case just adding parentheses around your expression is probably the wrong way to go.</p>
| 615 | 2008-09-09T23:52:05Z | [
"python",
"syntax",
"line-breaks",
"long-lines"
] |
How can I do a line break (line continuation) in Python? | 53,162 | <p>I have a long line of code that I want to break up among multiple lines. What do I use and what is the syntax?</p>
<p>For example, adding a bunch of strings,</p>
<pre><code>e = 'a' + 'b' + 'c' + 'd'
</code></pre>
<p>and have it like this:</p>
<pre><code>e = 'a' + 'b' +
'c' + 'd'
</code></pre>
| 535 | 2008-09-09T23:45:30Z | 53,182 | <blockquote>
<p>From the horse's mouth: <a href="http://docs.python.org/ref/explicit-joining.html">Explicit line
joining </a></p>
<p>Two or more physical lines may be
joined into logical lines using
backslash characters (<code>\</code>), as follows:
when a physical line ends in a
backslash that is not part of a string
literal or comment, it is joined with
the following forming a single logical
line, deleting the backslash and the
following end-of-line character. For
example:</p>
<pre><code>if 1900 < year < 2100 and 1 <= month <= 12 \
and 1 <= day <= 31 and 0 <= hour < 24 \
and 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date
return 1
</code></pre>
<p>A line ending in a backslash cannot
carry a comment. A backslash does not
continue a comment. A backslash does
not continue a token except for string
literals (i.e., tokens other than
string literals cannot be split across
physical lines using a backslash). A
backslash is illegal elsewhere on a
line outside a string literal. </p>
</blockquote>
| 9 | 2008-09-09T23:53:17Z | [
"python",
"syntax",
"line-breaks",
"long-lines"
] |
How can I do a line break (line continuation) in Python? | 53,162 | <p>I have a long line of code that I want to break up among multiple lines. What do I use and what is the syntax?</p>
<p>For example, adding a bunch of strings,</p>
<pre><code>e = 'a' + 'b' + 'c' + 'd'
</code></pre>
<p>and have it like this:</p>
<pre><code>e = 'a' + 'b' +
'c' + 'd'
</code></pre>
| 535 | 2008-09-09T23:45:30Z | 53,200 | <p>From <a href="http://www.python.org/dev/peps/pep-0008/">Style Guide for Python Code</a>:</p>
<blockquote>
<p><strong>The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces.</strong> Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.</p>
<p>Backslashes may still be appropriate at times. For example, long, multiple with-statements cannot use implicit continuation, so backslashes are acceptable:</p>
<pre><code>with open('/path/to/some/file/you/want/to/read') as file_1, \
open('/path/to/some/file/being/written', 'w') as file_2:
file_2.write(file_1.read())
</code></pre>
<p>Another such case is with assert statements.</p>
<p>Make sure to indent the continued line appropriately. The preferred place to break around a binary operator is <strong>after</strong> the operator, not before it. Some examples:</p>
<pre><code>class Rectangle(Blob):
def __init__(self, width, height,
color='black', emphasis=None, highlight=0):
if (width == 0 and height == 0 and
color == 'red' and emphasis == 'strong' or
highlight > 100):
raise ValueError("sorry, you lose")
if width == 0 and height == 0 and (color == 'red' or
emphasis is None):
raise ValueError("I don't think so -- values are %s, %s" %
(width, height))
Blob.__init__(self, width, height,
color, emphasis, highlight)
</code></pre>
</blockquote>
<p>EDIT: PEP8 now recommends the <em>opposite convention</em> (for breaking at binary operations) used by Mathematicians and their publishers to improve readability. </p>
<p>Donald Knuth's style of breaking <strong>before</strong> a binary operator aligns operators vertically, thus reducing the eye's workload when determining which items are added and subtracted.</p>
<p>From <a href="http://legacy.python.org/dev/peps/pep-0008/#should-a-line-break-before-or-after-a-binary-operator">PEP8: Should a line break before or after a binary operator?</a>:</p>
<blockquote>
<p>Donald Knuth explains the traditional rule in his Computers and Typesetting series: "Although formulas within a paragraph always break after binary operations and relations, displayed formulas always break before binary operations"[3].</p>
<p>Following the tradition from mathematics usually results in more readable code:</p>
<pre><code># Yes: easy to match operators with operands
income = (gross_wages
+ taxable_interest
+ (dividends - qualified_dividends)
- ira_deduction
- student_loan_interest)
</code></pre>
<p>In Python code, it is permissible to break before or after a binary operator, as long as the convention is consistent locally. For new code Knuth's style is suggested.</p>
</blockquote>
<p>[3]: Donald Knuth's The TeXBook, pages 195 and 196</p>
| 119 | 2008-09-10T00:06:39Z | [
"python",
"syntax",
"line-breaks",
"long-lines"
] |
How can I do a line break (line continuation) in Python? | 53,162 | <p>I have a long line of code that I want to break up among multiple lines. What do I use and what is the syntax?</p>
<p>For example, adding a bunch of strings,</p>
<pre><code>e = 'a' + 'b' + 'c' + 'd'
</code></pre>
<p>and have it like this:</p>
<pre><code>e = 'a' + 'b' +
'c' + 'd'
</code></pre>
| 535 | 2008-09-09T23:45:30Z | 61,933 | <p>The danger in using a backslash to end a line is that if whitespace is added after the backslash (which, of course, is very hard to see), the backslash is no longer doing what you thought it was.</p>
<p>See Python Idioms and Anti-Idioms (for <a href="https://docs.python.org/2/howto/doanddont.html#using-backslash-to-continue-statements">Python 2</a> or <a href="https://docs.python.org/3.1/howto/doanddont.html#using-backslash-to-continue-statements">Python 3</a>) for more.</p>
| 46 | 2008-09-15T06:28:30Z | [
"python",
"syntax",
"line-breaks",
"long-lines"
] |
How can I do a line break (line continuation) in Python? | 53,162 | <p>I have a long line of code that I want to break up among multiple lines. What do I use and what is the syntax?</p>
<p>For example, adding a bunch of strings,</p>
<pre><code>e = 'a' + 'b' + 'c' + 'd'
</code></pre>
<p>and have it like this:</p>
<pre><code>e = 'a' + 'b' +
'c' + 'd'
</code></pre>
| 535 | 2008-09-09T23:45:30Z | 110,882 | <p>You can break lines in between parenthesises and braces. Additionally, you can append the backslash character <code>\</code> to a line to explicitly break it:</p>
<pre><code>x = (tuples_first_value,
second_value)
y = 1 + \
2
</code></pre>
| 16 | 2008-09-21T12:20:08Z | [
"python",
"syntax",
"line-breaks",
"long-lines"
] |
How do you check whether a python method is bound or not? | 53,225 | <p>Given a reference to a method, is there a way to check whether the method is bound to an object or not? Can you also access the instance that it's bound to?</p>
| 22 | 2008-09-10T00:31:11Z | 53,237 | <p><a href="http://docs.python.org/ref/types.html" rel="nofollow"><strong>im_self</strong> attribute</a></p>
| 3 | 2008-09-10T00:42:13Z | [
"python",
"python-datamodel"
] |
How do you check whether a python method is bound or not? | 53,225 | <p>Given a reference to a method, is there a way to check whether the method is bound to an object or not? Can you also access the instance that it's bound to?</p>
| 22 | 2008-09-10T00:31:11Z | 53,322 | <pre><code>def isbound(method):
return method.im_self is not None
def instance(bounded_method):
return bounded_method.im_self
</code></pre>
<p><a href="http://docs.python.org/ref/types.html">User-defined methods:</a></p>
<blockquote>
<p>When a user-defined method object is
created by retrieving a user-defined
function object from a class, its
<code>im_self</code> attribute is <code>None</code> and the
method object is said to be unbound.
When one is created by retrieving a
user-defined function object from a
class via one of its instances, its
<code>im_self</code> attribute is the instance, and
the method object is said to be bound.
In either case, the new method's
<code>im_class</code> attribute is the class from
which the retrieval takes place, and
its <code>im_func</code> attribute is the original
function object.</p>
</blockquote>
<p>In Python <a href="http://docs.python.org/dev/whatsnew/2.6.html">2.6 and 3.0</a>:</p>
<blockquote>
<p>Instance method objects have new
attributes for the object and function
comprising the method; the new synonym
for <code>im_self</code> is <code>__self__</code>, and <code>im_func</code>
is also available as <code>__func__</code>. The old
names are still supported in Python
2.6, but are gone in 3.0.</p>
</blockquote>
| 27 | 2008-09-10T02:19:09Z | [
"python",
"python-datamodel"
] |
How do you check whether a python method is bound or not? | 53,225 | <p>Given a reference to a method, is there a way to check whether the method is bound to an object or not? Can you also access the instance that it's bound to?</p>
| 22 | 2008-09-10T00:31:11Z | 18,955,425 | <p>In python 3 the <code>__self__</code> attribute is <em>only</em> set on bound methods. It's not set to <code>None</code> on plain functions (or unbound methods, which are just plain functions in python 3). </p>
<p>Use something like this:</p>
<pre><code>def is_bound(m):
return hasattr(m, '__self__')
</code></pre>
| 4 | 2013-09-23T09:03:57Z | [
"python",
"python-datamodel"
] |
Best way to check if a list is empty | 53,513 | <p>For example, if passed the following:</p>
<pre><code>a = []
</code></pre>
<p>How do I check to see if <code>a</code> is empty?</p>
| 1,615 | 2008-09-10T06:20:11Z | 53,522 | <pre><code>if not a:
print("List is empty")
</code></pre>
<p>Using the implicit booleanness of the empty list <code>a</code> is quite pythonic.</p>
| 2,388 | 2008-09-10T06:28:05Z | [
"python",
"list"
] |
Best way to check if a list is empty | 53,513 | <p>For example, if passed the following:</p>
<pre><code>a = []
</code></pre>
<p>How do I check to see if <code>a</code> is empty?</p>
| 1,615 | 2008-09-10T06:20:11Z | 53,523 | <p>I have seen the below as preferred, as it will catch the null list as well:</p>
<pre><code>if not a:
print "The list is empty or null"
</code></pre>
| 35 | 2008-09-10T06:28:39Z | [
"python",
"list"
] |
Best way to check if a list is empty | 53,513 | <p>For example, if passed the following:</p>
<pre><code>a = []
</code></pre>
<p>How do I check to see if <code>a</code> is empty?</p>
| 1,615 | 2008-09-10T06:20:11Z | 53,525 | <p>An empty list is itself considered false in true value testing (see <a href="https://docs.python.org/2/library/stdtypes.html#truth-value-testing">python documentation</a>):</p>
<pre><code>a = []
if a:
print "not empty"
</code></pre>
<p>@Daren Thomas</p>
<blockquote>
<p>EDIT: Another point against testing
the empty list as False: What about
polymorphism? You shouldn't depend on
a list being a list. It should just
quack like a duck - how are you going
to get your duckCollection to quack
''False'' when it has no elements?</p>
</blockquote>
<p>Your duckCollection should implement <code>__nonzero__</code> or <code>__len__</code> so the if a: will work without problems.</p>
| 65 | 2008-09-10T06:31:22Z | [
"python",
"list"
] |
Best way to check if a list is empty | 53,513 | <p>For example, if passed the following:</p>
<pre><code>a = []
</code></pre>
<p>How do I check to see if <code>a</code> is empty?</p>
| 1,615 | 2008-09-10T06:20:11Z | 53,533 | <p>I prefer the following:</p>
<pre><code>if a == []:
print "The list is empty."
</code></pre>
<p>Readable and you don't have to worry about calling a function like <code>len()</code> to iterate through the variable. Although I'm not entirely sure what the BigO notation of something like this is... but Python's so blazingly fast I doubt it'd matter unless <code>a</code> was gigantic.</p>
| 4 | 2008-09-10T06:43:14Z | [
"python",
"list"
] |
Best way to check if a list is empty | 53,513 | <p>For example, if passed the following:</p>
<pre><code>a = []
</code></pre>
<p>How do I check to see if <code>a</code> is empty?</p>
| 1,615 | 2008-09-10T06:20:11Z | 53,752 | <p>The pythonic way to do it is from the <a href="https://www.python.org/dev/peps/pep-0008">PEP 8 style guide</a>:</p>
<blockquote>
<p>For sequences, (strings, lists, tuples), use the fact that empty sequences are false.
</p>
<pre><code><b>Yes:</b> if not seq:
if seq:
<b>No:</b> if len(seq):
if not len(seq):
</code></pre>
</blockquote>
| 565 | 2008-09-10T10:33:38Z | [
"python",
"list"
] |
Best way to check if a list is empty | 53,513 | <p>For example, if passed the following:</p>
<pre><code>a = []
</code></pre>
<p>How do I check to see if <code>a</code> is empty?</p>
| 1,615 | 2008-09-10T06:20:11Z | 61,918 | <p><a href="http://books.google.com/books?id=vpTAq4dnmuAC&pg=RA1-PA479&lpg=RA1-PA479&dq=Python+len+big+O&source=web&ots=AOM6A1K9Fy&sig=iQo8mV6Xf9KdzuNSa-Jkr8wDEuw&hl=en&sa=X&oi=book_result&resnum=4&ct=result"><code>len()</code> is an O(1) operation</a> for Python lists, strings, dicts, and sets. Python internally keeps track of the number of elements in these containers.</p>
<p>JavaScript <a href="http://www.isolani.co.uk/blog/javascript/TruthyFalsyAndTypeCasting">has a similar notion of truthy/falsy</a>.</p>
| 28 | 2008-09-15T05:50:48Z | [
"python",
"list"
] |
Best way to check if a list is empty | 53,513 | <p>For example, if passed the following:</p>
<pre><code>a = []
</code></pre>
<p>How do I check to see if <code>a</code> is empty?</p>
| 1,615 | 2008-09-10T06:20:11Z | 7,302,987 | <p>I prefer it explicitly:</p>
<pre><code>if len(li) == 0:
print 'the list is empty'
</code></pre>
<p>This way it's 100% clear that <code>li</code> is a sequence (list) and we want to test its size. My problem with <code>if not li: ...</code> is that it gives the false impression that <code>li</code> is a boolean variable.</p>
| 267 | 2011-09-05T00:30:30Z | [
"python",
"list"
] |
Best way to check if a list is empty | 53,513 | <p>For example, if passed the following:</p>
<pre><code>a = []
</code></pre>
<p>How do I check to see if <code>a</code> is empty?</p>
| 1,615 | 2008-09-10T06:20:11Z | 9,381,545 | <h1>Other methods don't work for numpy arrays</h1>
<p>Other people seem to be generalizing your question beyond just <code>list</code>s, so I thought I'd add a caveat for a different type of sequence that a lot of people might use. You need to be careful with numpy arrays, because other methods that work fine for <code>list</code>s fail for numpy arrays. I explain why below, but in short, the <a href="http://www.scipy.org/scipylib/faq.html#what-is-the-preferred-way-to-check-for-an-empty-zero-element-array">preferred method</a> is to use <code>size</code>.</p>
<h3>The "pythonic" way doesn't work I</h3>
<p>The "pythonic" way fails with numpy arrays because numpy tries to cast the array to an array of <code>bool</code>s, and <code>if x</code> tries to evaluate all of those <code>bool</code>s at once for some kind of aggregate truth value. But this doesn't make any sense, so you get a <code>ValueError</code>:</p>
<pre><code>>>> x = numpy.array([0,1])
>>> if x: print("x")
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
</code></pre>
<h3>The "pythonic" way doesn't work II</h3>
<p>But at least the case above tells you that it failed. If you happen to have a numpy array with exactly one element, the <code>if</code> statement will "work", in the sense that you don't get an error. However, if that one element happens to be <code>0</code> (or <code>0.0</code>, or <code>false</code>, ...), the <code>if</code> statement will incorrectly result in <code>false</code>:</p>
<pre><code>>>> x = numpy.array([0,])
>>> if x: print("x")
... else: print("No x")
No x
</code></pre>
<p>But clearly <code>x</code> exists and is not empty! This result is not what you wanted.</p>
<h3>Using <code>len</code> can give unexpected results</h3>
<p>For example,</p>
<pre><code>len( numpy.zeros((1,0)) )
</code></pre>
<p>returns 1, even though the array has zero elements.</p>
<h3>The numpythonic way</h3>
<p>As explained in the <a href="http://www.scipy.org/scipylib/faq.html#what-is-the-preferred-way-to-check-for-an-empty-zero-element-array">scipy FAQ</a>, the correct method in all cases where you know you have a numpy array is to use <code>if x.size</code>:</p>
<pre><code>>>> x = numpy.array([0,1])
>>> if x.size: print("x")
x
>>> x = numpy.array([0,])
>>> if x.size: print("x")
... else: print("No x")
x
>>> x = numpy.zeros((1,0))
>>> if x.size: print("x")
... else: print("No x")
No x
</code></pre>
<p>If you're not sure whether it might be a <code>list</code>, a numpy array, or something else, you should combine this approach with <a href="http://stackoverflow.com/a/10835703/1194883">the answer @dubiousjim gives</a> to make sure the right test is used for each type. Not very "pythonic", but it turns out that python itself isn't pythonic in this sense either...</p>
| 95 | 2012-02-21T16:48:02Z | [
"python",
"list"
] |
Best way to check if a list is empty | 53,513 | <p>For example, if passed the following:</p>
<pre><code>a = []
</code></pre>
<p>How do I check to see if <code>a</code> is empty?</p>
| 1,615 | 2008-09-10T06:20:11Z | 10,835,703 | <p>I had written:</p>
<pre><code>if isinstance(a, (list, some, other, types, i, accept)) and not a:
do_stuff
</code></pre>
<p>which was voted -1. I'm not sure if that's because readers objected to the strategy or thought the answer wasn't helpful as presented. I'll pretend it was the latter, since---whatever counts as "pythonic"---this is the correct strategy. Unless you've already ruled out, or are prepared to handle cases where <code>a</code> is, for example, <code>False</code>, you need a test more restrictive than just <code>if not a:</code>. You could use something like this:</p>
<pre><code>if isinstance(a, numpy.ndarray) and not a.size:
do_stuff
elif isinstance(a, collections.Sized) and not a:
do_stuff
</code></pre>
<p>the first test is in response to @Mike's answer, above. The third line could also be replaced with:</p>
<pre><code>elif isinstance(a, (list, tuple)) and not a:
</code></pre>
<p>if you only want to accept instances of particular types (and their subtypes), or with:</p>
<pre><code>elif isinstance(a, (list, tuple)) and not len(a):
</code></pre>
<p>You can get away without the explicit type check, but only if the surrounding context already assures you that <code>a</code> is a value of the types you're prepared to handle, or if you're sure that types you're not prepared to handle are going to raise errors (e.g., a <code>TypeError</code> if you call <code>len</code> on a value for which it's undefined) that you're prepared to handle. In general, the "pythonic" conventions seem to go this last way. Squeeze it like a duck and let it raise a DuckError if it doesn't know how to quack. You still have to <em>think</em> about what type assumptions you're making, though, and whether the cases you're not prepared to handle properly really are going to error out in the right places. The Numpy arrays are a good example where just blindly relying on <code>len</code> or the boolean typecast may not do precisely what you're expecting.</p>
| 15 | 2012-05-31T14:35:05Z | [
"python",
"list"
] |
Best way to check if a list is empty | 53,513 | <p>For example, if passed the following:</p>
<pre><code>a = []
</code></pre>
<p>How do I check to see if <code>a</code> is empty?</p>
| 1,615 | 2008-09-10T06:20:11Z | 10,863,668 | <p>Python is very uniform about the treatment of emptiness. Given the following:</p>
<pre><code>a = []
.
.
.
if a:
print("List is not empty.")
else:
print("List is empty.")
</code></pre>
<p>You simply check list a with an "if" statement to see if it is empty. From what I have read and been taught, this is the "Pythonic" way to see if a list or tuple is empty.</p>
| 16 | 2012-06-02T15:40:24Z | [
"python",
"list"
] |
Best way to check if a list is empty | 53,513 | <p>For example, if passed the following:</p>
<pre><code>a = []
</code></pre>
<p>How do I check to see if <code>a</code> is empty?</p>
| 1,615 | 2008-09-10T06:20:11Z | 22,674,207 | <p>A Python list is considered False when it is empty and True when it is not empty.
The following will work quite nicely</p>
<pre><code> if seq:print('List has items')
if not seq:print('List does not have items')
</code></pre>
<p>Also </p>
<pre><code> bool(seq) #will return true if the list has items and false if the list does not.
</code></pre>
<p>This will also work for any python sequences.</p>
| 3 | 2014-03-26T22:16:58Z | [
"python",
"list"
] |
Best way to check if a list is empty | 53,513 | <p>For example, if passed the following:</p>
<pre><code>a = []
</code></pre>
<p>How do I check to see if <code>a</code> is empty?</p>
| 1,615 | 2008-09-10T06:20:11Z | 26,579,625 | <p>some methods what i use:</p>
<pre><code>if not a:
print "list is empty"
if not bool(a):
print "list is empty"
if len(a) == 0:
print "list is empty"
</code></pre>
| 7 | 2014-10-27T00:35:45Z | [
"python",
"list"
] |
Best way to check if a list is empty | 53,513 | <p>For example, if passed the following:</p>
<pre><code>a = []
</code></pre>
<p>How do I check to see if <code>a</code> is empty?</p>
| 1,615 | 2008-09-10T06:20:11Z | 27,262,598 | <p><a href="http://stackoverflow.com/a/53522/908494">Patrick's (accepted) answer</a> is right: <code>if not a:</code> is the right way to do it. <a href="http://stackoverflow.com/a/53752/908494">Harley Holcombe's answer</a> is right that this is in the PEP 8 style guide. But what none of the answers explain is why it's a good idea to follow the idiomâeven if you personally find it's not explicit enough or confusing to Ruby users or whatever.</p>
<p>Python code, and the Python community, has very strong idioms. Following those idioms makes your code easier to read for anyone experienced in Python. And when you violate those idioms, that's a strong signal.</p>
<p>It's true that <code>if not a:</code> doesn't distinguish empty lists from <code>None</code>, or numeric 0, or empty tuples, or empty user-created collection types, or empty user-created not-quite-collection types, or single-element NumPy array acting as scalars with falsey values, etc. And sometimes it's important to be explicit about that. And in that case, you know <em>what</em> you want to be explicit about, so you can test for exactly that. For example, <code>if not a and a is not None:</code> means "anything falsey except None", while <code>if len(a) != 0:</code> means "only empty sequencesâand anything besides a sequence is an error here", and so on. Besides testing for exactly what you want to test, this also signals to the reader that this test is important.</p>
<p>But when you don't have anything to be explicit about, anything other than <code>if not a:</code> is misleading the reader. You're signaling something as important when it isn't. (You may also be making the code less flexible, or slower, or whatever, but that's all less important.) And if you <em>habitually</em> mislead the reader like this, then when you <em>do</em> need to make a distinction, it's going to pass unnoticed because you've been "crying wolf" all over your code.</p>
| 39 | 2014-12-03T02:21:29Z | [
"python",
"list"
] |
Best way to check if a list is empty | 53,513 | <p>For example, if passed the following:</p>
<pre><code>a = []
</code></pre>
<p>How do I check to see if <code>a</code> is empty?</p>
| 1,615 | 2008-09-10T06:20:11Z | 30,272,696 | <p>Try:</p>
<pre><code>if list:
#Not empty
else:
#Empty
</code></pre>
<p><code>if</code> executes the first statement if <code>bool(condition)</code> returns <code>True</code>. <code>bool(condition)</code> returns <code>False</code> if <code>condition</code> is an empty sequence, including a string, 0 or <code>False</code>. If else, it returns <code>True</code>. Actually, I don't know if <code>if</code> works it out like that, but it gets the exact same results.</p>
| 3 | 2015-05-16T06:50:09Z | [
"python",
"list"
] |
Best way to check if a list is empty | 53,513 | <p>For example, if passed the following:</p>
<pre><code>a = []
</code></pre>
<p>How do I check to see if <code>a</code> is empty?</p>
| 1,615 | 2008-09-10T06:20:11Z | 32,978,062 | <p>No one seems to have addressed questioning your <em>need</em> to test the list in the first place. Because you provided no additional context, I can imagine that you may not need to do this check in the first place, but are unfamiliar with list processing in Python.</p>
<p>I would argue that the <em>most pythonic</em> way is to not check at all, but rather to just process the list. That way it will do the right thing whether empty or full.</p>
<pre><code>a = []
for item in a:
<do something with item>
<rest of code>
</code></pre>
<p>This has the benefit of handling any contents of <strong>a</strong>, while not requiring a specific check for emptiness. If <strong>a</strong> is empty, the dependent block will not execute and the interpreter will fall through to the next line.</p>
<p>If you do actually need to check the array for emptiness, the other answers are sufficient.</p>
| 16 | 2015-10-06T19:25:34Z | [
"python",
"list"
] |
Best way to check if a list is empty | 53,513 | <p>For example, if passed the following:</p>
<pre><code>a = []
</code></pre>
<p>How do I check to see if <code>a</code> is empty?</p>
| 1,615 | 2008-09-10T06:20:11Z | 34,558,732 | <p>From <a href="https://docs.python.org/3.5/library/stdtypes.html#truth-value-testing">documentation</a> on truth value testing:</p>
<p>All values other than what is listed here are considered <code>True</code></p>
<ul>
<li><code>None</code></li>
<li><code>False</code></li>
<li>zero of any numeric type, for example, <code>0</code>, <code>0.0</code>, <code>0j</code>.</li>
<li>any empty sequence, for example, <code>''</code>, <code>()</code>, <code>[]</code>.</li>
<li>any empty mapping, for example, <code>{}</code>.</li>
<li>instances of user-defined classes, if the class defines a <code>__bool__()</code> or <code>__len__()</code> method, when that method returns the integer zero or bool value <code>False</code>.</li>
</ul>
<p>As can be seen, empty list <code>[]</code> is <em>falsy</em>, so doing what would be done to a boolean value sounds most efficient:</p>
<pre><code>if not a:
print('"a" is empty!')
</code></pre>
| 10 | 2016-01-01T18:18:58Z | [
"python",
"list"
] |
Best way to check if a list is empty | 53,513 | <p>For example, if passed the following:</p>
<pre><code>a = []
</code></pre>
<p>How do I check to see if <code>a</code> is empty?</p>
| 1,615 | 2008-09-10T06:20:11Z | 35,420,903 | <p>There is of course also</p>
<p><code>print a or "List is empty"</code></p>
| 5 | 2016-02-15T23:18:48Z | [
"python",
"list"
] |
Best way to check if a list is empty | 53,513 | <p>For example, if passed the following:</p>
<pre><code>a = []
</code></pre>
<p>How do I check to see if <code>a</code> is empty?</p>
| 1,615 | 2008-09-10T06:20:11Z | 36,610,301 | <pre><code>def list_test (L):
if L is None : print 'list is None'
elif not L : print 'list is empty'
else: print 'list has %d elements' % len(L)
list_test(None)
list_test([])
list_test([1,2,3])
</code></pre>
<p>It is sometimes good to test for <code>None</code> and for emptiness separately as those are two different states. The code above produces the following output:</p>
<pre><code>list is None
list is empty
list has 3 elements
</code></pre>
<p>Although it's worth nothing that <code>None</code> is falsy. So if you don't want to separate test for <code>None</code>-ness, you don't have to do that. </p>
<pre><code>def list_test2 (L):
if not L : print 'list is empty'
else: print 'list has %d elements' % len(L)
list_test2(None)
list_test2([])
list_test2([1,2,3])
</code></pre>
<p>produces expected</p>
<pre><code>list is empty
list is empty
list has 3 elements
</code></pre>
| 3 | 2016-04-13T21:55:32Z | [
"python",
"list"
] |
Best way to check if a list is empty | 53,513 | <p>For example, if passed the following:</p>
<pre><code>a = []
</code></pre>
<p>How do I check to see if <code>a</code> is empty?</p>
| 1,615 | 2008-09-10T06:20:11Z | 37,008,449 | <p>You could also do :</p>
<pre><code>if len(a_list):
print "it's not empty"
</code></pre>
| 5 | 2016-05-03T15:35:09Z | [
"python",
"list"
] |
Best way to check if a list is empty | 53,513 | <p>For example, if passed the following:</p>
<pre><code>a = []
</code></pre>
<p>How do I check to see if <code>a</code> is empty?</p>
| 1,615 | 2008-09-10T06:20:11Z | 37,353,236 | <p>The preferred way to check if any list, dictionary, set, string or tuple is empty in Python is to simply use an if statement to check it.</p>
<pre><code>def is_empty(any_structure):
if any_structure:
print('Structure is not empty.')
return False
else:
print('Structure is empty.')
return True
</code></pre>
| -3 | 2016-05-20T18:11:01Z | [
"python",
"list"
] |
Best way to check if a list is empty | 53,513 | <p>For example, if passed the following:</p>
<pre><code>a = []
</code></pre>
<p>How do I check to see if <code>a</code> is empty?</p>
| 1,615 | 2008-09-10T06:20:11Z | 38,492,895 | <pre><code>a = []
# First way
if a:
print 'yes'
else:
print 'no'
# Second way
if len(a) != 0:
print 'yes'
else:
print 'no'
</code></pre>
| 0 | 2016-07-21T00:24:05Z | [
"python",
"list"
] |
Best way to check if a list is empty | 53,513 | <p>For example, if passed the following:</p>
<pre><code>a = []
</code></pre>
<p>How do I check to see if <code>a</code> is empty?</p>
| 1,615 | 2008-09-10T06:20:11Z | 38,592,561 | <p>you can use try and except as it is cheaper than if else construct</p>
<pre><code>a=[]
try:
x=a[0]
except:
print(' list is empty')
</code></pre>
| -2 | 2016-07-26T14:25:29Z | [
"python",
"list"
] |
Best way to check if a list is empty | 53,513 | <p>For example, if passed the following:</p>
<pre><code>a = []
</code></pre>
<p>How do I check to see if <code>a</code> is empty?</p>
| 1,615 | 2008-09-10T06:20:11Z | 39,469,420 | <p>You can even try using bool() like this</p>
<pre><code> a = [1,2,3];
print bool(a); # it will return True
a = [];
print bool(a); # it will return False
</code></pre>
<p>I love this way for checking list is empty or not. </p>
<p>Very handy and useful.</p>
| 0 | 2016-09-13T11:53:56Z | [
"python",
"list"
] |
Best way to check if a list is empty | 53,513 | <p>For example, if passed the following:</p>
<pre><code>a = []
</code></pre>
<p>How do I check to see if <code>a</code> is empty?</p>
| 1,615 | 2008-09-10T06:20:11Z | 39,598,495 | <p>Demo: </p>
<pre><code>tasks = ['task1', 'task2']
# create new list
if len(tasks) == False:
print("empty")
'''
# There are many ways to check whether a List/Tuples/String is empty!
# method 1:
# if len(tasks) is False:
# method 2:
# if len(tasks) == False:
# method 3:
# if len(tasks) == 0:
# method 4:
# if len(tasks) is 0:
# method 5:
# if not tasks:
# method 6:
# if bool(tasks):
# method others ...
</code></pre>
<p><a href="http://i.stack.imgur.com/DORnA.png" rel="nofollow"><img src="http://i.stack.imgur.com/DORnA.png" alt="enter image description here"></a></p>
| 0 | 2016-09-20T15:45:59Z | [
"python",
"list"
] |
What are some strategies to write python code that works in CPython, Jython and IronPython | 53,543 | <p>Having tries to target two of these environments at the same time I can safely say the if you have to use a database etc. you end up having to write unique code for that environment. Have you got a great way to handle this situation?</p>
| 15 | 2008-09-10T07:04:43Z | 53,549 | <p>If you <em>do</em> find you need to write unique code for an environment, use pythons </p>
<pre><code>import mymodule_jython as mymodule
import mymodule_cpython as mymodule
</code></pre>
<p>have this stuff in a simple module (''module_importer''?) and write your code like this:</p>
<pre><code>from module_importer import mymodule
</code></pre>
<p>This way, all you need to do is alter <code>module_importer.py</code> per platform.</p>
| 14 | 2008-09-10T07:07:59Z | [
"python",
"ironpython",
"jython",
"cpython"
] |
What are some strategies to write python code that works in CPython, Jython and IronPython | 53,543 | <p>Having tries to target two of these environments at the same time I can safely say the if you have to use a database etc. you end up having to write unique code for that environment. Have you got a great way to handle this situation?</p>
| 15 | 2008-09-10T07:04:43Z | 55,312 | <p>@<a href="#53549" rel="nofollow">Daren Thomas</a>: I agree, but you should use the <a href="http://docs.python.org/dev/library/platform.html#platform.python_implementation" rel="nofollow">platform module</a> to determine which interpreter you're running.</p>
| 10 | 2008-09-10T21:00:04Z | [
"python",
"ironpython",
"jython",
"cpython"
] |
What are some strategies to write python code that works in CPython, Jython and IronPython | 53,543 | <p>Having tries to target two of these environments at the same time I can safely say the if you have to use a database etc. you end up having to write unique code for that environment. Have you got a great way to handle this situation?</p>
| 15 | 2008-09-10T07:04:43Z | 199,275 | <p>I write code for CPython and IronPython but tip should work for Jython as well.</p>
<p>Basically, I write all the platform specific code in separate modules/packages and then import the appropriate one based on platform I'm running on. (see cdleary's comment above)</p>
<p>This is especially important when it comes to the differences between the SQLite implementations and if you are implementing any GUI code.</p>
| 2 | 2008-10-13T22:33:17Z | [
"python",
"ironpython",
"jython",
"cpython"
] |
What are some strategies to write python code that works in CPython, Jython and IronPython | 53,543 | <p>Having tries to target two of these environments at the same time I can safely say the if you have to use a database etc. you end up having to write unique code for that environment. Have you got a great way to handle this situation?</p>
| 15 | 2008-09-10T07:04:43Z | 342,835 | <p>The #1 thing IMO: <strong>Focus on thread safety</strong>. CPython's GIL makes writing threadsafe code easy because only one thread can access the interpreter at a time. IronPython and Jython are a little less hand-holding though.</p>
| 1 | 2008-12-05T03:35:43Z | [
"python",
"ironpython",
"jython",
"cpython"
] |
What are some strategies to write python code that works in CPython, Jython and IronPython | 53,543 | <p>Having tries to target two of these environments at the same time I can safely say the if you have to use a database etc. you end up having to write unique code for that environment. Have you got a great way to handle this situation?</p>
| 15 | 2008-09-10T07:04:43Z | 342,845 | <p>I'm pretty sure you already know this but unfortunately Jython <a href="http://www.jython.org/Project/userfaq.html#is-jython-the-same-language-as-python" rel="nofollow">can't load c extension modules.</a></p>
| 0 | 2008-12-05T03:41:37Z | [
"python",
"ironpython",
"jython",
"cpython"
] |
What are some strategies to write python code that works in CPython, Jython and IronPython | 53,543 | <p>Having tries to target two of these environments at the same time I can safely say the if you have to use a database etc. you end up having to write unique code for that environment. Have you got a great way to handle this situation?</p>
| 15 | 2008-09-10T07:04:43Z | 637,549 | <p>There are two <em>major</em> issues at play here...</p>
<p>Firstly, to my knowledge, only CPython has RAII - you have to close your own resources in Jython, Ironpython, etc.</p>
<p>And Secondly, as has been mentioned, is thread safety.</p>
| 0 | 2009-03-12T06:11:27Z | [
"python",
"ironpython",
"jython",
"cpython"
] |
How do i generate a histogram for a given probability distribution (for functional testing a server)? | 53,786 | <p>I am trying to automate functional testing of a server using a realistic frequency distribution of requests. (sort of load testing, sort of simulation)</p>
<p>I've chosen the <a href="http://en.wikipedia.org/wiki/Weibull_distribution" rel="nofollow">Weibull</a> distribution as it "sort of" matches the distribution I've observed (ramps up quickly, drops off quickly but not instantly)</p>
<p>I use this distribution to generate the number of requests that should be sent each day between a given start and end date</p>
<p>I've hacked together an algorithm in Python that sort of works but it feels kludgy:</p>
<pre><code>how_many_days = (end_date - start_date).days
freqs = defaultdict(int)
for x in xrange(how_many_responses):
freqs[int(how_many_days * weibullvariate(0.5, 2))] += 1
timeline = []
day = start_date
for i,freq in sorted(freqs.iteritems()):
timeline.append((day, freq))
day += timedelta(days=1)
return timeline
</code></pre>
<p>What better ways are there to do this? </p>
| 3 | 2008-09-10T11:16:30Z | 53,791 | <p>Why don't you try <a href="http://grinder.sourceforge.net" rel="nofollow">The Grinder 3</a> to load test your server, it comes with all this and more prebuilt, and it supports python as a scripting language</p>
| 1 | 2008-09-10T11:20:27Z | [
"python",
"statistics",
"simulation",
"stress-testing"
] |
How do i generate a histogram for a given probability distribution (for functional testing a server)? | 53,786 | <p>I am trying to automate functional testing of a server using a realistic frequency distribution of requests. (sort of load testing, sort of simulation)</p>
<p>I've chosen the <a href="http://en.wikipedia.org/wiki/Weibull_distribution" rel="nofollow">Weibull</a> distribution as it "sort of" matches the distribution I've observed (ramps up quickly, drops off quickly but not instantly)</p>
<p>I use this distribution to generate the number of requests that should be sent each day between a given start and end date</p>
<p>I've hacked together an algorithm in Python that sort of works but it feels kludgy:</p>
<pre><code>how_many_days = (end_date - start_date).days
freqs = defaultdict(int)
for x in xrange(how_many_responses):
freqs[int(how_many_days * weibullvariate(0.5, 2))] += 1
timeline = []
day = start_date
for i,freq in sorted(freqs.iteritems()):
timeline.append((day, freq))
day += timedelta(days=1)
return timeline
</code></pre>
<p>What better ways are there to do this? </p>
| 3 | 2008-09-10T11:16:30Z | 56,032 | <p>Instead of giving the number of requests as a fixed value, why not use a scaling factor instead? At the moment, you're treating requests as a limited quantity, and randomising the days on which those requests fall. It would seem more reasonable to treat your requests-per-day as independent.</p>
<pre><code>from datetime import *
from random import *
timeline = []
scaling = 10
start_date = date(2008, 5, 1)
end_date = date(2008, 6, 1)
num_days = (end_date - start_date).days + 1
days = [start_date + timedelta(i) for i in range(num_days)]
requests = [int(scaling * weibullvariate(0.5, 2)) for i in range(num_days)]
timeline = zip(days, requests)
timeline
</code></pre>
| 0 | 2008-09-11T08:30:23Z | [
"python",
"statistics",
"simulation",
"stress-testing"
] |
How do i generate a histogram for a given probability distribution (for functional testing a server)? | 53,786 | <p>I am trying to automate functional testing of a server using a realistic frequency distribution of requests. (sort of load testing, sort of simulation)</p>
<p>I've chosen the <a href="http://en.wikipedia.org/wiki/Weibull_distribution" rel="nofollow">Weibull</a> distribution as it "sort of" matches the distribution I've observed (ramps up quickly, drops off quickly but not instantly)</p>
<p>I use this distribution to generate the number of requests that should be sent each day between a given start and end date</p>
<p>I've hacked together an algorithm in Python that sort of works but it feels kludgy:</p>
<pre><code>how_many_days = (end_date - start_date).days
freqs = defaultdict(int)
for x in xrange(how_many_responses):
freqs[int(how_many_days * weibullvariate(0.5, 2))] += 1
timeline = []
day = start_date
for i,freq in sorted(freqs.iteritems()):
timeline.append((day, freq))
day += timedelta(days=1)
return timeline
</code></pre>
<p>What better ways are there to do this? </p>
| 3 | 2008-09-10T11:16:30Z | 56,102 | <p>I rewrote the code above to be shorter (but maybe it's too obfuscated now?)</p>
<pre><code>timeline = (start_date + timedelta(days=days) for days in count(0))
how_many_days = (end_date - start_date).days
pick_a_day = lambda _:int(how_many_days * weibullvariate(0.5, 2))
days = sorted(imap(pick_a_day, xrange(how_many_responses)))
histogram = zip(timeline, (len(list(responses)) for day, responses in groupby(days)))
print '\n'.join((d.strftime('%Y-%m-%d ') + "*" * c) for d,c in histogram)
</code></pre>
| 0 | 2008-09-11T09:11:50Z | [
"python",
"statistics",
"simulation",
"stress-testing"
] |
How do i generate a histogram for a given probability distribution (for functional testing a server)? | 53,786 | <p>I am trying to automate functional testing of a server using a realistic frequency distribution of requests. (sort of load testing, sort of simulation)</p>
<p>I've chosen the <a href="http://en.wikipedia.org/wiki/Weibull_distribution" rel="nofollow">Weibull</a> distribution as it "sort of" matches the distribution I've observed (ramps up quickly, drops off quickly but not instantly)</p>
<p>I use this distribution to generate the number of requests that should be sent each day between a given start and end date</p>
<p>I've hacked together an algorithm in Python that sort of works but it feels kludgy:</p>
<pre><code>how_many_days = (end_date - start_date).days
freqs = defaultdict(int)
for x in xrange(how_many_responses):
freqs[int(how_many_days * weibullvariate(0.5, 2))] += 1
timeline = []
day = start_date
for i,freq in sorted(freqs.iteritems()):
timeline.append((day, freq))
day += timedelta(days=1)
return timeline
</code></pre>
<p>What better ways are there to do this? </p>
| 3 | 2008-09-10T11:16:30Z | 56,247 | <p>Slightly longer but probably more readable rework of your last four lines:</p>
<pre><code>samples = [0 for i in xrange(how_many_days + 1)]
for s in xrange(how_many_responses):
samples[min(int(how_many_days * weibullvariate(0.5, 2)), how_many_days)] += 1
histogram = zip(timeline, samples)
print '\n'.join((d.strftime('%Y-%m-%d ') + "*" * c) for d,c in histogram)
</code></pre>
<p>This always drops the samples within the date range, but you get a corresponding bump at the end of the timeline from all of the samples that are above the [0, 1] range.</p>
| 1 | 2008-09-11T10:47:06Z | [
"python",
"statistics",
"simulation",
"stress-testing"
] |
How do i generate a histogram for a given probability distribution (for functional testing a server)? | 53,786 | <p>I am trying to automate functional testing of a server using a realistic frequency distribution of requests. (sort of load testing, sort of simulation)</p>
<p>I've chosen the <a href="http://en.wikipedia.org/wiki/Weibull_distribution" rel="nofollow">Weibull</a> distribution as it "sort of" matches the distribution I've observed (ramps up quickly, drops off quickly but not instantly)</p>
<p>I use this distribution to generate the number of requests that should be sent each day between a given start and end date</p>
<p>I've hacked together an algorithm in Python that sort of works but it feels kludgy:</p>
<pre><code>how_many_days = (end_date - start_date).days
freqs = defaultdict(int)
for x in xrange(how_many_responses):
freqs[int(how_many_days * weibullvariate(0.5, 2))] += 1
timeline = []
day = start_date
for i,freq in sorted(freqs.iteritems()):
timeline.append((day, freq))
day += timedelta(days=1)
return timeline
</code></pre>
<p>What better ways are there to do this? </p>
| 3 | 2008-09-10T11:16:30Z | 56,548 | <p>This is quick and probably not that accurate, but if you calculate the PDF yourself, then at least you make it easier to lay several smaller/larger ones on a single timeline. <code>dev</code> is the std deviation in the Guassian noise, which controls the roughness. Note that this is <em>not</em> the 'right' way to generate what you want, but it's easy.</p>
<pre><code>import math
from datetime import datetime, timedelta, date
from random import gauss
how_many_responses = 1000
start_date = date(2008, 5, 1)
end_date = date(2008, 6, 1)
num_days = (end_date - start_date).days + 1
timeline = [start_date + timedelta(i) for i in xrange(num_days)]
def weibull(x, k, l):
return (k / l) * (x / l)**(k-1) * math.e**(-(x/l)**k)
dev = 0.1
samples = [i * 1.25/(num_days-1) for i in range(num_days)]
probs = [weibull(i, 2, 0.5) for i in samples]
noise = [gauss(0, dev) for i in samples]
simdata = [max(0., e + n) for (e, n) in zip(probs, noise)]
events = [int(p * (how_many_responses / sum(probs))) for p in simdata]
histogram = zip(timeline, events)
print '\n'.join((d.strftime('%Y-%m-%d ') + "*" * c) for d,c in histogram)
</code></pre>
| 1 | 2008-09-11T13:40:31Z | [
"python",
"statistics",
"simulation",
"stress-testing"
] |
How do i generate a histogram for a given probability distribution (for functional testing a server)? | 53,786 | <p>I am trying to automate functional testing of a server using a realistic frequency distribution of requests. (sort of load testing, sort of simulation)</p>
<p>I've chosen the <a href="http://en.wikipedia.org/wiki/Weibull_distribution" rel="nofollow">Weibull</a> distribution as it "sort of" matches the distribution I've observed (ramps up quickly, drops off quickly but not instantly)</p>
<p>I use this distribution to generate the number of requests that should be sent each day between a given start and end date</p>
<p>I've hacked together an algorithm in Python that sort of works but it feels kludgy:</p>
<pre><code>how_many_days = (end_date - start_date).days
freqs = defaultdict(int)
for x in xrange(how_many_responses):
freqs[int(how_many_days * weibullvariate(0.5, 2))] += 1
timeline = []
day = start_date
for i,freq in sorted(freqs.iteritems()):
timeline.append((day, freq))
day += timedelta(days=1)
return timeline
</code></pre>
<p>What better ways are there to do this? </p>
| 3 | 2008-09-10T11:16:30Z | 89,140 | <p>Another solution is to use <a href="http://rpy.sourceforge.net/" rel="nofollow">Rpy</a>, which puts all of the power of R (including lots of tools for distributions), easily into Python. </p>
| 0 | 2008-09-18T01:16:20Z | [
"python",
"statistics",
"simulation",
"stress-testing"
] |
Any good AJAX framework for Google App Engine apps? | 53,997 | <p>I am trying to implement AJAX in my Google App Engine application, and so I am looking for a good AJAX framework that will help me. Anyone has any idea?</p>
<p>I am thinking about Google Web Toolkit, how good it is in terms of creating AJAX for Google App Engine?</p>
| 12 | 2008-09-10T13:12:07Z | 54,008 | <p>As Google Web Toolkit is a <a href="http://code.google.com/support/bin/answer.py?answer=54830&topic=10208" rel="nofollow">subset of Java</a> it works best when you Java at the backend too. Since Google App Engine is currently <a href="http://code.google.com/appengine/kb/general.html#language" rel="nofollow">Python only</a> I think you'd have to do a lot of messing about to get your server and client to talk nicely to each other.</p>
<p>jQuery seems to be the most popular JavaScript library option in the <a href="http://www.djangosnippets.org/tags/ajax/?page=1" rel="nofollow">AJAX Tag at DjangoSnippets.com</a>.</p>
<p><strong>Edit:</strong> The above is only true of Google App Engine applications written in Python. As Google App Engine now supports Java, GWT could now be a good choice for writing an AJAX front end. <a href="http://code.google.com/webtoolkit/doc/latest/tutorial/appengine.html" rel="nofollow">Google even have a tutorial showing you how to do it.</a></p>
| 12 | 2008-09-10T13:14:54Z | [
"python",
"ajax",
"google-app-engine"
] |
Any good AJAX framework for Google App Engine apps? | 53,997 | <p>I am trying to implement AJAX in my Google App Engine application, and so I am looking for a good AJAX framework that will help me. Anyone has any idea?</p>
<p>I am thinking about Google Web Toolkit, how good it is in terms of creating AJAX for Google App Engine?</p>
| 12 | 2008-09-10T13:12:07Z | 54,015 | <p>I'd recommend looking into a pure javascript framework (probably Jquery) for your client-side code, and write JSON services in python- that seems to be the easiest / bestest way to go.</p>
<p>Google Web Toolkit lets you write the UI in Java and compile it to javascript. As Dave says, it may be a better choice where the backend is in Java, as it has nice RPC hooks for that case.</p>
| 3 | 2008-09-10T13:19:51Z | [
"python",
"ajax",
"google-app-engine"
] |