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
list |
|---|---|---|---|---|---|---|---|---|---|
FOSS HTML to PDF in Python, .Net or command line?
| 597,348
|
<p>I have google as much as I possible, checked stackoverflow several times, and yet I can not find a good <strong>html to pdf converter</strong> that can handle css. Is there a free and open source solution (even for commercial usage)? There are many solutions, with huge variety of price ranges, but I was looking for something open source and free. I have tried PISA for Python and it works fairly well, but is not free for commercial usage. Is there anything for .Net? I have not had success with iTextSharp. </p>
| 0
|
2009-02-28T01:56:26Z
| 597,368
|
<p>The fact that you're asking about C#/.NET makes me guess you're on a Windows platform, so this may not work for you, but I've had decent success using <a href="http://user.it.uu.se/~jan/html2ps.html" rel="nofollow"><strong>html2ps</strong></a> in conjunction with <a href="http://pages.cs.wisc.edu/~ghost/doc/AFPL/6.50/Ps2pdf.htm" rel="nofollow"><strong>ps2pdf</strong></a>: </p>
<pre><code>#! /bin/sh
TEMPDIR="/tmp"
html2ps -u $1 > $TEMPDIR'temp.ps'
ps2pdf $TEMPDIR'temp.ps' $2
</code></pre>
<p>That does handle CSS (at least all the CSS I've thrown at it so far) though there are some limitations if I remember right with regards to some in-line styles.</p>
<p><strong>NOTE</strong>: I think these are both available on Windows via Cygwin, if that's an acceptable solution for you.</p>
| 1
|
2009-02-28T02:12:59Z
|
[
"c#",
".net",
"python",
"html-to-pdf"
] |
FOSS HTML to PDF in Python, .Net or command line?
| 597,348
|
<p>I have google as much as I possible, checked stackoverflow several times, and yet I can not find a good <strong>html to pdf converter</strong> that can handle css. Is there a free and open source solution (even for commercial usage)? There are many solutions, with huge variety of price ranges, but I was looking for something open source and free. I have tried PISA for Python and it works fairly well, but is not free for commercial usage. Is there anything for .Net? I have not had success with iTextSharp. </p>
| 0
|
2009-02-28T01:56:26Z
| 597,840
|
<p>You can also try different approach like using virtual printers.</p>
| 0
|
2009-02-28T10:32:41Z
|
[
"c#",
".net",
"python",
"html-to-pdf"
] |
FOSS HTML to PDF in Python, .Net or command line?
| 597,348
|
<p>I have google as much as I possible, checked stackoverflow several times, and yet I can not find a good <strong>html to pdf converter</strong> that can handle css. Is there a free and open source solution (even for commercial usage)? There are many solutions, with huge variety of price ranges, but I was looking for something open source and free. I have tried PISA for Python and it works fairly well, but is not free for commercial usage. Is there anything for .Net? I have not had success with iTextSharp. </p>
| 0
|
2009-02-28T01:56:26Z
| 2,589,983
|
<p>I have had stunning success using the 'PISA' xhtml2pdf tool found here: <a href="http://www.xhtml2pdf.com/" rel="nofollow">http://www.xhtml2pdf.com/</a></p>
<p>Don't be scared off by the 'xhtml' part, it accepts a large range of html input, and produces PDFs according to CSS, including CSS print extensions.</p>
| 0
|
2010-04-07T04:24:09Z
|
[
"c#",
".net",
"python",
"html-to-pdf"
] |
How to create MS Paint clone with Python and pygame
| 597,369
|
<p>As I see it, there are two ways to handle mouse events to draw a picture.</p>
<p>The first is to detect when the mouse moves and draw a line to where the mouse is, shown <a href="http://www.cs.iupui.edu/~aharris/pygame/ch05/paint.py">here</a>. However, the problem with this is that with a large brush size, many gaps appear between each "line" that is not straight since it is using the line's stroke size to create thick lines.</p>
<p>The other way is to draw circles when the mouse moves as is shown <a href="http://www.ida.liu.se/~ETE257/timetable/LecturePythonPygame2.html">here</a>. The problem with this is that gaps appear between each circle if the mouse moves faster than the computer detects mouse input.</p>
<p>Here's a screenshot with my issues with both:</p>
<p><img src="http://i.stack.imgur.com/7ILzZ.png" alt="http://imgur.com/32DXN.jpg"></p>
<p>What is the best way to implement a brush like MS Paint's, with a decently-big brush size with no gaps in the stroke of the line or no gaps between each circle?</p>
| 9
|
2009-02-28T02:13:08Z
| 597,401
|
<p>Why not do both?</p>
<p>Draw a circle at each endpoint and a line between the two.</p>
<p><strong>EDIT</strong> rofl, just couldn't stop myself. </p>
<p>Actually, you don't want to use pygame.draw.line because it cheats. It fills a 1 pixel wide row or column (depending on angle of attack) of pixels. If you do go at a roughly perpendicular angle, 0 deg or 90 deg, this isn't an issue, but at 45's, you'll notice a sort of 'string bean' effect.</p>
<p>The only solution is to draw a circle at every pixel's distance. Here...</p>
<pre><code>import pygame, random
screen = pygame.display.set_mode((800,600))
draw_on = False
last_pos = (0, 0)
color = (255, 128, 0)
radius = 10
def roundline(srf, color, start, end, radius=1):
dx = end[0]-start[0]
dy = end[1]-start[1]
distance = max(abs(dx), abs(dy))
for i in range(distance):
x = int( start[0]+float(i)/distance*dx)
y = int( start[1]+float(i)/distance*dy)
pygame.draw.circle(srf, color, (x, y), radius)
try:
while True:
e = pygame.event.wait()
if e.type == pygame.QUIT:
raise StopIteration
if e.type == pygame.MOUSEBUTTONDOWN:
color = (random.randrange(256), random.randrange(256), random.randrange(256))
pygame.draw.circle(screen, color, e.pos, radius)
draw_on = True
if e.type == pygame.MOUSEBUTTONUP:
draw_on = False
if e.type == pygame.MOUSEMOTION:
if draw_on:
pygame.draw.circle(screen, color, e.pos, radius)
roundline(screen, color, e.pos, last_pos, radius)
last_pos = e.pos
pygame.display.flip()
except StopIteration:
pass
pygame.quit()
</code></pre>
| 11
|
2009-02-28T02:50:16Z
|
[
"python",
"mouse",
"pygame",
"draw",
"paint"
] |
How to create MS Paint clone with Python and pygame
| 597,369
|
<p>As I see it, there are two ways to handle mouse events to draw a picture.</p>
<p>The first is to detect when the mouse moves and draw a line to where the mouse is, shown <a href="http://www.cs.iupui.edu/~aharris/pygame/ch05/paint.py">here</a>. However, the problem with this is that with a large brush size, many gaps appear between each "line" that is not straight since it is using the line's stroke size to create thick lines.</p>
<p>The other way is to draw circles when the mouse moves as is shown <a href="http://www.ida.liu.se/~ETE257/timetable/LecturePythonPygame2.html">here</a>. The problem with this is that gaps appear between each circle if the mouse moves faster than the computer detects mouse input.</p>
<p>Here's a screenshot with my issues with both:</p>
<p><img src="http://i.stack.imgur.com/7ILzZ.png" alt="http://imgur.com/32DXN.jpg"></p>
<p>What is the best way to implement a brush like MS Paint's, with a decently-big brush size with no gaps in the stroke of the line or no gaps between each circle?</p>
| 9
|
2009-02-28T02:13:08Z
| 5,690,387
|
<p>For the first problem, you need have a background, even if its just a color. I had the same problem with a replica pong game i made. Here is an example of a replica paint program I made, left click to draw, right click to erase, click on the color image to choose a color, and up button to clear screen:</p>
<pre><code>import os
os.environ['SDL_VIDEO_CENTERED'] = '1'
from pygamehelper import *
from pygame import *
from pygame.locals import *
from vec2d import *
from math import e, pi, cos, sin, sqrt
from random import uniform
class Starter(PygameHelper):
def __init__(self):
self.w, self.h = 800, 600
PygameHelper.__init__(self, size=(self.w, self.h), fill=((255,255,255)))
self.img= pygame.image.load("colors.png")
self.screen.blit(self.img, (0,0))
self.drawcolor= (0,0,0)
self.x= 0
def update(self):
pass
def keyUp(self, key):
if key==K_UP:
self.screen.fill((255,255,255))
self.screen.blit(self.img, (0,0))
def mouseUp(self, button, pos):
pass
def mouseMotion(self, buttons, pos, rel):
if pos[1]>=172:
if buttons[0]==1:
#pygame.draw.circle(self.screen, (0,0,0), pos, 5)
pygame.draw.line(self.screen, self.drawcolor, pos, (pos[0]-rel[0], pos[1]-rel[1]),5)
if buttons[2]==1:
pygame.draw.circle(self.screen, (255,255,255), pos, 30)
if buttons[1]==1:
#RAINBOW MODE
color= self.screen.get_at((self.x, 0))
pygame.draw.line(self.screen, color, pos, (pos[0]-rel[0], pos[1]-rel[1]), 5)
self.x+= 1
if self.x>172: self.x=0
else:
if pos[0]<172:
if buttons[0]==1:
self.drawcolor= self.screen.get_at(pos)
pygame.draw.circle(self.screen, self.drawcolor, (250, 100), 30)
def draw(self):
pass
#self.screen.fill((255,255,255))
#pygame.draw.circle(self.screen, (0,0,0), (50,100), 20)
s = Starter()
s.mainLoop(40)
</code></pre>
| 1
|
2011-04-16T23:31:12Z
|
[
"python",
"mouse",
"pygame",
"draw",
"paint"
] |
How to create MS Paint clone with Python and pygame
| 597,369
|
<p>As I see it, there are two ways to handle mouse events to draw a picture.</p>
<p>The first is to detect when the mouse moves and draw a line to where the mouse is, shown <a href="http://www.cs.iupui.edu/~aharris/pygame/ch05/paint.py">here</a>. However, the problem with this is that with a large brush size, many gaps appear between each "line" that is not straight since it is using the line's stroke size to create thick lines.</p>
<p>The other way is to draw circles when the mouse moves as is shown <a href="http://www.ida.liu.se/~ETE257/timetable/LecturePythonPygame2.html">here</a>. The problem with this is that gaps appear between each circle if the mouse moves faster than the computer detects mouse input.</p>
<p>Here's a screenshot with my issues with both:</p>
<p><img src="http://i.stack.imgur.com/7ILzZ.png" alt="http://imgur.com/32DXN.jpg"></p>
<p>What is the best way to implement a brush like MS Paint's, with a decently-big brush size with no gaps in the stroke of the line or no gaps between each circle?</p>
| 9
|
2009-02-28T02:13:08Z
| 5,900,836
|
<p>Not blitting at each loop step can improve the speed of the drawing (using this code adapted from the previous one allow to remove lag problem on my machine)</p>
<pre><code>import pygame, random
screen = pygame.display.set_mode((800,600))
draw_on = False
last_pos = (0, 0)
color = (255, 128, 0)
radius = 10
def roundline(srf, color, start, end, radius=1):
dx = end[0]-start[0]
dy = end[1]-start[1]
distance = max(abs(dx), abs(dy))
for i in range(distance):
x = int( start[0]+float(i)/distance*dx)
y = int( start[1]+float(i)/distance*dy)
pygame.display.update(pygame.draw.circle(srf, color, (x, y), radius))
try:
while True:
e = pygame.event.wait()
if e.type == pygame.QUIT:
raise StopIteration
if e.type == pygame.MOUSEBUTTONDOWN:
color = (random.randrange(256), random.randrange(256), random.randrange(256))
pygame.draw.circle(screen, color, e.pos, radius)
draw_on = True
if e.type == pygame.MOUSEBUTTONUP:
draw_on = False
if e.type == pygame.MOUSEMOTION:
if draw_on:
pygame.display.update(pygame.draw.circle(screen, color, e.pos, radius))
roundline(screen, color, e.pos, last_pos, radius)
last_pos = e.pos
#pygame.display.flip()
except StopIteration:
pass
pygame.quit()
</code></pre>
| 2
|
2011-05-05T16:04:42Z
|
[
"python",
"mouse",
"pygame",
"draw",
"paint"
] |
How to concisely cascade through multiple regex statements in Python
| 597,476
|
<p>My dilemma: I'm passing my function a string that I need to then perform numerous regex manipulations on. The logic is if there's a match in the first regex, do one thing. If no match, check for a match with the second and do something else, if not check the third, and so forth. I could do something like this:</p>
<pre><code>if re.match('regex1', string):
match = re.match('regex1', string)
# Manipulate match.group(n) and return
elif re.match('regex2', string):
match = re.match('regex2', string)
# Do second manipulation
[etc.]
</code></pre>
<p>However, this feels unnecessarily verbose, and usually when that's the case it means there's a better way that I'm either overlooking or don't yet know about.</p>
<p>Does anyone have a suggestion for a better way to do this (better from a code-appearance standpoint, a memory usage standpoint, or both)?</p>
| 6
|
2009-02-28T04:06:31Z
| 597,485
|
<p>Hmm... you could use something with the <strong><code>with</code></strong> construct... um</p>
<pre><code>class rewrapper()
def __init__(self, pattern, target):
something
def __enter__(self):
something
def __exit__(self):
something
with rewrapper("regex1", string) as match:
etc
with rewrapper("regex2", string) as match:
and so forth
</code></pre>
| 0
|
2009-02-28T04:24:22Z
|
[
"python",
"regex",
"coding-style"
] |
How to concisely cascade through multiple regex statements in Python
| 597,476
|
<p>My dilemma: I'm passing my function a string that I need to then perform numerous regex manipulations on. The logic is if there's a match in the first regex, do one thing. If no match, check for a match with the second and do something else, if not check the third, and so forth. I could do something like this:</p>
<pre><code>if re.match('regex1', string):
match = re.match('regex1', string)
# Manipulate match.group(n) and return
elif re.match('regex2', string):
match = re.match('regex2', string)
# Do second manipulation
[etc.]
</code></pre>
<p>However, this feels unnecessarily verbose, and usually when that's the case it means there's a better way that I'm either overlooking or don't yet know about.</p>
<p>Does anyone have a suggestion for a better way to do this (better from a code-appearance standpoint, a memory usage standpoint, or both)?</p>
| 6
|
2009-02-28T04:06:31Z
| 597,487
|
<p>Are the manipulations for each regex similar? If so, try this:</p>
<pre><code>for regex in ('regex1', 'regex2', 'regex3', 'regex4'):
match = re.match(regex, string)
if match:
# Manipulate match.group(n)
return result
</code></pre>
| 0
|
2009-02-28T04:25:47Z
|
[
"python",
"regex",
"coding-style"
] |
How to concisely cascade through multiple regex statements in Python
| 597,476
|
<p>My dilemma: I'm passing my function a string that I need to then perform numerous regex manipulations on. The logic is if there's a match in the first regex, do one thing. If no match, check for a match with the second and do something else, if not check the third, and so forth. I could do something like this:</p>
<pre><code>if re.match('regex1', string):
match = re.match('regex1', string)
# Manipulate match.group(n) and return
elif re.match('regex2', string):
match = re.match('regex2', string)
# Do second manipulation
[etc.]
</code></pre>
<p>However, this feels unnecessarily verbose, and usually when that's the case it means there's a better way that I'm either overlooking or don't yet know about.</p>
<p>Does anyone have a suggestion for a better way to do this (better from a code-appearance standpoint, a memory usage standpoint, or both)?</p>
| 6
|
2009-02-28T04:06:31Z
| 597,492
|
<p>Here your regexs and matches are not repeated twice:</p>
<pre><code>match = re.match('regex1', string)
if match:
# do stuff
return
match = re.match('regex2', string)
if match:
# do stuff
return
</code></pre>
| 0
|
2009-02-28T04:30:40Z
|
[
"python",
"regex",
"coding-style"
] |
How to concisely cascade through multiple regex statements in Python
| 597,476
|
<p>My dilemma: I'm passing my function a string that I need to then perform numerous regex manipulations on. The logic is if there's a match in the first regex, do one thing. If no match, check for a match with the second and do something else, if not check the third, and so forth. I could do something like this:</p>
<pre><code>if re.match('regex1', string):
match = re.match('regex1', string)
# Manipulate match.group(n) and return
elif re.match('regex2', string):
match = re.match('regex2', string)
# Do second manipulation
[etc.]
</code></pre>
<p>However, this feels unnecessarily verbose, and usually when that's the case it means there's a better way that I'm either overlooking or don't yet know about.</p>
<p>Does anyone have a suggestion for a better way to do this (better from a code-appearance standpoint, a memory usage standpoint, or both)?</p>
| 6
|
2009-02-28T04:06:31Z
| 597,493
|
<p>Generally speaking, in these sorts of situations, you want to make the code "data driven". That is, put the important information in a container, and loop through it.</p>
<p>In your case, the important information is (string, function) pairs.</p>
<pre><code>import re
def fun1():
print('fun1')
def fun2():
print('fun2')
def fun3():
print('fun3')
regex_handlers = [
(r'regex1', fun1),
(r'regex2', fun2),
(r'regex3', fun3)
]
def example(string):
for regex, fun in regex_handlers:
if re.match(regex, string):
fun() # call the function
break
example('regex2')
</code></pre>
| 21
|
2009-02-28T04:31:57Z
|
[
"python",
"regex",
"coding-style"
] |
How to concisely cascade through multiple regex statements in Python
| 597,476
|
<p>My dilemma: I'm passing my function a string that I need to then perform numerous regex manipulations on. The logic is if there's a match in the first regex, do one thing. If no match, check for a match with the second and do something else, if not check the third, and so forth. I could do something like this:</p>
<pre><code>if re.match('regex1', string):
match = re.match('regex1', string)
# Manipulate match.group(n) and return
elif re.match('regex2', string):
match = re.match('regex2', string)
# Do second manipulation
[etc.]
</code></pre>
<p>However, this feels unnecessarily verbose, and usually when that's the case it means there's a better way that I'm either overlooking or don't yet know about.</p>
<p>Does anyone have a suggestion for a better way to do this (better from a code-appearance standpoint, a memory usage standpoint, or both)?</p>
| 6
|
2009-02-28T04:06:31Z
| 597,557
|
<p>Similar question from back in september: <a href="http://stackoverflow.com/questions/122277">How do you translate this regular-expression idiom from Perl into Python?</a></p>
<p>Using global variables in a module maybe not the best way to do it, but converting it into a class:</p>
<pre><code>import re
class Re(object):
def __init__(self):
self.last_match = None
def match(self,pattern,text):
self.last_match = re.match(pattern,text)
return self.last_match
def search(self,pattern,text):
self.last_match = re.search(pattern,text)
return self.last_match
gre = Re()
if gre.match(r'foo',text):
# do something with gre.last_match
elif gre.match(r'bar',text):
# do something with gre.last_match
else:
# do something else
</code></pre>
| 6
|
2009-02-28T05:32:56Z
|
[
"python",
"regex",
"coding-style"
] |
How to concisely cascade through multiple regex statements in Python
| 597,476
|
<p>My dilemma: I'm passing my function a string that I need to then perform numerous regex manipulations on. The logic is if there's a match in the first regex, do one thing. If no match, check for a match with the second and do something else, if not check the third, and so forth. I could do something like this:</p>
<pre><code>if re.match('regex1', string):
match = re.match('regex1', string)
# Manipulate match.group(n) and return
elif re.match('regex2', string):
match = re.match('regex2', string)
# Do second manipulation
[etc.]
</code></pre>
<p>However, this feels unnecessarily verbose, and usually when that's the case it means there's a better way that I'm either overlooking or don't yet know about.</p>
<p>Does anyone have a suggestion for a better way to do this (better from a code-appearance standpoint, a memory usage standpoint, or both)?</p>
| 6
|
2009-02-28T04:06:31Z
| 602,524
|
<p>I had the same problem as yours. Here´s my solution:</p>
<pre><code>import re
regexp = {
'key1': re.compile(r'regexp1'),
'key2': re.compile(r'regexp2'),
'key3': re.compile(r'regexp3'),
# ...
}
def test_all_regexp(string):
for key, pattern in regexp.items():
m = pattern.match(string)
if m:
# do what you want
break
</code></pre>
<p>It´s a slightly modified solution from the answer of <a href="http://stackoverflow.com/questions/481862/extracting-info-from-large-structured-text-files">Extracting info from large structured text files</a></p>
| 2
|
2009-03-02T14:27:29Z
|
[
"python",
"regex",
"coding-style"
] |
How to concisely cascade through multiple regex statements in Python
| 597,476
|
<p>My dilemma: I'm passing my function a string that I need to then perform numerous regex manipulations on. The logic is if there's a match in the first regex, do one thing. If no match, check for a match with the second and do something else, if not check the third, and so forth. I could do something like this:</p>
<pre><code>if re.match('regex1', string):
match = re.match('regex1', string)
# Manipulate match.group(n) and return
elif re.match('regex2', string):
match = re.match('regex2', string)
# Do second manipulation
[etc.]
</code></pre>
<p>However, this feels unnecessarily verbose, and usually when that's the case it means there's a better way that I'm either overlooking or don't yet know about.</p>
<p>Does anyone have a suggestion for a better way to do this (better from a code-appearance standpoint, a memory usage standpoint, or both)?</p>
| 6
|
2009-02-28T04:06:31Z
| 6,164,807
|
<pre><code>class RegexStore(object):
_searches = None
def __init__(self, pat_list):
# build RegEx searches
self._searches = [(name,re.compile(pat, re.VERBOSE)) for
name,pat in pat_list]
def match( self, text ):
match_all = ((x,y.match(text)) for x,y in self._searches)
try:
return ifilter(op.itemgetter(1), match_all).next()
except StopIteration, e:
# instead of 'name', in first arg, return bad 'text' line
return (text,None)
</code></pre>
<p>You can use this class like so:</p>
<pre><code>rs = RegexStore( (('pat1', r'.*STRING1.*'),
('pat2', r'.*STRING2.*')) )
name,match = rs.match( "MY SAMPLE STRING1" )
if name == 'pat1':
print 'found pat1'
elif name == 'pat2':
print 'found pat2'
</code></pre>
| 0
|
2011-05-28T22:46:01Z
|
[
"python",
"regex",
"coding-style"
] |
Why Jython behaves inconsistently when tested with PyStone?
| 597,483
|
<p>I've been playing recently with Jython and decided to do some quick and dirty benchmarking with pystone. In order to have a reference, I first tested cPython 2.6, with an increasing numbers of loops (I thought this may be relevant as Jython should start to profit from the JIT only after some time).</p>
<pre><code>(richard garibaldi):/usr/local/src/pybench% python ~/tmp/pystone.py
Pystone(1.1) time for 50000 passes = 1.04
This machine benchmarks at 48076.9 pystones/second
(richard garibaldi):/usr/local/src/pybench% python ~/tmp/pystone.py 500000
Pystone(1.1) time for 500000 passes = 10.33
This machine benchmarks at 48402.7 pystones/second
(richard garibaldi):/usr/local/src/pybench% python ~/tmp/pystone.py 1000000
Pystone(1.1) time for 1000000 passes = 19.6
This machine benchmarks at 51020.4 pystones/second
</code></pre>
<p>As you can see, cPython behaves consistently: the time it takes to complete the test increases linearly to the number of loops. Knowing this, I started testing Jython.</p>
<pre><code>(richard garibaldi):/usr/local/src/pybench% jython ~/tmp/pystone.py
Pystone(1.1) time for 50000 passes = 2.29807
This machine benchmarks at 21757.4 pystones/second
(richard garibaldi):/usr/local/src/pybench% jython ~/tmp/pystone.py 500000
Pystone(1.1) time for 500000 passes = 10.931
This machine benchmarks at 45741.4 pystones/second
(richard garibaldi):/usr/local/src/pybench% jython ~/tmp/pystone.py 1000000
Pystone(1.1) time for 1000000 passes = 107.183
This machine benchmarks at 9329.86 pystones/second
</code></pre>
<p>During the first run Jython runs rather lousily in comparison to its C brother. When increased the number of loops it started feeling better, coming close to cPython, like my initial hypothesis predicted. Note that the number of loops increased 10 times, but it took Jython only about 5 times longer to complete them. So, as you imagine, I was expecting that Jython would really rock in the final test. To my great disappointment, however, it did really bad: more than twice slower than in the initial run.</p>
<p>What are your hypotheses: why does Jython behave such an inconsistent manner? Could it be that GC is kicking in at some moment, and taking a lot of time? I've looked at PyStone's code and garbage collection doesn't seem to be turned off, but I would expect Java's GC to be at least as good as Python's... Do you think this slowing down is permanent, or it will go away at some point after increasing the number of loops? How shall Jython behave in a really long running processes?</p>
<p>EDIT: unfortunately, I get <code>java.lang.OutOfMemoryError</code> if I increase the number of loops to 2 million...</p>
<p>(Of course, Jython is still beta, so it should get better in the final release.)</p>
<p>I am using Jython 2.5b1 (trunk:5903:5905, Jan 9 2009, 16:01:29), Java(TM) SE Runtime Environment (build 1.6.0_07-b06-153) and Java HotSpot(TM) 64-Bit Server VM (build 1.6.0_07-b06-57, mixed mode) on MacOS X 10.5.</p>
<p>Thanks for your answers.</p>
| 2
|
2009-02-28T04:21:10Z
| 597,509
|
<p>I'm pretty sure that the results can be improved by tweaking the JVM configuration (JRuby is using quite a few interesting flags for doing it) and I'm also pretty sure that the garbage collection can be tuned.
If you are very interested in this benchmark here is a good resource for configuring your VM: <a href="http://java.sun.com/docs/hotspot/gc5.0/gc%5Ftuning%5F5.html" rel="nofollow">Tuning Garbage Collection</a>. I'd also take a look at JRuby configuration.</p>
<p>./alex</p>
| 1
|
2009-02-28T04:54:15Z
|
[
"java",
"python",
"performance",
"jython",
"benchmarking"
] |
Why Jython behaves inconsistently when tested with PyStone?
| 597,483
|
<p>I've been playing recently with Jython and decided to do some quick and dirty benchmarking with pystone. In order to have a reference, I first tested cPython 2.6, with an increasing numbers of loops (I thought this may be relevant as Jython should start to profit from the JIT only after some time).</p>
<pre><code>(richard garibaldi):/usr/local/src/pybench% python ~/tmp/pystone.py
Pystone(1.1) time for 50000 passes = 1.04
This machine benchmarks at 48076.9 pystones/second
(richard garibaldi):/usr/local/src/pybench% python ~/tmp/pystone.py 500000
Pystone(1.1) time for 500000 passes = 10.33
This machine benchmarks at 48402.7 pystones/second
(richard garibaldi):/usr/local/src/pybench% python ~/tmp/pystone.py 1000000
Pystone(1.1) time for 1000000 passes = 19.6
This machine benchmarks at 51020.4 pystones/second
</code></pre>
<p>As you can see, cPython behaves consistently: the time it takes to complete the test increases linearly to the number of loops. Knowing this, I started testing Jython.</p>
<pre><code>(richard garibaldi):/usr/local/src/pybench% jython ~/tmp/pystone.py
Pystone(1.1) time for 50000 passes = 2.29807
This machine benchmarks at 21757.4 pystones/second
(richard garibaldi):/usr/local/src/pybench% jython ~/tmp/pystone.py 500000
Pystone(1.1) time for 500000 passes = 10.931
This machine benchmarks at 45741.4 pystones/second
(richard garibaldi):/usr/local/src/pybench% jython ~/tmp/pystone.py 1000000
Pystone(1.1) time for 1000000 passes = 107.183
This machine benchmarks at 9329.86 pystones/second
</code></pre>
<p>During the first run Jython runs rather lousily in comparison to its C brother. When increased the number of loops it started feeling better, coming close to cPython, like my initial hypothesis predicted. Note that the number of loops increased 10 times, but it took Jython only about 5 times longer to complete them. So, as you imagine, I was expecting that Jython would really rock in the final test. To my great disappointment, however, it did really bad: more than twice slower than in the initial run.</p>
<p>What are your hypotheses: why does Jython behave such an inconsistent manner? Could it be that GC is kicking in at some moment, and taking a lot of time? I've looked at PyStone's code and garbage collection doesn't seem to be turned off, but I would expect Java's GC to be at least as good as Python's... Do you think this slowing down is permanent, or it will go away at some point after increasing the number of loops? How shall Jython behave in a really long running processes?</p>
<p>EDIT: unfortunately, I get <code>java.lang.OutOfMemoryError</code> if I increase the number of loops to 2 million...</p>
<p>(Of course, Jython is still beta, so it should get better in the final release.)</p>
<p>I am using Jython 2.5b1 (trunk:5903:5905, Jan 9 2009, 16:01:29), Java(TM) SE Runtime Environment (build 1.6.0_07-b06-153) and Java HotSpot(TM) 64-Bit Server VM (build 1.6.0_07-b06-57, mixed mode) on MacOS X 10.5.</p>
<p>Thanks for your answers.</p>
| 2
|
2009-02-28T04:21:10Z
| 597,905
|
<p>This might be a bug in jython 2.5b1. You should consider reporting it back to the jython team. I have just run the pystone benchmark on my MacBook with the current stable release of jython (2.2.1) and I get slow but consistent results:</p>
<pre><code>mo$ ~/Coding/Jython/jython2.2.1/jython pystone.py 50000
Pystone(1.1) time for 50000 passes = 2.365
This machine benchmarks at 21141.6 pystones/second
mo$ ~/Coding/Jython/jython2.2.1/jython pystone.py 500000
Pystone(1.1) time for 500000 passes = 22.246
This machine benchmarks at 22476 pystones/second
mo$ ~/Coding/Jython/jython2.2.1/jython pystone.py 1000000
Pystone(1.1) time for 1000000 passes = 43.94
This machine benchmarks at 22758.3 pystones/second
mo$ java -version
java version "1.5.0_16"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_16-b06-275)
Java HotSpot(TM) Client VM (build 1.5.0_16-132, mixed mode, sharing)
</code></pre>
<p>The cPython results for me are more or less the same. I reran eacht test three times and got very similar results all the time.</p>
<p>I also tried giving java a bigger initial and maximum Heap (-Xms256m -Xmx512m) without a noteworthy result</p>
<p>However, setting the JVM to -server (slower startup, better long running performance, not so good for "interactive" work) turned the picture a bit:</p>
<pre><code>mo$ ~/Coding/Jython/jython2.2.1/jython pystone.py 50000
Pystone(1.1) time for 50000 passes = 1.848
This machine benchmarks at 27056.3 pystones/second
mo$ ~/Coding/Jython/jython2.2.1/jython pystone.py 500000
Pystone(1.1) time for 500000 passes = 9.998
This machine benchmarks at 50010 pystones/second
mo$ ~/Coding/Jython/jython2.2.1/jython pystone.py 1000000
Pystone(1.1) time for 1000000 passes = 19.9
This machine benchmarks at 50251.3 pystones/second
</code></pre>
<p>I made one final run with (-server -Xms256m -Xmx512m):</p>
<pre><code>mo$ ~/Coding/Jython/jython2.2.1/jython pystone.py 5000000
Pystone(1.1) time for 5000000 passes = 108.664
This machine benchmarks at 46013.4 pystones/second
</code></pre>
<p>My guess would be, that the slow first run is due to VM startup/JIT not yet having really kicked in. The results of the longer runs are more or less consitent and show the effects of hotspot/JIT</p>
<p>Maybe you could rerun your last test with a bigger heap? To change the JVM switches, just edit the jython file in your Jython installation.</p>
| 2
|
2009-02-28T11:42:32Z
|
[
"java",
"python",
"performance",
"jython",
"benchmarking"
] |
Why Jython behaves inconsistently when tested with PyStone?
| 597,483
|
<p>I've been playing recently with Jython and decided to do some quick and dirty benchmarking with pystone. In order to have a reference, I first tested cPython 2.6, with an increasing numbers of loops (I thought this may be relevant as Jython should start to profit from the JIT only after some time).</p>
<pre><code>(richard garibaldi):/usr/local/src/pybench% python ~/tmp/pystone.py
Pystone(1.1) time for 50000 passes = 1.04
This machine benchmarks at 48076.9 pystones/second
(richard garibaldi):/usr/local/src/pybench% python ~/tmp/pystone.py 500000
Pystone(1.1) time for 500000 passes = 10.33
This machine benchmarks at 48402.7 pystones/second
(richard garibaldi):/usr/local/src/pybench% python ~/tmp/pystone.py 1000000
Pystone(1.1) time for 1000000 passes = 19.6
This machine benchmarks at 51020.4 pystones/second
</code></pre>
<p>As you can see, cPython behaves consistently: the time it takes to complete the test increases linearly to the number of loops. Knowing this, I started testing Jython.</p>
<pre><code>(richard garibaldi):/usr/local/src/pybench% jython ~/tmp/pystone.py
Pystone(1.1) time for 50000 passes = 2.29807
This machine benchmarks at 21757.4 pystones/second
(richard garibaldi):/usr/local/src/pybench% jython ~/tmp/pystone.py 500000
Pystone(1.1) time for 500000 passes = 10.931
This machine benchmarks at 45741.4 pystones/second
(richard garibaldi):/usr/local/src/pybench% jython ~/tmp/pystone.py 1000000
Pystone(1.1) time for 1000000 passes = 107.183
This machine benchmarks at 9329.86 pystones/second
</code></pre>
<p>During the first run Jython runs rather lousily in comparison to its C brother. When increased the number of loops it started feeling better, coming close to cPython, like my initial hypothesis predicted. Note that the number of loops increased 10 times, but it took Jython only about 5 times longer to complete them. So, as you imagine, I was expecting that Jython would really rock in the final test. To my great disappointment, however, it did really bad: more than twice slower than in the initial run.</p>
<p>What are your hypotheses: why does Jython behave such an inconsistent manner? Could it be that GC is kicking in at some moment, and taking a lot of time? I've looked at PyStone's code and garbage collection doesn't seem to be turned off, but I would expect Java's GC to be at least as good as Python's... Do you think this slowing down is permanent, or it will go away at some point after increasing the number of loops? How shall Jython behave in a really long running processes?</p>
<p>EDIT: unfortunately, I get <code>java.lang.OutOfMemoryError</code> if I increase the number of loops to 2 million...</p>
<p>(Of course, Jython is still beta, so it should get better in the final release.)</p>
<p>I am using Jython 2.5b1 (trunk:5903:5905, Jan 9 2009, 16:01:29), Java(TM) SE Runtime Environment (build 1.6.0_07-b06-153) and Java HotSpot(TM) 64-Bit Server VM (build 1.6.0_07-b06-57, mixed mode) on MacOS X 10.5.</p>
<p>Thanks for your answers.</p>
| 2
|
2009-02-28T04:21:10Z
| 602,574
|
<p>my bench on a XP_Win32_PC :</p>
<pre><code>C:\jython\jython2.5b1>bench "50000"
C:\jython\jython2.5b1>jython Lib\test\pystone.py "50000"
Pystone(1.1) time for 50000 passes = 1.73489
This machine benchmarks at 28820.2 pystones/second
C:\jython\jython2.5b1>bench "100000"
C:\jython\jython2.5b1>jython Lib\test\pystone.py "100000"
Pystone(1.1) time for 100000 passes = 3.36223
This machine benchmarks at 29742.2 pystones/second
C:\jython\jython2.5b1>bench "500000"
C:\jython\jython2.5b1>jython Lib\test\pystone.py "500000"
Pystone(1.1) time for 500000 passes = 15.8116
This machine benchmarks at 31622.3 pystones/second
C:\jython\jython2.5b1>bench "1000000"
C:\jython\jython2.5b1>jython Lib\test\pystone.py "1000000"
Pystone(1.1) time for 1000000 passes = 30.9763
This machine benchmarks at 32282.8 pystones/second
C:\jython\jython2.5b1>jython
Jython 2.5b1 (trunk:5903:5905, Jan 9 2009, 16:01:29)
[Java HotSpot(TM) Client VM (Sun Microsystems Inc.)] on java1.5.0_17
</code></pre>
<p>It is not so fast, but ...</p>
<p>no "special effects"</p>
<p>Is it a java-vm 'problem' ?</p>
<p>Add a comment if you want further infos to my benchmarking on this old Win32-PC</p>
| 1
|
2009-03-02T14:44:58Z
|
[
"java",
"python",
"performance",
"jython",
"benchmarking"
] |
Why Jython behaves inconsistently when tested with PyStone?
| 597,483
|
<p>I've been playing recently with Jython and decided to do some quick and dirty benchmarking with pystone. In order to have a reference, I first tested cPython 2.6, with an increasing numbers of loops (I thought this may be relevant as Jython should start to profit from the JIT only after some time).</p>
<pre><code>(richard garibaldi):/usr/local/src/pybench% python ~/tmp/pystone.py
Pystone(1.1) time for 50000 passes = 1.04
This machine benchmarks at 48076.9 pystones/second
(richard garibaldi):/usr/local/src/pybench% python ~/tmp/pystone.py 500000
Pystone(1.1) time for 500000 passes = 10.33
This machine benchmarks at 48402.7 pystones/second
(richard garibaldi):/usr/local/src/pybench% python ~/tmp/pystone.py 1000000
Pystone(1.1) time for 1000000 passes = 19.6
This machine benchmarks at 51020.4 pystones/second
</code></pre>
<p>As you can see, cPython behaves consistently: the time it takes to complete the test increases linearly to the number of loops. Knowing this, I started testing Jython.</p>
<pre><code>(richard garibaldi):/usr/local/src/pybench% jython ~/tmp/pystone.py
Pystone(1.1) time for 50000 passes = 2.29807
This machine benchmarks at 21757.4 pystones/second
(richard garibaldi):/usr/local/src/pybench% jython ~/tmp/pystone.py 500000
Pystone(1.1) time for 500000 passes = 10.931
This machine benchmarks at 45741.4 pystones/second
(richard garibaldi):/usr/local/src/pybench% jython ~/tmp/pystone.py 1000000
Pystone(1.1) time for 1000000 passes = 107.183
This machine benchmarks at 9329.86 pystones/second
</code></pre>
<p>During the first run Jython runs rather lousily in comparison to its C brother. When increased the number of loops it started feeling better, coming close to cPython, like my initial hypothesis predicted. Note that the number of loops increased 10 times, but it took Jython only about 5 times longer to complete them. So, as you imagine, I was expecting that Jython would really rock in the final test. To my great disappointment, however, it did really bad: more than twice slower than in the initial run.</p>
<p>What are your hypotheses: why does Jython behave such an inconsistent manner? Could it be that GC is kicking in at some moment, and taking a lot of time? I've looked at PyStone's code and garbage collection doesn't seem to be turned off, but I would expect Java's GC to be at least as good as Python's... Do you think this slowing down is permanent, or it will go away at some point after increasing the number of loops? How shall Jython behave in a really long running processes?</p>
<p>EDIT: unfortunately, I get <code>java.lang.OutOfMemoryError</code> if I increase the number of loops to 2 million...</p>
<p>(Of course, Jython is still beta, so it should get better in the final release.)</p>
<p>I am using Jython 2.5b1 (trunk:5903:5905, Jan 9 2009, 16:01:29), Java(TM) SE Runtime Environment (build 1.6.0_07-b06-153) and Java HotSpot(TM) 64-Bit Server VM (build 1.6.0_07-b06-57, mixed mode) on MacOS X 10.5.</p>
<p>Thanks for your answers.</p>
| 2
|
2009-02-28T04:21:10Z
| 608,604
|
<p>The same results from my laptop running Ubuntu Jaunty, with JRE 1.6.0_12-b04:</p>
<pre>nathell@breeze:/usr/lib/python2.5/test$ python pystone.py 500000
Pystone(1.1) time for 500000 passes = 12.98
This machine benchmarks at 38520.8 pystones/second
nathell@breeze:/usr/lib/python2.5/test$ python pystone.py 1000000
Pystone(1.1) time for 1000000 passes = 26.05
This machine benchmarks at 38387.7 pystones/second
nathell@breeze:/usr/lib/python2.5/test$ ~/jython/jython pystone.py
Pystone(1.1) time for 50000 passes = 2.47788
This machine benchmarks at 20178.6 pystones/second
nathell@breeze:/usr/lib/python2.5/test$ ~/jython/jython pystone.py 500000
Pystone(1.1) time for 500000 passes = 19.7294
This machine benchmarks at 25342.9 pystones/second
nathell@breeze:/usr/lib/python2.5/test$ ~/jython/jython pystone.py 1000000
Pystone(1.1) time for 1000000 passes = 38.9272
This machine benchmarks at 25689 pystones/second
</pre>
<p>So perhaps this is related to the JRE rather than Jython version, after all. The problems the Armed Bear Common Lisp project has had with early versions of JRE 1.6 might also hint at this.</p>
| 2
|
2009-03-03T22:58:52Z
|
[
"java",
"python",
"performance",
"jython",
"benchmarking"
] |
Why Jython behaves inconsistently when tested with PyStone?
| 597,483
|
<p>I've been playing recently with Jython and decided to do some quick and dirty benchmarking with pystone. In order to have a reference, I first tested cPython 2.6, with an increasing numbers of loops (I thought this may be relevant as Jython should start to profit from the JIT only after some time).</p>
<pre><code>(richard garibaldi):/usr/local/src/pybench% python ~/tmp/pystone.py
Pystone(1.1) time for 50000 passes = 1.04
This machine benchmarks at 48076.9 pystones/second
(richard garibaldi):/usr/local/src/pybench% python ~/tmp/pystone.py 500000
Pystone(1.1) time for 500000 passes = 10.33
This machine benchmarks at 48402.7 pystones/second
(richard garibaldi):/usr/local/src/pybench% python ~/tmp/pystone.py 1000000
Pystone(1.1) time for 1000000 passes = 19.6
This machine benchmarks at 51020.4 pystones/second
</code></pre>
<p>As you can see, cPython behaves consistently: the time it takes to complete the test increases linearly to the number of loops. Knowing this, I started testing Jython.</p>
<pre><code>(richard garibaldi):/usr/local/src/pybench% jython ~/tmp/pystone.py
Pystone(1.1) time for 50000 passes = 2.29807
This machine benchmarks at 21757.4 pystones/second
(richard garibaldi):/usr/local/src/pybench% jython ~/tmp/pystone.py 500000
Pystone(1.1) time for 500000 passes = 10.931
This machine benchmarks at 45741.4 pystones/second
(richard garibaldi):/usr/local/src/pybench% jython ~/tmp/pystone.py 1000000
Pystone(1.1) time for 1000000 passes = 107.183
This machine benchmarks at 9329.86 pystones/second
</code></pre>
<p>During the first run Jython runs rather lousily in comparison to its C brother. When increased the number of loops it started feeling better, coming close to cPython, like my initial hypothesis predicted. Note that the number of loops increased 10 times, but it took Jython only about 5 times longer to complete them. So, as you imagine, I was expecting that Jython would really rock in the final test. To my great disappointment, however, it did really bad: more than twice slower than in the initial run.</p>
<p>What are your hypotheses: why does Jython behave such an inconsistent manner? Could it be that GC is kicking in at some moment, and taking a lot of time? I've looked at PyStone's code and garbage collection doesn't seem to be turned off, but I would expect Java's GC to be at least as good as Python's... Do you think this slowing down is permanent, or it will go away at some point after increasing the number of loops? How shall Jython behave in a really long running processes?</p>
<p>EDIT: unfortunately, I get <code>java.lang.OutOfMemoryError</code> if I increase the number of loops to 2 million...</p>
<p>(Of course, Jython is still beta, so it should get better in the final release.)</p>
<p>I am using Jython 2.5b1 (trunk:5903:5905, Jan 9 2009, 16:01:29), Java(TM) SE Runtime Environment (build 1.6.0_07-b06-153) and Java HotSpot(TM) 64-Bit Server VM (build 1.6.0_07-b06-57, mixed mode) on MacOS X 10.5.</p>
<p>Thanks for your answers.</p>
| 2
|
2009-02-28T04:21:10Z
| 714,212
|
<p>Benchmarking a runtime environment as complex as the JVM is hard. Even excluding the JIT and GC, you've got a big heap, memory layout and cache variation between runs.</p>
<p>One thing that helps with Jython is simply running the benchmark more than once in a single VM session: once to warm up the JIT and one or more times you measure individually. I've done a lot of Jython benchmarking, and unfortunately it often takes 10-50 attempts to achieve a reasonable time</p>
<p>You can use some JVM flags to observe GC and JIT behavior to get some idea how long the warmup period should be, though obviously you shouldn't benchmark with the debugging flags turned on. For example:</p>
<pre><code>% ./jython -J-XX:+PrintCompilation -J-verbose:gc
1 java.lang.String::hashCode (60 bytes)
2 java.lang.String::charAt (33 bytes)
3 java.lang.String::lastIndexOf (156 bytes)
4 java.lang.String::indexOf (151 bytes)
[GC 1984K->286K(7616K), 0.0031513 secs]
</code></pre>
<p>If you do all this, and use the HotSpot Server VM, you'll find Jython slightly faster than CPython on pystone, but this is in no way representative of Jython performance in general. The Jython developers are paying much more attention to correctness than performance for the 2.5 release; over the next year or so with a 2.6/2.7/3.0 release performance will be more emphasized. You can see a few of the pain points by looking at some <a href="http://freya.cs.uiuc.edu/~njriley/plots.html" rel="nofollow">microbenchmarks</a> (originally derived from PyPy) I run.</p>
| 2
|
2009-04-03T14:41:15Z
|
[
"java",
"python",
"performance",
"jython",
"benchmarking"
] |
How can i use TurboMail 3 together with TurboGears 2
| 598,019
|
<p>Hy,
I want to use TurboMail3 (<a href="http://www.python-turbomail.org/wiki/3.0/BetaRelease" rel="nofollow">website</a>) together with a TurboGears 2(<a href="http://www.turbogears.org/2.0/" rel="nofollow">website</a>) project. Which files to I have to modify to include TurboMail into my TurboGears project? Everything I find on the web is for TurboMail2 and TurboGears1. </p>
<p>The TurboMail Documentation states that there actually is a TG2 integration but I never found documentation for it.</p>
<p>Thanks!</p>
| 1
|
2009-02-28T13:23:42Z
| 600,090
|
<p>The integration is currently the same as for Pylons. There is a ticket for a TG2 specific integration which is currently in our bug tracker. If you really want answers for that topic, please ask in the turbomail google group: <a href="http://groups.google.com/group/turbomail-devel" rel="nofollow">http://groups.google.com/group/turbomail-devel</a></p>
| 1
|
2009-03-01T16:51:28Z
|
[
"python",
"email",
"turbogears"
] |
How can i use TurboMail 3 together with TurboGears 2
| 598,019
|
<p>Hy,
I want to use TurboMail3 (<a href="http://www.python-turbomail.org/wiki/3.0/BetaRelease" rel="nofollow">website</a>) together with a TurboGears 2(<a href="http://www.turbogears.org/2.0/" rel="nofollow">website</a>) project. Which files to I have to modify to include TurboMail into my TurboGears project? Everything I find on the web is for TurboMail2 and TurboGears1. </p>
<p>The TurboMail Documentation states that there actually is a TG2 integration but I never found documentation for it.</p>
<p>Thanks!</p>
| 1
|
2009-02-28T13:23:42Z
| 1,310,195
|
<p>This might help you along: <a href="http://www.5dollarwhitebox.org/drupal/node/92" rel="nofollow">Getting TurboMail to work with TurboGears 2.0</a></p>
| 0
|
2009-08-21T05:19:34Z
|
[
"python",
"email",
"turbogears"
] |
Why does @foo.setter in Python not work for me?
| 598,077
|
<p>So, I'm playing with decorators in Python 2.6, and I'm having some trouble getting them to work. Here is my class file:</p>
<pre><code>class testDec:
@property
def x(self):
print 'called getter'
return self._x
@x.setter
def x(self, value):
print 'called setter'
self._x = value
</code></pre>
<p>What I thought this meant is to treat <code>x</code> like a property, but call these functions on get and set. So, I fired up IDLE and checked it:</p>
<pre><code>>>> from testDec import testDec
from testDec import testDec
>>> t = testDec()
t = testDec()
>>> t.x
t.x
called getter
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "testDec.py", line 18, in x
return self._x
AttributeError: testDec instance has no attribute '_x'
>>> t.x = 5
t.x = 5
>>> t.x
t.x
5
</code></pre>
<p>Clearly the first call works as expected, since I call the getter, and there is no default value, and it fails. OK, good, I understand. However, the call to assign <code>t.x = 5</code> seems to create a new property <code>x</code>, and now the getter doesn't work!</p>
<p>What am I missing?</p>
| 102
|
2009-02-28T14:33:50Z
| 598,090
|
<p>You need to use new-style classes which you do by deriving your class from object:</p>
<pre><code>class testDec(object):
....
</code></pre>
<p>Then it should work.</p>
| 22
|
2009-02-28T14:43:22Z
|
[
"python",
"decorator",
"new-style-class"
] |
Why does @foo.setter in Python not work for me?
| 598,077
|
<p>So, I'm playing with decorators in Python 2.6, and I'm having some trouble getting them to work. Here is my class file:</p>
<pre><code>class testDec:
@property
def x(self):
print 'called getter'
return self._x
@x.setter
def x(self, value):
print 'called setter'
self._x = value
</code></pre>
<p>What I thought this meant is to treat <code>x</code> like a property, but call these functions on get and set. So, I fired up IDLE and checked it:</p>
<pre><code>>>> from testDec import testDec
from testDec import testDec
>>> t = testDec()
t = testDec()
>>> t.x
t.x
called getter
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "testDec.py", line 18, in x
return self._x
AttributeError: testDec instance has no attribute '_x'
>>> t.x = 5
t.x = 5
>>> t.x
t.x
5
</code></pre>
<p>Clearly the first call works as expected, since I call the getter, and there is no default value, and it fails. OK, good, I understand. However, the call to assign <code>t.x = 5</code> seems to create a new property <code>x</code>, and now the getter doesn't work!</p>
<p>What am I missing?</p>
| 102
|
2009-02-28T14:33:50Z
| 598,092
|
<p>You seem to be using <a href="https://docs.python.org/2/glossary.html#term-classic-class">classic old-style classes</a>. In order for <a href="https://docs.python.org/2/library/functions.html#property">properties</a> to work correctly you need to use <a href="https://docs.python.org/2/glossary.html#term-new-style-class">new-style classes</a> instead (<a href="https://docs.python.org/2/reference/datamodel.html#newstyle">inherit from <code>object</code></a>). Just declare your class as <code>MyClass(object)</code>:</p>
<pre><code>class testDec(object):
@property
def x(self):
print 'called getter'
return self._x
@x.setter
def x(self, value):
print 'called setter'
self._x = value
</code></pre>
<p>It works:</p>
<pre><code>>>> k = testDec()
>>> k.x
called getter
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/devel/class_test.py", line 6, in x
return self._x
AttributeError: 'testDec' object has no attribute '_x'
>>> k.x = 5
called setter
>>> k.x
called getter
5
>>>
</code></pre>
| 213
|
2009-02-28T14:43:40Z
|
[
"python",
"decorator",
"new-style-class"
] |
Why does @foo.setter in Python not work for me?
| 598,077
|
<p>So, I'm playing with decorators in Python 2.6, and I'm having some trouble getting them to work. Here is my class file:</p>
<pre><code>class testDec:
@property
def x(self):
print 'called getter'
return self._x
@x.setter
def x(self, value):
print 'called setter'
self._x = value
</code></pre>
<p>What I thought this meant is to treat <code>x</code> like a property, but call these functions on get and set. So, I fired up IDLE and checked it:</p>
<pre><code>>>> from testDec import testDec
from testDec import testDec
>>> t = testDec()
t = testDec()
>>> t.x
t.x
called getter
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "testDec.py", line 18, in x
return self._x
AttributeError: testDec instance has no attribute '_x'
>>> t.x = 5
t.x = 5
>>> t.x
t.x
5
</code></pre>
<p>Clearly the first call works as expected, since I call the getter, and there is no default value, and it fails. OK, good, I understand. However, the call to assign <code>t.x = 5</code> seems to create a new property <code>x</code>, and now the getter doesn't work!</p>
<p>What am I missing?</p>
| 102
|
2009-02-28T14:33:50Z
| 17,395,735
|
<p>Just a note for other people who stumble here looking for this exception: both functions need to have the same name. Naming the methods as follows will result in an exception:</p>
<pre><code>@property
def x(self): pass
@x.setter
def x_setter(self, value): pass
</code></pre>
<p>Instead give both methods the same name</p>
<pre><code>@property
def x(self): pass
@x.setter
def x(self, value): pass
</code></pre>
| 34
|
2013-06-30T23:20:33Z
|
[
"python",
"decorator",
"new-style-class"
] |
Why does @foo.setter in Python not work for me?
| 598,077
|
<p>So, I'm playing with decorators in Python 2.6, and I'm having some trouble getting them to work. Here is my class file:</p>
<pre><code>class testDec:
@property
def x(self):
print 'called getter'
return self._x
@x.setter
def x(self, value):
print 'called setter'
self._x = value
</code></pre>
<p>What I thought this meant is to treat <code>x</code> like a property, but call these functions on get and set. So, I fired up IDLE and checked it:</p>
<pre><code>>>> from testDec import testDec
from testDec import testDec
>>> t = testDec()
t = testDec()
>>> t.x
t.x
called getter
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "testDec.py", line 18, in x
return self._x
AttributeError: testDec instance has no attribute '_x'
>>> t.x = 5
t.x = 5
>>> t.x
t.x
5
</code></pre>
<p>Clearly the first call works as expected, since I call the getter, and there is no default value, and it fails. OK, good, I understand. However, the call to assign <code>t.x = 5</code> seems to create a new property <code>x</code>, and now the getter doesn't work!</p>
<p>What am I missing?</p>
| 102
|
2009-02-28T14:33:50Z
| 28,464,787
|
<p>In case anybody comes here from google, in addition to the above answers I would like to add that this needs careful attention when invoking the setter from the <code>__init__</code> method of your class based on <a href="http://stackoverflow.com/a/3942118/808734">this answer</a>
Specifically:</p>
<pre><code>class testDec(object):
def __init__(self, value):
print 'We are in __init__'
self.x = value # Will call the setter. Note just x here
#self._x = value # Will not call the setter
@property
def x(self):
print 'called getter'
return self._x # Note the _x here
@x.setter
def x(self, value):
print 'called setter'
self._x = value # Note the _x here
t = testDec(17)
print t.x
Output:
We are in __init__
called setter
called getter
17
</code></pre>
| 3
|
2015-02-11T21:23:33Z
|
[
"python",
"decorator",
"new-style-class"
] |
Cheap exception handling in Python?
| 598,157
|
<p>I read in an earlier <a href="http://stackoverflow.com/questions/576988/python-specific-antipatterns/577731#577731">answer</a> that exception handling is cheap in Python so we shouldn't do pre-conditional checking.</p>
<p>I have not heard of this before, but I'm relatively new to Python. Exception handling means a dynamic call and a static return, whereas an <code>if</code> statement is static call, static return.</p>
<p>How can doing the checking be bad and the <code>try-except</code> be good, seems to be the other way around. Can someone explain this to me?</p>
| 22
|
2009-02-28T15:30:19Z
| 598,168
|
<p>You might find this post helpful: <a href="http://paltman.com/2008/jan/18/try-except-performance-in-python-a-simple-test/"><strong>Try / Except Performance in Python: A Simple Test</strong></a> where Patrick Altman did some simple testing to see what the performance is in various scenarios pre-conditional checking (specific to dictionary keys in this case) and using only exceptions. Code is provided as well if you want to adapt it to test other conditionals.</p>
<p>The conclusions he came to: </p>
<blockquote>
<p>From these results, I think it is fair
to quickly determine a number of
conclusions:</p>
<ol>
<li>If there is a high likelihood that the element doesn't exist, then
you are better off checking for it
with has_key.</li>
<li>If you are not going to do anything with the Exception if it is
raised, then you are better off not
putting one have the except</li>
<li>If it is likely that the element does exist, then there is a very
slight advantage to using a try/except
block instead of using has_key,
however, the advantage is very slight.</li>
</ol>
</blockquote>
| 24
|
2009-02-28T15:40:15Z
|
[
"python",
"performance",
"exception-handling"
] |
Cheap exception handling in Python?
| 598,157
|
<p>I read in an earlier <a href="http://stackoverflow.com/questions/576988/python-specific-antipatterns/577731#577731">answer</a> that exception handling is cheap in Python so we shouldn't do pre-conditional checking.</p>
<p>I have not heard of this before, but I'm relatively new to Python. Exception handling means a dynamic call and a static return, whereas an <code>if</code> statement is static call, static return.</p>
<p>How can doing the checking be bad and the <code>try-except</code> be good, seems to be the other way around. Can someone explain this to me?</p>
| 22
|
2009-02-28T15:30:19Z
| 598,189
|
<p>I am a python beginner as well. While I cannot say why exactly Exception handling has been called cheap in the context of that answer, here are my thoughts:</p>
<p>Note that checking with if-elif-else has to evaluate a condition every time. Exception handling, including the search for an exception handler occurs only in an exceptional condition, which is likely to be rare in most cases. That is a clear efficiency gain.
As pointed out by Jay, it is better to use conditional logic rather than exceptions when there is a high likelihood of the key being absent. This is because if the key is absent most of the time, it is not an exceptional condition. </p>
<p><strong>That said, I suggest that you don't worry about efficiency and rather about meaning. Use exception handling to detect exceptional cases and checking conditions when you want to decide upon something.</strong> I was reminded about the importance of meaning by S.Lott just yesterday.</p>
<p><strong>Case in point:</strong> </p>
<pre><code>def xyz(key):
dictOb = {x:1, y:2, z:3}
#Condition evaluated every time
if dictOb.has_key(key): #Access 1 to dict
print dictOb[key] #Access 2
</code></pre>
<p>Versus</p>
<pre><code>#Exception mechanism is in play only when the key isn't found.
def xyz(key):
dictOb = {x:1, y:2, z:3}
try:
print dictOb[key] #Access 1
except KeyError:
print "Not Found"
</code></pre>
<p>Overall, having some code that handles something,like a missing key, <strong>just in case</strong> needs exception handling, but in situations like when the key isn't present most of the time, what you really want to do is to decide if the key is present => if-else. Python emphasizes and encourages saying what you mean.</p>
<p>Why Exceptions are preferred to if-elif -></p>
<ol>
<li>It expresses the meaning more clearly when you are looking foe <strong><em>exceptional</em></strong> aka unusual/unexpected conditions in your code.</li>
<li>It is cleaner and a whole lot more readable.</li>
<li>It is more flexible.</li>
<li>It can be used to write more concise code.</li>
<li>Avoids a lot of nasty checking. </li>
<li>It is more maintainable.</li>
</ol>
<p><strong>Note</strong>
When we avoid using try-except, Exceptions continue being raised. Exceptions which aren't handled simply go to the default handler. When you use try-except, you can handle the error yourself. It might be more efficient because if-else requires condition evaluation, while looking for an exception handler may be cheaper. Even if this is true, the gain from it will be too minor to bother thinking about. </p>
<p>I hope my answer helps.</p>
| 4
|
2009-02-28T15:48:52Z
|
[
"python",
"performance",
"exception-handling"
] |
Cheap exception handling in Python?
| 598,157
|
<p>I read in an earlier <a href="http://stackoverflow.com/questions/576988/python-specific-antipatterns/577731#577731">answer</a> that exception handling is cheap in Python so we shouldn't do pre-conditional checking.</p>
<p>I have not heard of this before, but I'm relatively new to Python. Exception handling means a dynamic call and a static return, whereas an <code>if</code> statement is static call, static return.</p>
<p>How can doing the checking be bad and the <code>try-except</code> be good, seems to be the other way around. Can someone explain this to me?</p>
| 22
|
2009-02-28T15:30:19Z
| 598,217
|
<p>What are static versus dynamic calls and returns, and why do you think that calls and returns are any different in Python depending on if you are doing it in a try/except block? Even if you aren't catching an exception, Python still has to handle the call possibly raising something, so it doesn't make a difference to Python in regards to how the calls and returns are handled.</p>
<p>Every function call in Python involves pushing the arguments onto the stack, and invoking the callable. Every single function termination is followed by the caller, in the internal wiring of Python, checking for a successful or exception termination, and handles it accordingly. In other words, if you think that there is some additional handling when you are in a try/except block that is somehow skipped when you are not in one, you are mistaken. I assume that is what you "static" versus "dynamic" distinction was about.</p>
<p>Further, it is a matter of style, and experienced Python developers come to read exception catching well, so that when they see the appropriate try/except around a call, it is more readable than a conditional check.</p>
| 1
|
2009-02-28T16:03:45Z
|
[
"python",
"performance",
"exception-handling"
] |
Cheap exception handling in Python?
| 598,157
|
<p>I read in an earlier <a href="http://stackoverflow.com/questions/576988/python-specific-antipatterns/577731#577731">answer</a> that exception handling is cheap in Python so we shouldn't do pre-conditional checking.</p>
<p>I have not heard of this before, but I'm relatively new to Python. Exception handling means a dynamic call and a static return, whereas an <code>if</code> statement is static call, static return.</p>
<p>How can doing the checking be bad and the <code>try-except</code> be good, seems to be the other way around. Can someone explain this to me?</p>
| 22
|
2009-02-28T15:30:19Z
| 598,219
|
<p>With Python, it is easy to check different possibilities for speed - get to know the <a href="http://docs.python.org/library/timeit.html#module-timeit" rel="nofollow">timeit module</a> :</p>
<blockquote>
<p>... example session (using the command line) that compare the cost of using hasattr() vs. try/except to test for missing and present object attributes.</p>
</blockquote>
<pre><code>% timeit.py 'try:' ' str.__nonzero__' 'except AttributeError:' ' pass'
100000 loops, best of 3: 15.7 usec per loop
% timeit.py 'if hasattr(str, "__nonzero__"): pass'
100000 loops, best of 3: 4.26 usec per loop
% timeit.py 'try:' ' int.__nonzero__' 'except AttributeError:' ' pass'
1000000 loops, best of 3: 1.43 usec per loop
% timeit.py 'if hasattr(int, "__nonzero__"): pass'
100000 loops, best of 3: 2.23 usec per loop
</code></pre>
<p>These timing results show in the <code>hasattr()</code> case, raising an exception is slow, but performing a test is slower than not raising the exception. So, in terms of running time, using an exception for handling <em>exceptional</em> cases makes sense.</p>
<p>EDIT: The command line option <code>-n</code> will default to a large enough count so that the run time is meaningful. A <a href="http://docs.python.org/library/timeit.html#command-line-interface" rel="nofollow">quote from the manual</a>:</p>
<blockquote>
<p>If -n is not given, a suitable number of loops is calculated by trying successive powers of 10 until the total time is at least 0.2 seconds.</p>
</blockquote>
| 8
|
2009-02-28T16:04:16Z
|
[
"python",
"performance",
"exception-handling"
] |
Cheap exception handling in Python?
| 598,157
|
<p>I read in an earlier <a href="http://stackoverflow.com/questions/576988/python-specific-antipatterns/577731#577731">answer</a> that exception handling is cheap in Python so we shouldn't do pre-conditional checking.</p>
<p>I have not heard of this before, but I'm relatively new to Python. Exception handling means a dynamic call and a static return, whereas an <code>if</code> statement is static call, static return.</p>
<p>How can doing the checking be bad and the <code>try-except</code> be good, seems to be the other way around. Can someone explain this to me?</p>
| 22
|
2009-02-28T15:30:19Z
| 598,221
|
<p>Don't sweat the small stuff. You've already picked one of the slower scripting languages out there, so trying to optimize down to the opcode is not going to help you much. The reason to choose an interpreted, dynamic language like Python is to optimize your time, not the CPU's.</p>
<p>If you use common language idioms, then you'll see all the benefits of fast prototyping and clean design and your code will naturally run faster as new versions of Python are released and the computer hardware is upgraded.</p>
<p>If you have performance problems, then profile your code and optimize your slow algorithms. But in the mean time, use exceptions for exceptional situations since it will make any refactoring you ultimately do along these lines a lot easier.</p>
| 33
|
2009-02-28T16:05:27Z
|
[
"python",
"performance",
"exception-handling"
] |
Cheap exception handling in Python?
| 598,157
|
<p>I read in an earlier <a href="http://stackoverflow.com/questions/576988/python-specific-antipatterns/577731#577731">answer</a> that exception handling is cheap in Python so we shouldn't do pre-conditional checking.</p>
<p>I have not heard of this before, but I'm relatively new to Python. Exception handling means a dynamic call and a static return, whereas an <code>if</code> statement is static call, static return.</p>
<p>How can doing the checking be bad and the <code>try-except</code> be good, seems to be the other way around. Can someone explain this to me?</p>
| 22
|
2009-02-28T15:30:19Z
| 598,227
|
<p>"Can someone explain this to me?"</p>
<p>Depends. </p>
<p>Here's one explanation, but it's not helpful. Your question stems from your assumptions. Since the real world conflicts with your assumptions, it must mean your assumptions are wrong. Not much of an explanation, but that's why you're asking.</p>
<p>"Exception handling means a dynamic call and a static return, whereas an if statement is static call, static return."</p>
<p>What does "dynamic call" mean? Searching stack frames for a handler? I'm assuming that's what you're talking about. And a "static call" is somehow locating the block after the if statement.</p>
<p>Perhaps this "dynamic call" is not the most costly part of the operation. Perhaps the if-statement expression evaluation is slightly more expensive than the simpler "try-it-and-fail".</p>
<p>Turns out that Python's internal integrity checks are almost the same as your if-statement, and have to be done anyway. Since Python's always going to check, your if-statement is (mostly) redundant.</p>
<p>You can read about low-level exception handling in <a href="http://docs.python.org/c-api/intro.html#exceptions">http://docs.python.org/c-api/intro.html#exceptions</a>. </p>
<p><hr /></p>
<p><strong>Edit</strong></p>
<p>More to the point: <strong>The if vs. except debate doesn't matter.</strong></p>
<p>Since exceptions are cheap, do not label them as a performance problem.</p>
<p>Use what makes your code <strong>clear</strong> and <strong>meaningful</strong>. Don't waste time on micro-optimizations like this. </p>
| 9
|
2009-02-28T16:07:32Z
|
[
"python",
"performance",
"exception-handling"
] |
Cheap exception handling in Python?
| 598,157
|
<p>I read in an earlier <a href="http://stackoverflow.com/questions/576988/python-specific-antipatterns/577731#577731">answer</a> that exception handling is cheap in Python so we shouldn't do pre-conditional checking.</p>
<p>I have not heard of this before, but I'm relatively new to Python. Exception handling means a dynamic call and a static return, whereas an <code>if</code> statement is static call, static return.</p>
<p>How can doing the checking be bad and the <code>try-except</code> be good, seems to be the other way around. Can someone explain this to me?</p>
| 22
|
2009-02-28T15:30:19Z
| 598,559
|
<p>Putting aside the performance measurements that others have said, the guiding principle is often structured as "it is easier to ask forgiveness than ask permission" vs. "look before you leap."</p>
<p>Consider these two snippets:</p>
<pre><code># Look before you leap
if not os.path.exists(filename):
raise SomeError("Cannot open configuration file")
f = open(filename)
</code></pre>
<p>vs.</p>
<pre><code># Ask forgiveness ...
try:
f = open(filename)
except IOError:
raise SomeError("Cannot open configuration file")
</code></pre>
<p>Equivalent? Not really. OSes are multi-taking systems. What happens if the file was deleted between the test for 'exists' and 'open' call?</p>
<p>What happens if the file exists but it's not readable? What if it's a directory name instead of a file. There can be many possible failure modes and checking all of them is a lot of work. Especially since the 'open' call already checks and reports all of those possible failures.</p>
<p>The guideline should be to reduce the chance of inconsistent state, and the best way for that is to use exceptions instead of test/call.</p>
| 20
|
2009-02-28T19:50:34Z
|
[
"python",
"performance",
"exception-handling"
] |
Cheap exception handling in Python?
| 598,157
|
<p>I read in an earlier <a href="http://stackoverflow.com/questions/576988/python-specific-antipatterns/577731#577731">answer</a> that exception handling is cheap in Python so we shouldn't do pre-conditional checking.</p>
<p>I have not heard of this before, but I'm relatively new to Python. Exception handling means a dynamic call and a static return, whereas an <code>if</code> statement is static call, static return.</p>
<p>How can doing the checking be bad and the <code>try-except</code> be good, seems to be the other way around. Can someone explain this to me?</p>
| 22
|
2009-02-28T15:30:19Z
| 600,628
|
<p>The general message, as S.Lott said, is that try/except <em>doesn't hurt</em> so you should feel free to use it whenever it seems appropriate.</p>
<p>This debate is often called "LBYL vs EAFP" â that's "look before you leap" vs "easier to ask forgiveness than permission". <a href="http://en.wikipedia.org/wiki/Alex%5FMartelli" rel="nofollow">Alex Martelli</a> weighs forth on the subject here: <a href="http://mail.python.org/pipermail/python-list/2003-May/205182.html" rel="nofollow">http://mail.python.org/pipermail/python-list/2003-May/205182.html</a> This debate is almost six years old, but I don't think the basic issues have changed very much.</p>
| 1
|
2009-03-01T21:56:02Z
|
[
"python",
"performance",
"exception-handling"
] |
When is it (not) appropriate to bundle dependencies with an application?
| 598,299
|
<p><strong>Summary</strong></p>
<p>I recently had a conversation with the creator of a framework that one of my applications depends on. During that conversation he mentioned as a sort of aside that it would make my life simpler if I just bundled his framework with my application and delivered to the end user a version that I knew was consistent with my code. Intuitively I have always tried to avoid doing this and, in fact, I have taken pains to segment my own code so that portions of it could be redistributed without taking the entire project (even when there was precious little chance anyone would ever reuse any of it). However, after mulling it over for some time I have not been able to come up with a particularly good reason <em>why</em> I do this. In fact, now that I have thought about it, I'm seeing a pretty compelling case to bundle <em>all</em> my smaller dependencies. I have come up with a list of pros and cons and I'm hoping someone can point out anything that I'm missing.</p>
<p><strong>Pros</strong></p>
<ul>
<li>Consistency of versions means easier
testing and troubleshooting.</li>
<li>Application may reach a wider
audience since there appear to be
fewer components to install.</li>
<li>Small tweaks to the dependency can
more easily be made downstream and
delivered with the application,
rather than waiting for them to
percolate into the upstream code base.</li>
</ul>
<p><strong>Cons</strong></p>
<ul>
<li>More complex packaging process to include
dependencies.</li>
<li>User may end up with multiple copies
of a dependency on their machine.</li>
<li>Per bortzmeyer's response, there are potential security concerns with not being able to upgrade individual components.</li>
</ul>
<p><strong>Notes</strong></p>
<p>For reference, my application is written in Python and the dependencies I'm referencing are "light", by which I mean small and not in very common use. (So they do not exist on all machines or even in all repositories.) And when I say "package with" my application, I mean distribute under my own source tree, not install with a script that resides inside my package, so there would be no chance of conflicting versions. I am also developing solely on Linux so there are no Windows installation issues to worry about.</p>
<p>All that being said, I am interested in hearing any thoughts on the broader (language-independent) issue of packaging dependencies as well. Is there something I am missing or is this an easy decision that I am just over-thinking?</p>
<p><strong>Addendum 1</strong></p>
<p>It is worth mentioning that I am also quite sensitive to the needs of downstream packagers. I would like it to be as straightforward as possible to wrap the application up in a distribution-specific Deb or RPM.</p>
| 12
|
2009-02-28T16:59:37Z
| 598,333
|
<p>Just my experience, take it with a grain of salt.</p>
<p>My preference for a couple of open-source libraries that I author is for independence from additional libs as much as possible. Reason being, not only am I on the hook for distribution of additional libraries along with mine, I'm also obliged to update my application for compatibility as those other libraries are updated as well.</p>
<p>From the libraries I've used from others that carry dependencies of "common" libraries, invariably I end up with requiring multiple versions of the common library on my system. The relative update speed of the niche libraries I'm using just isn't that fast, while the common libraries are updated much more often. Versioning hell.</p>
<p>But that's speaking generically. If I can aid my project and users NOW by incorporating a dependency, I'm always looking at the downstream and later-date effects of that decision. If I can manage it, I can confidently include the dependency.</p>
<p>As always, your mileage may vary.</p>
| 1
|
2009-02-28T17:16:29Z
|
[
"python",
"dependencies",
"distribution",
"packaging"
] |
When is it (not) appropriate to bundle dependencies with an application?
| 598,299
|
<p><strong>Summary</strong></p>
<p>I recently had a conversation with the creator of a framework that one of my applications depends on. During that conversation he mentioned as a sort of aside that it would make my life simpler if I just bundled his framework with my application and delivered to the end user a version that I knew was consistent with my code. Intuitively I have always tried to avoid doing this and, in fact, I have taken pains to segment my own code so that portions of it could be redistributed without taking the entire project (even when there was precious little chance anyone would ever reuse any of it). However, after mulling it over for some time I have not been able to come up with a particularly good reason <em>why</em> I do this. In fact, now that I have thought about it, I'm seeing a pretty compelling case to bundle <em>all</em> my smaller dependencies. I have come up with a list of pros and cons and I'm hoping someone can point out anything that I'm missing.</p>
<p><strong>Pros</strong></p>
<ul>
<li>Consistency of versions means easier
testing and troubleshooting.</li>
<li>Application may reach a wider
audience since there appear to be
fewer components to install.</li>
<li>Small tweaks to the dependency can
more easily be made downstream and
delivered with the application,
rather than waiting for them to
percolate into the upstream code base.</li>
</ul>
<p><strong>Cons</strong></p>
<ul>
<li>More complex packaging process to include
dependencies.</li>
<li>User may end up with multiple copies
of a dependency on their machine.</li>
<li>Per bortzmeyer's response, there are potential security concerns with not being able to upgrade individual components.</li>
</ul>
<p><strong>Notes</strong></p>
<p>For reference, my application is written in Python and the dependencies I'm referencing are "light", by which I mean small and not in very common use. (So they do not exist on all machines or even in all repositories.) And when I say "package with" my application, I mean distribute under my own source tree, not install with a script that resides inside my package, so there would be no chance of conflicting versions. I am also developing solely on Linux so there are no Windows installation issues to worry about.</p>
<p>All that being said, I am interested in hearing any thoughts on the broader (language-independent) issue of packaging dependencies as well. Is there something I am missing or is this an easy decision that I am just over-thinking?</p>
<p><strong>Addendum 1</strong></p>
<p>It is worth mentioning that I am also quite sensitive to the needs of downstream packagers. I would like it to be as straightforward as possible to wrap the application up in a distribution-specific Deb or RPM.</p>
| 12
|
2009-02-28T16:59:37Z
| 598,343
|
<p>Can't you just rely on a certain version of those dependencies? E.g. in Python with <a href="http://peak.telecommunity.com/DevCenter/setuptools" rel="nofollow">setuptools</a> you can specify which exact version it needs or even give some conditions like <= > etc. This of course only applies to Python and on the specifc package manager but I would personally always first try not to bundle everything. With shipping it as a Python egg you will also have all the dependencies installed automatically. </p>
<p>You might of course also use a two-way strategy in providing your own package with just links to the dependencies and nevertheless provide a complete setup in some installer like fashion. But even then (in the python case) I would suggest to simply bundle the eggs with it. </p>
<p>For some introduction into eggs see <a href="http://mrtopf.de/blog/python%5Fzope/a-small-introduction-to-python-eggs/" rel="nofollow">this post of mine</a>.</p>
<p>Of course this is very Python specific but I assume that other language might have similar packaging tools.</p>
| 3
|
2009-02-28T17:24:01Z
|
[
"python",
"dependencies",
"distribution",
"packaging"
] |
When is it (not) appropriate to bundle dependencies with an application?
| 598,299
|
<p><strong>Summary</strong></p>
<p>I recently had a conversation with the creator of a framework that one of my applications depends on. During that conversation he mentioned as a sort of aside that it would make my life simpler if I just bundled his framework with my application and delivered to the end user a version that I knew was consistent with my code. Intuitively I have always tried to avoid doing this and, in fact, I have taken pains to segment my own code so that portions of it could be redistributed without taking the entire project (even when there was precious little chance anyone would ever reuse any of it). However, after mulling it over for some time I have not been able to come up with a particularly good reason <em>why</em> I do this. In fact, now that I have thought about it, I'm seeing a pretty compelling case to bundle <em>all</em> my smaller dependencies. I have come up with a list of pros and cons and I'm hoping someone can point out anything that I'm missing.</p>
<p><strong>Pros</strong></p>
<ul>
<li>Consistency of versions means easier
testing and troubleshooting.</li>
<li>Application may reach a wider
audience since there appear to be
fewer components to install.</li>
<li>Small tweaks to the dependency can
more easily be made downstream and
delivered with the application,
rather than waiting for them to
percolate into the upstream code base.</li>
</ul>
<p><strong>Cons</strong></p>
<ul>
<li>More complex packaging process to include
dependencies.</li>
<li>User may end up with multiple copies
of a dependency on their machine.</li>
<li>Per bortzmeyer's response, there are potential security concerns with not being able to upgrade individual components.</li>
</ul>
<p><strong>Notes</strong></p>
<p>For reference, my application is written in Python and the dependencies I'm referencing are "light", by which I mean small and not in very common use. (So they do not exist on all machines or even in all repositories.) And when I say "package with" my application, I mean distribute under my own source tree, not install with a script that resides inside my package, so there would be no chance of conflicting versions. I am also developing solely on Linux so there are no Windows installation issues to worry about.</p>
<p>All that being said, I am interested in hearing any thoughts on the broader (language-independent) issue of packaging dependencies as well. Is there something I am missing or is this an easy decision that I am just over-thinking?</p>
<p><strong>Addendum 1</strong></p>
<p>It is worth mentioning that I am also quite sensitive to the needs of downstream packagers. I would like it to be as straightforward as possible to wrap the application up in a distribution-specific Deb or RPM.</p>
| 12
|
2009-02-28T16:59:37Z
| 598,397
|
<p>I favor bundling dependencies, <em>if</em> it's not feasible to use a system for automatic dependency resolution (i.e. setuptools), and <em>if</em> you can do it without introducing version conflicts. You still have to consider your application and your audience; serious developers or enthusiasts are more likely to want to work with a specific (latest) version of the dependency. Bundling stuff in may be annoying for them, since it's not what they expect.</p>
<p>But, especially for end-users of an application, I seriously doubt most people enjoy having to search for dependencies. As far as having duplicate copies goes, I would much rather spend an extra 10 milliseconds downloading some additional kilobytes, or spend whatever fraction of a cent on the extra meg of disk space, than spend 10+ minutes searching through websites (which may be down), downloading, installing (which may fail if versions are incompatible), etc.</p>
<p>I don't care how many copies of a library I have on my disk, as long as they don't get in each others' way. Disk space is really, really cheap.</p>
| 8
|
2009-02-28T18:03:58Z
|
[
"python",
"dependencies",
"distribution",
"packaging"
] |
When is it (not) appropriate to bundle dependencies with an application?
| 598,299
|
<p><strong>Summary</strong></p>
<p>I recently had a conversation with the creator of a framework that one of my applications depends on. During that conversation he mentioned as a sort of aside that it would make my life simpler if I just bundled his framework with my application and delivered to the end user a version that I knew was consistent with my code. Intuitively I have always tried to avoid doing this and, in fact, I have taken pains to segment my own code so that portions of it could be redistributed without taking the entire project (even when there was precious little chance anyone would ever reuse any of it). However, after mulling it over for some time I have not been able to come up with a particularly good reason <em>why</em> I do this. In fact, now that I have thought about it, I'm seeing a pretty compelling case to bundle <em>all</em> my smaller dependencies. I have come up with a list of pros and cons and I'm hoping someone can point out anything that I'm missing.</p>
<p><strong>Pros</strong></p>
<ul>
<li>Consistency of versions means easier
testing and troubleshooting.</li>
<li>Application may reach a wider
audience since there appear to be
fewer components to install.</li>
<li>Small tweaks to the dependency can
more easily be made downstream and
delivered with the application,
rather than waiting for them to
percolate into the upstream code base.</li>
</ul>
<p><strong>Cons</strong></p>
<ul>
<li>More complex packaging process to include
dependencies.</li>
<li>User may end up with multiple copies
of a dependency on their machine.</li>
<li>Per bortzmeyer's response, there are potential security concerns with not being able to upgrade individual components.</li>
</ul>
<p><strong>Notes</strong></p>
<p>For reference, my application is written in Python and the dependencies I'm referencing are "light", by which I mean small and not in very common use. (So they do not exist on all machines or even in all repositories.) And when I say "package with" my application, I mean distribute under my own source tree, not install with a script that resides inside my package, so there would be no chance of conflicting versions. I am also developing solely on Linux so there are no Windows installation issues to worry about.</p>
<p>All that being said, I am interested in hearing any thoughts on the broader (language-independent) issue of packaging dependencies as well. Is there something I am missing or is this an easy decision that I am just over-thinking?</p>
<p><strong>Addendum 1</strong></p>
<p>It is worth mentioning that I am also quite sensitive to the needs of downstream packagers. I would like it to be as straightforward as possible to wrap the application up in a distribution-specific Deb or RPM.</p>
| 12
|
2009-02-28T16:59:37Z
| 598,599
|
<p>I always include all dependancies for my web applications. Not only does this make installation simpler, the application remains stable and working the way you expect it to even when other components on the system are upgraded.</p>
| 1
|
2009-02-28T20:14:12Z
|
[
"python",
"dependencies",
"distribution",
"packaging"
] |
When is it (not) appropriate to bundle dependencies with an application?
| 598,299
|
<p><strong>Summary</strong></p>
<p>I recently had a conversation with the creator of a framework that one of my applications depends on. During that conversation he mentioned as a sort of aside that it would make my life simpler if I just bundled his framework with my application and delivered to the end user a version that I knew was consistent with my code. Intuitively I have always tried to avoid doing this and, in fact, I have taken pains to segment my own code so that portions of it could be redistributed without taking the entire project (even when there was precious little chance anyone would ever reuse any of it). However, after mulling it over for some time I have not been able to come up with a particularly good reason <em>why</em> I do this. In fact, now that I have thought about it, I'm seeing a pretty compelling case to bundle <em>all</em> my smaller dependencies. I have come up with a list of pros and cons and I'm hoping someone can point out anything that I'm missing.</p>
<p><strong>Pros</strong></p>
<ul>
<li>Consistency of versions means easier
testing and troubleshooting.</li>
<li>Application may reach a wider
audience since there appear to be
fewer components to install.</li>
<li>Small tweaks to the dependency can
more easily be made downstream and
delivered with the application,
rather than waiting for them to
percolate into the upstream code base.</li>
</ul>
<p><strong>Cons</strong></p>
<ul>
<li>More complex packaging process to include
dependencies.</li>
<li>User may end up with multiple copies
of a dependency on their machine.</li>
<li>Per bortzmeyer's response, there are potential security concerns with not being able to upgrade individual components.</li>
</ul>
<p><strong>Notes</strong></p>
<p>For reference, my application is written in Python and the dependencies I'm referencing are "light", by which I mean small and not in very common use. (So they do not exist on all machines or even in all repositories.) And when I say "package with" my application, I mean distribute under my own source tree, not install with a script that resides inside my package, so there would be no chance of conflicting versions. I am also developing solely on Linux so there are no Windows installation issues to worry about.</p>
<p>All that being said, I am interested in hearing any thoughts on the broader (language-independent) issue of packaging dependencies as well. Is there something I am missing or is this an easy decision that I am just over-thinking?</p>
<p><strong>Addendum 1</strong></p>
<p>It is worth mentioning that I am also quite sensitive to the needs of downstream packagers. I would like it to be as straightforward as possible to wrap the application up in a distribution-specific Deb or RPM.</p>
| 12
|
2009-02-28T16:59:37Z
| 598,614
|
<p>Beware reproducing the classic Windows DLL hell. By all means minimize the number of dependencies: ideally, just depend on your language and its framework, nothing else, if you can.</p>
<p>After all, preserving hard disk space is hardly the objective any more, so users need not care about having multiple copies. Also, unless you have a minuscule number of users, be sure to take the onus of packaging on yourself rather than requiring them to obtain all dependencies!</p>
| 1
|
2009-02-28T20:19:48Z
|
[
"python",
"dependencies",
"distribution",
"packaging"
] |
When is it (not) appropriate to bundle dependencies with an application?
| 598,299
|
<p><strong>Summary</strong></p>
<p>I recently had a conversation with the creator of a framework that one of my applications depends on. During that conversation he mentioned as a sort of aside that it would make my life simpler if I just bundled his framework with my application and delivered to the end user a version that I knew was consistent with my code. Intuitively I have always tried to avoid doing this and, in fact, I have taken pains to segment my own code so that portions of it could be redistributed without taking the entire project (even when there was precious little chance anyone would ever reuse any of it). However, after mulling it over for some time I have not been able to come up with a particularly good reason <em>why</em> I do this. In fact, now that I have thought about it, I'm seeing a pretty compelling case to bundle <em>all</em> my smaller dependencies. I have come up with a list of pros and cons and I'm hoping someone can point out anything that I'm missing.</p>
<p><strong>Pros</strong></p>
<ul>
<li>Consistency of versions means easier
testing and troubleshooting.</li>
<li>Application may reach a wider
audience since there appear to be
fewer components to install.</li>
<li>Small tweaks to the dependency can
more easily be made downstream and
delivered with the application,
rather than waiting for them to
percolate into the upstream code base.</li>
</ul>
<p><strong>Cons</strong></p>
<ul>
<li>More complex packaging process to include
dependencies.</li>
<li>User may end up with multiple copies
of a dependency on their machine.</li>
<li>Per bortzmeyer's response, there are potential security concerns with not being able to upgrade individual components.</li>
</ul>
<p><strong>Notes</strong></p>
<p>For reference, my application is written in Python and the dependencies I'm referencing are "light", by which I mean small and not in very common use. (So they do not exist on all machines or even in all repositories.) And when I say "package with" my application, I mean distribute under my own source tree, not install with a script that resides inside my package, so there would be no chance of conflicting versions. I am also developing solely on Linux so there are no Windows installation issues to worry about.</p>
<p>All that being said, I am interested in hearing any thoughts on the broader (language-independent) issue of packaging dependencies as well. Is there something I am missing or is this an easy decision that I am just over-thinking?</p>
<p><strong>Addendum 1</strong></p>
<p>It is worth mentioning that I am also quite sensitive to the needs of downstream packagers. I would like it to be as straightforward as possible to wrap the application up in a distribution-specific Deb or RPM.</p>
| 12
|
2009-02-28T16:59:37Z
| 603,778
|
<p>For Linux, don't even think about bundling. You aren't smarter than the package manager or the packagers, and each distribution takes approach their own way - they won't be happy if you attempt to go your way. At best, they won't bother with packaging your app, which isn't great.</p>
<p>Keep in mind that in Linux, dependencies are automatically pulled in for you. It's not a matter of making the user get them. It's already done for you.</p>
<p>For windows, feel free to bundle, you're on your own there.</p>
| 2
|
2009-03-02T20:05:06Z
|
[
"python",
"dependencies",
"distribution",
"packaging"
] |
When is it (not) appropriate to bundle dependencies with an application?
| 598,299
|
<p><strong>Summary</strong></p>
<p>I recently had a conversation with the creator of a framework that one of my applications depends on. During that conversation he mentioned as a sort of aside that it would make my life simpler if I just bundled his framework with my application and delivered to the end user a version that I knew was consistent with my code. Intuitively I have always tried to avoid doing this and, in fact, I have taken pains to segment my own code so that portions of it could be redistributed without taking the entire project (even when there was precious little chance anyone would ever reuse any of it). However, after mulling it over for some time I have not been able to come up with a particularly good reason <em>why</em> I do this. In fact, now that I have thought about it, I'm seeing a pretty compelling case to bundle <em>all</em> my smaller dependencies. I have come up with a list of pros and cons and I'm hoping someone can point out anything that I'm missing.</p>
<p><strong>Pros</strong></p>
<ul>
<li>Consistency of versions means easier
testing and troubleshooting.</li>
<li>Application may reach a wider
audience since there appear to be
fewer components to install.</li>
<li>Small tweaks to the dependency can
more easily be made downstream and
delivered with the application,
rather than waiting for them to
percolate into the upstream code base.</li>
</ul>
<p><strong>Cons</strong></p>
<ul>
<li>More complex packaging process to include
dependencies.</li>
<li>User may end up with multiple copies
of a dependency on their machine.</li>
<li>Per bortzmeyer's response, there are potential security concerns with not being able to upgrade individual components.</li>
</ul>
<p><strong>Notes</strong></p>
<p>For reference, my application is written in Python and the dependencies I'm referencing are "light", by which I mean small and not in very common use. (So they do not exist on all machines or even in all repositories.) And when I say "package with" my application, I mean distribute under my own source tree, not install with a script that resides inside my package, so there would be no chance of conflicting versions. I am also developing solely on Linux so there are no Windows installation issues to worry about.</p>
<p>All that being said, I am interested in hearing any thoughts on the broader (language-independent) issue of packaging dependencies as well. Is there something I am missing or is this an easy decision that I am just over-thinking?</p>
<p><strong>Addendum 1</strong></p>
<p>It is worth mentioning that I am also quite sensitive to the needs of downstream packagers. I would like it to be as straightforward as possible to wrap the application up in a distribution-specific Deb or RPM.</p>
| 12
|
2009-02-28T16:59:37Z
| 603,843
|
<p>If you're producing software for an end-user, the goal is to let the customer use your software. Anything that stands in the way is counter-productive. If they have to download dependencies themselves, there's a possibility that they'll decide to avoid your software instead. You can't control whether libraries will be backwards compatible, and you don't want your software to stop working because the user updated their system. Similarly, you don't want a customer to install an old version of your software with old libraries and have the rest of the system break. </p>
<p>This means bundling is generally the way to go. If you can ensure that your software will install smoothly without bundling dependencies, and that's less work, then that may be a better option. It's about what satisfies your customers.</p>
| 3
|
2009-03-02T20:20:52Z
|
[
"python",
"dependencies",
"distribution",
"packaging"
] |
When is it (not) appropriate to bundle dependencies with an application?
| 598,299
|
<p><strong>Summary</strong></p>
<p>I recently had a conversation with the creator of a framework that one of my applications depends on. During that conversation he mentioned as a sort of aside that it would make my life simpler if I just bundled his framework with my application and delivered to the end user a version that I knew was consistent with my code. Intuitively I have always tried to avoid doing this and, in fact, I have taken pains to segment my own code so that portions of it could be redistributed without taking the entire project (even when there was precious little chance anyone would ever reuse any of it). However, after mulling it over for some time I have not been able to come up with a particularly good reason <em>why</em> I do this. In fact, now that I have thought about it, I'm seeing a pretty compelling case to bundle <em>all</em> my smaller dependencies. I have come up with a list of pros and cons and I'm hoping someone can point out anything that I'm missing.</p>
<p><strong>Pros</strong></p>
<ul>
<li>Consistency of versions means easier
testing and troubleshooting.</li>
<li>Application may reach a wider
audience since there appear to be
fewer components to install.</li>
<li>Small tweaks to the dependency can
more easily be made downstream and
delivered with the application,
rather than waiting for them to
percolate into the upstream code base.</li>
</ul>
<p><strong>Cons</strong></p>
<ul>
<li>More complex packaging process to include
dependencies.</li>
<li>User may end up with multiple copies
of a dependency on their machine.</li>
<li>Per bortzmeyer's response, there are potential security concerns with not being able to upgrade individual components.</li>
</ul>
<p><strong>Notes</strong></p>
<p>For reference, my application is written in Python and the dependencies I'm referencing are "light", by which I mean small and not in very common use. (So they do not exist on all machines or even in all repositories.) And when I say "package with" my application, I mean distribute under my own source tree, not install with a script that resides inside my package, so there would be no chance of conflicting versions. I am also developing solely on Linux so there are no Windows installation issues to worry about.</p>
<p>All that being said, I am interested in hearing any thoughts on the broader (language-independent) issue of packaging dependencies as well. Is there something I am missing or is this an easy decision that I am just over-thinking?</p>
<p><strong>Addendum 1</strong></p>
<p>It is worth mentioning that I am also quite sensitive to the needs of downstream packagers. I would like it to be as straightforward as possible to wrap the application up in a distribution-specific Deb or RPM.</p>
| 12
|
2009-02-28T16:59:37Z
| 609,861
|
<p>An important point seems to have been forgotten in the Cons of bundling libraries/frameworks/etc with the application: security updates.</p>
<p>Most Web frameworks are full of security holes and require frequent patching. Any library, anyway, may have to be upgraded one day or the other for a security bug.</p>
<p>If you do not bundle, sysadmins will just upgrade one copy of the library and restart depending applications. </p>
<p>If you bundle, sysadmins will probably not even <strong>know</strong> they have to upgrade something.</p>
<p>So, the issue with bundling is not the disk space, it's the risk of letting old and dangerous copies around.</p>
| 2
|
2009-03-04T09:32:22Z
|
[
"python",
"dependencies",
"distribution",
"packaging"
] |
Searching a list of objects in Python
| 598,398
|
<p>Let's assume I'm creating a simple class to work similar to a C-style struct, to just hold data elements. I'm trying to figure out how to search the list of objects for objects with a certain attribute. Below is a trivial example to illustrate what I'm trying to do.</p>
<p>For instance:</p>
<pre><code>class Data:
pass
myList = []
for i in range(20):
data = Data()
data.n = i
data.n_squared = i * i
myList.append(data)
</code></pre>
<p>How would I go about searching the myList list to determine if it contains an element with n == 5?</p>
<p>I've been Googling and searching the Python docs, and I think I might be able to do this with a list comprehension, but I'm not sure. I might add that I'm having to use Python 2.4.3 by the way, so any new gee-whiz 2.6 or 3.x features aren't available to me.</p>
| 32
|
2009-02-28T18:06:20Z
| 598,405
|
<p>You should add a <code>__eq__</code> and a <code>__hash__</code> method to your <code>Data</code> class, it could check if the <code>__dict__</code> attributes are equal (same properties) and then if their values are equal, too.</p>
<p>If you did that, you can use</p>
<pre><code>test = Data()
test.n = 5
found = test in myList
</code></pre>
<p>The <code>in</code> keyword checks if <code>test</code> is in <code>myList</code>.</p>
<p>If you only want to a a <code>n</code> property in <code>Data</code> you could use:</p>
<pre><code>class Data(object):
__slots__ = ['n']
def __init__(self, n):
self.n = n
def __eq__(self, other):
if not isinstance(other, Data):
return False
if self.n != other.n:
return False
return True
def __hash__(self):
return self.n
myList = [ Data(1), Data(2), Data(3) ]
Data(2) in myList #==> True
Data(5) in myList #==> False
</code></pre>
| 1
|
2009-02-28T18:10:38Z
|
[
"python"
] |
Searching a list of objects in Python
| 598,398
|
<p>Let's assume I'm creating a simple class to work similar to a C-style struct, to just hold data elements. I'm trying to figure out how to search the list of objects for objects with a certain attribute. Below is a trivial example to illustrate what I'm trying to do.</p>
<p>For instance:</p>
<pre><code>class Data:
pass
myList = []
for i in range(20):
data = Data()
data.n = i
data.n_squared = i * i
myList.append(data)
</code></pre>
<p>How would I go about searching the myList list to determine if it contains an element with n == 5?</p>
<p>I've been Googling and searching the Python docs, and I think I might be able to do this with a list comprehension, but I'm not sure. I might add that I'm having to use Python 2.4.3 by the way, so any new gee-whiz 2.6 or 3.x features aren't available to me.</p>
| 32
|
2009-02-28T18:06:20Z
| 598,407
|
<p>You can get a list of <em>all</em> matching elements with a list comprehension:</p>
<pre><code>[x for x in myList if x.n == 30] # list of all elements with .n==30
</code></pre>
<p>If you simply want to determine if the list contains <em>any</em> element that matches and do it (relatively) efficiently, you can do</p>
<pre><code>def contains(list, filter):
for x in list:
if filter(x):
return True
return False
if contains(myList, lambda x: x.n == 3) # True if any element has .n==3
# do stuff
</code></pre>
| 45
|
2009-02-28T18:11:05Z
|
[
"python"
] |
Searching a list of objects in Python
| 598,398
|
<p>Let's assume I'm creating a simple class to work similar to a C-style struct, to just hold data elements. I'm trying to figure out how to search the list of objects for objects with a certain attribute. Below is a trivial example to illustrate what I'm trying to do.</p>
<p>For instance:</p>
<pre><code>class Data:
pass
myList = []
for i in range(20):
data = Data()
data.n = i
data.n_squared = i * i
myList.append(data)
</code></pre>
<p>How would I go about searching the myList list to determine if it contains an element with n == 5?</p>
<p>I've been Googling and searching the Python docs, and I think I might be able to do this with a list comprehension, but I'm not sure. I might add that I'm having to use Python 2.4.3 by the way, so any new gee-whiz 2.6 or 3.x features aren't available to me.</p>
| 32
|
2009-02-28T18:06:20Z
| 598,415
|
<pre><code>[x for x in myList if x.n == 30] # list of all matches
any(x.n == 30 for x in myList) # if there is any matches
[i for i,x in enumerate(myList) if x.n == 30] # indices of all matches
def first(iterable, default=None):
for item in iterable:
return item
return default
first(x for x in myList if x.n == 30) # the first match, if any
</code></pre>
| 20
|
2009-02-28T18:19:28Z
|
[
"python"
] |
Searching a list of objects in Python
| 598,398
|
<p>Let's assume I'm creating a simple class to work similar to a C-style struct, to just hold data elements. I'm trying to figure out how to search the list of objects for objects with a certain attribute. Below is a trivial example to illustrate what I'm trying to do.</p>
<p>For instance:</p>
<pre><code>class Data:
pass
myList = []
for i in range(20):
data = Data()
data.n = i
data.n_squared = i * i
myList.append(data)
</code></pre>
<p>How would I go about searching the myList list to determine if it contains an element with n == 5?</p>
<p>I've been Googling and searching the Python docs, and I think I might be able to do this with a list comprehension, but I'm not sure. I might add that I'm having to use Python 2.4.3 by the way, so any new gee-whiz 2.6 or 3.x features aren't available to me.</p>
| 32
|
2009-02-28T18:06:20Z
| 598,417
|
<p>Just for completeness, let's not forget the Simplest Thing That Could Possibly Work:</p>
<pre><code>for i in list:
if i.n == 5:
# do something with it
print "YAY! Found one!"
</code></pre>
| 32
|
2009-02-28T18:20:01Z
|
[
"python"
] |
Searching a list of objects in Python
| 598,398
|
<p>Let's assume I'm creating a simple class to work similar to a C-style struct, to just hold data elements. I'm trying to figure out how to search the list of objects for objects with a certain attribute. Below is a trivial example to illustrate what I'm trying to do.</p>
<p>For instance:</p>
<pre><code>class Data:
pass
myList = []
for i in range(20):
data = Data()
data.n = i
data.n_squared = i * i
myList.append(data)
</code></pre>
<p>How would I go about searching the myList list to determine if it contains an element with n == 5?</p>
<p>I've been Googling and searching the Python docs, and I think I might be able to do this with a list comprehension, but I'm not sure. I might add that I'm having to use Python 2.4.3 by the way, so any new gee-whiz 2.6 or 3.x features aren't available to me.</p>
| 32
|
2009-02-28T18:06:20Z
| 598,424
|
<pre><code>filter(lambda x: x.n == 5, myList)
</code></pre>
| 18
|
2009-02-28T18:22:06Z
|
[
"python"
] |
Searching a list of objects in Python
| 598,398
|
<p>Let's assume I'm creating a simple class to work similar to a C-style struct, to just hold data elements. I'm trying to figure out how to search the list of objects for objects with a certain attribute. Below is a trivial example to illustrate what I'm trying to do.</p>
<p>For instance:</p>
<pre><code>class Data:
pass
myList = []
for i in range(20):
data = Data()
data.n = i
data.n_squared = i * i
myList.append(data)
</code></pre>
<p>How would I go about searching the myList list to determine if it contains an element with n == 5?</p>
<p>I've been Googling and searching the Python docs, and I think I might be able to do this with a list comprehension, but I'm not sure. I might add that I'm having to use Python 2.4.3 by the way, so any new gee-whiz 2.6 or 3.x features aren't available to me.</p>
| 32
|
2009-02-28T18:06:20Z
| 598,427
|
<p>You can use <code>in</code> to look for an item in a collection, and a list comprehension to extract the field you are interested in. This (works for lists, sets, tuples, and anything that defines <code>__contains__</code> or <code>__getitem__</code>). </p>
<pre><code>if 5 in [data.n for data in myList]:
print "Found it"
</code></pre>
<p>See also:</p>
<ul>
<li><a href="http://docs.python.org/reference/datamodel.html#object.%5F%5Fcontains%5F%5F">Contains Method</a></li>
<li><a href="http://docs.python.org/reference/expressions.html#in">In operation</a></li>
</ul>
| 7
|
2009-02-28T18:23:29Z
|
[
"python"
] |
Searching a list of objects in Python
| 598,398
|
<p>Let's assume I'm creating a simple class to work similar to a C-style struct, to just hold data elements. I'm trying to figure out how to search the list of objects for objects with a certain attribute. Below is a trivial example to illustrate what I'm trying to do.</p>
<p>For instance:</p>
<pre><code>class Data:
pass
myList = []
for i in range(20):
data = Data()
data.n = i
data.n_squared = i * i
myList.append(data)
</code></pre>
<p>How would I go about searching the myList list to determine if it contains an element with n == 5?</p>
<p>I've been Googling and searching the Python docs, and I think I might be able to do this with a list comprehension, but I'm not sure. I might add that I'm having to use Python 2.4.3 by the way, so any new gee-whiz 2.6 or 3.x features aren't available to me.</p>
| 32
|
2009-02-28T18:06:20Z
| 598,602
|
<p><strong>Simple, Elegant, and Powerful:</strong></p>
<p>A generator expression in conjuction with a builtin⦠(python 2.5+)</p>
<pre><code>any(x for x in mylist if x.n == 10)
</code></pre>
<p>Uses the Python <a href="http://docs.python.org/2/library/functions.html#any"><code>any()</code></a> builtin, which is defined as follows:</p>
<blockquote>
<p><strong>any(iterable)</strong> <code>-></code>
Return True if any element of the iterable is true. Equivalent to:</p>
</blockquote>
<pre><code>def any(iterable):
for element in iterable:
if element:
return True
return False
</code></pre>
| 31
|
2009-02-28T20:15:28Z
|
[
"python"
] |
Searching a list of objects in Python
| 598,398
|
<p>Let's assume I'm creating a simple class to work similar to a C-style struct, to just hold data elements. I'm trying to figure out how to search the list of objects for objects with a certain attribute. Below is a trivial example to illustrate what I'm trying to do.</p>
<p>For instance:</p>
<pre><code>class Data:
pass
myList = []
for i in range(20):
data = Data()
data.n = i
data.n_squared = i * i
myList.append(data)
</code></pre>
<p>How would I go about searching the myList list to determine if it contains an element with n == 5?</p>
<p>I've been Googling and searching the Python docs, and I think I might be able to do this with a list comprehension, but I'm not sure. I might add that I'm having to use Python 2.4.3 by the way, so any new gee-whiz 2.6 or 3.x features aren't available to me.</p>
| 32
|
2009-02-28T18:06:20Z
| 599,045
|
<p>Consider using a dictionary:</p>
<pre><code>myDict = {}
for i in range(20):
myDict[i] = i * i
print(5 in myDict)
</code></pre>
| 3
|
2009-03-01T01:14:25Z
|
[
"python"
] |
Calling function defined in exe
| 598,569
|
<p>I need to know a way to call a function defined in the exe from a python script.
I know how to call entire exe from py file.</p>
| 3
|
2009-02-28T19:55:21Z
| 598,571
|
<p>Unless the said executable takes command line arguments which will specify which function to use, I don't think this is possible.</p>
<p>With that being said, if you created the EXE, command line arguments are a good way to implement the functionality you're looking for.</p>
| 0
|
2009-02-28T19:57:59Z
|
[
"python"
] |
Calling function defined in exe
| 598,569
|
<p>I need to know a way to call a function defined in the exe from a python script.
I know how to call entire exe from py file.</p>
| 3
|
2009-02-28T19:55:21Z
| 598,582
|
<p>Unless your EXE is a COM object, or specifically exports certain functions like a dll does, then this is not possible. </p>
<p>For the COM method take a look at these resources:</p>
<ul>
<li><a href="http://oreilly.com/catalog/9781565926219/" rel="nofollow">Python Programming On Win32</a> book, by Mark Hammond and Andy Robinson.</li>
<li><a href="http://techarttiki.blogspot.com/2008/03/calling-python-from-maxscript.html" rel="nofollow">COM and Python</a> quick start on learning COM with python</li>
</ul>
<p>For the exported functions like a dll method, please use python's win32 module along with the Win32 API LoadLibrary and related functions.</p>
<p><strong>If you have access to the EXE's source code:</strong></p>
<p>If you have access to the source code of this EXE though, you should define command line arguments and tie that into calling the function you want to call. In this case you can use the python <em>os.system</em> call to start your application or <em>subprocess.call()</em>. </p>
| 6
|
2009-02-28T20:04:04Z
|
[
"python"
] |
Calling function defined in exe
| 598,569
|
<p>I need to know a way to call a function defined in the exe from a python script.
I know how to call entire exe from py file.</p>
| 3
|
2009-02-28T19:55:21Z
| 598,585
|
<p>Not sure if it is for windows. But you can treat an exe like a dll (if functions are exported). And they can be used by other programs.</p>
| 1
|
2009-02-28T20:05:16Z
|
[
"python"
] |
What SHOULDN'T Django's admin interface be used for?
| 598,577
|
<p>I've been applying Django's automatic administration capabilities to some applications who had previously been very difficult to administer. I'm thinking of a lot of ways to apply it to other applications we use (including using it to replace some internal apps altogether). Before I go overboard though, is there anything in particular I <em>shouldn't</em> use it for?</p>
| 4
|
2009-02-28T20:00:03Z
| 598,580
|
<p>User-specific privileges. I myself had been trying to work it into that-- some of the new (and at least at the time, undocumented) features (from newforms-admin) make it actually possible. Depending on how fine you want the control to be, though, you can end up getting very, very deep into the Django/admin internals. Just because you can doesn't mean you should-- it's easier and less fragile to do so with a custom admin app.</p>
| 7
|
2009-02-28T20:03:46Z
|
[
"python",
"django",
"administration"
] |
What SHOULDN'T Django's admin interface be used for?
| 598,577
|
<p>I've been applying Django's automatic administration capabilities to some applications who had previously been very difficult to administer. I'm thinking of a lot of ways to apply it to other applications we use (including using it to replace some internal apps altogether). Before I go overboard though, is there anything in particular I <em>shouldn't</em> use it for?</p>
| 4
|
2009-02-28T20:00:03Z
| 599,054
|
<p>Generally, you shouldn't use the admin for access by people you don't really trust. Even though there's plenty of flexibility in terms of locking things down and controlling access (much more so since Django 1.0), the admin is still designed on the assumption that the people using it are trusted members of your staff.</p>
| 5
|
2009-03-01T01:28:57Z
|
[
"python",
"django",
"administration"
] |
AppEngine: Query datastore for records with <missing> value
| 598,605
|
<p>I created a new property for my db model in the Google App Engine Datastore.</p>
<p>Old:</p>
<pre><code>class Logo(db.Model):
name = db.StringProperty()
image = db.BlobProperty()
</code></pre>
<p>New:</p>
<pre><code>class Logo(db.Model):
name = db.StringProperty()
image = db.BlobProperty()
is_approved = db.BooleanProperty(default=False)
</code></pre>
<p>How to query for the Logo records, which to not have the 'is_approved' value set?
I tried </p>
<pre><code>logos.filter("is_approved = ", None)
</code></pre>
<p>but it didn't work.
In the Data Viewer the new field values are displayed as .</p>
| 20
|
2009-02-28T20:16:28Z
| 598,975
|
<p>According to the App Engine documentation on <a href="http://code.google.com/appengine/docs/python/datastore/queriesandindexes.html#Introducing%5FIndexes">Queries and Indexes</a>, there is a distinction between entities that have <em>no</em> value for a property, and those that have a <em>null</em> value for it; and "Entities Without a Filtered Property Are Never Returned by a Query." So it is not possible to write a query for these old records.</p>
<p>A useful article is <a href="http://code.google.com/appengine/articles/update%5Fschema.html">Updating Your Model's Schema</a>, which says that the only currently-supported way to find entities missing some property is to examine all of them. The article has example code showing how to cycle through a large set of entities and update them.</p>
| 30
|
2009-03-01T00:26:57Z
|
[
"python",
"google-app-engine",
"google-cloud-datastore"
] |
AppEngine: Query datastore for records with <missing> value
| 598,605
|
<p>I created a new property for my db model in the Google App Engine Datastore.</p>
<p>Old:</p>
<pre><code>class Logo(db.Model):
name = db.StringProperty()
image = db.BlobProperty()
</code></pre>
<p>New:</p>
<pre><code>class Logo(db.Model):
name = db.StringProperty()
image = db.BlobProperty()
is_approved = db.BooleanProperty(default=False)
</code></pre>
<p>How to query for the Logo records, which to not have the 'is_approved' value set?
I tried </p>
<pre><code>logos.filter("is_approved = ", None)
</code></pre>
<p>but it didn't work.
In the Data Viewer the new field values are displayed as .</p>
| 20
|
2009-02-28T20:16:28Z
| 8,599,897
|
<p>Maybe this has changed, but I am able to filter records based on <strong>null</strong> fields.</p>
<p>When I try the GQL query <code>SELECT * FROM Contact WHERE demo=NULL</code>, it returns only records for which the demo field is missing.</p>
<p>According to the doc <a href="http://code.google.com/appengine/docs/python/datastore/gqlreference.html" rel="nofollow">http://code.google.com/appengine/docs/python/datastore/gqlreference.html</a>:</p>
<blockquote>
<p>The right-hand side of a comparison can be one of the following (as
appropriate for the property's data type): [...] a Boolean literal, as TRUE or
FALSE; the <strong>NULL</strong> literal, which represents the null value (None in
Python).</p>
</blockquote>
<p>I'm not sure that <strong>"null"</strong> is the same as <strong>"missing"</strong> though : in my case, these fields already existed in my model but were not populated on creation. Maybe Federico you could let us know if the NULL query works in your specific case?</p>
| 2
|
2011-12-22T05:49:05Z
|
[
"python",
"google-app-engine",
"google-cloud-datastore"
] |
Where is the function get_example_data in matplotlib? It seems to be missing but its in examples/tutorials
| 598,626
|
<p>Looking at this tutorial here: <a href="http://matplotlib.sourceforge.net/plot%5Fdirective/mpl%5Fexamples/pylab%5Fexamples/finance%5Fwork2.py" rel="nofollow">link text</a> it references matplotlib.get_example_data('goog.npy'). I get an error when I run this, and furthermore I can't even find the mpl-data/ folder in my macosx installation of matplot lib when searching using Spotlight. Any idea what this function is now called?</p>
| 2
|
2009-02-28T20:28:37Z
| 598,653
|
<p>It's defined in <code>__init__.py</code> (around line 490), if that's what you're asking.</p>
<p>-- MarkusQ</p>
<p>P.S. The <code>mpl_data/</code> directory is there too (both of them are in the top level directory). Are you sure you've got a good / complete installation?</p>
| 1
|
2009-02-28T20:45:37Z
|
[
"python",
"graph",
"visualization",
"matplotlib"
] |
Where is the function get_example_data in matplotlib? It seems to be missing but its in examples/tutorials
| 598,626
|
<p>Looking at this tutorial here: <a href="http://matplotlib.sourceforge.net/plot%5Fdirective/mpl%5Fexamples/pylab%5Fexamples/finance%5Fwork2.py" rel="nofollow">link text</a> it references matplotlib.get_example_data('goog.npy'). I get an error when I run this, and furthermore I can't even find the mpl-data/ folder in my macosx installation of matplot lib when searching using Spotlight. Any idea what this function is now called?</p>
| 2
|
2009-02-28T20:28:37Z
| 9,392,115
|
<p>I just had a similar (the same?) problem for Ubuntu 10.04 (Python 2.6.5, MPL 0.99.1.1).</p>
<p>There was no <code>get_sample_data</code>, however a <code>get_example_data</code> in <code>/usr/lib/pymodules/python2.6/matplotlib/__init__.py</code> which didn't really work. The directory <code>/usr/local/lib/python2.6/site-packages</code> was empty.</p>
<p>As a workaround, I downloaded the file <a href="https://github.com/matplotlib/sample_data/blob/master/goog.npy" rel="nofollow">goog.npy</a> directly and replaced the loading of the data with (probably similar)</p>
<pre><code>with open("goog.npy") as f:
r = np.load(f).view(np.recarray)
</code></pre>
| 0
|
2012-02-22T09:26:26Z
|
[
"python",
"graph",
"visualization",
"matplotlib"
] |
External classes in Python
| 598,668
|
<p>I'm just beginning Python, and I'd like to use an external RSS class. Where do I put that class and how do I import it? I'd like to eventually be able to share python programs.</p>
| 4
|
2009-02-28T20:54:02Z
| 598,674
|
<pre><code>from [module] import [classname]
</code></pre>
<p>Where the module is somewhere on your python path.</p>
| 1
|
2009-02-28T20:55:38Z
|
[
"python",
"python-module",
"python-import"
] |
External classes in Python
| 598,668
|
<p>I'm just beginning Python, and I'd like to use an external RSS class. Where do I put that class and how do I import it? I'd like to eventually be able to share python programs.</p>
| 4
|
2009-02-28T20:54:02Z
| 598,685
|
<p>About modules and packages:</p>
<ul>
<li><p>a module is a file ending with <code>.py</code>. You can put your class in such a file. As said by Andy, it needs to be in your python path (<code>PYTHONPATH</code>). Usually you will put the additional module in the same directory as your script is though which can be directly imported.</p></li>
<li><p>a package is a directory containing an <code>__init__.py</code> (can be empty) and contains module files. You can then import a la <code>from <package>.<module> import <class></code>. Again this needs to be on your python path.</p></li>
</ul>
<p>You can find more <a href="http://docs.python.org/tutorial/modules.html" rel="nofollow">in the documenation</a>.</p>
| 1
|
2009-02-28T21:03:26Z
|
[
"python",
"python-module",
"python-import"
] |
External classes in Python
| 598,668
|
<p>I'm just beginning Python, and I'd like to use an external RSS class. Where do I put that class and how do I import it? I'd like to eventually be able to share python programs.</p>
| 4
|
2009-02-28T20:54:02Z
| 598,686
|
<p><strong>About the <code>import</code> statement:</strong></p>
<p>(a good writeup is at <a href="http://effbot.org/zone/import-confusion.htm">http://effbot.org/zone/import-confusion.htm</a> and the python tutorial goes into detail at <a href="http://docs.python.org/tutorial/modules.html">http://docs.python.org/tutorial/modules.html</a> )</p>
<p>There are two normal ways to import code into a python program. </p>
<ol>
<li>Modules</li>
<li>Packages</li>
</ol>
<p>A module is <strong>simply</strong> a file that ends in .py. In order for python, it must exist on the search path (as defined in sys.path). The search path usually consists of the same directory of the .py that is being run, as well as the python system directories.</p>
<p>Given the following directory structure:</p>
<pre><code>myprogram/main.py
myprogram/rss.py
</code></pre>
<p>From main.py, you can "import" the rss classes by running:</p>
<pre><code>import rss
rss.rss_class()
#alternativly you can use:
from rss import rss_class
rss_class()
</code></pre>
<p><hr /></p>
<p>Packages provide a more structured way to contain larger python programs. They are simply a directory which contains an <code>__init__.py</code> as well as other python files.</p>
<p>As long as the package directory is on <code>sys.path</code>, then it can be used exactly the same as above.</p>
<p><hr /></p>
<p>To find your current path, run this:</p>
<pre><code>import sys
print(sys.path)
</code></pre>
| 12
|
2009-02-28T21:03:54Z
|
[
"python",
"python-module",
"python-import"
] |
External classes in Python
| 598,668
|
<p>I'm just beginning Python, and I'd like to use an external RSS class. Where do I put that class and how do I import it? I'd like to eventually be able to share python programs.</p>
| 4
|
2009-02-28T20:54:02Z
| 598,720
|
<p>I don't really like answering so late, but I'm not entirely satisfied with the existing answers.</p>
<blockquote>
<p>I'm just beginning Python, and I'd like to use an external RSS class. Where do I put that class and how do I import it?</p>
</blockquote>
<p>You put it in a python file, and give the python file an extension of .py . Then you can import a module representing that file, and access the class. Supposing you want to import it, you must put the python file somewhere in your import search path-- you can see this at run-time with <code>sys.path</code>, and possibly the most significant thing to know is that the site-packages (install-specific) and current directory ('') are generally in the import search path. When you have a single homogeneous project, you generally put it in the same directory as your other modules and let them import each other from the same directory.</p>
<blockquote>
<p>I'd like to eventually be able to share python programs.</p>
</blockquote>
<p>After you have it set up as a standalone file, you can get it set up for distribution using <a href="http://docs.python.org/distutils/" rel="nofollow">distutils</a>. That way you don't have to worry about where, exactly, it should be installed-- distutils will worry for you. There are many other additional means of distribution as well, many OS-specific-- distutils works for modules, but if you want to distribute a proper program that users are meant to run, other options exist, such as using <a href="http://www.py2exe.org/" rel="nofollow">py2exe</a> for Windows.</p>
<p>As for the modules/packages distinction, well, here it goes. If you've got a whole bunch of classes that you want divided up so that you don't have one big mess of a python file, you can separate it into multiple python files in a directory, and give the directory an <code>__init__.py</code> . The important thing to note is that from Python, there's no difference between a package and any other module. A package is a module, it's just a different way of representing one on the filesystem. Similarly, a module is <em>not</em> just a .py file-- if that were the case, <code>sys</code> would not be a module, since it has no .py file. It's built-in to the interpreter. There are infinitely many ways to represent modules on the filesystem, since you can add import hooks that can create ways other than directories and .py files to represent modules. One could, hypothetically, create an import hook that used spidermonkey to load Javascript files as Python modules.</p>
| 2
|
2009-02-28T21:32:13Z
|
[
"python",
"python-module",
"python-import"
] |
External classes in Python
| 598,668
|
<p>I'm just beginning Python, and I'd like to use an external RSS class. Where do I put that class and how do I import it? I'd like to eventually be able to share python programs.</p>
| 4
|
2009-02-28T20:54:02Z
| 15,196,925
|
<p>If you want to store your RSS file in a different place use sys.append("") and pout the module in that directory and use
import or from import *</p>
| 0
|
2013-03-04T07:55:03Z
|
[
"python",
"python-module",
"python-import"
] |
How to match a text node then follow parent nodes using XPath
| 598,722
|
<p>I'm trying to parse some HTML with XPath. Following the simplified XML example below, I want to match the string 'Text 1', then grab the contents of the relevant <code>content</code> node.</p>
<pre><code><doc>
<block>
<title>Text 1</title>
<content>Stuff I want</content>
</block>
<block>
<title>Text 2</title>
<content>Stuff I don't want</content>
</block>
</doc>
</code></pre>
<p>My Python code throws a wobbly:</p>
<pre><code>>>> from lxml import etree
>>>
>>> tree = etree.XML("<doc><block><title>Text 1</title><content>Stuff
I want</content></block><block><title>Text 2</title><content>Stuff I d
on't want</content></block></doc>")
>>>
>>> # get all titles
... tree.xpath('//title/text()')
['Text 1', 'Text 2']
>>>
>>> # match 'Text 1'
... tree.xpath('//title/text()="Text 1"')
True
>>>
>>> # Follow parent from selected nodes
... tree.xpath('//title/text()/../..//text()')
['Text 1', 'Stuff I want', 'Text 2', "Stuff I don't want"]
>>>
>>> # Follow parent from selected node
... tree.xpath('//title/text()="Text 1"/../..//text()')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "lxml.etree.pyx", line 1330, in lxml.etree._Element.xpath (src/
lxml/lxml.etree.c:14542)
File "xpath.pxi", line 287, in lxml.etree.XPathElementEvaluator.__ca
ll__ (src/lxml/lxml.etree.c:90093)
File "xpath.pxi", line 209, in lxml.etree._XPathEvaluatorBase._handl
e_result (src/lxml/lxml.etree.c:89446)
File "xpath.pxi", line 194, in lxml.etree._XPathEvaluatorBase._raise
_eval_error (src/lxml/lxml.etree.c:89281)
lxml.etree.XPathEvalError: Invalid type
</code></pre>
<p>Is this possible in XPath? Do I need to express what I want to do in a different way?</p>
| 14
|
2009-02-28T21:33:20Z
| 598,732
|
<p>Do you want that?</p>
<pre><code>//title[text()='Text 1']/../content/text()
</code></pre>
| 22
|
2009-02-28T21:40:19Z
|
[
"python",
"html",
"xpath",
"lxml"
] |
How to match a text node then follow parent nodes using XPath
| 598,722
|
<p>I'm trying to parse some HTML with XPath. Following the simplified XML example below, I want to match the string 'Text 1', then grab the contents of the relevant <code>content</code> node.</p>
<pre><code><doc>
<block>
<title>Text 1</title>
<content>Stuff I want</content>
</block>
<block>
<title>Text 2</title>
<content>Stuff I don't want</content>
</block>
</doc>
</code></pre>
<p>My Python code throws a wobbly:</p>
<pre><code>>>> from lxml import etree
>>>
>>> tree = etree.XML("<doc><block><title>Text 1</title><content>Stuff
I want</content></block><block><title>Text 2</title><content>Stuff I d
on't want</content></block></doc>")
>>>
>>> # get all titles
... tree.xpath('//title/text()')
['Text 1', 'Text 2']
>>>
>>> # match 'Text 1'
... tree.xpath('//title/text()="Text 1"')
True
>>>
>>> # Follow parent from selected nodes
... tree.xpath('//title/text()/../..//text()')
['Text 1', 'Stuff I want', 'Text 2', "Stuff I don't want"]
>>>
>>> # Follow parent from selected node
... tree.xpath('//title/text()="Text 1"/../..//text()')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "lxml.etree.pyx", line 1330, in lxml.etree._Element.xpath (src/
lxml/lxml.etree.c:14542)
File "xpath.pxi", line 287, in lxml.etree.XPathElementEvaluator.__ca
ll__ (src/lxml/lxml.etree.c:90093)
File "xpath.pxi", line 209, in lxml.etree._XPathEvaluatorBase._handl
e_result (src/lxml/lxml.etree.c:89446)
File "xpath.pxi", line 194, in lxml.etree._XPathEvaluatorBase._raise
_eval_error (src/lxml/lxml.etree.c:89281)
lxml.etree.XPathEvalError: Invalid type
</code></pre>
<p>Is this possible in XPath? Do I need to express what I want to do in a different way?</p>
| 14
|
2009-02-28T21:33:20Z
| 599,061
|
<p><strong>Use</strong>:</p>
<pre><code>string(/*/*/title[. = 'Text 1']/following-sibling::content)
</code></pre>
<p><strong>This represents at least two improvements</strong> as compared to the currently accepted solution of Johannes WeiÃ:</p>
<ol>
<li><p><strong>The very expensive abbreviation "//"</strong> (usually causing the whole XML document to be scanned) <strong>is avoided</strong> as it should be whenever the structure of the XML document is known in advance.</p></li>
<li><p><strong>There is no return back to the parent</strong> (the location step "/.." is avoided)</p></li>
</ol>
| 15
|
2009-03-01T01:37:19Z
|
[
"python",
"html",
"xpath",
"lxml"
] |
Python HTML removal
| 598,817
|
<p>How can I remove all HTML from a string in Python? For example, how can I turn:</p>
<pre><code>blah blah <a href="blah">link</a>
</code></pre>
<p>into</p>
<pre><code>blah blah link
</code></pre>
<p>Thanks!</p>
| 6
|
2009-02-28T22:39:55Z
| 598,824
|
<p>You can use a regular expression to remove all the tags:</p>
<pre><code>>>> import re
>>> s = 'blah blah <a href="blah">link</a>'
>>> re.sub('<[^>]*>', '', s)
'blah blah link'
</code></pre>
| 7
|
2009-02-28T22:43:17Z
|
[
"python",
"string"
] |
Python HTML removal
| 598,817
|
<p>How can I remove all HTML from a string in Python? For example, how can I turn:</p>
<pre><code>blah blah <a href="blah">link</a>
</code></pre>
<p>into</p>
<pre><code>blah blah link
</code></pre>
<p>Thanks!</p>
| 6
|
2009-02-28T22:39:55Z
| 598,838
|
<p>Try <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a>. Throw away everything except the text.</p>
| 3
|
2009-02-28T22:52:16Z
|
[
"python",
"string"
] |
Python HTML removal
| 598,817
|
<p>How can I remove all HTML from a string in Python? For example, how can I turn:</p>
<pre><code>blah blah <a href="blah">link</a>
</code></pre>
<p>into</p>
<pre><code>blah blah link
</code></pre>
<p>Thanks!</p>
| 6
|
2009-02-28T22:39:55Z
| 598,881
|
<pre><code>>>> import re
>>> s = 'blah blah <a href="blah">link</a>'
>>> q = re.compile(r'<.*?>', re.IGNORECASE)
>>> re.sub(q, '', s)
'blah blah link'
</code></pre>
| 0
|
2009-02-28T23:23:36Z
|
[
"python",
"string"
] |
Python HTML removal
| 598,817
|
<p>How can I remove all HTML from a string in Python? For example, how can I turn:</p>
<pre><code>blah blah <a href="blah">link</a>
</code></pre>
<p>into</p>
<pre><code>blah blah link
</code></pre>
<p>Thanks!</p>
| 6
|
2009-02-28T22:39:55Z
| 599,080
|
<p>When your regular expression solution hits a wall, try this super easy (and reliable) <a href="http://www.crummy.com/software/BeautifulSoup/">BeautifulSoup</a> program.</p>
<pre><code>from BeautifulSoup import BeautifulSoup
html = "<a> Keep me </a>"
soup = BeautifulSoup(html)
text_parts = soup.findAll(text=True)
text = ''.join(text_parts)
</code></pre>
| 18
|
2009-03-01T02:00:18Z
|
[
"python",
"string"
] |
Python HTML removal
| 598,817
|
<p>How can I remove all HTML from a string in Python? For example, how can I turn:</p>
<pre><code>blah blah <a href="blah">link</a>
</code></pre>
<p>into</p>
<pre><code>blah blah link
</code></pre>
<p>Thanks!</p>
| 6
|
2009-02-28T22:39:55Z
| 599,924
|
<p>There is also a small library called <a href="http://pypi.python.org/pypi/stripogram">stripogram</a> which can be used to strip away some or all HTML tags.</p>
<p>You can use it like this:</p>
<pre><code>from stripogram import html2text, html2safehtml
# Only allow <b>, <a>, <i>, <br>, and <p> tags
clean_html = html2safehtml(original_html,valid_tags=("b", "a", "i", "br", "p"))
# Don't process <img> tags, just strip them out. Use an indent of 4 spaces
# and a page that's 80 characters wide.
text = html2text(original_html,ignore_tags=("img",),indent_width=4,page_width=80)
</code></pre>
<p>So if you want to simply strip out all HTML, you pass valid_tags=() to the first function.</p>
<p>You can find the <a href="http://zope.org/Members/chrisw/StripOGram/readme">documentation here</a>.</p>
| 10
|
2009-03-01T14:45:46Z
|
[
"python",
"string"
] |
Python HTML removal
| 598,817
|
<p>How can I remove all HTML from a string in Python? For example, how can I turn:</p>
<pre><code>blah blah <a href="blah">link</a>
</code></pre>
<p>into</p>
<pre><code>blah blah link
</code></pre>
<p>Thanks!</p>
| 6
|
2009-02-28T22:39:55Z
| 600,252
|
<p><a href="http://www.aaronsw.com/2002/html2text/" rel="nofollow">html2text</a> will do something like this.</p>
| 2
|
2009-03-01T18:38:03Z
|
[
"python",
"string"
] |
Python HTML removal
| 598,817
|
<p>How can I remove all HTML from a string in Python? For example, how can I turn:</p>
<pre><code>blah blah <a href="blah">link</a>
</code></pre>
<p>into</p>
<pre><code>blah blah link
</code></pre>
<p>Thanks!</p>
| 6
|
2009-02-28T22:39:55Z
| 600,471
|
<p>Regexs, BeautifulSoup, html2text <strong>don't work</strong> if an attribute has <strong>'<code>></code>'</strong> in it. See <a href="http://stackoverflow.com/questions/94528/is-u003e-greater-than-sign-allowed-inside-an-html-element-attribute-value">Is â>â (U+003E GREATER-THAN SIGN) allowed inside an html-element attribute value?</a></p>
<p>'HTML/XML parser'-based solution might help in such cases e.g., <a href="http://pypi.python.org/pypi/stripogram">stripogram</a> <a href="http://stackoverflow.com/questions/598817/python-html-removal/599924#599924">suggested by @MrTopf</a> does work. </p>
<p>Here's <a href="http://effbot.org/zone/element-index.htm">ElementTree</a>-based solution: </p>
<pre><code>####from xml.etree import ElementTree as etree # stdlib
from lxml import etree
str_ = 'blah blah <a href="blah">link</a> END'
root = etree.fromstring('<html>%s</html>' % str_)
print ''.join(root.itertext()) # lxml or ElementTree 1.3+
</code></pre>
<p>Output:</p>
<pre><code>blah blah link END
</code></pre>
| 5
|
2009-03-01T20:42:41Z
|
[
"python",
"string"
] |
Python HTML removal
| 598,817
|
<p>How can I remove all HTML from a string in Python? For example, how can I turn:</p>
<pre><code>blah blah <a href="blah">link</a>
</code></pre>
<p>into</p>
<pre><code>blah blah link
</code></pre>
<p>Thanks!</p>
| 6
|
2009-02-28T22:39:55Z
| 11,266,485
|
<p>I just wrote this. I need it. It uses html2text and takes a file path, although I would prefer a URL. The output of html2text is stored in TextFromHtml2Text.text
print it, store it, feed it to your pet canary.</p>
<pre><code>import html2text
class TextFromHtml2Text:
def __init__(self, url = ''):
if url == '':
raise TypeError("Needs a URL")
self.text = ""
self.url = url
self.html = ""
self.gethtmlfile()
self.maytheswartzbewithyou()
def gethtmlfile(self):
file = open(self.url)
for line in file.readlines():
self.html += line
def maytheswartzbewithyou(self):
self.text = html2text.html2text(self.html)
</code></pre>
| 1
|
2012-06-29T17:41:43Z
|
[
"python",
"string"
] |
Python HTML removal
| 598,817
|
<p>How can I remove all HTML from a string in Python? For example, how can I turn:</p>
<pre><code>blah blah <a href="blah">link</a>
</code></pre>
<p>into</p>
<pre><code>blah blah link
</code></pre>
<p>Thanks!</p>
| 6
|
2009-02-28T22:39:55Z
| 14,464,562
|
<p>There's a simple way to this:</p>
<pre><code>def remove_html_markup(s):
tag = False
quote = False
out = ""
for c in s:
if c == '<' and not quote:
tag = True
elif c == '>' and not quote:
tag = False
elif (c == '"' or c == "'") and tag:
quote = not quote
elif not tag:
out = out + c
return out
</code></pre>
<p>The idea is explained here: <a href="http://youtu.be/2tu9LTDujbw" rel="nofollow">http://youtu.be/2tu9LTDujbw</a></p>
<p>You can see it working here: <a href="http://youtu.be/HPkNPcYed9M?t=35s" rel="nofollow">http://youtu.be/HPkNPcYed9M?t=35s</a></p>
<p>PS - If you're interested in the class(about smart debugging with python) I give you a link: <a href="http://www.udacity.com/overview/Course/cs259/CourseRev/1" rel="nofollow">http://www.udacity.com/overview/Course/cs259/CourseRev/1</a>. It's free! </p>
<p>You're welcome! :)</p>
| 1
|
2013-01-22T17:31:08Z
|
[
"python",
"string"
] |
Working with MySQL booleans in python
| 598,879
|
<p>I am querying a MySQL database in python and selecting a boolean value -- so the response from MySQL is either the string 'True' or 'False'. I would like to execute further code based on the boolean value from MySQL. </p>
<p>E.g.</p>
<pre><code>data = 'False' # assume this is what was returned by MySQL.
if data:
print 'Success' #really this would be where I would execute other if True.
else:
print 'Fail' #really this would be where I would execute other code if False
</code></pre>
<p>But I can't do this because</p>
<pre><code>if data:
</code></pre>
<p>will always return True</p>
<p>So how do I convert the string that MySQL is returning into a boolean in python?</p>
<p>Currently I have:</p>
<pre><code>data = 'False' # assume this is what was returned by MySQL.
if data == 'True':
print 'Success'
else:
print 'Fail'
</code></pre>
<p>I believe there must be a better way to do this in python -- likely there is something simple I am missing.</p>
| 2
|
2009-02-28T23:22:02Z
| 598,882
|
<p>Boolean in MySQL is TINYINT(1). Checking for 1 or 0 might work</p>
| 2
|
2009-02-28T23:24:17Z
|
[
"python",
"mysql",
"boolean"
] |
Working with MySQL booleans in python
| 598,879
|
<p>I am querying a MySQL database in python and selecting a boolean value -- so the response from MySQL is either the string 'True' or 'False'. I would like to execute further code based on the boolean value from MySQL. </p>
<p>E.g.</p>
<pre><code>data = 'False' # assume this is what was returned by MySQL.
if data:
print 'Success' #really this would be where I would execute other if True.
else:
print 'Fail' #really this would be where I would execute other code if False
</code></pre>
<p>But I can't do this because</p>
<pre><code>if data:
</code></pre>
<p>will always return True</p>
<p>So how do I convert the string that MySQL is returning into a boolean in python?</p>
<p>Currently I have:</p>
<pre><code>data = 'False' # assume this is what was returned by MySQL.
if data == 'True':
print 'Success'
else:
print 'Fail'
</code></pre>
<p>I believe there must be a better way to do this in python -- likely there is something simple I am missing.</p>
| 2
|
2009-02-28T23:22:02Z
| 598,963
|
<p>If the column is always one of the actual strings <code>"False"</code> or <code>"True"</code> (as opposed to integers or something) then I'd recommend some variation on:</p>
<pre><code>value = {'False' : False, 'True' : True}[data]
</code></pre>
| 1
|
2009-03-01T00:19:40Z
|
[
"python",
"mysql",
"boolean"
] |
Working with MySQL booleans in python
| 598,879
|
<p>I am querying a MySQL database in python and selecting a boolean value -- so the response from MySQL is either the string 'True' or 'False'. I would like to execute further code based on the boolean value from MySQL. </p>
<p>E.g.</p>
<pre><code>data = 'False' # assume this is what was returned by MySQL.
if data:
print 'Success' #really this would be where I would execute other if True.
else:
print 'Fail' #really this would be where I would execute other code if False
</code></pre>
<p>But I can't do this because</p>
<pre><code>if data:
</code></pre>
<p>will always return True</p>
<p>So how do I convert the string that MySQL is returning into a boolean in python?</p>
<p>Currently I have:</p>
<pre><code>data = 'False' # assume this is what was returned by MySQL.
if data == 'True':
print 'Success'
else:
print 'Fail'
</code></pre>
<p>I believe there must be a better way to do this in python -- likely there is something simple I am missing.</p>
| 2
|
2009-02-28T23:22:02Z
| 599,022
|
<p>If your db connection doesn't know how to transform the values for you, then you need to use a better one. This should not be something you need to do yourself. If these are not actual booleans, but just an int column you only store 0 or 1 in, then you should fix your schema. Alternatively, if you always get the values 'True' and 'False', maybe you are accidentally converting it to a string somewhere?</p>
| 2
|
2009-03-01T00:56:37Z
|
[
"python",
"mysql",
"boolean"
] |
Working with MySQL booleans in python
| 598,879
|
<p>I am querying a MySQL database in python and selecting a boolean value -- so the response from MySQL is either the string 'True' or 'False'. I would like to execute further code based on the boolean value from MySQL. </p>
<p>E.g.</p>
<pre><code>data = 'False' # assume this is what was returned by MySQL.
if data:
print 'Success' #really this would be where I would execute other if True.
else:
print 'Fail' #really this would be where I would execute other code if False
</code></pre>
<p>But I can't do this because</p>
<pre><code>if data:
</code></pre>
<p>will always return True</p>
<p>So how do I convert the string that MySQL is returning into a boolean in python?</p>
<p>Currently I have:</p>
<pre><code>data = 'False' # assume this is what was returned by MySQL.
if data == 'True':
print 'Success'
else:
print 'Fail'
</code></pre>
<p>I believe there must be a better way to do this in python -- likely there is something simple I am missing.</p>
| 2
|
2009-02-28T23:22:02Z
| 600,044
|
<p>Your solution is actually quite OK, but there are alternatives:</p>
<p>If you are using Python 2.5 or higher, you can shorten the if statement:</p>
<pre><code>print 'Success' if data == 'True' else 'Fail'
</code></pre>
<p>If you are finding yourself repeating the check often, you might consider writing a function for it to make it more readable:</p>
<pre><code>def is_true(mysql_boolean):
if mysql_boolean == "True":
return True
else:
return False
# now you can use this:
if is_true(data):
# this is really going to be more than one line of code anyway.
# or maybe a function call, in which your solution might be enough.
print "Success"
else:
print "Fail"
</code></pre>
<p>You can achieve the same thing with a dictionary, but I don't find this as elegant:</p>
<pre><code>mysql_bool = {'True': True, 'False': False}
if mysql_bool[data]:
print "Success"
</code></pre>
<p>That said, what are you using to connect to the DB? There is probably a way to directly get a bool out of there. Please update your Question!</p>
| 0
|
2009-03-01T16:28:36Z
|
[
"python",
"mysql",
"boolean"
] |
Working with MySQL booleans in python
| 598,879
|
<p>I am querying a MySQL database in python and selecting a boolean value -- so the response from MySQL is either the string 'True' or 'False'. I would like to execute further code based on the boolean value from MySQL. </p>
<p>E.g.</p>
<pre><code>data = 'False' # assume this is what was returned by MySQL.
if data:
print 'Success' #really this would be where I would execute other if True.
else:
print 'Fail' #really this would be where I would execute other code if False
</code></pre>
<p>But I can't do this because</p>
<pre><code>if data:
</code></pre>
<p>will always return True</p>
<p>So how do I convert the string that MySQL is returning into a boolean in python?</p>
<p>Currently I have:</p>
<pre><code>data = 'False' # assume this is what was returned by MySQL.
if data == 'True':
print 'Success'
else:
print 'Fail'
</code></pre>
<p>I believe there must be a better way to do this in python -- likely there is something simple I am missing.</p>
| 2
|
2009-02-28T23:22:02Z
| 601,295
|
<p>You can find the place MySQLDdb converts the values in the converters.py file in the MySQLdb directory.</p>
<p>here's the snippet dealing with bool:</p>
<pre><code>conversions = {
...
types.BooleanType: Bool2Str,
...
}
</code></pre>
<p>And the Bool2Str function:</p>
<pre><code>def Bool2Str(s, d): return str(int(s))
</code></pre>
<p>If you want different behavior, import the conversions dict and change it.</p>
| 2
|
2009-03-02T04:43:23Z
|
[
"python",
"mysql",
"boolean"
] |
Working with MySQL booleans in python
| 598,879
|
<p>I am querying a MySQL database in python and selecting a boolean value -- so the response from MySQL is either the string 'True' or 'False'. I would like to execute further code based on the boolean value from MySQL. </p>
<p>E.g.</p>
<pre><code>data = 'False' # assume this is what was returned by MySQL.
if data:
print 'Success' #really this would be where I would execute other if True.
else:
print 'Fail' #really this would be where I would execute other code if False
</code></pre>
<p>But I can't do this because</p>
<pre><code>if data:
</code></pre>
<p>will always return True</p>
<p>So how do I convert the string that MySQL is returning into a boolean in python?</p>
<p>Currently I have:</p>
<pre><code>data = 'False' # assume this is what was returned by MySQL.
if data == 'True':
print 'Success'
else:
print 'Fail'
</code></pre>
<p>I believe there must be a better way to do this in python -- likely there is something simple I am missing.</p>
| 2
|
2009-02-28T23:22:02Z
| 14,554,324
|
<p>This handles the way it's returned by MySQLdb.</p>
<pre><code>if data == '\x01':
print 'Success'
else:
print 'Fail'
</code></pre>
| 0
|
2013-01-28T01:37:21Z
|
[
"python",
"mysql",
"boolean"
] |
Difference between class (Python) and struct (C)
| 598,931
|
<p>I'm new to python. I've studied C and I noticed that that the C structure (struct) seemed to have the same task as "class" in python. So what is, conceptually, the difference? </p>
| 1
|
2009-03-01T00:03:43Z
| 598,937
|
<p>Aside from numerous technical differences between how they're implemented, they serve roughly the same purpose: the organization of data. </p>
<p>The big difference is that in Python (and other object oriented languages such as C++, Java, or C#), a class can also have functions associated with it that operate only on the instance of the class, whereas in C, a function that wishes to operate on a struct must accept the structure as a parameter in some way, usually by pointer. </p>
<p>I won't delve into the technical differences between the two, as they are fairly significant, but I suggest you look into the concept of <a href="http://en.wikipedia.org/wiki/Object-oriented%5Fprogramming" rel="nofollow">Object Oriented Programming</a>.</p>
| 8
|
2009-03-01T00:08:08Z
|
[
"python",
"c"
] |
Difference between class (Python) and struct (C)
| 598,931
|
<p>I'm new to python. I've studied C and I noticed that that the C structure (struct) seemed to have the same task as "class" in python. So what is, conceptually, the difference? </p>
| 1
|
2009-03-01T00:03:43Z
| 598,941
|
<p>Classes typically have methods (which are mostly just functions) associated with them, whereas C structs don't. You'll probably want to learn about what object-oriented programming is, if you want to make effective use of classes in Python (or any other object-oriented language, like Java or C++).</p>
<p>Of course, it is possible to use a Python class the same way you'd use a C struct, as a container for data. But that's not done very often.</p>
| 3
|
2009-03-01T00:09:14Z
|
[
"python",
"c"
] |
Difference between class (Python) and struct (C)
| 598,931
|
<p>I'm new to python. I've studied C and I noticed that that the C structure (struct) seemed to have the same task as "class" in python. So what is, conceptually, the difference? </p>
| 1
|
2009-03-01T00:03:43Z
| 598,945
|
<p>Without taking pages and pages to go into the details, think of a C struct as a way to organize data, while a Python (or C++ or Objective-C) "class" is a way to organize not only your data, but the operations for that data. A Python "class," for example, can inherit from other objects, to give you an interator for the data associated with it (or you can write your own interator in the class). There's more to say, I'm sure, but this gets into "what is OOP" pretty quickly, well beyond the scope of this thread.</p>
| 5
|
2009-03-01T00:10:30Z
|
[
"python",
"c"
] |
Difference between class (Python) and struct (C)
| 598,931
|
<p>I'm new to python. I've studied C and I noticed that that the C structure (struct) seemed to have the same task as "class" in python. So what is, conceptually, the difference? </p>
| 1
|
2009-03-01T00:03:43Z
| 598,955
|
<p>Structs encapsulate data.</p>
<p>Classes encapsulate behavior and data.</p>
| 18
|
2009-03-01T00:16:32Z
|
[
"python",
"c"
] |
Difference between class (Python) and struct (C)
| 598,931
|
<p>I'm new to python. I've studied C and I noticed that that the C structure (struct) seemed to have the same task as "class" in python. So what is, conceptually, the difference? </p>
| 1
|
2009-03-01T00:03:43Z
| 599,017
|
<p>One thing that hasn't been mentioned is that C structs are value types, whereas Python classes are reference types.</p>
<p>For example, consider this statement:</p>
<pre><code>var1 = var2
</code></pre>
<p>If var1 and var2 were C structs, then that statement would copy the contents of var2 into var1. That's <strong>copy by value</strong>.</p>
<p>If however var1 and var2 were Python objects, then that statement would make var1 refer to the object that var2 was referring to. (They are like pointers to structs in C.) That's <strong>copy by by reference</strong>.</p>
<p>The same thing happens when passing arguments to functions (because they have to be copied to get into the function).</p>
| 5
|
2009-03-01T00:52:41Z
|
[
"python",
"c"
] |
What's the best technology for connecting from linux to MS SQL Server using python? ODBC?
| 598,979
|
<p>By best, I mean most-common, easiest to setup, free. Performance doesn't matter.</p>
| 5
|
2009-03-01T00:29:11Z
| 598,986
|
<p>I'm just learning Python myself, but it seems like there are Python libraries that look more like Java JDBC drivers. Google found these articles about <a href="http://www.ibm.com/developerworks/opensource/library/os-pythonsqlo/" rel="nofollow">SQLObject</a> and <a href="http://www.oracle.com/technology/pub/articles/devlin-python-oracle.html" rel="nofollow">cx_Oracle</a>.</p>
| 0
|
2009-03-01T00:32:52Z
|
[
"python"
] |
What's the best technology for connecting from linux to MS SQL Server using python? ODBC?
| 598,979
|
<p>By best, I mean most-common, easiest to setup, free. Performance doesn't matter.</p>
| 5
|
2009-03-01T00:29:11Z
| 598,988
|
<p><a href="http://pymssql.sourceforge.net/" rel="nofollow">pymssql</a>, the simple MS SQL Python extension module.</p>
| 2
|
2009-03-01T00:33:49Z
|
[
"python"
] |
What's the best technology for connecting from linux to MS SQL Server using python? ODBC?
| 598,979
|
<p>By best, I mean most-common, easiest to setup, free. Performance doesn't matter.</p>
| 5
|
2009-03-01T00:29:11Z
| 598,993
|
<p>You may find this topic helpful:</p>
<p><a href="http://stackoverflow.com/questions/289978/whats-the-simplest-way-to-access-mssql-with-python-or-ironpython">http://stackoverflow.com/questions/289978/whats-the-simplest-way-to-access-mssql-with-python-or-ironpython</a></p>
| 2
|
2009-03-01T00:36:48Z
|
[
"python"
] |
What's the best technology for connecting from linux to MS SQL Server using python? ODBC?
| 598,979
|
<p>By best, I mean most-common, easiest to setup, free. Performance doesn't matter.</p>
| 5
|
2009-03-01T00:29:11Z
| 599,833
|
<p>I decided that pyodbc was the best fit. Very simple, stable, supported:<br />
<a href="http://code.google.com/p/pyodbc/" rel="nofollow">http://code.google.com/p/pyodbc/</a></p>
| 3
|
2009-03-01T13:38:49Z
|
[
"python"
] |
What's the best technology for connecting from linux to MS SQL Server using python? ODBC?
| 598,979
|
<p>By best, I mean most-common, easiest to setup, free. Performance doesn't matter.</p>
| 5
|
2009-03-01T00:29:11Z
| 601,276
|
<p><a href="http://www.freetds.org/" rel="nofollow">FreeTDS</a></p>
| 1
|
2009-03-02T04:30:41Z
|
[
"python"
] |
How can I manually register distributions with pkg_resources?
| 599,205
|
<p>I'm trying to get a package installed on Google App Engine. The package relies rather extensively on <code>pkg_resources</code>, but there's no way to run <code>setup.py</code> on App Engine.</p>
<p>There's no platform-specific code in the source, however, so it's no problem to just zip up the source and include those in the system path. And I've gotten a version of <code>pkg_resources</code> installed and working as well.</p>
<p>The only problem is getting the package actually <em>registered</em> with <code>pkg_resources</code> so when it calls <code>iter_entry_points</code> it can find the appropriate plugins.</p>
<p>What methods do I need to call to register modules on <code>sys.path</code> with all the appropriate metadata, and how do I figure out what that metadata needs to be?</p>
| 1
|
2009-03-01T03:40:26Z
| 676,517
|
<p>Yes, for setuptools-based libraries you'll need to deploy the library's "Egg" metadata along with it. The easiest way I've found is to deploy a whole <a href="http://pypi.python.org/pypi/virtualenv/1.3.3" rel="nofollow">virtualenv</a> environment containing your project and the required libraries.</p>
<p>I did this process manually and added this code to main.py to initialize the site-packages folder in a way that <code>pkg_resources</code> will work:</p>
<pre><code>import site
site.addsitedir('lib/python2.5/site-packages')
</code></pre>
<p>However, you could try <a href="http://code.google.com/p/appengine-monkey/wiki/Pylons" rel="nofollow">appengine-monkey</a> which automates most of this for you.</p>
| 1
|
2009-03-24T08:19:40Z
|
[
"python",
"google-app-engine",
"setuptools",
"pkg-resources"
] |
How can I manually register distributions with pkg_resources?
| 599,205
|
<p>I'm trying to get a package installed on Google App Engine. The package relies rather extensively on <code>pkg_resources</code>, but there's no way to run <code>setup.py</code> on App Engine.</p>
<p>There's no platform-specific code in the source, however, so it's no problem to just zip up the source and include those in the system path. And I've gotten a version of <code>pkg_resources</code> installed and working as well.</p>
<p>The only problem is getting the package actually <em>registered</em> with <code>pkg_resources</code> so when it calls <code>iter_entry_points</code> it can find the appropriate plugins.</p>
<p>What methods do I need to call to register modules on <code>sys.path</code> with all the appropriate metadata, and how do I figure out what that metadata needs to be?</p>
| 1
|
2009-03-01T03:40:26Z
| 744,882
|
<p>On your local development system, run <code>python setup.py bdist_egg</code>, which will create a Zip archive with the necessary metadata included. Add it to your <code>sys.path</code>, and it should work properly.</p>
| 0
|
2009-04-13T18:24:17Z
|
[
"python",
"google-app-engine",
"setuptools",
"pkg-resources"
] |
How can I manually register distributions with pkg_resources?
| 599,205
|
<p>I'm trying to get a package installed on Google App Engine. The package relies rather extensively on <code>pkg_resources</code>, but there's no way to run <code>setup.py</code> on App Engine.</p>
<p>There's no platform-specific code in the source, however, so it's no problem to just zip up the source and include those in the system path. And I've gotten a version of <code>pkg_resources</code> installed and working as well.</p>
<p>The only problem is getting the package actually <em>registered</em> with <code>pkg_resources</code> so when it calls <code>iter_entry_points</code> it can find the appropriate plugins.</p>
<p>What methods do I need to call to register modules on <code>sys.path</code> with all the appropriate metadata, and how do I figure out what that metadata needs to be?</p>
| 1
|
2009-03-01T03:40:26Z
| 2,164,138
|
<p>Create a setup.py for the package just as you would normally, and then use "setup.py sdist --formats=zip" to build your source zip. The built source zip will include an .egg-info metadata directory, which will then be findable by pkg_resources. Alternately, you can use bdist_egg for all your packages.</p>
| 0
|
2010-01-29T18:15:48Z
|
[
"python",
"google-app-engine",
"setuptools",
"pkg-resources"
] |
Authentication Required - Problems Establishing AIM OSCAR Session using Python
| 599,218
|
<p>I'm writing a simple python script that will interface with the AIM servers using the <a href="http://dev.aol.com/aim/oscar/" rel="nofollow">OSCAR protocol</a>. It includes a somewhat complex handshake protocol. You essentially have to send a GET request to a specific URL, receive XML or JSON encoded reply, extract a special session token and secret key, then generate a response using the token and the key.</p>
<p>I tried to follow <a href="http://dev.aol.com/aim/oscar/#AUTH" rel="nofollow">these steps</a> to a tee, but the process fails in the last one. Here is my code:</p>
<pre><code>class simpleOSCAR:
def __init__(self, username, password):
self.username = username
self.password = password
self.open_aim_key = 'whatever'
self.client_name = 'blah blah blah'
self.client_version = 'yadda yadda yadda'
def authenticate(self):
# STEP 1
url = 'https://api.screenname.aol.com/auth/clientLogin?f=json'
data = urllib.urlencode( [
('k', self.open_aim_key),
('s', self.username),
('pwd', self.password),
('clientVersion', self.client_version),
('clientName', self.client_name)]
)
response = urllib2.urlopen(url, data)
json_response = simplejson.loads(urllib.unquote(response.read()))
session_secret = json_response['response']['data']['sessionSecret']
host_time = json_response['response']['data']['hostTime']
self.token = json_response['response']['data']['token']['a']
# STEP 2
self.session_key = base64.b64encode(hmac.new(self.password, session_secret, sha256).digest())
#STEP 3
uri = "http://api.oscar.aol.com/aim/startOSCARSession?"
data = urllib.urlencode([
('a', self.token),
('clientName', self.client_name),
('clientVersion', self.client_version),
('f', 'json'),
('k', self.open_aim_key),
('ts', host_time),
]
)
urldata = uri+data
hashdata = "GET&" + urllib.quote("http://api.oscar.aol.com/aim/startOSCARSession?") + data
digest = base64.b64encode(hmac.new(self.session_key, hashdata, sha256).digest())
urldata = urldata + "&sig_sha256=" + digest
print urldata + "\n"
response = urllib2.urlopen(urldata)
json_response = urllib.unquote(response.read())
print json_response
if __name__ == '__main__':
so = simpleOSCAR("aimscreenname", "somepassword")
so.authenticate()
</code></pre>
<p>I get the following response from the server:</p>
<pre><code>{ "response" : {
"statusCode":401,
"statusText":"Authentication Required. statusDetailCode 1014",
"statusDetailCode":1014,
"data":{
"ts":1235878395
}
}
}
</code></pre>
<p>I tried troubleshooting it in various ways, but the URL's I generate look the same as the ones shown in the <a href="http://dev.aol.com/aim/oscar/#SIGNON" rel="nofollow">signon flow example</a>. And yet, it fails.</p>
<p>Any idea what I'm doing wrong here? Am I hashing the values wrong? Am I encoding something improperly? Is my session timing out?</p>
| 1
|
2009-03-01T03:52:58Z
| 644,921
|
<p>URI Encode your digest?</p>
<p>-moxford</p>
| 0
|
2009-03-13T23:00:37Z
|
[
"python",
"json",
"aim"
] |
Authentication Required - Problems Establishing AIM OSCAR Session using Python
| 599,218
|
<p>I'm writing a simple python script that will interface with the AIM servers using the <a href="http://dev.aol.com/aim/oscar/" rel="nofollow">OSCAR protocol</a>. It includes a somewhat complex handshake protocol. You essentially have to send a GET request to a specific URL, receive XML or JSON encoded reply, extract a special session token and secret key, then generate a response using the token and the key.</p>
<p>I tried to follow <a href="http://dev.aol.com/aim/oscar/#AUTH" rel="nofollow">these steps</a> to a tee, but the process fails in the last one. Here is my code:</p>
<pre><code>class simpleOSCAR:
def __init__(self, username, password):
self.username = username
self.password = password
self.open_aim_key = 'whatever'
self.client_name = 'blah blah blah'
self.client_version = 'yadda yadda yadda'
def authenticate(self):
# STEP 1
url = 'https://api.screenname.aol.com/auth/clientLogin?f=json'
data = urllib.urlencode( [
('k', self.open_aim_key),
('s', self.username),
('pwd', self.password),
('clientVersion', self.client_version),
('clientName', self.client_name)]
)
response = urllib2.urlopen(url, data)
json_response = simplejson.loads(urllib.unquote(response.read()))
session_secret = json_response['response']['data']['sessionSecret']
host_time = json_response['response']['data']['hostTime']
self.token = json_response['response']['data']['token']['a']
# STEP 2
self.session_key = base64.b64encode(hmac.new(self.password, session_secret, sha256).digest())
#STEP 3
uri = "http://api.oscar.aol.com/aim/startOSCARSession?"
data = urllib.urlencode([
('a', self.token),
('clientName', self.client_name),
('clientVersion', self.client_version),
('f', 'json'),
('k', self.open_aim_key),
('ts', host_time),
]
)
urldata = uri+data
hashdata = "GET&" + urllib.quote("http://api.oscar.aol.com/aim/startOSCARSession?") + data
digest = base64.b64encode(hmac.new(self.session_key, hashdata, sha256).digest())
urldata = urldata + "&sig_sha256=" + digest
print urldata + "\n"
response = urllib2.urlopen(urldata)
json_response = urllib.unquote(response.read())
print json_response
if __name__ == '__main__':
so = simpleOSCAR("aimscreenname", "somepassword")
so.authenticate()
</code></pre>
<p>I get the following response from the server:</p>
<pre><code>{ "response" : {
"statusCode":401,
"statusText":"Authentication Required. statusDetailCode 1014",
"statusDetailCode":1014,
"data":{
"ts":1235878395
}
}
}
</code></pre>
<p>I tried troubleshooting it in various ways, but the URL's I generate look the same as the ones shown in the <a href="http://dev.aol.com/aim/oscar/#SIGNON" rel="nofollow">signon flow example</a>. And yet, it fails.</p>
<p>Any idea what I'm doing wrong here? Am I hashing the values wrong? Am I encoding something improperly? Is my session timing out?</p>
| 1
|
2009-03-01T03:52:58Z
| 1,005,063
|
<p>Try using <a href="http://twistedmatrix.com/trac/browser/trunk/twisted/words/protocols/oscar.py" rel="nofollow">Twisted's OSCAR support</a> instead of writing your own? It hasn't seen a lot of maintenance, but I believe it works.</p>
| 1
|
2009-06-17T04:03:55Z
|
[
"python",
"json",
"aim"
] |
How to pass information using an HTTP redirect (in Django)
| 599,280
|
<p>I have a view that accepts a form submission and updates a model.</p>
<p>After updating the model, I want to redirect to another page, and I want a message such as "Field X successfully updated" to appear on this page.</p>
<p>How can I "pass" this message to the other page? HttpResponseRedirect only accepts a <a href="http://en.wikipedia.org/wiki/Uniform_Resource_Locator" rel="nofollow">URL</a>. I've seen this done before on other sites. How is this accomplished?</p>
| 19
|
2009-03-01T05:02:13Z
| 599,319
|
<p>Can you just pass the message as a query param oon the URL to which you're redirecting? It's not terribly RESTy, but it ought to work:</p>
<pre><code>return HttpResponseRedirect('/polls/%s/results/?message=Updated" % p.id)
</code></pre>
<p>and have that view check for a message param, scrub it for nasties, and display it at the top.</p>
| 0
|
2009-03-01T05:40:29Z
|
[
"python",
"django",
"http"
] |
How to pass information using an HTTP redirect (in Django)
| 599,280
|
<p>I have a view that accepts a form submission and updates a model.</p>
<p>After updating the model, I want to redirect to another page, and I want a message such as "Field X successfully updated" to appear on this page.</p>
<p>How can I "pass" this message to the other page? HttpResponseRedirect only accepts a <a href="http://en.wikipedia.org/wiki/Uniform_Resource_Locator" rel="nofollow">URL</a>. I've seen this done before on other sites. How is this accomplished?</p>
| 19
|
2009-03-01T05:02:13Z
| 599,704
|
<p>This is a built-in feature of Django, called "messages"</p>
<p>See <a href="http://docs.djangoproject.com/en/dev/topics/auth/#messages">http://docs.djangoproject.com/en/dev/topics/auth/#messages</a></p>
<p>From the documentation:</p>
<blockquote>
<p>A message is associated with a User.
There's no concept of expiration or
timestamps.</p>
<p>Messages are used by the Django admin
after successful actions. For example,
"The poll Foo was created
successfully." is a message.</p>
</blockquote>
| 11
|
2009-03-01T11:56:07Z
|
[
"python",
"django",
"http"
] |
How to pass information using an HTTP redirect (in Django)
| 599,280
|
<p>I have a view that accepts a form submission and updates a model.</p>
<p>After updating the model, I want to redirect to another page, and I want a message such as "Field X successfully updated" to appear on this page.</p>
<p>How can I "pass" this message to the other page? HttpResponseRedirect only accepts a <a href="http://en.wikipedia.org/wiki/Uniform_Resource_Locator" rel="nofollow">URL</a>. I've seen this done before on other sites. How is this accomplished?</p>
| 19
|
2009-03-01T05:02:13Z
| 600,593
|
<p>You can use django-flashcookie app
<a href="http://bitbucket.org/offline/django-flashcookie/wiki/Home">http://bitbucket.org/offline/django-flashcookie/wiki/Home</a></p>
<p>it can send multiple messages and have unlimited types of messages. Lets say you want one message type for warning and one for error messages, you can write</p>
<pre><code>def simple_action(request):
...
request.flash['notice'] = 'Hello World'
return HttpResponseRedirect("/")
</code></pre>
<p>or</p>
<pre><code>def simple_action(request):
...
request.flash['error'] = 'something wrong'
return HttpResponseRedirect("/")
</code></pre>
<p>or </p>
<pre><code>def simple_action(request):
...
request.flash['notice'] = 'Hello World'
request.flash['error'] = 'something wrong'
return HttpResponseRedirect("/")
</code></pre>
<p>or even</p>
<pre><code>def simple_action(request):
...
request.flash['notice'] = 'Hello World'
request.flash['notice'] = 'Hello World 2'
request.flash['error'] = 'something wrong'
request.flash['error'] = 'something wrong 2'
return HttpResponseRedirect("/")
</code></pre>
<p>and then in you template show it with</p>
<pre><code>{% for message in flash.notice %}
{{ message }}
{% endfor }}
</code></pre>
<p>or </p>
<pre><code>{% for message in flash.notice %}
{{ message }}
{% endfor }}
{% for message in flash.error %}
{{ message }}
{% endfor }}
</code></pre>
| 8
|
2009-03-01T21:41:14Z
|
[
"python",
"django",
"http"
] |
How to pass information using an HTTP redirect (in Django)
| 599,280
|
<p>I have a view that accepts a form submission and updates a model.</p>
<p>After updating the model, I want to redirect to another page, and I want a message such as "Field X successfully updated" to appear on this page.</p>
<p>How can I "pass" this message to the other page? HttpResponseRedirect only accepts a <a href="http://en.wikipedia.org/wiki/Uniform_Resource_Locator" rel="nofollow">URL</a>. I've seen this done before on other sites. How is this accomplished?</p>
| 19
|
2009-03-01T05:02:13Z
| 607,585
|
<p>While all suggestions so far work, I would suggest going with Ry4an's (pass it in the request URL) - just change the actual text to a coded text within a predefined set of text messages. </p>
<p>Two advantages here:</p>
<ol>
<li>Less chance of something hacking through your scrubbing of bad content</li>
<li>You can localize your messages later if needed.</li>
</ol>
<p>The other cookie related methods.. well, they don't work if the browser doesn't support cookies, and are slightly more expensive.. But only slightly. They're indeed cleaner to the eye.</p>
| 0
|
2009-03-03T18:34:01Z
|
[
"python",
"django",
"http"
] |
How to pass information using an HTTP redirect (in Django)
| 599,280
|
<p>I have a view that accepts a form submission and updates a model.</p>
<p>After updating the model, I want to redirect to another page, and I want a message such as "Field X successfully updated" to appear on this page.</p>
<p>How can I "pass" this message to the other page? HttpResponseRedirect only accepts a <a href="http://en.wikipedia.org/wiki/Uniform_Resource_Locator" rel="nofollow">URL</a>. I've seen this done before on other sites. How is this accomplished?</p>
| 19
|
2009-03-01T05:02:13Z
| 1,912,778
|
<p>Take a look at Django's messages framework. <a href="http://docs.djangoproject.com/en/dev/ref/contrib/messages/#ref-contrib-messages" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/contrib/messages/#ref-contrib-messages</a></p>
| 0
|
2009-12-16T06:49:38Z
|
[
"python",
"django",
"http"
] |
How to pass information using an HTTP redirect (in Django)
| 599,280
|
<p>I have a view that accepts a form submission and updates a model.</p>
<p>After updating the model, I want to redirect to another page, and I want a message such as "Field X successfully updated" to appear on this page.</p>
<p>How can I "pass" this message to the other page? HttpResponseRedirect only accepts a <a href="http://en.wikipedia.org/wiki/Uniform_Resource_Locator" rel="nofollow">URL</a>. I've seen this done before on other sites. How is this accomplished?</p>
| 19
|
2009-03-01T05:02:13Z
| 1,912,876
|
<p>There is a lot of solutions</p>
<p>1 Use Django-trunk version - it support sending messages to Anonymous Users</p>
<p>2 Sessions</p>
<pre><code>def view1(request):
request.session['message'] = 'Hello view2!'
return HttpResponseRedirect('/view2/')
def view2(request):
return HttpResponse(request.session['message'])
</code></pre>
<p>3 redirect with param</p>
<pre><code>return HttpResponseRedirect('/view2/?message=Hello+view2')
</code></pre>
<p>4 Cookies</p>
| 2
|
2009-12-16T07:11:51Z
|
[
"python",
"django",
"http"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.