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 listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
How can I check for a blank image in Qt or PyQt? | 1,110,403 | <p>I have generated a collection of images. Some of them are blank as in their background is white. I have access to the QImage object of each of the images. Is there a Qt way to check for blank images? If not, can someone recommend the best way to do it in Python?</p>
| 4 | 2009-07-10T15:52:21Z | 1,110,455 | <p>Well, I would count the colors in the image. If there is only one, then the image is blank. I do not know enough Python or qt to write code for this but I am sure there is a library that can tell you how many colors there are in an image (I am going to look into using ImageMagick for this right after I post this).</p>
<p><strong>Update:</strong> Here is the Perl code (apologies) to do this using <a href="http://www.imagemagick.org/script/perl-magick.php" rel="nofollow">Image::Magick</a>. You should be able to convert it to Python using the <a href="http://www.imagemagick.org/download/python/" rel="nofollow">Python bindings</a>.</p>
<p>Clearly, this only works for palette based images.</p>
<pre><code>#!/usr/bin/perl
use strict;
use warnings;
use Image::Magick;
die "Call with image file name\n" unless @ARGV == 1;
my ($file) = @ARGV;
my $image = Image::Magick->new;
my $result = $image->Read( $file );
die "$result" if "$result";
my $colors = $image->Get('colors');
my %unique_colors;
for ( my $i = 0; $i < $colors; ++$i ) {
$unique_colors{ $image->Get("colormap[$i]") } = undef;
}
print "'$file' is blank\n" if keys %unique_colors == 1;
__END__
</code></pre>
| 1 | 2009-07-10T15:59:38Z | [
"python",
"qt4",
"pyqt4"
] |
How can I check for a blank image in Qt or PyQt? | 1,110,403 | <p>I have generated a collection of images. Some of them are blank as in their background is white. I have access to the QImage object of each of the images. Is there a Qt way to check for blank images? If not, can someone recommend the best way to do it in Python?</p>
| 4 | 2009-07-10T15:52:21Z | 1,110,492 | <p>I don't know about Qt, but there is an easy and efficient way to do it in <a href="http://www.pythonware.com/products/pil/">PIL</a>
Using the <a href="http://www.pythonware.com/library/pil/handbook/image.htm">getextrema</a> method, example:</p>
<pre><code>im = Image.open('image.png')
bands = im.split()
isBlank = all(band.getextrema() == (255, 255) for band in bands)
</code></pre>
<p>From the documentation:</p>
<blockquote>
<p>im.getextrema() => 2-tuple</p>
<p>Returns a 2-tuple containing the
minimum and maximum values of the
image. In the current version of PIL,
this is only applicable to single-band
images.</p>
</blockquote>
| 5 | 2009-07-10T16:07:25Z | [
"python",
"qt4",
"pyqt4"
] |
Why does Django's signal handling use weak references for callbacks by default? | 1,110,668 | <p>The <a href="http://docs.djangoproject.com/en/dev/ref/signals/">Django docs</a> say this on the subject:</p>
<blockquote>
<p>Note also that Django stores signal
handlers as weak references by
default, so if your handler is a local
function, it may be garbage collected.
To prevent this, pass weak=False when
you call the signalâs connect().</p>
</blockquote>
<p>I haven't been able to find any justification for why this is the default, and I don't understand why you would ever want a signal that you explicitly registered to implicitly disappear. So what is the use-case for weak references here? And why is it the default?</p>
<p>I realize it probably doesn't matter either way in 99% of cases, but clearly there's something I don't understand here, and I want to know if there's any "gotchas" lurking that might bite me someday.</p>
| 15 | 2009-07-10T16:47:10Z | 1,110,874 | <p>Signals handlers are stored as weak references to avoid the object they reference from not being garbage collected (for example after explicit deletion of the signal handler), just because a signal is still flying around.</p>
| 8 | 2009-07-10T17:26:14Z | [
"python",
"django",
"garbage-collection",
"weak-references",
"django-signals"
] |
Why does Django's signal handling use weak references for callbacks by default? | 1,110,668 | <p>The <a href="http://docs.djangoproject.com/en/dev/ref/signals/">Django docs</a> say this on the subject:</p>
<blockquote>
<p>Note also that Django stores signal
handlers as weak references by
default, so if your handler is a local
function, it may be garbage collected.
To prevent this, pass weak=False when
you call the signalâs connect().</p>
</blockquote>
<p>I haven't been able to find any justification for why this is the default, and I don't understand why you would ever want a signal that you explicitly registered to implicitly disappear. So what is the use-case for weak references here? And why is it the default?</p>
<p>I realize it probably doesn't matter either way in 99% of cases, but clearly there's something I don't understand here, and I want to know if there's any "gotchas" lurking that might bite me someday.</p>
| 15 | 2009-07-10T16:47:10Z | 1,111,287 | <p>Bound methods keep a reference to the object they belong to (otherwise, they cannot fill <code>self</code>, cf. the <a href="http://docs.python.org/library/stdtypes.html?highlight=im%5Fself" rel="nofollow">Python documentation</a>). Consider the following code:</p>
<pre><code>import gc
class SomeLargeObject(object):
def on_foo(self): pass
slo = SomeLargeObject()
callbacks = [slo.on_foo]
print [o for o in gc.get_objects() if isinstance(o, SomeLargeObject)]
del slo
print [o for o in gc.get_objects() if isinstance(o, SomeLargeObject)]
callbacks = []
print [o for o in gc.get_objects() if isinstance(o, SomeLargeObject)]
</code></pre>
<p>The output:</p>
<pre><code>[<__main__.SomeLargeObject object at 0x15001d0>]
[<__main__.SomeLargeObject object at 0x15001d0>]
[]
</code></pre>
<p>One important thing to know when keeping weakrefs on callbacks is that you cannot weakref bound methods directly, because they are always created on the fly:</p>
<pre><code>>>> class SomeLargeObject(object):
... def on_foo(self): pass
>>> import weakref
>>> def report(o):
... print "about to collect"
>>> slo = SomeLargeObject()
>>> #second argument: function that is called when weakref'ed object is finalized
>>> weakref.proxy(slo.on_foo, report)
about to collect
<weakproxy at 0x7f9abd3be208 to NoneType at 0x72ecc0>
</code></pre>
| 4 | 2009-07-10T18:46:07Z | [
"python",
"django",
"garbage-collection",
"weak-references",
"django-signals"
] |
Python subprocess question | 1,110,804 | <p>I would like to be able to spawn a process in python and have two way communication. Of course, Pexpect does this and is indeed a way I might go. However, it is not quite ideal.</p>
<p>My ideal situation would be to have a cross platform generic technique that involved only the standard python libraries. Subprocess gets pretty close, but the fact that I have to wait for the process to terminate before safely interacting with it is not desirable.</p>
<p>Looking at the documentation, it does say there is a stdin,stdout and stderr file descriptors that I can directly manipulate, but there is a big fat warning that says "Don't Do This". Unfortunately its not entirely clear why this warning exists, but from what I gather from google is that it is related to os buffering, and it is possible to write code that unexpectedly deadlocks when those internal buffers fail (as a side note, any examples that show the wrong way and right way would be appreciated).</p>
<p>So, risking my code to potential deadlocks, I thought it might be interesting to use poll or select to interactively read from the running process without killing it. Although I lose (i think) the cross platform ability, I like the fact that it requires no additional libraries. But more importantly, I would like to know if this is this a good idea. I have yet to try this approach, but I am concerned about gotchas that could potentially devastate my program. Can it work? What should I test for?</p>
<p>In my specific case I am not really concerned about being able to write to the process, just repeatedly reading from it. Also, I don't expect my processes to dump huge amounts of text, so I hope to avoid the deadlocking issue, however I would like to know exactly what those limits are and be able to write some tests to see where it breaks down.</p>
| 4 | 2009-07-10T17:16:05Z | 1,110,847 | <p>The short answer is that there is no such thing as a good cross platform system for process management, without designing that concept into your system. This is especially in the standar libraries. Even the various unix versions have their own compatibility issues.</p>
<p>Your best bet is to instrument all the processes with the proper event handling to notice events that come in from whatever IPC system works best on whatever platform. Named pipes
will be the general route for the problem you describe, but there will be implementation
differences on each platform.</p>
| 0 | 2009-07-10T17:22:49Z | [
"python",
"subprocess"
] |
Python subprocess question | 1,110,804 | <p>I would like to be able to spawn a process in python and have two way communication. Of course, Pexpect does this and is indeed a way I might go. However, it is not quite ideal.</p>
<p>My ideal situation would be to have a cross platform generic technique that involved only the standard python libraries. Subprocess gets pretty close, but the fact that I have to wait for the process to terminate before safely interacting with it is not desirable.</p>
<p>Looking at the documentation, it does say there is a stdin,stdout and stderr file descriptors that I can directly manipulate, but there is a big fat warning that says "Don't Do This". Unfortunately its not entirely clear why this warning exists, but from what I gather from google is that it is related to os buffering, and it is possible to write code that unexpectedly deadlocks when those internal buffers fail (as a side note, any examples that show the wrong way and right way would be appreciated).</p>
<p>So, risking my code to potential deadlocks, I thought it might be interesting to use poll or select to interactively read from the running process without killing it. Although I lose (i think) the cross platform ability, I like the fact that it requires no additional libraries. But more importantly, I would like to know if this is this a good idea. I have yet to try this approach, but I am concerned about gotchas that could potentially devastate my program. Can it work? What should I test for?</p>
<p>In my specific case I am not really concerned about being able to write to the process, just repeatedly reading from it. Also, I don't expect my processes to dump huge amounts of text, so I hope to avoid the deadlocking issue, however I would like to know exactly what those limits are and be able to write some tests to see where it breaks down.</p>
| 4 | 2009-07-10T17:16:05Z | 1,112,027 | <p>Use the <a href="http://docs.python.org/library/multiprocessing.html" rel="nofollow">multiprocessing</a> module in the Python 2.6 standard library. </p>
<p>It has a <a href="http://docs.python.org/library/multiprocessing.html#multiprocessing.Queue" rel="nofollow">Queue class</a> that can be used for both reading and writing.</p>
| 3 | 2009-07-10T21:16:58Z | [
"python",
"subprocess"
] |
Python subprocess question | 1,110,804 | <p>I would like to be able to spawn a process in python and have two way communication. Of course, Pexpect does this and is indeed a way I might go. However, it is not quite ideal.</p>
<p>My ideal situation would be to have a cross platform generic technique that involved only the standard python libraries. Subprocess gets pretty close, but the fact that I have to wait for the process to terminate before safely interacting with it is not desirable.</p>
<p>Looking at the documentation, it does say there is a stdin,stdout and stderr file descriptors that I can directly manipulate, but there is a big fat warning that says "Don't Do This". Unfortunately its not entirely clear why this warning exists, but from what I gather from google is that it is related to os buffering, and it is possible to write code that unexpectedly deadlocks when those internal buffers fail (as a side note, any examples that show the wrong way and right way would be appreciated).</p>
<p>So, risking my code to potential deadlocks, I thought it might be interesting to use poll or select to interactively read from the running process without killing it. Although I lose (i think) the cross platform ability, I like the fact that it requires no additional libraries. But more importantly, I would like to know if this is this a good idea. I have yet to try this approach, but I am concerned about gotchas that could potentially devastate my program. Can it work? What should I test for?</p>
<p>In my specific case I am not really concerned about being able to write to the process, just repeatedly reading from it. Also, I don't expect my processes to dump huge amounts of text, so I hope to avoid the deadlocking issue, however I would like to know exactly what those limits are and be able to write some tests to see where it breaks down.</p>
| 4 | 2009-07-10T17:16:05Z | 1,116,958 | <p>I do this in a separate thread, using message queues to communicate between the threads. In my case the subprocess prints % complete to stdout. I wanted the main thread to put up a pretty progress bar.</p>
<pre><code> if sys.platform == 'win32':
self.shell = False
self.startupinfo = subprocess.STARTUPINFO()
self.startupinfo.dwFlags = 0x01
self.startupinfo.wShowWindow = 0
else:
self.shell = True
self.startupinfo = None
</code></pre>
<p>.
.
.</p>
<pre><code>f = subprocess.Popen( cmd, stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE, env = env, shell = self.shell, startupinfo = self.startupinfo )
f.stdin.close()
line = ''
while True:
log.debug('reading')
c = f.stdout.read(1)
log.debug(c)
if len(c) == 0:
log.info('stdout empty; must be done')
break;
if ord(c) == 13:
continue
if c == '%':
# post % complete message to waiting thread.
line = ''
else:
line += c
log.info('checking for errors')
errs = f.stderr.readlines()
if errs:
prettyErrs = 'Reported Errors: '
for i in errs:
prettyErrs += i.rstrip('\n')
log.warn( prettyErrs )
#post errors to waiting thread
else:
print 'done'
return
</code></pre>
| 1 | 2009-07-12T21:25:18Z | [
"python",
"subprocess"
] |
Python subprocess question | 1,110,804 | <p>I would like to be able to spawn a process in python and have two way communication. Of course, Pexpect does this and is indeed a way I might go. However, it is not quite ideal.</p>
<p>My ideal situation would be to have a cross platform generic technique that involved only the standard python libraries. Subprocess gets pretty close, but the fact that I have to wait for the process to terminate before safely interacting with it is not desirable.</p>
<p>Looking at the documentation, it does say there is a stdin,stdout and stderr file descriptors that I can directly manipulate, but there is a big fat warning that says "Don't Do This". Unfortunately its not entirely clear why this warning exists, but from what I gather from google is that it is related to os buffering, and it is possible to write code that unexpectedly deadlocks when those internal buffers fail (as a side note, any examples that show the wrong way and right way would be appreciated).</p>
<p>So, risking my code to potential deadlocks, I thought it might be interesting to use poll or select to interactively read from the running process without killing it. Although I lose (i think) the cross platform ability, I like the fact that it requires no additional libraries. But more importantly, I would like to know if this is this a good idea. I have yet to try this approach, but I am concerned about gotchas that could potentially devastate my program. Can it work? What should I test for?</p>
<p>In my specific case I am not really concerned about being able to write to the process, just repeatedly reading from it. Also, I don't expect my processes to dump huge amounts of text, so I hope to avoid the deadlocking issue, however I would like to know exactly what those limits are and be able to write some tests to see where it breaks down.</p>
| 4 | 2009-07-10T17:16:05Z | 1,295,006 | <p>Forgive my ignorance on this topic, but couldn't you just launch python with the -u flag for "unbuffered"? </p>
<p>This might also be of interest...
<a href="http://www.gossamer-threads.com/lists/python/python/658167" rel="nofollow">http://www.gossamer-threads.com/lists/python/python/658167</a></p>
| 0 | 2009-08-18T16:28:37Z | [
"python",
"subprocess"
] |
python sqlalchemy performance? | 1,110,805 | <p>HI ï¼ I made a ICAPServer (similar with httpserver) for which the performance is very important.
The DB module is sqlalchemy.
I then made a test about the performance of sqlalchemy, as a result, i found that it takes about 30ms for sqlalchemy to write <50kb data to DB (Oracle), i don`t know if the result is normal, or i did something wrong?
BUT, no matter right or wrong, it seems the bottle-neck comes from the DB part.
HOW can i improve the performance of sqlalchemy? OR it is up to DBA to improve Oracle?</p>
<p>BTW, ICAPServer and Oracle are on the same pc , and i used the essential way of sqlalchemy..</p>
| 1 | 2009-07-10T17:16:11Z | 1,110,888 | <p>You can only push SQLAlchemy so far as a programmer. I would agree with you that the rest of the performance is up to your DBA, including creating proper indexes on tables, etc.</p>
| 1 | 2009-07-10T17:28:23Z | [
"python",
"sqlalchemy"
] |
python sqlalchemy performance? | 1,110,805 | <p>HI ï¼ I made a ICAPServer (similar with httpserver) for which the performance is very important.
The DB module is sqlalchemy.
I then made a test about the performance of sqlalchemy, as a result, i found that it takes about 30ms for sqlalchemy to write <50kb data to DB (Oracle), i don`t know if the result is normal, or i did something wrong?
BUT, no matter right or wrong, it seems the bottle-neck comes from the DB part.
HOW can i improve the performance of sqlalchemy? OR it is up to DBA to improve Oracle?</p>
<p>BTW, ICAPServer and Oracle are on the same pc , and i used the essential way of sqlalchemy..</p>
| 1 | 2009-07-10T17:16:11Z | 1,110,960 | <p>You should first <em>measure</em> where your bottleneck is, for example using the <a href="http://docs.python.org/library/profile.html">profile</a> module.</p>
<p>Then optimize, if you have the possibility to, the slowest part of the system.</p>
| 5 | 2009-07-10T17:41:18Z | [
"python",
"sqlalchemy"
] |
python sqlalchemy performance? | 1,110,805 | <p>HI ï¼ I made a ICAPServer (similar with httpserver) for which the performance is very important.
The DB module is sqlalchemy.
I then made a test about the performance of sqlalchemy, as a result, i found that it takes about 30ms for sqlalchemy to write <50kb data to DB (Oracle), i don`t know if the result is normal, or i did something wrong?
BUT, no matter right or wrong, it seems the bottle-neck comes from the DB part.
HOW can i improve the performance of sqlalchemy? OR it is up to DBA to improve Oracle?</p>
<p>BTW, ICAPServer and Oracle are on the same pc , and i used the essential way of sqlalchemy..</p>
| 1 | 2009-07-10T17:16:11Z | 1,110,990 | <p>I had some issues with sqlalchemy's performance as well - I think you should first figure out in which ways you are using it ... they recommend that for big data sets is better to use the sql expression language. Either ways try and optimize the sqlalchemy code and have the Oracle database optimized as well, so you can better figure out what's wrong.
Also, do some tests on the database.</p>
| 1 | 2009-07-10T17:46:49Z | [
"python",
"sqlalchemy"
] |
Get time zone information of the system in Python? | 1,111,056 | <p>I want to get the default timezone (PST) of my system from Python. What's the best way to do that? I'd like to avoid forking another process.</p>
| 26 | 2009-07-10T17:59:28Z | 1,111,079 | <p>Check out the Python <a href="http://docs.python.org/library/time.html" rel="nofollow">Time</a> Module.</p>
<pre><code>from time import gmtime, strftime
print strftime("%z", gmtime())
</code></pre>
<p>Pacific Standard Time</p>
| 4 | 2009-07-10T18:04:15Z | [
"python",
"datetime"
] |
Get time zone information of the system in Python? | 1,111,056 | <p>I want to get the default timezone (PST) of my system from Python. What's the best way to do that? I'd like to avoid forking another process.</p>
| 26 | 2009-07-10T17:59:28Z | 1,111,110 | <p>That should work:</p>
<pre><code>import time
time.tzname
</code></pre>
<p>it returns a tuple of two strings: the first is the name of the local non-DST timezone, the second is the name of the local DST timezone.</p>
| 43 | 2009-07-10T18:09:09Z | [
"python",
"datetime"
] |
Get time zone information of the system in Python? | 1,111,056 | <p>I want to get the default timezone (PST) of my system from Python. What's the best way to do that? I'd like to avoid forking another process.</p>
| 26 | 2009-07-10T17:59:28Z | 1,111,887 | <p>If you prefer UTC offsets over strings:</p>
<pre><code>time.timezone / -(60*60)
</code></pre>
| 4 | 2009-07-10T20:44:15Z | [
"python",
"datetime"
] |
Get time zone information of the system in Python? | 1,111,056 | <p>I want to get the default timezone (PST) of my system from Python. What's the best way to do that? I'd like to avoid forking another process.</p>
| 26 | 2009-07-10T17:59:28Z | 10,854,983 | <p>Gives a UTC offset like in ThomasH's answer, but takes daylight savings into account.</p>
<pre><code>>>> import time
>>> offset = time.timezone if (time.localtime().tm_isdst == 0) else time.altzone
>>> offset / 60 / 60 * -1
-9
</code></pre>
<p>The value of <code>time.timezone</code> or <code>time.altzone</code> is in seconds West of UTC (with areas East of UTC getting a negative value). This is the opposite to how we'd actually like it, hence the * -1.</p>
<p><code>time.localtime().tm_isdst</code> will be zero if daylight savings is currently not in effect (although this may not be correct if an area has recently changed their daylight savings law).</p>
<p>EDIT: marr75 is correct, I've edited the answer accordingly.</p>
| 19 | 2012-06-01T17:44:34Z | [
"python",
"datetime"
] |
Get time zone information of the system in Python? | 1,111,056 | <p>I want to get the default timezone (PST) of my system from Python. What's the best way to do that? I'd like to avoid forking another process.</p>
| 26 | 2009-07-10T17:59:28Z | 13,406,277 | <p>The code snippets for calculating offset are incorrect, see <a href="http://bugs.python.org/issue7229">http://bugs.python.org/issue7229</a>.</p>
<p>The correct way to handle this is:</p>
<pre><code>def local_time_offset(t=None):
"""Return offset of local zone from GMT, either at present or at time t."""
# python2.3 localtime() can't take None
if t is None:
t = time.time()
if time.localtime(t).tm_isdst and time.daylight:
return -time.altzone
else:
return -time.timezone
</code></pre>
<p>This is in all likelihood, not the exact question that the OP asked, but there are two incorrect snippets on the page and time bugs suck to track down and fix.</p>
| 10 | 2012-11-15T21:11:00Z | [
"python",
"datetime"
] |
How to build an Ecommerce Shopping Cart in Django? | 1,111,173 | <p>Is there a book or a tutorial which teaches how to build a shopping cart with django or any other python framework ?</p>
| 1 | 2009-07-10T18:22:48Z | 1,111,460 | <p>Satchmo project is a known open source shopping cart.<br />
<a href="http://www.satchmoproject.com/" rel="nofollow">http://www.satchmoproject.com/</a></p>
| 5 | 2009-07-10T19:17:46Z | [
"python",
"django",
"shopping-cart"
] |
How to build an Ecommerce Shopping Cart in Django? | 1,111,173 | <p>Is there a book or a tutorial which teaches how to build a shopping cart with django or any other python framework ?</p>
| 1 | 2009-07-10T18:22:48Z | 1,111,510 | <p>Ingredients:</p>
<ul>
<li>one cup PayPal (or subsitute with other equivalent payment system)</li>
<li>few cups html</li>
<li>add css to taste</li>
<li>add django if desired</li>
</ul>
<p>Cooking:</p>
<ul>
<li>Mix well.</li>
<li>Bake for 1-2 month.</li>
</ul>
<p>Release as open source :-) </p>
| 2 | 2009-07-10T19:27:35Z | [
"python",
"django",
"shopping-cart"
] |
How to build an Ecommerce Shopping Cart in Django? | 1,111,173 | <p>Is there a book or a tutorial which teaches how to build a shopping cart with django or any other python framework ?</p>
| 1 | 2009-07-10T18:22:48Z | 1,111,525 | <p>There's a book coming out that talks about just that. See here:</p>
<p><a href="http://www.apress.com/book/view/9781430225355">http://www.apress.com/book/view/9781430225355</a></p>
| 7 | 2009-07-10T19:29:44Z | [
"python",
"django",
"shopping-cart"
] |
How do Python and PHP compare for ecommerce? | 1,111,207 | <p>If I were to start an ecommerce store, which language would you suggest I start with? Python or PHP?</p>
<p>And would it be wise to use Python for an ecommerce site in favor of PHP? PHP has lots of shopping carts, both open source and commercial. </p>
<p>Is Python the future of Web Development ?</p>
<p>Edit:</p>
<p>I would like to clear out that i am not asking for Shopping carts solutions and links to them.</p>
| 5 | 2009-07-10T18:28:39Z | 1,111,278 | <p>PHP's memory management issues are overlooked because it's a language designed for the web, where long lasting processes aren't a problem.</p>
<p>This is the main reason I never favor PHP.</p>
| -4 | 2009-07-10T18:42:51Z | [
"php",
"python",
"django",
"e-commerce",
"turbogears"
] |
How do Python and PHP compare for ecommerce? | 1,111,207 | <p>If I were to start an ecommerce store, which language would you suggest I start with? Python or PHP?</p>
<p>And would it be wise to use Python for an ecommerce site in favor of PHP? PHP has lots of shopping carts, both open source and commercial. </p>
<p>Is Python the future of Web Development ?</p>
<p>Edit:</p>
<p>I would like to clear out that i am not asking for Shopping carts solutions and links to them.</p>
| 5 | 2009-07-10T18:28:39Z | 1,111,391 | <p>Whatever language you know better. I think this should be the first criterion.</p>
| 5 | 2009-07-10T19:03:24Z | [
"php",
"python",
"django",
"e-commerce",
"turbogears"
] |
How do Python and PHP compare for ecommerce? | 1,111,207 | <p>If I were to start an ecommerce store, which language would you suggest I start with? Python or PHP?</p>
<p>And would it be wise to use Python for an ecommerce site in favor of PHP? PHP has lots of shopping carts, both open source and commercial. </p>
<p>Is Python the future of Web Development ?</p>
<p>Edit:</p>
<p>I would like to clear out that i am not asking for Shopping carts solutions and links to them.</p>
| 5 | 2009-07-10T18:28:39Z | 1,111,393 | <p>I don't think you'll get a good answer to this one. Everyone uses php, and python ecommerce is probably mainly in-house built. If there was a popular python solution (something like django for web platforms) - then I doubt there would be any discussion.</p>
<p>However - as of now I have yet to see a good all-in one system.
On the upside, using python you can easily create something simple for your business.</p>
<p>As there are not going to be a lot of new drastic revisions to the Python language in the future, we can expect some good apps to come out soon. My bet today is on django apps.</p>
<p>Using php is probably good in the short run. Not that I would ever go back to it...</p>
<p>PS: I forgot about another one: ASP.NET (mvc?). If you are feeling particularly adventurous, they have loads of "controls" and products. However it all confuses me a lot.</p>
| 2 | 2009-07-10T19:03:53Z | [
"php",
"python",
"django",
"e-commerce",
"turbogears"
] |
How do Python and PHP compare for ecommerce? | 1,111,207 | <p>If I were to start an ecommerce store, which language would you suggest I start with? Python or PHP?</p>
<p>And would it be wise to use Python for an ecommerce site in favor of PHP? PHP has lots of shopping carts, both open source and commercial. </p>
<p>Is Python the future of Web Development ?</p>
<p>Edit:</p>
<p>I would like to clear out that i am not asking for Shopping carts solutions and links to them.</p>
| 5 | 2009-07-10T18:28:39Z | 1,111,394 | <p>I'd think that the overall implementation of any solution you choose (whether off-the-shelf or custom built) will be more important than any inherent speed differences between Python and PHP.</p>
<p>There are some truly shocking examples out there so it's worth doing research based upon your exact requirements. A shopping cart itself is a relatively simple object with standard functionality so if this is for a small-medium size store I'd go for whatever you feel more comfortable with.</p>
| 2 | 2009-07-10T19:04:02Z | [
"php",
"python",
"django",
"e-commerce",
"turbogears"
] |
How do Python and PHP compare for ecommerce? | 1,111,207 | <p>If I were to start an ecommerce store, which language would you suggest I start with? Python or PHP?</p>
<p>And would it be wise to use Python for an ecommerce site in favor of PHP? PHP has lots of shopping carts, both open source and commercial. </p>
<p>Is Python the future of Web Development ?</p>
<p>Edit:</p>
<p>I would like to clear out that i am not asking for Shopping carts solutions and links to them.</p>
| 5 | 2009-07-10T18:28:39Z | 1,111,400 | <p>I would say that PHP carts are probably more mature and have more features than the Django ones. (Note I've only had experience with 2 PHP shopping carts and no Python ones)</p>
<p>On the other hand, PHP is a poorly designed language and is usually slower than Python in benchmarks. Depending on your needs, a Python shopping cart may suffice.</p>
| 1 | 2009-07-10T19:04:26Z | [
"php",
"python",
"django",
"e-commerce",
"turbogears"
] |
How do Python and PHP compare for ecommerce? | 1,111,207 | <p>If I were to start an ecommerce store, which language would you suggest I start with? Python or PHP?</p>
<p>And would it be wise to use Python for an ecommerce site in favor of PHP? PHP has lots of shopping carts, both open source and commercial. </p>
<p>Is Python the future of Web Development ?</p>
<p>Edit:</p>
<p>I would like to clear out that i am not asking for Shopping carts solutions and links to them.</p>
| 5 | 2009-07-10T18:28:39Z | 1,112,457 | <p>I'm personally a fan of Python, specificity with Django for the web. For ecommerce applications there is the <a href="http://www.satchmoproject.com/" rel="nofollow">Satchmo Project</a>.</p>
| 4 | 2009-07-10T23:43:55Z | [
"php",
"python",
"django",
"e-commerce",
"turbogears"
] |
How do Python and PHP compare for ecommerce? | 1,111,207 | <p>If I were to start an ecommerce store, which language would you suggest I start with? Python or PHP?</p>
<p>And would it be wise to use Python for an ecommerce site in favor of PHP? PHP has lots of shopping carts, both open source and commercial. </p>
<p>Is Python the future of Web Development ?</p>
<p>Edit:</p>
<p>I would like to clear out that i am not asking for Shopping carts solutions and links to them.</p>
| 5 | 2009-07-10T18:28:39Z | 1,112,465 | <p>Honestly, the languages don't really matter. </p>
<p>Both PHP and Python are capable to develop great websites and there are many examples for that.</p>
| 4 | 2009-07-10T23:46:55Z | [
"php",
"python",
"django",
"e-commerce",
"turbogears"
] |
How do Python and PHP compare for ecommerce? | 1,111,207 | <p>If I were to start an ecommerce store, which language would you suggest I start with? Python or PHP?</p>
<p>And would it be wise to use Python for an ecommerce site in favor of PHP? PHP has lots of shopping carts, both open source and commercial. </p>
<p>Is Python the future of Web Development ?</p>
<p>Edit:</p>
<p>I would like to clear out that i am not asking for Shopping carts solutions and links to them.</p>
| 5 | 2009-07-10T18:28:39Z | 2,787,433 | <p>This is a challenging question to answer. If you are going for an off the-shelf package you're going to need to use PHP - this then gives you a range of packages including Magento, osCommerce (yuck) and so on.</p>
<p>If you are planning to develop a bespoke, or partially bespoke solution, then you probably want to look at using a framework to cut down the amount of code you need to write from the outset. Again, there are various options for each language. </p>
<p>Python and Django has a web framework for satchmo that could really take the legwork out of an ecommerce build whilst giving a level of flexibility that you usually don't get from an off-the-shelf package.</p>
| 2 | 2010-05-07T09:13:35Z | [
"php",
"python",
"django",
"e-commerce",
"turbogears"
] |
How do Python and PHP compare for ecommerce? | 1,111,207 | <p>If I were to start an ecommerce store, which language would you suggest I start with? Python or PHP?</p>
<p>And would it be wise to use Python for an ecommerce site in favor of PHP? PHP has lots of shopping carts, both open source and commercial. </p>
<p>Is Python the future of Web Development ?</p>
<p>Edit:</p>
<p>I would like to clear out that i am not asking for Shopping carts solutions and links to them.</p>
| 5 | 2009-07-10T18:28:39Z | 9,123,535 | <p>More important than the language is the developer's ability to translate business logic into elegant and maintainable code. But I <i>would</i> recommend building with an MVC framework in whatever language you choose. Both PHP and Python have options there (django, CakePHP are popular choices).</p>
| 1 | 2012-02-03T04:06:07Z | [
"php",
"python",
"django",
"e-commerce",
"turbogears"
] |
How do Python and PHP compare for ecommerce? | 1,111,207 | <p>If I were to start an ecommerce store, which language would you suggest I start with? Python or PHP?</p>
<p>And would it be wise to use Python for an ecommerce site in favor of PHP? PHP has lots of shopping carts, both open source and commercial. </p>
<p>Is Python the future of Web Development ?</p>
<p>Edit:</p>
<p>I would like to clear out that i am not asking for Shopping carts solutions and links to them.</p>
| 5 | 2009-07-10T18:28:39Z | 38,287,718 | <p>I prefer php since its rapidly used for web application and continuously developed by a very large community. Also when you are in php you have to less worry about server, URL etc stuff how works. So you can dig into deep of developments. And finally now php 7 comes out and itâs vast stable then previous with OOP. So my advice go with php until any specific things you need which available in python only.</p>
| 0 | 2016-07-10T01:12:23Z | [
"php",
"python",
"django",
"e-commerce",
"turbogears"
] |
@staticmethod gives SyntaxError: invalid syntax | 1,111,227 | <p>I have been using a python script for a long while and all of sudden it gives me:</p>
<pre><code> File "youtube-dl.py", line 103
@staticmethod
^
SyntaxError: invalid syntax
</code></pre>
<p>If you want to see the script, its right here: <a href="http://bitbucket.org/rg3/youtube-dl/raw/2009.06.29/youtube-dl" rel="nofollow">http://bitbucket.org/rg3/youtube-dl/raw/2009.06.29/youtube-dl</a></p>
<p>What could be the reason?</p>
<h2>Update</h2>
<p>I am using python version Python 2.3.4.</p>
| 1 | 2009-07-10T18:31:40Z | 1,111,235 | <p>You might be using an old Python version that didn't support <a href="http://www.python.org/dev/peps/pep-0318/" rel="nofollow">decorators</a> yet.</p>
| 4 | 2009-07-10T18:33:43Z | [
"python"
] |
Problem loading a specific website through Qt Webkit | 1,111,267 | <p>I am currently using the following PyQt code to create a simple browser:</p>
<pre><code>import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
app = QApplication(sys.argv)
web = QWebView()
web.load(QUrl("http://www.robeez.com"))
web.show()
sys.exit(app.exec_())
</code></pre>
<p>Websites like google.com or stackoverflow.com work fine but robeez.com doesn't. Does anyone with Webkit experience know what might be wrong? robeez.com works fine in a regular browser like Chrome or Firefox.</p>
| 0 | 2009-07-10T18:40:37Z | 1,111,422 | <p>try <a href="http://code.google.com/p/arora/" rel="nofollow">arora</a> (a very simple wrapping on top of QtWebKit); if it works, its your code. if it doesn't, its the website.</p>
| 0 | 2009-07-10T19:09:29Z | [
"python",
"webkit",
"pyqt",
"qtwebkit"
] |
Problem loading a specific website through Qt Webkit | 1,111,267 | <p>I am currently using the following PyQt code to create a simple browser:</p>
<pre><code>import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
app = QApplication(sys.argv)
web = QWebView()
web.load(QUrl("http://www.robeez.com"))
web.show()
sys.exit(app.exec_())
</code></pre>
<p>Websites like google.com or stackoverflow.com work fine but robeez.com doesn't. Does anyone with Webkit experience know what might be wrong? robeez.com works fine in a regular browser like Chrome or Firefox.</p>
| 0 | 2009-07-10T18:40:37Z | 1,201,076 | <p>For some reason <a href="http://www.robeeez.com" rel="nofollow">http://www.robeeez.com</a> which I think redirects to rebeez.com DOES work.
In some cases rebeez.com sends out a blank index.html page, dillo and wget also receive
nothing as does the qt45 demo browser. So is it the browser or the way the site is set up??</p>
| 0 | 2009-07-29T15:23:14Z | [
"python",
"webkit",
"pyqt",
"qtwebkit"
] |
Problem loading a specific website through Qt Webkit | 1,111,267 | <p>I am currently using the following PyQt code to create a simple browser:</p>
<pre><code>import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
app = QApplication(sys.argv)
web = QWebView()
web.load(QUrl("http://www.robeez.com"))
web.show()
sys.exit(app.exec_())
</code></pre>
<p>Websites like google.com or stackoverflow.com work fine but robeez.com doesn't. Does anyone with Webkit experience know what might be wrong? robeez.com works fine in a regular browser like Chrome or Firefox.</p>
| 0 | 2009-07-10T18:40:37Z | 1,503,085 | <p>Try sending the Accept-Language header also, it then works for me.</p>
| 0 | 2009-10-01T10:15:59Z | [
"python",
"webkit",
"pyqt",
"qtwebkit"
] |
How do I print a Python datetime in the local timezone? | 1,111,317 | <p>Let's say I have a variable t that's set to this:</p>
<pre><code>datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=<UTC>)
</code></pre>
<p>If I say <code>str(t)</code>, i get:</p>
<pre><code>'2009-07-10 18:44:59.193982+00:00'
</code></pre>
<p>How can I get a similar string, except printed in the local timezone rather than UTC?</p>
| 10 | 2009-07-10T18:50:59Z | 1,111,345 | <p>Think your should look around: datetime.astimezone()</p>
<p><strong><a href="http://docs.python.org/library/datetime.html#datetime.datetime.astimezone">http://docs.python.org/library/datetime.html#datetime.datetime.astimezone</a></strong></p>
<p>Also see pytz module - it's quite easy to use -- as example:</p>
<pre><code>eastern = timezone('US/Eastern')
</code></pre>
<p><strong><a href="http://pytz.sourceforge.net/">http://pytz.sourceforge.net/</a></strong></p>
<p>Example:</p>
<pre><code>from datetime import datetime
import pytz
from tzlocal import get_localzone # $ pip install tzlocal
utc_dt = datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=pytz.utc)
print(utc_dt.astimezone(get_localzone())) # print local time
# -> 2009-07-10 14:44:59.193982-04:00
</code></pre>
| 12 | 2009-07-10T18:54:42Z | [
"python",
"timezone"
] |
How do I print a Python datetime in the local timezone? | 1,111,317 | <p>Let's say I have a variable t that's set to this:</p>
<pre><code>datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=<UTC>)
</code></pre>
<p>If I say <code>str(t)</code>, i get:</p>
<pre><code>'2009-07-10 18:44:59.193982+00:00'
</code></pre>
<p>How can I get a similar string, except printed in the local timezone rather than UTC?</p>
| 10 | 2009-07-10T18:50:59Z | 1,111,655 | <p>I wrote something like this the other day:</p>
<pre><code>import time, datetime
def nowString():
# we want something like '2007-10-18 14:00+0100'
mytz="%+4.4d" % (time.timezone / -(60*60) * 100) # time.timezone counts westwards!
dt = datetime.datetime.now()
dts = dt.strftime('%Y-%m-%d %H:%M') # %Z (timezone) would be empty
nowstring="%s%s" % (dts,mytz)
return nowstring
</code></pre>
<p>So the interesting part for you is probably the line starting with "mytz=...". time.timezone returns the local timezone, albeit with opposite sign compared to UTC. So it says "-3600" to express UTC+1.</p>
<p>Despite its ignorance towards Daylight Saving Time (DST, see comment), I'm leaving this in for people fiddling around with <code>time.timezone</code>.</p>
| 0 | 2009-07-10T19:57:17Z | [
"python",
"timezone"
] |
How do I print a Python datetime in the local timezone? | 1,111,317 | <p>Let's say I have a variable t that's set to this:</p>
<pre><code>datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=<UTC>)
</code></pre>
<p>If I say <code>str(t)</code>, i get:</p>
<pre><code>'2009-07-10 18:44:59.193982+00:00'
</code></pre>
<p>How can I get a similar string, except printed in the local timezone rather than UTC?</p>
| 10 | 2009-07-10T18:50:59Z | 2,071,364 | <p>I believe the best way to do this is to use the <code>LocalTimezone</code> class defined in the <code>datetime.tzinfo</code> documentation (goto <a href="http://docs.python.org/library/datetime.html#tzinfo-objects">http://docs.python.org/library/datetime.html#tzinfo-objects</a> and scroll down to the "Example tzinfo classes" section):</p>
<p>Assuming <code>Local</code> is an instance of <code>LocalTimezone</code></p>
<pre><code>t = datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=utc)
local_t = t.astimezone(Local)
</code></pre>
<p>then <code>str(local_t)</code> gives:</p>
<pre><code>'2009-07-11 04:44:59.193982+10:00'
</code></pre>
<p>which is what you want.</p>
<p>(Note: this may look weird to you because I'm in New South Wales, Australia which is 10 or 11 hours <em>ahead</em> of UTC)</p>
| 8 | 2010-01-15T12:23:54Z | [
"python",
"timezone"
] |
How do I print a Python datetime in the local timezone? | 1,111,317 | <p>Let's say I have a variable t that's set to this:</p>
<pre><code>datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=<UTC>)
</code></pre>
<p>If I say <code>str(t)</code>, i get:</p>
<pre><code>'2009-07-10 18:44:59.193982+00:00'
</code></pre>
<p>How can I get a similar string, except printed in the local timezone rather than UTC?</p>
| 10 | 2009-07-10T18:50:59Z | 18,647,007 | <p><a href="http://stackoverflow.com/a/18646797/2697658">This answer</a> shows a simple way to use <a href="http://docs.python.org/2/library/datetime.html#datetime.datetime.astimezone" rel="nofollow">astimezone</a>.</p>
| 0 | 2013-09-05T22:33:22Z | [
"python",
"timezone"
] |
How do I print a Python datetime in the local timezone? | 1,111,317 | <p>Let's say I have a variable t that's set to this:</p>
<pre><code>datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=<UTC>)
</code></pre>
<p>If I say <code>str(t)</code>, i get:</p>
<pre><code>'2009-07-10 18:44:59.193982+00:00'
</code></pre>
<p>How can I get a similar string, except printed in the local timezone rather than UTC?</p>
| 10 | 2009-07-10T18:50:59Z | 18,812,308 | <p>I use this function <code>datetime_to_local_timezone()</code>, which seems overly convoluted but I found no simpler version of a function that converts a <code>datetime</code> instance to the local time zone, as configured in the <em>operating system</em>, with the UTC offset that was in effect <em>at that time</em>:</p>
<pre><code>import time, datetime
def datetime_to_local_timezone(dt):
epoch = dt.timestamp() # Get POSIX timestamp of the specified datetime.
st_time = time.localtime(epoch) # Get struct_time for the timestamp. This will be created using the system's locale and it's time zone information.
tz = datetime.timezone(datetime.timedelta(seconds = st_time.tm_gmtoff)) # Create a timezone object with the computed offset in the struct_time.
return dt.astimezone(tz) # Move the datetime instance to the new time zone.
utc = datetime.timezone(datetime.timedelta())
dt1 = datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, utc) # DST was in effect
dt2 = datetime.datetime(2009, 1, 10, 18, 44, 59, 193982, utc) # DST was not in effect
print(dt1)
print(datetime_to_local_timezone(dt1))
print(dt2)
print(datetime_to_local_timezone(dt2))
</code></pre>
<p>This example prints four dates. For two moments in time, one in January and one in July 2009, each, it prints the timestamp once in UTC and once in the local time zone. Here, where CET (UTC+01:00) is used in the winter and CEST (UTC+02:00) is used in the summer, it prints the following:</p>
<pre><code>2009-07-10 18:44:59.193982+00:00
2009-07-10 20:44:59.193982+02:00
2009-01-10 18:44:59.193982+00:00
2009-01-10 19:44:59.193982+01:00
</code></pre>
| 0 | 2013-09-15T12:21:39Z | [
"python",
"timezone"
] |
Is there anything like HTTP::Recorder for Python? | 1,111,356 | <p>I really like Perl's <a href="http://search.cpan.org/~leira/HTTP-Recorder-0.05/" rel="nofollow">HTTP::Recorder</a>. Is there something like it for Python?</p>
| 2 | 2009-07-10T18:56:40Z | 1,111,469 | <p>I'm aware of Scotch and FunkLoad, but I don't know how they compare with HTTP::Recorder. See the following links for more details:</p>
<ul>
<li><p><a href="http://darcs.idyll.org/~t/projects/scotch/doc/" rel="nofollow">http://darcs.idyll.org/~t/projects/scotch/doc/</a></p>
<ul>
<li>also see the subsection "Other Python Recorders and Proxies"</li>
</ul></li>
<li><p><a href="http://funkload.nuxeo.org/#test-recorder" rel="nofollow">http://funkload.nuxeo.org/#test-recorder</a></p></li>
</ul>
| 4 | 2009-07-10T19:19:20Z | [
"python",
"http",
"proxy",
"record"
] |
Is it really OK to do object closeing/disposing in __del__? | 1,111,505 | <p>I have been thinking about how I write classes in Python. More specifically how the constructor is implemented and how the object should be destroyed. I don't want to rely on CPython's reference counting to do object cleanup. This basically tells me I should use with statements to manage my object life times and that I need an explicit close/dispose method (this method could be called from <code>__exit__</code> if the object is also a context manager).</p>
<pre><code>class Foo(object):
def __init__(self):
pass
def close(self):
pass
</code></pre>
<p>Now, if all my objects behave in this way and all my code uses with statements or explicit calls to <code>close()</code> (or <code>dispose()</code>) I don't realy see the need for me to put any code in <code>__del__</code>. Should we really use <code>__del__</code> to dispose of our objects?</p>
| 7 | 2009-07-10T19:26:49Z | 1,111,564 | <p>Not necessarily. You'll encounter problems when you have cyclic references. Eli Bendersky does a good job of explaining this in his blog post:</p>
<ul>
<li><a href="http://eli.thegreenplace.net/2009/06/12/safely-using-destructors-in-python/">Safely using destructors in Python</a></li>
</ul>
| 8 | 2009-07-10T19:37:47Z | [
"python"
] |
Is it really OK to do object closeing/disposing in __del__? | 1,111,505 | <p>I have been thinking about how I write classes in Python. More specifically how the constructor is implemented and how the object should be destroyed. I don't want to rely on CPython's reference counting to do object cleanup. This basically tells me I should use with statements to manage my object life times and that I need an explicit close/dispose method (this method could be called from <code>__exit__</code> if the object is also a context manager).</p>
<pre><code>class Foo(object):
def __init__(self):
pass
def close(self):
pass
</code></pre>
<p>Now, if all my objects behave in this way and all my code uses with statements or explicit calls to <code>close()</code> (or <code>dispose()</code>) I don't realy see the need for me to put any code in <code>__del__</code>. Should we really use <code>__del__</code> to dispose of our objects?</p>
| 7 | 2009-07-10T19:26:49Z | 1,112,052 | <p>If you are sure you will not go into cyclic references, then using <code>__del__</code> in that way is OK: as soon as the reference count goes to zero, the CPython VM will call that method and destroy the object. </p>
<p>If you plan to use cyclic references - please think it very thoroughly, and check if weak references may help; in many cases, cyclic references are a first symptom of bad design. </p>
<p>If you have no control on the way your object is going to be used, then using <code>__del__</code> may not be safe. </p>
<p>If you plan to use JPython or IronPython, <code>__del__</code> is unreliable at all, because final object destruction will happen at garbage collection, and that's something you cannot control. </p>
<p>In sum, in my opinion, <code>__del__</code> is usually perfectly safe and good; however, in many situation it could be better to make a step back, and try to look at the problem from a different perspective; a good use of try/except and of with contexts may be a more pythonic solution. </p>
| 0 | 2009-07-10T21:21:52Z | [
"python"
] |
Is it really OK to do object closeing/disposing in __del__? | 1,111,505 | <p>I have been thinking about how I write classes in Python. More specifically how the constructor is implemented and how the object should be destroyed. I don't want to rely on CPython's reference counting to do object cleanup. This basically tells me I should use with statements to manage my object life times and that I need an explicit close/dispose method (this method could be called from <code>__exit__</code> if the object is also a context manager).</p>
<pre><code>class Foo(object):
def __init__(self):
pass
def close(self):
pass
</code></pre>
<p>Now, if all my objects behave in this way and all my code uses with statements or explicit calls to <code>close()</code> (or <code>dispose()</code>) I don't realy see the need for me to put any code in <code>__del__</code>. Should we really use <code>__del__</code> to dispose of our objects?</p>
| 7 | 2009-07-10T19:26:49Z | 1,113,173 | <p>Short answer : No.</p>
<p>Long answer: Using <code>__del__</code> is tricky, mainly because it's not guaranteed to be called. That means you can't do things there that absolutely has to be done. This in turn means that <code>__del__</code> basically only can be used for cleanups that would happen sooner or later anyway, like cleaning up resources that would be cleaned up when the process exits, so it doesn't matter if <code>__del__</code> doesn't get called. Of course, these are also generally the same things Python will do for you. So that kinda makes <code>__del__</code> useless.</p>
<p>Also, <code>__del__</code> gets called when Python garbage collects, and you didn't want to wait for Pythons garbage collecting, which means you can't use <code>__del__</code> anyway.</p>
<p>So, don't use <code>__del__</code>. Use <code>__enter__/__exit__</code> instead.</p>
<p>FYI: Here is an example of a non-circular situation where the destructor did not get called:</p>
<pre><code>class A(object):
def __init__(self):
print('Constructing A')
def __del__(self):
print('Destructing A')
class B(object):
a = A()
</code></pre>
<p>OK, so it's a class attribute. Evidently that's a special case. But it just goes to show that making sure <code>__del__</code> gets called isn't straightforward. I'm pretty sure I've seen more non-circular situations where <code>__del__</code> isn't called.</p>
| 10 | 2009-07-11T07:38:25Z | [
"python"
] |
Why is BeautifulSoup throwing this HTMLParseError? | 1,111,656 | <p>I thought BeautifulSoup will be able to handle malformed documents, but when I sent it the source of a page, the following traceback got printed:</p>
<pre><code>
Traceback (most recent call last):
File "mx.py", line 7, in
s = BeautifulSoup(content)
File "build\bdist.win32\egg\BeautifulSoup.py", line 1499, in __init__
File "build\bdist.win32\egg\BeautifulSoup.py", line 1230, in __init__
File "build\bdist.win32\egg\BeautifulSoup.py", line 1263, in _feed
File "C:\Python26\lib\HTMLParser.py", line 108, in feed
self.goahead(0)
File "C:\Python26\lib\HTMLParser.py", line 150, in goahead
k = self.parse_endtag(i)
File "C:\Python26\lib\HTMLParser.py", line 314, in parse_endtag
self.error("bad end tag: %r" % (rawdata[i:j],))
File "C:\Python26\lib\HTMLParser.py", line 115, in error
raise HTMLParseError(message, self.getpos())
HTMLParser.HTMLParseError: bad end tag: u"", at line 258, column 34
</code></pre>
<p>Shouldn't it be able to handle this sort of stuff? If it can handle them, how could I do it? If not, is there a module that can handle malformed documents?</p>
<p>EDIT: here's an update. I saved the page locally, using firefox, and I tried to create a soup object from the contents of the file. That's where BeautifulSoup fails. If I try to create a soup object directly from the website, it works.<a href="http://pastie.org/541966" rel="nofollow">Here's</a> the document that causes trouble for soup.</p>
| 1 | 2009-07-10T19:57:17Z | 1,111,787 | <p>In my experience BeautifulSoup isn't that fault tolerant. I had to use it once for a small script and ran into these problems. I think using a regular expression to strip out the tags helped a bit, but I eventually just gave up and moved the script over to Ruby and Nokogiri.</p>
| 1 | 2009-07-10T20:25:16Z | [
"python",
"exception",
"parsing",
"beautifulsoup",
"malformed"
] |
Why is BeautifulSoup throwing this HTMLParseError? | 1,111,656 | <p>I thought BeautifulSoup will be able to handle malformed documents, but when I sent it the source of a page, the following traceback got printed:</p>
<pre><code>
Traceback (most recent call last):
File "mx.py", line 7, in
s = BeautifulSoup(content)
File "build\bdist.win32\egg\BeautifulSoup.py", line 1499, in __init__
File "build\bdist.win32\egg\BeautifulSoup.py", line 1230, in __init__
File "build\bdist.win32\egg\BeautifulSoup.py", line 1263, in _feed
File "C:\Python26\lib\HTMLParser.py", line 108, in feed
self.goahead(0)
File "C:\Python26\lib\HTMLParser.py", line 150, in goahead
k = self.parse_endtag(i)
File "C:\Python26\lib\HTMLParser.py", line 314, in parse_endtag
self.error("bad end tag: %r" % (rawdata[i:j],))
File "C:\Python26\lib\HTMLParser.py", line 115, in error
raise HTMLParseError(message, self.getpos())
HTMLParser.HTMLParseError: bad end tag: u"", at line 258, column 34
</code></pre>
<p>Shouldn't it be able to handle this sort of stuff? If it can handle them, how could I do it? If not, is there a module that can handle malformed documents?</p>
<p>EDIT: here's an update. I saved the page locally, using firefox, and I tried to create a soup object from the contents of the file. That's where BeautifulSoup fails. If I try to create a soup object directly from the website, it works.<a href="http://pastie.org/541966" rel="nofollow">Here's</a> the document that causes trouble for soup.</p>
| 1 | 2009-07-10T19:57:17Z | 1,112,480 | <p>Worked fine for me using BeautifulSoup version 3.0.7. The latest is 3.1.0, but there's a note on the BeautifulSoup home page to try 3.0.7a if you're having trouble. I think I ran into a similar problem as yours some time ago and reverted, which fixed the problem; I'd try that. </p>
<p>If you want to stick with your current version, I suggest removing the large <code><script></code> block at the top, since that is where the error occurs, and since you cannot parse that section with BeautifulSoup anyway.</p>
| 5 | 2009-07-10T23:52:26Z | [
"python",
"exception",
"parsing",
"beautifulsoup",
"malformed"
] |
Why is BeautifulSoup throwing this HTMLParseError? | 1,111,656 | <p>I thought BeautifulSoup will be able to handle malformed documents, but when I sent it the source of a page, the following traceback got printed:</p>
<pre><code>
Traceback (most recent call last):
File "mx.py", line 7, in
s = BeautifulSoup(content)
File "build\bdist.win32\egg\BeautifulSoup.py", line 1499, in __init__
File "build\bdist.win32\egg\BeautifulSoup.py", line 1230, in __init__
File "build\bdist.win32\egg\BeautifulSoup.py", line 1263, in _feed
File "C:\Python26\lib\HTMLParser.py", line 108, in feed
self.goahead(0)
File "C:\Python26\lib\HTMLParser.py", line 150, in goahead
k = self.parse_endtag(i)
File "C:\Python26\lib\HTMLParser.py", line 314, in parse_endtag
self.error("bad end tag: %r" % (rawdata[i:j],))
File "C:\Python26\lib\HTMLParser.py", line 115, in error
raise HTMLParseError(message, self.getpos())
HTMLParser.HTMLParseError: bad end tag: u"", at line 258, column 34
</code></pre>
<p>Shouldn't it be able to handle this sort of stuff? If it can handle them, how could I do it? If not, is there a module that can handle malformed documents?</p>
<p>EDIT: here's an update. I saved the page locally, using firefox, and I tried to create a soup object from the contents of the file. That's where BeautifulSoup fails. If I try to create a soup object directly from the website, it works.<a href="http://pastie.org/541966" rel="nofollow">Here's</a> the document that causes trouble for soup.</p>
| 1 | 2009-07-10T19:57:17Z | 1,112,713 | <p>The problem appears to be the<br />
<code>contents = contents.replace(/</g, '&lt;');</code><br />
in line 258 plus the similar<br />
<code>contents = contents.replace(/>/g, '&gt;');</code><br />
in the next line.</p>
<p>I'd just use re.sub to clobber all occurrences of r"replace(/[<>]/" with something inocuous before feeding it to BeautifulSoup ... moving away from BeautifulSoup would be like throwing out the baby with the bathwater IMHO.</p>
| 1 | 2009-07-11T01:51:12Z | [
"python",
"exception",
"parsing",
"beautifulsoup",
"malformed"
] |
Replace URL with a link using regex in python | 1,112,012 | <p>how do I convert some text to a link? Back in PHP, I used this piece of code that worked well for my purpose:</p>
<pre><code> $text = preg_replace("#(^|[\n ])(([\w]+?://[\w\#$%&~.\-;:=,?@\[\]+]*)(/[\w\#$%&~/.\-;:=,?@\[\]+]*)?)#is", "\\1<a href=\"\\2\" target=\"_blank\">\\3</a>", $text);
$text = preg_replace("#(^|[\n ])(((www|ftp)\.[\w\#$%&~.\-;:=,?@\[\]+]*)(/[\w\#$%&~/.\-;:=,?@\[\]+]*)?)#is", "\\1<a href=\"http://\\2\" target=\"_blank\">\\3</a>", $text);
</code></pre>
<p>I tried around in Python, but was unable to get it to work.. Would be very nice if someone could translate this to Python :)..</p>
| 3 | 2009-07-10T21:12:32Z | 1,112,670 | <p>The code below is a simple translation to python. You should confirm that it actually does what you want. For more information, please see the <a href="http://www.amk.ca/python/howto/regex/regex.html" rel="nofollow">Python Regular Expression HOWTO</a>.</p>
<pre><code>import re
pat1 = re.compile(r"(^|[\n ])(([\w]+?://[\w\#$%&~.\-;:=,?@\[\]+]*)(/[\w\#$%&~/.\-;:=,?@\[\]+]*)?)", re.IGNORECASE | re.DOTALL)
pat2 = re.compile(r"#(^|[\n ])(((www|ftp)\.[\w\#$%&~.\-;:=,?@\[\]+]*)(/[\w\#$%&~/.\-;:=,?@\[\]+]*)?)", re.IGNORECASE | re.DOTALL)
urlstr = 'http://www.example.com/foo/bar.html'
urlstr = pat1.sub(r'\1<a href="\2" target="_blank">\3</a>', urlstr)
urlstr = pat2.sub(r'\1<a href="http:/\2" target="_blank">\3</a>', urlstr)
print urlstr
</code></pre>
<p>Here's what the output looks like at my end:</p>
<pre><code><a href="http://www.example.com/foo/bar.html" target="_blank">http://www.example.com</a>
</code></pre>
| 5 | 2009-07-11T01:28:11Z | [
"python",
"regex",
"url",
"hyperlink"
] |
Accessing Clipboard in Python version 3.1 | 1,112,057 | <p>I want to access the clipboard using Python 3.1. I've obviously come across win32clipboard, but it requires pywin32 and in its site I only found download versions for up to Python 2.13 or so.</p>
<p>Bottom line: Is there a way to access the clipboard in Python 3.1 or do I have to revert to an old Python version?</p>
| 0 | 2009-07-10T21:23:36Z | 1,112,081 | <p>No you don't need to revert, it will be quite strange. Go to <strong><a href="http://sourceforge.net/projects/pywin32/files/" rel="nofollow">http://sourceforge.net/projects/pywin32/files/</a></strong> and download package for Python 3.1 from there.</p>
| 1 | 2009-07-10T21:29:04Z | [
"python",
"clipboard"
] |
What are the different possible values for __name__ in a Python script, and what do they mean? | 1,112,198 | <p>Checking to see if <code>__name__ == '__main__'</code> is a common idiom to run some code when the file is being called directly, rather than through a module.</p>
<p>In the process of writing a custom command for Django's manage.py, I found myself needing to use <code>code.InteractiveConsole</code>, which gives the effect to the user of a standard python shell. In some test code I was doing, I found that in the script I'm trying to execute, I get that <code>__name__</code> is <code>__console__</code>, which caused my code (dependent on <code>__main__</code>) to not run.</p>
<p>I'm fairly certain that I have some things in my original implementation to change, but it got me wondering as to what different things <code>__name__</code> could be. I couldn't find any documentation on the possible values, nor what they mean, so that's how I ended up here.</p>
| 6 | 2009-07-10T21:59:09Z | 1,112,223 | <p><code>__name__</code> is usually the module name, but it's changed to <code>'__main__'</code> when the module in question is executed directly instead of being imported by another one.</p>
<p>I understand that other values can only be set directly by the code you're running.</p>
| 4 | 2009-07-10T22:04:25Z | [
"python"
] |
What are the different possible values for __name__ in a Python script, and what do they mean? | 1,112,198 | <p>Checking to see if <code>__name__ == '__main__'</code> is a common idiom to run some code when the file is being called directly, rather than through a module.</p>
<p>In the process of writing a custom command for Django's manage.py, I found myself needing to use <code>code.InteractiveConsole</code>, which gives the effect to the user of a standard python shell. In some test code I was doing, I found that in the script I'm trying to execute, I get that <code>__name__</code> is <code>__console__</code>, which caused my code (dependent on <code>__main__</code>) to not run.</p>
<p>I'm fairly certain that I have some things in my original implementation to change, but it got me wondering as to what different things <code>__name__</code> could be. I couldn't find any documentation on the possible values, nor what they mean, so that's how I ended up here.</p>
| 6 | 2009-07-10T21:59:09Z | 1,112,293 | <p>from the <a href="http://docs.python.org/library/code.html#code.InteractiveInterpreter">document</a> of class code.InteractiveInterpreter([locals]):<br />
The optional locals argument specifies the dictionary in which code will be executed; it defaults to a newly created dictionary with key <code>'__name__'</code> set to <code>'__console__'</code> and key <code>'__doc__'</code> set to <code>None</code>.
maybe u can turnning the locals argument, set <code>__name__</code> with <code>__main__</code>, or change the test clause from </p>
<pre><code>if __name__ == '__main__'
to
if __name__ in set(["__main__", "__console__"])
</code></pre>
<p>Hope it helps.</p>
| 6 | 2009-07-10T22:30:21Z | [
"python"
] |
How do I capture SIGINT in Python? | 1,112,343 | <p>I'm working on a python script that starts several processes and database connections. Every now and then I want to kill the script with a <kbd>Ctrl</kbd>+<kbd>C</kbd> signal, and I'd like to do some cleanup.</p>
<p>In Perl I'd do this:</p>
<pre class="lang-perl prettyprint-override"><code>$SIG{'INT'} = 'exit_gracefully';
sub exit_gracefully {
print "Caught ^C \n";
exit (0);
}
</code></pre>
<p>How do I do the analogue of this in Python?</p>
| 286 | 2009-07-10T22:49:21Z | 1,112,350 | <p>Register your handler with <code>signal.signal</code> like this:</p>
<pre><code>#!/usr/bin/env python
import signal
import sys
def signal_handler(signal, frame):
print('You pressed Ctrl+C!')
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
print('Press Ctrl+C')
signal.pause()
</code></pre>
<p>Code adapted from <a href="http://www.linuxjournal.com/article/3946">here</a>.</p>
<p>More documentation on <code>signal</code> can be found <a href="http://docs.python.org/library/signal.html">here</a>. </p>
| 405 | 2009-07-10T22:52:48Z | [
"python",
"control",
"signals"
] |
How do I capture SIGINT in Python? | 1,112,343 | <p>I'm working on a python script that starts several processes and database connections. Every now and then I want to kill the script with a <kbd>Ctrl</kbd>+<kbd>C</kbd> signal, and I'd like to do some cleanup.</p>
<p>In Perl I'd do this:</p>
<pre class="lang-perl prettyprint-override"><code>$SIG{'INT'} = 'exit_gracefully';
sub exit_gracefully {
print "Caught ^C \n";
exit (0);
}
</code></pre>
<p>How do I do the analogue of this in Python?</p>
| 286 | 2009-07-10T22:49:21Z | 1,112,352 | <p>You can handle Ctrl-C by catching the <code>KeyboardInterrupt</code> exception. You can implement any clean-up code in the exception handler.</p>
| 18 | 2009-07-10T22:52:51Z | [
"python",
"control",
"signals"
] |
How do I capture SIGINT in Python? | 1,112,343 | <p>I'm working on a python script that starts several processes and database connections. Every now and then I want to kill the script with a <kbd>Ctrl</kbd>+<kbd>C</kbd> signal, and I'd like to do some cleanup.</p>
<p>In Perl I'd do this:</p>
<pre class="lang-perl prettyprint-override"><code>$SIG{'INT'} = 'exit_gracefully';
sub exit_gracefully {
print "Caught ^C \n";
exit (0);
}
</code></pre>
<p>How do I do the analogue of this in Python?</p>
| 286 | 2009-07-10T22:49:21Z | 1,112,357 | <p>You can treat it like an exception (KeyboardInterrupt), like any other. Make a new file and run it from your shell with the following contents to see what I mean:</p>
<pre><code>import time, sys
x = 1
while True:
try:
print x
time.sleep(.3)
x += 1
except KeyboardInterrupt:
print "Bye"
sys.exit()
</code></pre>
| 110 | 2009-07-10T22:54:24Z | [
"python",
"control",
"signals"
] |
How do I capture SIGINT in Python? | 1,112,343 | <p>I'm working on a python script that starts several processes and database connections. Every now and then I want to kill the script with a <kbd>Ctrl</kbd>+<kbd>C</kbd> signal, and I'd like to do some cleanup.</p>
<p>In Perl I'd do this:</p>
<pre class="lang-perl prettyprint-override"><code>$SIG{'INT'} = 'exit_gracefully';
sub exit_gracefully {
print "Caught ^C \n";
exit (0);
}
</code></pre>
<p>How do I do the analogue of this in Python?</p>
| 286 | 2009-07-10T22:49:21Z | 1,112,360 | <p>You can use the functions in Python's built-in <a href="http://docs.python.org/library/signal.html" rel="nofollow">signal module</a> to set up signal handlers in python. Specifically the <code>signal.signal(signalnum, handler)</code> function is used to register the <code>handler</code> function for signal <code>signalnum</code>.</p>
| 3 | 2009-07-10T22:54:43Z | [
"python",
"control",
"signals"
] |
How do I capture SIGINT in Python? | 1,112,343 | <p>I'm working on a python script that starts several processes and database connections. Every now and then I want to kill the script with a <kbd>Ctrl</kbd>+<kbd>C</kbd> signal, and I'd like to do some cleanup.</p>
<p>In Perl I'd do this:</p>
<pre class="lang-perl prettyprint-override"><code>$SIG{'INT'} = 'exit_gracefully';
sub exit_gracefully {
print "Caught ^C \n";
exit (0);
}
</code></pre>
<p>How do I do the analogue of this in Python?</p>
| 286 | 2009-07-10T22:49:21Z | 1,112,363 | <p>From Python's <a href="http://docs.python.org/library/signal.html">documentation</a>:</p>
<pre class="lang-py prettyprint-override"><code>import signal
import time
def handler(signum, frame):
print 'Here you go'
signal.signal(signal.SIGINT, handler)
time.sleep(10) # Press Ctrl+c here
</code></pre>
| 14 | 2009-07-10T22:56:19Z | [
"python",
"control",
"signals"
] |
How do I capture SIGINT in Python? | 1,112,343 | <p>I'm working on a python script that starts several processes and database connections. Every now and then I want to kill the script with a <kbd>Ctrl</kbd>+<kbd>C</kbd> signal, and I'd like to do some cleanup.</p>
<p>In Perl I'd do this:</p>
<pre class="lang-perl prettyprint-override"><code>$SIG{'INT'} = 'exit_gracefully';
sub exit_gracefully {
print "Caught ^C \n";
exit (0);
}
</code></pre>
<p>How do I do the analogue of this in Python?</p>
| 286 | 2009-07-10T22:49:21Z | 10,972,804 | <p>And as a context manager:</p>
<pre><code>import signal
class GracefulInterruptHandler(object):
def __init__(self, sig=signal.SIGINT):
self.sig = sig
def __enter__(self):
self.interrupted = False
self.released = False
self.original_handler = signal.getsignal(self.sig)
def handler(signum, frame):
self.release()
self.interrupted = True
signal.signal(self.sig, handler)
return self
def __exit__(self, type, value, tb):
self.release()
def release(self):
if self.released:
return False
signal.signal(self.sig, self.original_handler)
self.released = True
return True
</code></pre>
<p>To use:</p>
<pre><code>with GracefulInterruptHandler() as h:
for i in xrange(1000):
print "..."
time.sleep(1)
if h.interrupted:
print "interrupted!"
time.sleep(2)
break
</code></pre>
<p>Nested handlers:</p>
<pre><code>with GracefulInterruptHandler() as h1:
while True:
print "(1)..."
time.sleep(1)
with GracefulInterruptHandler() as h2:
while True:
print "\t(2)..."
time.sleep(1)
if h2.interrupted:
print "\t(2) interrupted!"
time.sleep(2)
break
if h1.interrupted:
print "(1) interrupted!"
time.sleep(2)
break
</code></pre>
<p>From here: <a href="https://gist.github.com/2907502">https://gist.github.com/2907502</a></p>
| 34 | 2012-06-10T22:23:26Z | [
"python",
"control",
"signals"
] |
How do I capture SIGINT in Python? | 1,112,343 | <p>I'm working on a python script that starts several processes and database connections. Every now and then I want to kill the script with a <kbd>Ctrl</kbd>+<kbd>C</kbd> signal, and I'd like to do some cleanup.</p>
<p>In Perl I'd do this:</p>
<pre class="lang-perl prettyprint-override"><code>$SIG{'INT'} = 'exit_gracefully';
sub exit_gracefully {
print "Caught ^C \n";
exit (0);
}
</code></pre>
<p>How do I do the analogue of this in Python?</p>
| 286 | 2009-07-10T22:49:21Z | 32,025,948 | <h1>Yet Another Snippet</h1>
<p>Referred <code>main</code> as the main function and <code>exit_gracefully</code> as the <kbd>CTRL</kbd> + <kbd>c</kbd> handler</p>
<pre><code>if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
pass
finally:
exit_gracefully()
</code></pre>
| 4 | 2015-08-15T15:00:27Z | [
"python",
"control",
"signals"
] |
How do I capture SIGINT in Python? | 1,112,343 | <p>I'm working on a python script that starts several processes and database connections. Every now and then I want to kill the script with a <kbd>Ctrl</kbd>+<kbd>C</kbd> signal, and I'd like to do some cleanup.</p>
<p>In Perl I'd do this:</p>
<pre class="lang-perl prettyprint-override"><code>$SIG{'INT'} = 'exit_gracefully';
sub exit_gracefully {
print "Caught ^C \n";
exit (0);
}
</code></pre>
<p>How do I do the analogue of this in Python?</p>
| 286 | 2009-07-10T22:49:21Z | 35,798,485 | <p>I adapted the code from @udi to support multiple signals (nothing fancy) :</p>
<pre><code>class GracefulInterruptHandler(object):
def __init__(self, signals=(signal.SIGINT, signal.SIGTERM)):
self.signals = signals
self.original_handlers = {}
def __enter__(self):
self.interrupted = False
self.released = False
for sig in self.signals:
self.original_handlers[sig] = signal.getsignal(sig)
signal.signal(sig, self.handler)
return self
def handler(self, signum, frame):
self.release()
self.interrupted = True
def __exit__(self, type, value, tb):
self.release()
def release(self):
if self.released:
return False
for sig in self.signals:
signal.signal(sig, self.original_handlers[sig])
self.released = True
return True
</code></pre>
<p>This code support the keyboard interrupt call (<code>SIGINT</code>) and the <code>SIGTERM</code> (<code>kill <process></code>)</p>
| 0 | 2016-03-04T14:27:35Z | [
"python",
"control",
"signals"
] |
Perl equivalent of (Python-) list comprehension | 1,112,444 | <p>I'm looking for ways to express this Python snippet in Perl:</p>
<pre><code>data = {"A": None, "B": "yes", "C": None}
key_list = [k for k in data if data[k]]
# in this case the same as filter(lambda k: data[k], data) but let's ignore that
</code></pre>
<p>So looking at it one way, I just want the keys where the values are <em>None</em> or <em>undef</em>. Looking at it another way, what I want is the concise perl equivalent of a <a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions">list comprehension with conditional</a>.</p>
| 13 | 2009-07-10T23:39:07Z | 1,112,455 | <p>Use <a href="http://perldoc.perl.org/functions/grep.html">grep</a>:</p>
<pre><code>#!/usr/bin/perl
use strict;
use warnings;
my %data = ("A" => 0, "B" => "yes", "C" => 0 );
my @keys = grep { $data{$_} } keys %data;
</code></pre>
<p>Grep returns the values from the list on the right-hand side for which the expression in braces evaluates to a true value. As <a href="http://stackoverflow.com/users/26702/telemachus">telemachus</a> points out, you want to make sure you understand true/false values in Perl. <a href="http://stackoverflow.com/questions/1036347/how-do-i-use-boolean-variables-in-perl/">This question</a> has a good overview of truth in Perl. </p>
<p>You'll likely want a look at <a href="http://perldoc.perl.org/functions/map.html">map</a>, which applies an expression in braces to each element of a list and returns the result. An example would be:</p>
<pre><code>my @data = ("A" => 0, "B" => 1, "C" => 0 );
my @modified_data = map { $data{$_} + 1 } @data;
print join ' ', @data, "\n";
print join ' ', @modified_data, "\n";
</code></pre>
| 13 | 2009-07-10T23:42:52Z | [
"python",
"perl",
"list-comprehension"
] |
Perl equivalent of (Python-) list comprehension | 1,112,444 | <p>I'm looking for ways to express this Python snippet in Perl:</p>
<pre><code>data = {"A": None, "B": "yes", "C": None}
key_list = [k for k in data if data[k]]
# in this case the same as filter(lambda k: data[k], data) but let's ignore that
</code></pre>
<p>So looking at it one way, I just want the keys where the values are <em>None</em> or <em>undef</em>. Looking at it another way, what I want is the concise perl equivalent of a <a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions">list comprehension with conditional</a>.</p>
| 13 | 2009-07-10T23:39:07Z | 1,112,462 | <p>I think you want <a href="http://perldoc.perl.org/functions/grep.html"><code>grep</code></a>:</p>
<pre><code>#!/usr/bin/env perl
use strict;
use warnings;
my %data = ( A => undef, B => 'yes', C => undef );
my @keys = grep { defined $data{$_} } keys %data;
print "Key: $_\n" for @keys;
</code></pre>
<p>I also think that I type too slowly, and that I should reload the page before posting answers. By the way, either a value of <code>0</code> or <code>undef</code> can be a good way to handle <em>null</em> values, but make sure you remember which you're using. A false value and and undefined value aren't the same thing in Perl. To clarify: <code>undef</code> returns false in a boolean test, but so does <code>0</code>. If <code>0</code> is a valid value, then you want to explicitly test for definedness, not simply truth. (I mention it because James went for <code>0</code> and I went the other way, and you may or may not know if it matters.)</p>
| 21 | 2009-07-10T23:46:05Z | [
"python",
"perl",
"list-comprehension"
] |
Perl equivalent of (Python-) list comprehension | 1,112,444 | <p>I'm looking for ways to express this Python snippet in Perl:</p>
<pre><code>data = {"A": None, "B": "yes", "C": None}
key_list = [k for k in data if data[k]]
# in this case the same as filter(lambda k: data[k], data) but let's ignore that
</code></pre>
<p>So looking at it one way, I just want the keys where the values are <em>None</em> or <em>undef</em>. Looking at it another way, what I want is the concise perl equivalent of a <a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions">list comprehension with conditional</a>.</p>
| 13 | 2009-07-10T23:39:07Z | 1,113,675 | <p>For variation on the theme have a look at <a href="http://search.cpan.org/dist/autobox/">autobox</a> (see its implementations <a href="http://search.cpan.org/dist/autobox-Core/">autobox::Core</a> and <a href="http://search.cpan.org/dist/Moose-Autobox/">Moose::Autobox</a> )</p>
<pre><code>use autobox::Core;
my %data = ( A => undef, B => 'yes', C => undef );
my $key_list = %data->keys->grep( sub { defined $data{$_} } );
say "Key: $_" for @$key_list;
# => Key: B
</code></pre>
<p><br />
Moose::Autobox comes with key/value 'kv' which makes the code DRYer:</p>
<pre><code>my $key_list = %data->kv->grep( sub{ defined $_->[1] } )->map( sub{ $_->[0] } );
</code></pre>
<p>Here is a more explicit and even longer version of above: </p>
<pre><code>my $key_list = %data->kv
->grep( sub { my ($k, $v) = @$_; defined $v } )
->map( sub { my ($k, $v) = @$_; $k } );
</code></pre>
<p>/I3az/</p>
| 6 | 2009-07-11T13:03:46Z | [
"python",
"perl",
"list-comprehension"
] |
os.path.basename works with URLs, why? | 1,112,545 | <pre><code>>>> os.path.basename('http://example.com/file.txt')
'file.txt'
</code></pre>
<p>.. and I thought <code>os.path.*</code> work only on local paths and not URLs? Note that the above example was run on Windows too .. with similar result.</p>
| 6 | 2009-07-11T00:16:17Z | 1,112,556 | <p>On windows, look at the source code: C:\Python25\Lib\ntpath.py</p>
<pre><code>def basename(p):
"""Returns the final component of a pathname"""
return split(p)[1]
</code></pre>
<p>os.path.split (in the same file) just split "\" (and sth. else)</p>
| 3 | 2009-07-11T00:19:59Z | [
"python",
"url",
"path"
] |
os.path.basename works with URLs, why? | 1,112,545 | <pre><code>>>> os.path.basename('http://example.com/file.txt')
'file.txt'
</code></pre>
<p>.. and I thought <code>os.path.*</code> work only on local paths and not URLs? Note that the above example was run on Windows too .. with similar result.</p>
| 6 | 2009-07-11T00:16:17Z | 1,112,557 | <p>Use the source Luke:</p>
<pre><code>
def basename(p):
"""Returns the final component of a pathname"""
i = p.rfind('/') + 1
return p[i:]
</code></pre>
<p><strong>Edit (response to clarification):</strong></p>
<p>It works for URLs by accident, that's it. Because of that, exploiting its behaviour could be considered code smell by some. </p>
<p>Trying to "fix" it (check if passed path is not url) is also surprisingly difficult</p>
<pre><code>www.google.com/test.php
me@other.place.com/12
./src/bin/doc/goto.c
</code></pre>
<p>are at the same time correct pathnames and URLs (relative), so is the <code>http:/hello.txt</code> (one /, and only on linux, and it's kinda stupid :)). You could "fix" it for absolute urls but relative ones will still work. Handling one special case in differently is a big no no in the python world. </p>
<p>To sum it up: <strong>import this</strong></p>
| 2 | 2009-07-11T00:20:40Z | [
"python",
"url",
"path"
] |
os.path.basename works with URLs, why? | 1,112,545 | <pre><code>>>> os.path.basename('http://example.com/file.txt')
'file.txt'
</code></pre>
<p>.. and I thought <code>os.path.*</code> work only on local paths and not URLs? Note that the above example was run on Windows too .. with similar result.</p>
| 6 | 2009-07-11T00:16:17Z | 1,112,575 | <p>Why? Because it's useful for parsing URLs as well as local file paths. Why not?</p>
| 0 | 2009-07-11T00:29:58Z | [
"python",
"url",
"path"
] |
os.path.basename works with URLs, why? | 1,112,545 | <pre><code>>>> os.path.basename('http://example.com/file.txt')
'file.txt'
</code></pre>
<p>.. and I thought <code>os.path.*</code> work only on local paths and not URLs? Note that the above example was run on Windows too .. with similar result.</p>
| 6 | 2009-07-11T00:16:17Z | 1,112,701 | <p>In practice many functions of <code>os.path</code> are just string manipulation functions (which just <em>happen</em> to be especially handy for path manipulation) -- and since that's innocuous and occasionally handy, while formally speaking "incorrect", I doubt this will change anytime soon -- for more details, use the following simple one-liner at a shell/command prompt:</p>
<pre><code>$ python -c"import sys; import StringIO; x=StringIO.StringIO(); sys.stdout=x; import this; sys.stdout = sys.__stdout__; print x.getvalue().splitlines()[10][9:]"
</code></pre>
| 12 | 2009-07-11T01:45:00Z | [
"python",
"url",
"path"
] |
os.path.basename works with URLs, why? | 1,112,545 | <pre><code>>>> os.path.basename('http://example.com/file.txt')
'file.txt'
</code></pre>
<p>.. and I thought <code>os.path.*</code> work only on local paths and not URLs? Note that the above example was run on Windows too .. with similar result.</p>
| 6 | 2009-07-11T00:16:17Z | 35,088,278 | <p>Forward slash is also an acceptable path delimiter in Windows.</p>
<p>It is merely that the command line does not accept paths that begin with a / because that character is reserved for args switches.</p>
| 1 | 2016-01-29T15:37:15Z | [
"python",
"url",
"path"
] |
Import python package from local directory into interpreter | 1,112,618 | <p>I'm developing/testing a package in my local directory. I want to import it in the interpreter (v2.5), but sys.path does not include the current directory. Right now I type in <code>sys.path.insert(0,'.')</code>. Is there a better way? </p>
<p>Also, </p>
<pre><code>from . import mypackage
</code></pre>
<p>fails with this error:</p>
<pre><code>ValueError: Attempted relative import in non-package
</code></pre>
| 36 | 2009-07-11T00:57:52Z | 1,112,623 | <p>Using <code>sys.path</code> should include current directory already.</p>
<p>Try:</p>
<pre><code>import .
</code></pre>
<p>or:</p>
<pre><code>from . import sth
</code></pre>
<p>however it may be not a good practice, so why not just use:</p>
<pre><code>import mypackage
</code></pre>
| 1 | 2009-07-11T01:00:51Z | [
"python"
] |
Import python package from local directory into interpreter | 1,112,618 | <p>I'm developing/testing a package in my local directory. I want to import it in the interpreter (v2.5), but sys.path does not include the current directory. Right now I type in <code>sys.path.insert(0,'.')</code>. Is there a better way? </p>
<p>Also, </p>
<pre><code>from . import mypackage
</code></pre>
<p>fails with this error:</p>
<pre><code>ValueError: Attempted relative import in non-package
</code></pre>
| 36 | 2009-07-11T00:57:52Z | 1,112,654 | <p>See the documentation for sys.path:</p>
<p><a href="http://docs.python.org/library/sys.html#sys.path">http://docs.python.org/library/sys.html#sys.path</a></p>
<p>To quote:</p>
<blockquote>
<p>If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first.</p>
</blockquote>
<p>So, there's no need to monkey with sys.path if you're starting the python interpreter from the directory containing your module.</p>
<p>Also, to import your package, just do:</p>
<pre><code>import mypackage
</code></pre>
<p>Since the directory containing the package is already in sys.path, it should work fine.</p>
| 9 | 2009-07-11T01:23:31Z | [
"python"
] |
Import python package from local directory into interpreter | 1,112,618 | <p>I'm developing/testing a package in my local directory. I want to import it in the interpreter (v2.5), but sys.path does not include the current directory. Right now I type in <code>sys.path.insert(0,'.')</code>. Is there a better way? </p>
<p>Also, </p>
<pre><code>from . import mypackage
</code></pre>
<p>fails with this error:</p>
<pre><code>ValueError: Attempted relative import in non-package
</code></pre>
| 36 | 2009-07-11T00:57:52Z | 1,112,661 | <p>You can use relative imports only from in a module that was in turn imported as part of a package -- your script or interactive interpreter wasn't, so of course <code>from . import</code> (which means "import from the same package I got imported from") doesn't work. <code>import mypackage</code> will be fine once you ensure the parent directory of <code>mypackage</code> is in <code>sys.path</code> (how you managed to get your current directory <em>away</em> from <code>sys.path</code> I don't know -- do you have something strange in site.py, or...?)</p>
<p>To get your current directory back into <code>sys.path</code> there is in fact no better way than putting it there;-).</p>
| 20 | 2009-07-11T01:24:47Z | [
"python"
] |
Import python package from local directory into interpreter | 1,112,618 | <p>I'm developing/testing a package in my local directory. I want to import it in the interpreter (v2.5), but sys.path does not include the current directory. Right now I type in <code>sys.path.insert(0,'.')</code>. Is there a better way? </p>
<p>Also, </p>
<pre><code>from . import mypackage
</code></pre>
<p>fails with this error:</p>
<pre><code>ValueError: Attempted relative import in non-package
</code></pre>
| 36 | 2009-07-11T00:57:52Z | 2,204,578 | <p>A simple way to make it work is to run your script from the parent directory using python's <code>-m</code> flag, e.g. <code>python -m packagename.scriptname</code>. Obviously in this situation you need an <code>__init__.py</code> file to turn your directory into a package.</p>
| 3 | 2010-02-05T01:52:44Z | [
"python"
] |
Import python package from local directory into interpreter | 1,112,618 | <p>I'm developing/testing a package in my local directory. I want to import it in the interpreter (v2.5), but sys.path does not include the current directory. Right now I type in <code>sys.path.insert(0,'.')</code>. Is there a better way? </p>
<p>Also, </p>
<pre><code>from . import mypackage
</code></pre>
<p>fails with this error:</p>
<pre><code>ValueError: Attempted relative import in non-package
</code></pre>
| 36 | 2009-07-11T00:57:52Z | 22,091,228 | <p>Keep it simple:</p>
<pre><code> try:
from . import mymodule # "myapp" case
except:
import mymodule # "__main__" case
</code></pre>
| 2 | 2014-02-28T09:33:52Z | [
"python"
] |
Where to put message queue consumer in Django? | 1,112,645 | <p>I'm using Carrot for a message queue in a Django project and followed <a href="http://github.com/ask/carrot/tree/master" rel="nofollow">the tutorial</a>, and it works fine. But the example runs in the console, and I'm wondering how I apply this in Django. The publisher class I'm calling from one of my models in models.py, so that's OK. But I have no idea where to put the consumer class. </p>
<p>Since it just sits there with .wait(), I don't know at what point or where I need to instantiate it so that it's always running and listening for messages!</p>
<p>Thanks!</p>
| 1 | 2009-07-11T01:15:39Z | 1,112,764 | <p>The consumer is simply a long running script in the example you cite from the tutorial. It pops a message from the queue, does something, then calls wait and essentially goes to sleep until another message comes in. </p>
<p>This script could just be running at the console under your account or configured as a unix daemon or a win32 service. In production, you'd want to make sure that if it dies, it can be restarted, etc (a daemon or service would be more appropriate here). </p>
<p>Or you could take out the wait call and run it under the windows scheduler or as a cron job. So it processes the queue every n minutes or something and exits. It really depends on your application requirements, how fast your queue is filling up, etc.</p>
<p>Does that make sense or have I totally missed what you were asking? </p>
| 5 | 2009-07-11T02:16:28Z | [
"python",
"django",
"message-queue",
"rabbitmq",
"amqp"
] |
Where to put message queue consumer in Django? | 1,112,645 | <p>I'm using Carrot for a message queue in a Django project and followed <a href="http://github.com/ask/carrot/tree/master" rel="nofollow">the tutorial</a>, and it works fine. But the example runs in the console, and I'm wondering how I apply this in Django. The publisher class I'm calling from one of my models in models.py, so that's OK. But I have no idea where to put the consumer class. </p>
<p>Since it just sits there with .wait(), I don't know at what point or where I need to instantiate it so that it's always running and listening for messages!</p>
<p>Thanks!</p>
| 1 | 2009-07-11T01:15:39Z | 1,160,225 | <p>If what you are doing is processing tasks, please check out celery: <a href="http://github.com/ask/celery/" rel="nofollow">http://github.com/ask/celery/</a></p>
| 0 | 2009-07-21T16:17:45Z | [
"python",
"django",
"message-queue",
"rabbitmq",
"amqp"
] |
Safety of Python 'eval' For List Deserialization | 1,112,665 | <p>Are there any security exploits that could occur in this scenario:</p>
<pre><code>eval(repr(unsanitized_user_input), {"__builtins__": None}, {"True":True, "False":False})
</code></pre>
<p>where <code>unsanitized_user_input</code> is a str object. The string is user-generated and could be nasty. Assuming our web framework hasn't failed us, it's a real honest-to-god str instance from the Python builtins.</p>
<p>If this is dangerous, can we do anything to the input to make it safe?</p>
<p>We definitely <em>don't</em> want to execute anything contained in the string.</p>
<p>See also:</p>
<ul>
<li><a href="http://blog.thetonk.com/archives/dont-be-lazy-dont-use-eval/comment-page-2#comments" rel="nofollow">Funny blog post about eval safety</a></li>
<li><a href="http://stackoverflow.com/questions/661084/security-of-pythons-eval-on-untrusted-strings">Previous Question</a></li>
<li><a href="http://blog.metaoptimize.com/2009/03/22/fast-deserialization-in-python/" rel="nofollow">Blog: Fast deserialization in Python</a></li>
</ul>
<p>The larger context which is (I believe) not essential to the question is that we have thousands of these:</p>
<pre><code>repr([unsanitized_user_input_1,
unsanitized_user_input_2,
unsanitized_user_input_3,
unsanitized_user_input_4,
...])
</code></pre>
<p>in some cases nested:</p>
<pre><code>repr([[unsanitized_user_input_1,
unsanitized_user_input_2],
[unsanitized_user_input_3,
unsanitized_user_input_4],
...])
</code></pre>
<p>which are themselves converted to strings with <code>repr()</code>, put in persistent storage, and eventually read back into memory with eval.</p>
<p>Eval deserialized the strings from persistent storage much faster than pickle and simplejson. The interpreter is Python 2.5 so json and ast aren't available. Due to the App Engine environment no C modules are allowed and cPickle is not allowed.</p>
| 6 | 2009-07-11T01:25:19Z | 1,112,684 | <p>It is indeed dangerous and the safest alternative is <code>ast.literal_eval</code> (see the <a href="http://docs.python.org/library/ast.html#module-ast" rel="nofollow">ast</a> module in the standard library). You can of course build and alter an <code>ast</code> to provide e.g. evaluation of variables and the like before you eval the resulting AST (when it's down to literals).</p>
<p>The possible exploit of <code>eval</code> starts with any object it can get its hands on (say <code>True</code> here) and going via .__class_ to its type object, etc. up to <code>object</code>, then gets its subclasses... basically it can get to ANY object type and wreck havoc. I can be more specific but I'd rather not do it in a public forum (the exploit is well known, but considering how many people still ignore it, revealing it to wannabe script kiddies could make things worse... just avoid <code>eval</code> on unsanitized user input and live happily ever after!-).</p>
| 18 | 2009-07-11T01:33:02Z | [
"python",
"google-app-engine",
"eval"
] |
Safety of Python 'eval' For List Deserialization | 1,112,665 | <p>Are there any security exploits that could occur in this scenario:</p>
<pre><code>eval(repr(unsanitized_user_input), {"__builtins__": None}, {"True":True, "False":False})
</code></pre>
<p>where <code>unsanitized_user_input</code> is a str object. The string is user-generated and could be nasty. Assuming our web framework hasn't failed us, it's a real honest-to-god str instance from the Python builtins.</p>
<p>If this is dangerous, can we do anything to the input to make it safe?</p>
<p>We definitely <em>don't</em> want to execute anything contained in the string.</p>
<p>See also:</p>
<ul>
<li><a href="http://blog.thetonk.com/archives/dont-be-lazy-dont-use-eval/comment-page-2#comments" rel="nofollow">Funny blog post about eval safety</a></li>
<li><a href="http://stackoverflow.com/questions/661084/security-of-pythons-eval-on-untrusted-strings">Previous Question</a></li>
<li><a href="http://blog.metaoptimize.com/2009/03/22/fast-deserialization-in-python/" rel="nofollow">Blog: Fast deserialization in Python</a></li>
</ul>
<p>The larger context which is (I believe) not essential to the question is that we have thousands of these:</p>
<pre><code>repr([unsanitized_user_input_1,
unsanitized_user_input_2,
unsanitized_user_input_3,
unsanitized_user_input_4,
...])
</code></pre>
<p>in some cases nested:</p>
<pre><code>repr([[unsanitized_user_input_1,
unsanitized_user_input_2],
[unsanitized_user_input_3,
unsanitized_user_input_4],
...])
</code></pre>
<p>which are themselves converted to strings with <code>repr()</code>, put in persistent storage, and eventually read back into memory with eval.</p>
<p>Eval deserialized the strings from persistent storage much faster than pickle and simplejson. The interpreter is Python 2.5 so json and ast aren't available. Due to the App Engine environment no C modules are allowed and cPickle is not allowed.</p>
| 6 | 2009-07-11T01:25:19Z | 1,112,692 | <p>Generally, you should never allow <strong>anyone</strong> to post code. </p>
<p>So called "paid professional programmers" have a hard-enough time writing code that actually works.</p>
<p>Accepting code from the anonymous public -- without benefit of formal QA -- is the worst of all possible scenarios.</p>
<p>Professional programmers -- without good, solid formal QA -- will make a hash of almost any web site. Indeed, I'm reverse engineering some unbelievably bad code from paid professionals. </p>
<p>The idea of allowing a non-professional -- unencumbered by QA -- to post code is truly terrifying.</p>
| 3 | 2009-07-11T01:38:39Z | [
"python",
"google-app-engine",
"eval"
] |
Safety of Python 'eval' For List Deserialization | 1,112,665 | <p>Are there any security exploits that could occur in this scenario:</p>
<pre><code>eval(repr(unsanitized_user_input), {"__builtins__": None}, {"True":True, "False":False})
</code></pre>
<p>where <code>unsanitized_user_input</code> is a str object. The string is user-generated and could be nasty. Assuming our web framework hasn't failed us, it's a real honest-to-god str instance from the Python builtins.</p>
<p>If this is dangerous, can we do anything to the input to make it safe?</p>
<p>We definitely <em>don't</em> want to execute anything contained in the string.</p>
<p>See also:</p>
<ul>
<li><a href="http://blog.thetonk.com/archives/dont-be-lazy-dont-use-eval/comment-page-2#comments" rel="nofollow">Funny blog post about eval safety</a></li>
<li><a href="http://stackoverflow.com/questions/661084/security-of-pythons-eval-on-untrusted-strings">Previous Question</a></li>
<li><a href="http://blog.metaoptimize.com/2009/03/22/fast-deserialization-in-python/" rel="nofollow">Blog: Fast deserialization in Python</a></li>
</ul>
<p>The larger context which is (I believe) not essential to the question is that we have thousands of these:</p>
<pre><code>repr([unsanitized_user_input_1,
unsanitized_user_input_2,
unsanitized_user_input_3,
unsanitized_user_input_4,
...])
</code></pre>
<p>in some cases nested:</p>
<pre><code>repr([[unsanitized_user_input_1,
unsanitized_user_input_2],
[unsanitized_user_input_3,
unsanitized_user_input_4],
...])
</code></pre>
<p>which are themselves converted to strings with <code>repr()</code>, put in persistent storage, and eventually read back into memory with eval.</p>
<p>Eval deserialized the strings from persistent storage much faster than pickle and simplejson. The interpreter is Python 2.5 so json and ast aren't available. Due to the App Engine environment no C modules are allowed and cPickle is not allowed.</p>
| 6 | 2009-07-11T01:25:19Z | 1,112,699 | <p>If you can prove beyond doubt that <code>unsanitized_user_input</code> is a <code>str</code> instance from the Python built-ins with nothing tampered, then this is always safe. In fact, it'll be safe even without all those extra arguments since <code>eval(repr(astr)) = astr</code> for all such string objects. You put in a string, you get back out a string. All you did was escape and unescape it.</p>
<p>This all leads me to think that <code>eval(repr(x))</code> isn't what you want--no code will ever be executed unless someone gives you an <code>unsanitized_user_input</code> object that looks like a string but isn't, but that's a different question--unless you're trying to copy a string instance in the slowest way possible :D.</p>
| 8 | 2009-07-11T01:42:00Z | [
"python",
"google-app-engine",
"eval"
] |
Safety of Python 'eval' For List Deserialization | 1,112,665 | <p>Are there any security exploits that could occur in this scenario:</p>
<pre><code>eval(repr(unsanitized_user_input), {"__builtins__": None}, {"True":True, "False":False})
</code></pre>
<p>where <code>unsanitized_user_input</code> is a str object. The string is user-generated and could be nasty. Assuming our web framework hasn't failed us, it's a real honest-to-god str instance from the Python builtins.</p>
<p>If this is dangerous, can we do anything to the input to make it safe?</p>
<p>We definitely <em>don't</em> want to execute anything contained in the string.</p>
<p>See also:</p>
<ul>
<li><a href="http://blog.thetonk.com/archives/dont-be-lazy-dont-use-eval/comment-page-2#comments" rel="nofollow">Funny blog post about eval safety</a></li>
<li><a href="http://stackoverflow.com/questions/661084/security-of-pythons-eval-on-untrusted-strings">Previous Question</a></li>
<li><a href="http://blog.metaoptimize.com/2009/03/22/fast-deserialization-in-python/" rel="nofollow">Blog: Fast deserialization in Python</a></li>
</ul>
<p>The larger context which is (I believe) not essential to the question is that we have thousands of these:</p>
<pre><code>repr([unsanitized_user_input_1,
unsanitized_user_input_2,
unsanitized_user_input_3,
unsanitized_user_input_4,
...])
</code></pre>
<p>in some cases nested:</p>
<pre><code>repr([[unsanitized_user_input_1,
unsanitized_user_input_2],
[unsanitized_user_input_3,
unsanitized_user_input_4],
...])
</code></pre>
<p>which are themselves converted to strings with <code>repr()</code>, put in persistent storage, and eventually read back into memory with eval.</p>
<p>Eval deserialized the strings from persistent storage much faster than pickle and simplejson. The interpreter is Python 2.5 so json and ast aren't available. Due to the App Engine environment no C modules are allowed and cPickle is not allowed.</p>
| 6 | 2009-07-11T01:25:19Z | 1,113,480 | <p>With everything as you describe, it is technically safe to eval repred strings, however, I'd avoid doing it anyway as it's asking for trouble:</p>
<ul>
<li><p>There could be some weird corner-case where your assumption that only repred strings are stored (eg. a bug / different pathway into the storage that doesn't repr instantly becmes a code injection exploit where it might otherwise be unexploitable)</p></li>
<li><p>Even if everything is OK now, assumptions might change at some point, and unsanitised data may get stored in that field by someone unaware of the eval code.</p></li>
<li><p>Your code may get reused (or worse, copy+pasted) into a situation you didn't consider.</p></li>
</ul>
<p>As <a href="http://stackoverflow.com/questions/1112665/safety-of-python-eval/1112684#1112684">Alex Martelli</a> pointed out, in python2.6 and higher, there is ast.literal_eval which will safely handle both strings and other simple datatypes like tuples. This is probably the safest and most complete solution.</p>
<p>Another possibility however is to use the <code>string-escape</code> codec. This is much faster than eval (about 10 times according to timeit), available in earlier versions than literal_eval, and should do what you want:</p>
<pre><code>>>> s = 'he\nllo\' wo"rld\0\x03\r\n\tabc'
>>> repr(s)[1:-1].decode('string-escape') == s
True
</code></pre>
<p>(The [1:-1] is to strip the outer quotes repr adds.)</p>
| 4 | 2009-07-11T10:57:19Z | [
"python",
"google-app-engine",
"eval"
] |
Safety of Python 'eval' For List Deserialization | 1,112,665 | <p>Are there any security exploits that could occur in this scenario:</p>
<pre><code>eval(repr(unsanitized_user_input), {"__builtins__": None}, {"True":True, "False":False})
</code></pre>
<p>where <code>unsanitized_user_input</code> is a str object. The string is user-generated and could be nasty. Assuming our web framework hasn't failed us, it's a real honest-to-god str instance from the Python builtins.</p>
<p>If this is dangerous, can we do anything to the input to make it safe?</p>
<p>We definitely <em>don't</em> want to execute anything contained in the string.</p>
<p>See also:</p>
<ul>
<li><a href="http://blog.thetonk.com/archives/dont-be-lazy-dont-use-eval/comment-page-2#comments" rel="nofollow">Funny blog post about eval safety</a></li>
<li><a href="http://stackoverflow.com/questions/661084/security-of-pythons-eval-on-untrusted-strings">Previous Question</a></li>
<li><a href="http://blog.metaoptimize.com/2009/03/22/fast-deserialization-in-python/" rel="nofollow">Blog: Fast deserialization in Python</a></li>
</ul>
<p>The larger context which is (I believe) not essential to the question is that we have thousands of these:</p>
<pre><code>repr([unsanitized_user_input_1,
unsanitized_user_input_2,
unsanitized_user_input_3,
unsanitized_user_input_4,
...])
</code></pre>
<p>in some cases nested:</p>
<pre><code>repr([[unsanitized_user_input_1,
unsanitized_user_input_2],
[unsanitized_user_input_3,
unsanitized_user_input_4],
...])
</code></pre>
<p>which are themselves converted to strings with <code>repr()</code>, put in persistent storage, and eventually read back into memory with eval.</p>
<p>Eval deserialized the strings from persistent storage much faster than pickle and simplejson. The interpreter is Python 2.5 so json and ast aren't available. Due to the App Engine environment no C modules are allowed and cPickle is not allowed.</p>
| 6 | 2009-07-11T01:25:19Z | 1,114,008 | <blockquote>
<pre><code>repr([unsanitized_user_input_1,
unsanitized_user_input_2,
...
</code></pre>
<p>... <code>unsanitized_user_input</code> is a <code>str</code> object</p>
</blockquote>
<p>You shouldn't have to serialise strings to store them in a database..</p>
<p>If these are all strings, as you mentioned - why can't you just store the strings in a <code>db.StringListProperty</code>?</p>
<p>The nested entries might be a bit more complicated, but why is this the case? When you have to resort to eval to get data from the database, you're probably doing something wrong..</p>
<p>Couldn't you store each <code>unsanitized_user_input_x</code> as it's own <code>db.StringProperty</code> row, and have group them by an reference field?</p>
<p>Either of those may not be applicable, since I've no idea what you're trying to achieve, but my point is - can you not structure the data in a way you where don't have to rely on <code>eval</code> (and also rely on it not being a security issue)?</p>
| 1 | 2009-07-11T16:03:55Z | [
"python",
"google-app-engine",
"eval"
] |
Python Win32 Extensions not Available? | 1,112,784 | <p>I am trying to get a post-commit.bat script running on a Windows Vista Ultimate machine for Trac. </p>
<p>I have installed Trac and its working fine - but when I run this script I get the error:</p>
<p><strong>"The Python Win32 extensions for NT (service, event, logging) appear not to be Available."</strong></p>
<p>Anyone know why this would occur ?</p>
| 2 | 2009-07-11T02:38:20Z | 1,112,794 | <p>have u installed the <a href="http://sourceforge.net/projects/pywin32/files/">Python Win32 module</a>?</p>
| 5 | 2009-07-11T02:44:44Z | [
"python",
"trac"
] |
List of installed fonts OS X / C | 1,113,040 | <p>I'm trying to programatically get a list of installed fonts in C or Python. I need to be able to do this on OS X, does anyone know how?</p>
| 4 | 2009-07-11T05:45:38Z | 1,113,055 | <p>Do you want to <em>write</em> a program to do it, or do you want to <em>use</em> a program to do it? There are many programs that list fonts, xlsfonts comes to mind.</p>
| 1 | 2009-07-11T05:54:14Z | [
"python",
"c",
"osx",
"fonts"
] |
List of installed fonts OS X / C | 1,113,040 | <p>I'm trying to programatically get a list of installed fonts in C or Python. I need to be able to do this on OS X, does anyone know how?</p>
| 4 | 2009-07-11T05:45:38Z | 1,113,072 | <p>Not exactly C, but in Objective-C, you can easily get a list of installed fonts via the Cocoa framework:</p>
<pre><code>// This returns an array of NSStrings that gives you each font installed on the system
NSArray *fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
// Does the same as the above, but includes each available font style (e.g. you get
// Verdana, "Verdana-Bold", "Verdana-BoldItalic", and "Verdana-Italic" for Verdana).
NSArray *fonts = [[NSFontManager sharedFontManager] availableFonts];
</code></pre>
<p>You can access the Cocoa framework from Python via <a href="http://pyobjc.sourceforge.net/" rel="nofollow">PyObjC</a>, if you want.</p>
<p>In C, I think you can do something similar in Carbon with the ATSUI library, although I'm not entirely sure how to do this, since I haven't worked with fonts in Carbon before. Nevertheless, from browsing the ATSUI docs, I'd recommend looking into the <a href="http://developer.apple.com/documentation/Carbon/Reference/ATSUI%5FReference/Reference/reference.html#//apple%5Fref/c/func/ATSUGetFontIDs" rel="nofollow"><code>ATSUGetFontIDs</code></a> and the <a href="http://developer.apple.com/documentation/Carbon/Reference/ATSUI%5FReference/Reference/reference.html#//apple%5Fref/c/func/ATSUGetIndFontName" rel="nofollow"><code>ATSUGetIndFontName</code></a> functions. Here's a link to the <a href="http://developer.apple.com/documentation/Carbon/Reference/ATSUI%5FReference/Reference/reference.html" rel="nofollow">ATSUI documentation</a> for more information.</p>
| 3 | 2009-07-11T06:12:55Z | [
"python",
"c",
"osx",
"fonts"
] |
List of installed fonts OS X / C | 1,113,040 | <p>I'm trying to programatically get a list of installed fonts in C or Python. I need to be able to do this on OS X, does anyone know how?</p>
| 4 | 2009-07-11T05:45:38Z | 1,113,078 | <p>You can get an array of available fonts using Objective-C and Cocoa. The method you are looking for is <a href="http://devworld.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSFontManager%5FClass/Reference/Reference.html#//apple%5Fref/occ/instm/NSFontManager/availableFonts" rel="nofollow"><code>NSFontManager</code>'s <code>availableFonts</code></a>.</p>
<p>I don't believe there is a standard way to determine what the system fonts are using pure C. However, you can freely mix C and Objective-C, so it really shouldn't be to hard to use this method to do what you'd like.</p>
| 0 | 2009-07-11T06:18:03Z | [
"python",
"c",
"osx",
"fonts"
] |
List of installed fonts OS X / C | 1,113,040 | <p>I'm trying to programatically get a list of installed fonts in C or Python. I need to be able to do this on OS X, does anyone know how?</p>
| 4 | 2009-07-11T05:45:38Z | 1,113,084 | <p>Why not use the Terminal?</p>
<p><strong>System Fonts:</strong></p>
<pre><code>ls -R /System/Library/Fonts | grep ttf
</code></pre>
<p><strong>User Fonts:</strong></p>
<pre><code>ls -R ~/Library/Fonts | grep ttf
</code></pre>
<p><strong>Mac OS X Default fonts:</strong></p>
<pre><code>ls -R /Library/Fonts | grep ttf
</code></pre>
<p>If you need to run it inside your C program:</p>
<pre><code>void main()
{
printf("System fonts: ");
execl("/bin/ls","ls -R /System/Library/Fonts | grep ttf", "-l",0);
printf("Mac OS X Default fonts: ");
execl("/bin/ls","ls -R /Library/Fonts | grep ttf", "-l",0);
printf("User fonts: ");
execl("/bin/ls","ls -R ~/Library/Fonts | grep ttf", "-l",0);
}
</code></pre>
| 3 | 2009-07-11T06:25:30Z | [
"python",
"c",
"osx",
"fonts"
] |
List of installed fonts OS X / C | 1,113,040 | <p>I'm trying to programatically get a list of installed fonts in C or Python. I need to be able to do this on OS X, does anyone know how?</p>
| 4 | 2009-07-11T05:45:38Z | 1,113,150 | <p>Python with PyObjC installed (which is the case for Mac OS X 10.5+, so this code will work without having to install anything):</p>
<pre><code>import Cocoa
manager = Cocoa.NSFontManager.sharedFontManager()
font_families = list(manager.availableFontFamilies())
</code></pre>
<p>(based on <a href="#1113072">htw's answer</a>)</p>
| 10 | 2009-07-11T07:23:45Z | [
"python",
"c",
"osx",
"fonts"
] |
How to keep an App Engine/Java app running with deaf requests from a Java/Python web cron? | 1,113,066 | <ol>
<li>App Engine allows you 30 seconds to load your application</li>
<li>My application takes around 30 seconds - sometimes more, sometimes less. I don't know how to fix this.</li>
<li>If the app is idle (does not receive a request for a while), it needs to be re-loaded. </li>
</ol>
<p>So, to avoid the app needing to be reloaded, I want to simulate user activity by pinging the app every so often.</p>
<p>But there's a catch . . .</p>
<p>If I ping the app and it has already been unloaded by App Engine, my web request will be the first request to the app and the app will try to reload. This could take longer than 30 seconds and exceed the loading time limit.</p>
<p>So my idea is to ping the app but not wait for the response. I have simulated this manually by going to the site from a browser, making the request and immediately closing the browser - it seems to keep the app alive.</p>
<p>Any suggestions for a good way to do this in a Python or Java web cron (I'm assuming a Python solution will be simpler)?</p>
| 3 | 2009-07-11T06:02:43Z | 1,113,110 | <p>I think what you want is just:</p>
<pre><code>import httplib
hcon = httplib.HTTPConnection("foo.appspot.com")
hcon.request("GET", "/someURL")
hcon.close()
</code></pre>
| 1 | 2009-07-11T06:44:31Z | [
"java",
"python",
"google-app-engine",
"httpwebrequest",
"keep-alive"
] |
How to keep an App Engine/Java app running with deaf requests from a Java/Python web cron? | 1,113,066 | <ol>
<li>App Engine allows you 30 seconds to load your application</li>
<li>My application takes around 30 seconds - sometimes more, sometimes less. I don't know how to fix this.</li>
<li>If the app is idle (does not receive a request for a while), it needs to be re-loaded. </li>
</ol>
<p>So, to avoid the app needing to be reloaded, I want to simulate user activity by pinging the app every so often.</p>
<p>But there's a catch . . .</p>
<p>If I ping the app and it has already been unloaded by App Engine, my web request will be the first request to the app and the app will try to reload. This could take longer than 30 seconds and exceed the loading time limit.</p>
<p>So my idea is to ping the app but not wait for the response. I have simulated this manually by going to the site from a browser, making the request and immediately closing the browser - it seems to keep the app alive.</p>
<p>Any suggestions for a good way to do this in a Python or Java web cron (I'm assuming a Python solution will be simpler)?</p>
| 3 | 2009-07-11T06:02:43Z | 1,113,300 | <p>the simplest Java http pinger:</p>
<pre><code>URLConnection hcon = new URL("http://www.google.com").openConnection();
hcon.connect();
hcon.getInputStream().read();
</code></pre>
| 1 | 2009-07-11T09:12:07Z | [
"java",
"python",
"google-app-engine",
"httpwebrequest",
"keep-alive"
] |
How to keep an App Engine/Java app running with deaf requests from a Java/Python web cron? | 1,113,066 | <ol>
<li>App Engine allows you 30 seconds to load your application</li>
<li>My application takes around 30 seconds - sometimes more, sometimes less. I don't know how to fix this.</li>
<li>If the app is idle (does not receive a request for a while), it needs to be re-loaded. </li>
</ol>
<p>So, to avoid the app needing to be reloaded, I want to simulate user activity by pinging the app every so often.</p>
<p>But there's a catch . . .</p>
<p>If I ping the app and it has already been unloaded by App Engine, my web request will be the first request to the app and the app will try to reload. This could take longer than 30 seconds and exceed the loading time limit.</p>
<p>So my idea is to ping the app but not wait for the response. I have simulated this manually by going to the site from a browser, making the request and immediately closing the browser - it seems to keep the app alive.</p>
<p>Any suggestions for a good way to do this in a Python or Java web cron (I'm assuming a Python solution will be simpler)?</p>
| 3 | 2009-07-11T06:02:43Z | 1,113,400 | <p>It would probably be easier use the <a href="http://code.google.com/appengine/docs/java/config/cron.html" rel="nofollow">cron built in to App Engine</a> to keep your application alive.</p>
| 1 | 2009-07-11T10:15:49Z | [
"java",
"python",
"google-app-engine",
"httpwebrequest",
"keep-alive"
] |
How to keep an App Engine/Java app running with deaf requests from a Java/Python web cron? | 1,113,066 | <ol>
<li>App Engine allows you 30 seconds to load your application</li>
<li>My application takes around 30 seconds - sometimes more, sometimes less. I don't know how to fix this.</li>
<li>If the app is idle (does not receive a request for a while), it needs to be re-loaded. </li>
</ol>
<p>So, to avoid the app needing to be reloaded, I want to simulate user activity by pinging the app every so often.</p>
<p>But there's a catch . . .</p>
<p>If I ping the app and it has already been unloaded by App Engine, my web request will be the first request to the app and the app will try to reload. This could take longer than 30 seconds and exceed the loading time limit.</p>
<p>So my idea is to ping the app but not wait for the response. I have simulated this manually by going to the site from a browser, making the request and immediately closing the browser - it seems to keep the app alive.</p>
<p>Any suggestions for a good way to do this in a Python or Java web cron (I'm assuming a Python solution will be simpler)?</p>
| 3 | 2009-07-11T06:02:43Z | 4,707,002 | <p>App engine also has a new PAY feature where you can have it "always-on". Costs about $0.30 USD cents a day. Just go into your billing settings and enable it if you don't mind paying for the feature. I believe it guarantees you at least 3 instances always running.</p>
<p>(I didn't realize hitting a /ping url which caused an instance to spin up would cause it to exceed the 30 sec limit!)</p>
| 1 | 2011-01-16T17:52:55Z | [
"java",
"python",
"google-app-engine",
"httpwebrequest",
"keep-alive"
] |
Pure Python Tidy-like application/library | 1,113,421 | <p>I'm looking for a pure Python library which works like Tidy. Please kindly advise. Thank you.</p>
| 4 | 2009-07-11T10:27:46Z | 1,113,488 | <p>Use <a href="http://effbot.org/zone/element-tidylib.htm" rel="nofollow">ElementTree Tidy HTML Tree Builder</a>.</p>
| 1 | 2009-07-11T10:59:59Z | [
"python",
"html",
"xml",
"xhtml",
"tidy"
] |
How can I match two songs? | 1,113,449 | <p>What is the best way to match two songs? IE. Have a song stored in the database in whatever format is best and then play another song and match the two together?<br />
In Python ideally please.</p>
<p>Thanks!</p>
| 2 | 2009-07-11T10:40:33Z | 1,113,483 | <p>I think you might be looking for something called <a href="http://en.wikipedia.org/wiki/Acoustic%5Ffingerprint" rel="nofollow">Acoustic Fingerprinting</a>. It generates a brief description of a song which can be compared against other songs. This allows the matching of audio which is similiar but not exactly the same.</p>
| 4 | 2009-07-11T10:58:59Z | [
"python",
"algorithm",
"music",
"matching"
] |
How can I match two songs? | 1,113,449 | <p>What is the best way to match two songs? IE. Have a song stored in the database in whatever format is best and then play another song and match the two together?<br />
In Python ideally please.</p>
<p>Thanks!</p>
| 2 | 2009-07-11T10:40:33Z | 1,113,486 | <p>You can download the tarball from </p>
<p><a href="http://rudd-o.com/new-projects/python-audioprocessing" rel="nofollow">http://rudd-o.com/new-projects/python-audioprocessing</a></p>
<p>They say their goal is to identify the same songs released in different albums. Basically to avoid storing two-copies considered separately. I think the algorithm will help you.</p>
| 3 | 2009-07-11T10:59:49Z | [
"python",
"algorithm",
"music",
"matching"
] |
How can I match two songs? | 1,113,449 | <p>What is the best way to match two songs? IE. Have a song stored in the database in whatever format is best and then play another song and match the two together?<br />
In Python ideally please.</p>
<p>Thanks!</p>
| 2 | 2009-07-11T10:40:33Z | 1,114,109 | <p>By 'matching' do you mean finding tracks that are identical - or do you mean 'beat matching' - to dovetail two songs together so that the beats align to give you a seamless song transition. If you are talking about the latter then check out remix. A python library for automatic remixing: <a href="http://code.google.com/p/echo-nest-remix/" rel="nofollow">http://code.google.com/p/echo-nest-remix/</a></p>
| 1 | 2009-07-11T16:49:36Z | [
"python",
"algorithm",
"music",
"matching"
] |
Where to store secret keys and password in Python | 1,113,479 | <p>I have a small Python program, which uses a Google Maps API secret key. I'm getting ready to check-in my code, and I don't want to include the secret key in SVN. </p>
<p>In the canonical PHP app you put secret keys, database passwords, and other app specific config in LocalSettings.php. Is there a similar file/location which Python programmers expect to find and modify?</p>
| 3 | 2009-07-11T10:57:06Z | 1,113,496 | <p>No, there's no standard location - on Windows, it's usually in the directory <code>os.path.join(os.environ['APPDATA'], 'appname')</code> and on Unix it's usually <code>os.path.join(os.environ['HOME'], '.appname')</code>.</p>
| 3 | 2009-07-11T11:04:23Z | [
"python",
"configuration",
"google-maps"
] |
Where to store secret keys and password in Python | 1,113,479 | <p>I have a small Python program, which uses a Google Maps API secret key. I'm getting ready to check-in my code, and I don't want to include the secret key in SVN. </p>
<p>In the canonical PHP app you put secret keys, database passwords, and other app specific config in LocalSettings.php. Is there a similar file/location which Python programmers expect to find and modify?</p>
| 3 | 2009-07-11T10:57:06Z | 1,113,506 | <p>A user must configure their own secret key. A configuration file is the perfect place to keep this information.</p>
<p>You several choices for configuration files.</p>
<ol>
<li><p>Use <a href="http://docs.python.org/library/configparser.html" rel="nofollow"><code>ConfigParser</code></a> to parse a config file.</p></li>
<li><p>Use a simple Python module as the configuration file. You can simply <a href="http://docs.python.org/library/functions.html#execfile" rel="nofollow"><code>execfile</code></a> to load values from that file.</p></li>
<li><p>Invent your own configuration file notation and parse that.</p></li>
</ol>
| 3 | 2009-07-11T11:08:06Z | [
"python",
"configuration",
"google-maps"
] |
Where to store secret keys and password in Python | 1,113,479 | <p>I have a small Python program, which uses a Google Maps API secret key. I'm getting ready to check-in my code, and I don't want to include the secret key in SVN. </p>
<p>In the canonical PHP app you put secret keys, database passwords, and other app specific config in LocalSettings.php. Is there a similar file/location which Python programmers expect to find and modify?</p>
| 3 | 2009-07-11T10:57:06Z | 1,113,642 | <p>Any path can reference the user's home directory in a cross-platform way by expanding the common ~ (tilde) with <code>os.path.expanduser()</code>, like so:</p>
<pre><code>appdir = os.path.join(os.path.expanduser('~'), '.myapp')
</code></pre>
| 1 | 2009-07-11T12:43:17Z | [
"python",
"configuration",
"google-maps"
] |
What does Ruby have that Python doesn't, and vice versa? | 1,113,611 | <p>There is a lot of discussions of Python vs Ruby, and I all find them completely unhelpful, because they all turn around why feature X sucks in language Y, or that claim language Y doesn't have X, although in fact it does. I also know exactly why I prefer Python, but that's also subjective, and wouldn't help anybody choosing, as they might not have the same tastes in development as I do.</p>
<p>It would therefore be interesting to list the differences, objectively. So no "Python's lambdas sucks". Instead explain what Ruby's lambdas can do that Python's can't. No subjectivity. Example code is good!</p>
<p>Don't have several differences in one answer, please. And vote up the ones you know are correct, and down those you know are incorrect (or are subjective). Also, differences in syntax is not interesting. We know Python does with indentation what Ruby does with brackets and ends, and that @ is called self in Python.</p>
<p>UPDATE: This is now a community wiki, so we can add the big differences here.</p>
<h2>Ruby has a class reference in the class body</h2>
<p>In Ruby you have a reference to the class (self) already in the class body. In Python you don't have a reference to the class until after the class construction is finished.</p>
<p>An example:</p>
<pre><code>class Kaka
puts self
end
</code></pre>
<p>self in this case is the class, and this code would print out "Kaka". There is no way to print out the class name or in other ways access the class from the class definition body in Python (outside method definitions).</p>
<h2>All classes are mutable in Ruby</h2>
<p>This lets you develop extensions to core classes. Here's an example of a rails extension:</p>
<pre><code>class String
def starts_with?(other)
head = self[0, other.length]
head == other
end
end
</code></pre>
<p>Python (imagine there were no <code>''.startswith</code> method):</p>
<pre><code>def starts_with(s, prefix):
return s[:len(prefix)] == prefix
</code></pre>
<p>You could use it on any sequence (not just strings). In order to use it you should import it <em>explicitly</em> e.g., <code>from some_module import starts_with</code>.</p>
<h2>Ruby has Perl-like scripting features</h2>
<p>Ruby has first class regexps, $-variables, the awk/perl line by line input loop and other features that make it more suited to writing small shell scripts that munge text files or act as glue code for other programs.</p>
<h2>Ruby has first class continuations</h2>
<p>Thanks to the callcc statement. In Python you can create continuations by various techniques, but there is no support built in to the language.</p>
<h2>Ruby has blocks</h2>
<p>With the "do" statement you can create a multi-line anonymous function in Ruby, which will be passed in as an argument into the method in front of do, and called from there. In Python you would instead do this either by passing a method or with generators.</p>
<p>Ruby:</p>
<pre><code>amethod { |here|
many=lines+of+code
goes(here)
}
</code></pre>
<p>Python (Ruby blocks correspond to different constructs in Python):</p>
<pre><code>with amethod() as here: # `amethod() is a context manager
many=lines+of+code
goes(here)
</code></pre>
<p>Or</p>
<pre><code>for here in amethod(): # `amethod()` is an iterable
many=lines+of+code
goes(here)
</code></pre>
<p>Or</p>
<pre><code>def function(here):
many=lines+of+code
goes(here)
amethod(function) # `function` is a callback
</code></pre>
<p>Interestingly, the convenience statement in Ruby for calling a block is called "yield", which in Python will create a generator.</p>
<p>Ruby:</p>
<pre><code>def themethod
yield 5
end
themethod do |foo|
puts foo
end
</code></pre>
<p>Python:</p>
<pre><code>def themethod():
yield 5
for foo in themethod():
print foo
</code></pre>
<p>Although the principles are different, the result is strikingly similar.</p>
<h2>Ruby supports functional style (pipe-like) programming more easily</h2>
<pre><code>myList.map(&:description).reject(&:empty?).join("\n")
</code></pre>
<p>Python:</p>
<pre><code>descriptions = (f.description() for f in mylist)
"\n".join(filter(len, descriptions))
</code></pre>
<h2>Python has built-in generators (which are used like Ruby blocks, as noted above)</h2>
<p>Python has support for generators in the language. In Ruby 1.8 you can use the generator module which uses continuations to create a generator from a block. Or, you could just use a block/proc/lambda! Moreover, in Ruby 1.9 Fibers are, and can be used as, generators, and the Enumerator class is a built-in generator <a href="http://wiki.github.com/rdp/ruby_tutorials_core/enumerator" rel="nofollow">4</a></p>
<p><a href="http://docs.python.org/tutorial/classes.html#generators" rel="nofollow">docs.python.org</a> has this generator example:</p>
<pre><code>def reverse(data):
for index in range(len(data)-1, -1, -1):
yield data[index]
</code></pre>
<p>Contrast this with the above block examples.</p>
<h2>Python has flexible name space handling</h2>
<p>In Ruby, when you import a file with <code>require</code>, all the things defined in that file will end up in your global namespace. This causes namespace pollution. The solution to that is Rubys modules. But if you create a namespace with a module, then you have to use that namespace to access the contained classes.</p>
<p>In Python, the file is a module, and you can import its contained names with <code>from themodule import *</code>, thereby polluting the namespace if you want. But you can also import just selected names with <code>from themodule import aname, another</code> or you can simply <code>import themodule</code> and then access the names with <code>themodule.aname</code>. If you want more levels in your namespace you can have packages, which are directories with modules and an <code>__init__.py</code> file.</p>
<h2>Python has docstrings</h2>
<p>Docstrings are strings that are attached to modules, functions and methods and can be
introspected at runtime. This helps for creating such things as the help command and
automatic documentation.</p>
<pre><code>def frobnicate(bar):
"""frobnicate takes a bar and frobnicates it
>>> bar = Bar()
>>> bar.is_frobnicated()
False
>>> frobnicate(bar)
>>> bar.is_frobnicated()
True
"""
</code></pre>
<p>Ruby's equivalent are similar to javadocs, and located above the method instead of within it. They can be retrieved at runtime from the files by using 1.9's Method#source_location <a href="http://github.com/rdp/ri_for" rel="nofollow" title="example use">example use</a></p>
<h2>Python has multiple inheritance</h2>
<p>Ruby does not ("on purpose" -- see Ruby's website, <a href="http://codeidol.com/other/rubyckbk/Modules-and-Namespaces/Simulating-Multiple-Inheritance-with-Mixins/" rel="nofollow">see here how it's done in Ruby</a>). It does reuse the module concept as a type of abstract classes.</p>
<h2>Python has list/dict comprehensions</h2>
<p>Python:</p>
<pre><code>res = [x*x for x in range(1, 10)]
</code></pre>
<p>Ruby:</p>
<pre><code>res = (0..9).map { |x| x * x }
</code></pre>
<p>Python:</p>
<pre><code>>>> (x*x for x in range(10))
<generator object <genexpr> at 0xb7c1ccd4>
>>> list(_)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
</code></pre>
<p>Ruby:</p>
<pre><code>p = proc { |x| x * x }
(0..9).map(&p)
</code></pre>
<p>Python <strong>2.7+</strong>:</p>
<pre><code>>>> {x:str(y*y) for x,y in {1:2, 3:4}.items()}
{1: '4', 3: '16'}
</code></pre>
<p>Ruby:</p>
<pre><code>>> Hash[{1=>2, 3=>4}.map{|x,y| [x,(y*y).to_s]}]
=> {1=>"4", 3=>"16"}
</code></pre>
<h2>Python has decorators</h2>
<p>Things similar to decorators can also be created in Ruby, and it can also be argued that they aren't as necessary as in Python.</p>
<h2>Syntax differences</h2>
<p>Ruby requires "end" or "}" to close all of its scopes, while Python uses white-space only. There have been recent attempts in Ruby to allow for whitespace only indentation <a href="http://github.com/michaeledgar/seamless" rel="nofollow">http://github.com/michaeledgar/seamless</a></p>
| 264 | 2009-07-11T12:24:26Z | 1,113,613 | <p>You can have code in the class definition in both Ruby and Python. However, in Ruby you have a reference to the class (self). In Python you don't have a reference to the class, as the class isn't defined yet.</p>
<p>An example:</p>
<pre><code>class Kaka
puts self
end
</code></pre>
<p>self in this case is the class, and this code would print out "Kaka". There is no way to print out the class name or in other ways access the class from the class definition body in Python.</p>
| 5 | 2009-07-11T12:26:09Z | [
"python",
"ruby"
] |
What does Ruby have that Python doesn't, and vice versa? | 1,113,611 | <p>There is a lot of discussions of Python vs Ruby, and I all find them completely unhelpful, because they all turn around why feature X sucks in language Y, or that claim language Y doesn't have X, although in fact it does. I also know exactly why I prefer Python, but that's also subjective, and wouldn't help anybody choosing, as they might not have the same tastes in development as I do.</p>
<p>It would therefore be interesting to list the differences, objectively. So no "Python's lambdas sucks". Instead explain what Ruby's lambdas can do that Python's can't. No subjectivity. Example code is good!</p>
<p>Don't have several differences in one answer, please. And vote up the ones you know are correct, and down those you know are incorrect (or are subjective). Also, differences in syntax is not interesting. We know Python does with indentation what Ruby does with brackets and ends, and that @ is called self in Python.</p>
<p>UPDATE: This is now a community wiki, so we can add the big differences here.</p>
<h2>Ruby has a class reference in the class body</h2>
<p>In Ruby you have a reference to the class (self) already in the class body. In Python you don't have a reference to the class until after the class construction is finished.</p>
<p>An example:</p>
<pre><code>class Kaka
puts self
end
</code></pre>
<p>self in this case is the class, and this code would print out "Kaka". There is no way to print out the class name or in other ways access the class from the class definition body in Python (outside method definitions).</p>
<h2>All classes are mutable in Ruby</h2>
<p>This lets you develop extensions to core classes. Here's an example of a rails extension:</p>
<pre><code>class String
def starts_with?(other)
head = self[0, other.length]
head == other
end
end
</code></pre>
<p>Python (imagine there were no <code>''.startswith</code> method):</p>
<pre><code>def starts_with(s, prefix):
return s[:len(prefix)] == prefix
</code></pre>
<p>You could use it on any sequence (not just strings). In order to use it you should import it <em>explicitly</em> e.g., <code>from some_module import starts_with</code>.</p>
<h2>Ruby has Perl-like scripting features</h2>
<p>Ruby has first class regexps, $-variables, the awk/perl line by line input loop and other features that make it more suited to writing small shell scripts that munge text files or act as glue code for other programs.</p>
<h2>Ruby has first class continuations</h2>
<p>Thanks to the callcc statement. In Python you can create continuations by various techniques, but there is no support built in to the language.</p>
<h2>Ruby has blocks</h2>
<p>With the "do" statement you can create a multi-line anonymous function in Ruby, which will be passed in as an argument into the method in front of do, and called from there. In Python you would instead do this either by passing a method or with generators.</p>
<p>Ruby:</p>
<pre><code>amethod { |here|
many=lines+of+code
goes(here)
}
</code></pre>
<p>Python (Ruby blocks correspond to different constructs in Python):</p>
<pre><code>with amethod() as here: # `amethod() is a context manager
many=lines+of+code
goes(here)
</code></pre>
<p>Or</p>
<pre><code>for here in amethod(): # `amethod()` is an iterable
many=lines+of+code
goes(here)
</code></pre>
<p>Or</p>
<pre><code>def function(here):
many=lines+of+code
goes(here)
amethod(function) # `function` is a callback
</code></pre>
<p>Interestingly, the convenience statement in Ruby for calling a block is called "yield", which in Python will create a generator.</p>
<p>Ruby:</p>
<pre><code>def themethod
yield 5
end
themethod do |foo|
puts foo
end
</code></pre>
<p>Python:</p>
<pre><code>def themethod():
yield 5
for foo in themethod():
print foo
</code></pre>
<p>Although the principles are different, the result is strikingly similar.</p>
<h2>Ruby supports functional style (pipe-like) programming more easily</h2>
<pre><code>myList.map(&:description).reject(&:empty?).join("\n")
</code></pre>
<p>Python:</p>
<pre><code>descriptions = (f.description() for f in mylist)
"\n".join(filter(len, descriptions))
</code></pre>
<h2>Python has built-in generators (which are used like Ruby blocks, as noted above)</h2>
<p>Python has support for generators in the language. In Ruby 1.8 you can use the generator module which uses continuations to create a generator from a block. Or, you could just use a block/proc/lambda! Moreover, in Ruby 1.9 Fibers are, and can be used as, generators, and the Enumerator class is a built-in generator <a href="http://wiki.github.com/rdp/ruby_tutorials_core/enumerator" rel="nofollow">4</a></p>
<p><a href="http://docs.python.org/tutorial/classes.html#generators" rel="nofollow">docs.python.org</a> has this generator example:</p>
<pre><code>def reverse(data):
for index in range(len(data)-1, -1, -1):
yield data[index]
</code></pre>
<p>Contrast this with the above block examples.</p>
<h2>Python has flexible name space handling</h2>
<p>In Ruby, when you import a file with <code>require</code>, all the things defined in that file will end up in your global namespace. This causes namespace pollution. The solution to that is Rubys modules. But if you create a namespace with a module, then you have to use that namespace to access the contained classes.</p>
<p>In Python, the file is a module, and you can import its contained names with <code>from themodule import *</code>, thereby polluting the namespace if you want. But you can also import just selected names with <code>from themodule import aname, another</code> or you can simply <code>import themodule</code> and then access the names with <code>themodule.aname</code>. If you want more levels in your namespace you can have packages, which are directories with modules and an <code>__init__.py</code> file.</p>
<h2>Python has docstrings</h2>
<p>Docstrings are strings that are attached to modules, functions and methods and can be
introspected at runtime. This helps for creating such things as the help command and
automatic documentation.</p>
<pre><code>def frobnicate(bar):
"""frobnicate takes a bar and frobnicates it
>>> bar = Bar()
>>> bar.is_frobnicated()
False
>>> frobnicate(bar)
>>> bar.is_frobnicated()
True
"""
</code></pre>
<p>Ruby's equivalent are similar to javadocs, and located above the method instead of within it. They can be retrieved at runtime from the files by using 1.9's Method#source_location <a href="http://github.com/rdp/ri_for" rel="nofollow" title="example use">example use</a></p>
<h2>Python has multiple inheritance</h2>
<p>Ruby does not ("on purpose" -- see Ruby's website, <a href="http://codeidol.com/other/rubyckbk/Modules-and-Namespaces/Simulating-Multiple-Inheritance-with-Mixins/" rel="nofollow">see here how it's done in Ruby</a>). It does reuse the module concept as a type of abstract classes.</p>
<h2>Python has list/dict comprehensions</h2>
<p>Python:</p>
<pre><code>res = [x*x for x in range(1, 10)]
</code></pre>
<p>Ruby:</p>
<pre><code>res = (0..9).map { |x| x * x }
</code></pre>
<p>Python:</p>
<pre><code>>>> (x*x for x in range(10))
<generator object <genexpr> at 0xb7c1ccd4>
>>> list(_)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
</code></pre>
<p>Ruby:</p>
<pre><code>p = proc { |x| x * x }
(0..9).map(&p)
</code></pre>
<p>Python <strong>2.7+</strong>:</p>
<pre><code>>>> {x:str(y*y) for x,y in {1:2, 3:4}.items()}
{1: '4', 3: '16'}
</code></pre>
<p>Ruby:</p>
<pre><code>>> Hash[{1=>2, 3=>4}.map{|x,y| [x,(y*y).to_s]}]
=> {1=>"4", 3=>"16"}
</code></pre>
<h2>Python has decorators</h2>
<p>Things similar to decorators can also be created in Ruby, and it can also be argued that they aren't as necessary as in Python.</p>
<h2>Syntax differences</h2>
<p>Ruby requires "end" or "}" to close all of its scopes, while Python uses white-space only. There have been recent attempts in Ruby to allow for whitespace only indentation <a href="http://github.com/michaeledgar/seamless" rel="nofollow">http://github.com/michaeledgar/seamless</a></p>
| 264 | 2009-07-11T12:24:26Z | 1,113,624 | <p>Ruby has the concepts of <em>blocks</em>, which are essentially syntactic sugar around a section of code; they are a way to create closures and pass them to another method which may or may not use the block. A block can be invoked later on through a <code>yield</code> statement.</p>
<p>For example, a simple definition of an <code>each</code> method on <code>Array</code> might be something like:</p>
<pre><code>class Array
def each
for i in self
yield(i) # If a block has been passed, control will be passed here.
end
end
end
</code></pre>
<p>Then you can invoke this like so:</p>
<pre><code># Add five to each element.
[1, 2, 3, 4].each{ |e| puts e + 5 }
> [6, 7, 8, 9]
</code></pre>
<p>Python has anonymous functions/closures/lambdas, but it doesn't quite have blocks since it's missing some of the useful syntactic sugar. However, there's at least one way to get it in an ad-hoc fashion. See, for example, <a href="http://nicolas-lara.blogspot.com/2009/01/emulating-ruby-blocks-in-python.html" rel="nofollow"><strong>here</strong></a>.</p>
| 34 | 2009-07-11T12:32:48Z | [
"python",
"ruby"
] |
What does Ruby have that Python doesn't, and vice versa? | 1,113,611 | <p>There is a lot of discussions of Python vs Ruby, and I all find them completely unhelpful, because they all turn around why feature X sucks in language Y, or that claim language Y doesn't have X, although in fact it does. I also know exactly why I prefer Python, but that's also subjective, and wouldn't help anybody choosing, as they might not have the same tastes in development as I do.</p>
<p>It would therefore be interesting to list the differences, objectively. So no "Python's lambdas sucks". Instead explain what Ruby's lambdas can do that Python's can't. No subjectivity. Example code is good!</p>
<p>Don't have several differences in one answer, please. And vote up the ones you know are correct, and down those you know are incorrect (or are subjective). Also, differences in syntax is not interesting. We know Python does with indentation what Ruby does with brackets and ends, and that @ is called self in Python.</p>
<p>UPDATE: This is now a community wiki, so we can add the big differences here.</p>
<h2>Ruby has a class reference in the class body</h2>
<p>In Ruby you have a reference to the class (self) already in the class body. In Python you don't have a reference to the class until after the class construction is finished.</p>
<p>An example:</p>
<pre><code>class Kaka
puts self
end
</code></pre>
<p>self in this case is the class, and this code would print out "Kaka". There is no way to print out the class name or in other ways access the class from the class definition body in Python (outside method definitions).</p>
<h2>All classes are mutable in Ruby</h2>
<p>This lets you develop extensions to core classes. Here's an example of a rails extension:</p>
<pre><code>class String
def starts_with?(other)
head = self[0, other.length]
head == other
end
end
</code></pre>
<p>Python (imagine there were no <code>''.startswith</code> method):</p>
<pre><code>def starts_with(s, prefix):
return s[:len(prefix)] == prefix
</code></pre>
<p>You could use it on any sequence (not just strings). In order to use it you should import it <em>explicitly</em> e.g., <code>from some_module import starts_with</code>.</p>
<h2>Ruby has Perl-like scripting features</h2>
<p>Ruby has first class regexps, $-variables, the awk/perl line by line input loop and other features that make it more suited to writing small shell scripts that munge text files or act as glue code for other programs.</p>
<h2>Ruby has first class continuations</h2>
<p>Thanks to the callcc statement. In Python you can create continuations by various techniques, but there is no support built in to the language.</p>
<h2>Ruby has blocks</h2>
<p>With the "do" statement you can create a multi-line anonymous function in Ruby, which will be passed in as an argument into the method in front of do, and called from there. In Python you would instead do this either by passing a method or with generators.</p>
<p>Ruby:</p>
<pre><code>amethod { |here|
many=lines+of+code
goes(here)
}
</code></pre>
<p>Python (Ruby blocks correspond to different constructs in Python):</p>
<pre><code>with amethod() as here: # `amethod() is a context manager
many=lines+of+code
goes(here)
</code></pre>
<p>Or</p>
<pre><code>for here in amethod(): # `amethod()` is an iterable
many=lines+of+code
goes(here)
</code></pre>
<p>Or</p>
<pre><code>def function(here):
many=lines+of+code
goes(here)
amethod(function) # `function` is a callback
</code></pre>
<p>Interestingly, the convenience statement in Ruby for calling a block is called "yield", which in Python will create a generator.</p>
<p>Ruby:</p>
<pre><code>def themethod
yield 5
end
themethod do |foo|
puts foo
end
</code></pre>
<p>Python:</p>
<pre><code>def themethod():
yield 5
for foo in themethod():
print foo
</code></pre>
<p>Although the principles are different, the result is strikingly similar.</p>
<h2>Ruby supports functional style (pipe-like) programming more easily</h2>
<pre><code>myList.map(&:description).reject(&:empty?).join("\n")
</code></pre>
<p>Python:</p>
<pre><code>descriptions = (f.description() for f in mylist)
"\n".join(filter(len, descriptions))
</code></pre>
<h2>Python has built-in generators (which are used like Ruby blocks, as noted above)</h2>
<p>Python has support for generators in the language. In Ruby 1.8 you can use the generator module which uses continuations to create a generator from a block. Or, you could just use a block/proc/lambda! Moreover, in Ruby 1.9 Fibers are, and can be used as, generators, and the Enumerator class is a built-in generator <a href="http://wiki.github.com/rdp/ruby_tutorials_core/enumerator" rel="nofollow">4</a></p>
<p><a href="http://docs.python.org/tutorial/classes.html#generators" rel="nofollow">docs.python.org</a> has this generator example:</p>
<pre><code>def reverse(data):
for index in range(len(data)-1, -1, -1):
yield data[index]
</code></pre>
<p>Contrast this with the above block examples.</p>
<h2>Python has flexible name space handling</h2>
<p>In Ruby, when you import a file with <code>require</code>, all the things defined in that file will end up in your global namespace. This causes namespace pollution. The solution to that is Rubys modules. But if you create a namespace with a module, then you have to use that namespace to access the contained classes.</p>
<p>In Python, the file is a module, and you can import its contained names with <code>from themodule import *</code>, thereby polluting the namespace if you want. But you can also import just selected names with <code>from themodule import aname, another</code> or you can simply <code>import themodule</code> and then access the names with <code>themodule.aname</code>. If you want more levels in your namespace you can have packages, which are directories with modules and an <code>__init__.py</code> file.</p>
<h2>Python has docstrings</h2>
<p>Docstrings are strings that are attached to modules, functions and methods and can be
introspected at runtime. This helps for creating such things as the help command and
automatic documentation.</p>
<pre><code>def frobnicate(bar):
"""frobnicate takes a bar and frobnicates it
>>> bar = Bar()
>>> bar.is_frobnicated()
False
>>> frobnicate(bar)
>>> bar.is_frobnicated()
True
"""
</code></pre>
<p>Ruby's equivalent are similar to javadocs, and located above the method instead of within it. They can be retrieved at runtime from the files by using 1.9's Method#source_location <a href="http://github.com/rdp/ri_for" rel="nofollow" title="example use">example use</a></p>
<h2>Python has multiple inheritance</h2>
<p>Ruby does not ("on purpose" -- see Ruby's website, <a href="http://codeidol.com/other/rubyckbk/Modules-and-Namespaces/Simulating-Multiple-Inheritance-with-Mixins/" rel="nofollow">see here how it's done in Ruby</a>). It does reuse the module concept as a type of abstract classes.</p>
<h2>Python has list/dict comprehensions</h2>
<p>Python:</p>
<pre><code>res = [x*x for x in range(1, 10)]
</code></pre>
<p>Ruby:</p>
<pre><code>res = (0..9).map { |x| x * x }
</code></pre>
<p>Python:</p>
<pre><code>>>> (x*x for x in range(10))
<generator object <genexpr> at 0xb7c1ccd4>
>>> list(_)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
</code></pre>
<p>Ruby:</p>
<pre><code>p = proc { |x| x * x }
(0..9).map(&p)
</code></pre>
<p>Python <strong>2.7+</strong>:</p>
<pre><code>>>> {x:str(y*y) for x,y in {1:2, 3:4}.items()}
{1: '4', 3: '16'}
</code></pre>
<p>Ruby:</p>
<pre><code>>> Hash[{1=>2, 3=>4}.map{|x,y| [x,(y*y).to_s]}]
=> {1=>"4", 3=>"16"}
</code></pre>
<h2>Python has decorators</h2>
<p>Things similar to decorators can also be created in Ruby, and it can also be argued that they aren't as necessary as in Python.</p>
<h2>Syntax differences</h2>
<p>Ruby requires "end" or "}" to close all of its scopes, while Python uses white-space only. There have been recent attempts in Ruby to allow for whitespace only indentation <a href="http://github.com/michaeledgar/seamless" rel="nofollow">http://github.com/michaeledgar/seamless</a></p>
| 264 | 2009-07-11T12:24:26Z | 1,113,713 | <p>Python has docstrings and ruby doesn't... Or if it doesn't, they are not accessible as easily as in python. </p>
<p>Ps. If im wrong, pretty please, leave an example? I have a workaround that i could monkeypatch into classes quite easily but i'd like to have docstring kinda of a feature in "native way".</p>
| 5 | 2009-07-11T13:24:40Z | [
"python",
"ruby"
] |
What does Ruby have that Python doesn't, and vice versa? | 1,113,611 | <p>There is a lot of discussions of Python vs Ruby, and I all find them completely unhelpful, because they all turn around why feature X sucks in language Y, or that claim language Y doesn't have X, although in fact it does. I also know exactly why I prefer Python, but that's also subjective, and wouldn't help anybody choosing, as they might not have the same tastes in development as I do.</p>
<p>It would therefore be interesting to list the differences, objectively. So no "Python's lambdas sucks". Instead explain what Ruby's lambdas can do that Python's can't. No subjectivity. Example code is good!</p>
<p>Don't have several differences in one answer, please. And vote up the ones you know are correct, and down those you know are incorrect (or are subjective). Also, differences in syntax is not interesting. We know Python does with indentation what Ruby does with brackets and ends, and that @ is called self in Python.</p>
<p>UPDATE: This is now a community wiki, so we can add the big differences here.</p>
<h2>Ruby has a class reference in the class body</h2>
<p>In Ruby you have a reference to the class (self) already in the class body. In Python you don't have a reference to the class until after the class construction is finished.</p>
<p>An example:</p>
<pre><code>class Kaka
puts self
end
</code></pre>
<p>self in this case is the class, and this code would print out "Kaka". There is no way to print out the class name or in other ways access the class from the class definition body in Python (outside method definitions).</p>
<h2>All classes are mutable in Ruby</h2>
<p>This lets you develop extensions to core classes. Here's an example of a rails extension:</p>
<pre><code>class String
def starts_with?(other)
head = self[0, other.length]
head == other
end
end
</code></pre>
<p>Python (imagine there were no <code>''.startswith</code> method):</p>
<pre><code>def starts_with(s, prefix):
return s[:len(prefix)] == prefix
</code></pre>
<p>You could use it on any sequence (not just strings). In order to use it you should import it <em>explicitly</em> e.g., <code>from some_module import starts_with</code>.</p>
<h2>Ruby has Perl-like scripting features</h2>
<p>Ruby has first class regexps, $-variables, the awk/perl line by line input loop and other features that make it more suited to writing small shell scripts that munge text files or act as glue code for other programs.</p>
<h2>Ruby has first class continuations</h2>
<p>Thanks to the callcc statement. In Python you can create continuations by various techniques, but there is no support built in to the language.</p>
<h2>Ruby has blocks</h2>
<p>With the "do" statement you can create a multi-line anonymous function in Ruby, which will be passed in as an argument into the method in front of do, and called from there. In Python you would instead do this either by passing a method or with generators.</p>
<p>Ruby:</p>
<pre><code>amethod { |here|
many=lines+of+code
goes(here)
}
</code></pre>
<p>Python (Ruby blocks correspond to different constructs in Python):</p>
<pre><code>with amethod() as here: # `amethod() is a context manager
many=lines+of+code
goes(here)
</code></pre>
<p>Or</p>
<pre><code>for here in amethod(): # `amethod()` is an iterable
many=lines+of+code
goes(here)
</code></pre>
<p>Or</p>
<pre><code>def function(here):
many=lines+of+code
goes(here)
amethod(function) # `function` is a callback
</code></pre>
<p>Interestingly, the convenience statement in Ruby for calling a block is called "yield", which in Python will create a generator.</p>
<p>Ruby:</p>
<pre><code>def themethod
yield 5
end
themethod do |foo|
puts foo
end
</code></pre>
<p>Python:</p>
<pre><code>def themethod():
yield 5
for foo in themethod():
print foo
</code></pre>
<p>Although the principles are different, the result is strikingly similar.</p>
<h2>Ruby supports functional style (pipe-like) programming more easily</h2>
<pre><code>myList.map(&:description).reject(&:empty?).join("\n")
</code></pre>
<p>Python:</p>
<pre><code>descriptions = (f.description() for f in mylist)
"\n".join(filter(len, descriptions))
</code></pre>
<h2>Python has built-in generators (which are used like Ruby blocks, as noted above)</h2>
<p>Python has support for generators in the language. In Ruby 1.8 you can use the generator module which uses continuations to create a generator from a block. Or, you could just use a block/proc/lambda! Moreover, in Ruby 1.9 Fibers are, and can be used as, generators, and the Enumerator class is a built-in generator <a href="http://wiki.github.com/rdp/ruby_tutorials_core/enumerator" rel="nofollow">4</a></p>
<p><a href="http://docs.python.org/tutorial/classes.html#generators" rel="nofollow">docs.python.org</a> has this generator example:</p>
<pre><code>def reverse(data):
for index in range(len(data)-1, -1, -1):
yield data[index]
</code></pre>
<p>Contrast this with the above block examples.</p>
<h2>Python has flexible name space handling</h2>
<p>In Ruby, when you import a file with <code>require</code>, all the things defined in that file will end up in your global namespace. This causes namespace pollution. The solution to that is Rubys modules. But if you create a namespace with a module, then you have to use that namespace to access the contained classes.</p>
<p>In Python, the file is a module, and you can import its contained names with <code>from themodule import *</code>, thereby polluting the namespace if you want. But you can also import just selected names with <code>from themodule import aname, another</code> or you can simply <code>import themodule</code> and then access the names with <code>themodule.aname</code>. If you want more levels in your namespace you can have packages, which are directories with modules and an <code>__init__.py</code> file.</p>
<h2>Python has docstrings</h2>
<p>Docstrings are strings that are attached to modules, functions and methods and can be
introspected at runtime. This helps for creating such things as the help command and
automatic documentation.</p>
<pre><code>def frobnicate(bar):
"""frobnicate takes a bar and frobnicates it
>>> bar = Bar()
>>> bar.is_frobnicated()
False
>>> frobnicate(bar)
>>> bar.is_frobnicated()
True
"""
</code></pre>
<p>Ruby's equivalent are similar to javadocs, and located above the method instead of within it. They can be retrieved at runtime from the files by using 1.9's Method#source_location <a href="http://github.com/rdp/ri_for" rel="nofollow" title="example use">example use</a></p>
<h2>Python has multiple inheritance</h2>
<p>Ruby does not ("on purpose" -- see Ruby's website, <a href="http://codeidol.com/other/rubyckbk/Modules-and-Namespaces/Simulating-Multiple-Inheritance-with-Mixins/" rel="nofollow">see here how it's done in Ruby</a>). It does reuse the module concept as a type of abstract classes.</p>
<h2>Python has list/dict comprehensions</h2>
<p>Python:</p>
<pre><code>res = [x*x for x in range(1, 10)]
</code></pre>
<p>Ruby:</p>
<pre><code>res = (0..9).map { |x| x * x }
</code></pre>
<p>Python:</p>
<pre><code>>>> (x*x for x in range(10))
<generator object <genexpr> at 0xb7c1ccd4>
>>> list(_)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
</code></pre>
<p>Ruby:</p>
<pre><code>p = proc { |x| x * x }
(0..9).map(&p)
</code></pre>
<p>Python <strong>2.7+</strong>:</p>
<pre><code>>>> {x:str(y*y) for x,y in {1:2, 3:4}.items()}
{1: '4', 3: '16'}
</code></pre>
<p>Ruby:</p>
<pre><code>>> Hash[{1=>2, 3=>4}.map{|x,y| [x,(y*y).to_s]}]
=> {1=>"4", 3=>"16"}
</code></pre>
<h2>Python has decorators</h2>
<p>Things similar to decorators can also be created in Ruby, and it can also be argued that they aren't as necessary as in Python.</p>
<h2>Syntax differences</h2>
<p>Ruby requires "end" or "}" to close all of its scopes, while Python uses white-space only. There have been recent attempts in Ruby to allow for whitespace only indentation <a href="http://github.com/michaeledgar/seamless" rel="nofollow">http://github.com/michaeledgar/seamless</a></p>
| 264 | 2009-07-11T12:24:26Z | 1,113,741 | <p>What Ruby has over Python are its scripting language capabilities. Scripting language in this context meaning to be used for "glue code" in shell scripts and general text manipulation.</p>
<p>These are mostly shared with Perl. First-class built-in regular expressions, $-Variables, useful command line options like Perl (-a, -e) etc.</p>
<p>Together with its terse yet epxressive syntax it is perfect for these kind of tasks.</p>
<p>Python to me is more of a dynamically typed business language that is very easy to learn and has a neat syntax. Not as "cool" as Ruby but neat.
What Python has over Ruby to me is the vast number of bindings for other libs. Bindings to Qt and other GUI libs, many game support libraries and and and. Ruby has much less. While much used bindings e.g. to Databases are of good quality I found niche libs to be better supported in Python even if for the same library there is also a Ruby binding.</p>
<p>So, I'd say both languages have its use and it is the task that defines which one to use. Both are easy enough to learn. I use them side-by-side. Ruby for scripting and Python for stand-alone apps.</p>
| 12 | 2009-07-11T13:41:54Z | [
"python",
"ruby"
] |
What does Ruby have that Python doesn't, and vice versa? | 1,113,611 | <p>There is a lot of discussions of Python vs Ruby, and I all find them completely unhelpful, because they all turn around why feature X sucks in language Y, or that claim language Y doesn't have X, although in fact it does. I also know exactly why I prefer Python, but that's also subjective, and wouldn't help anybody choosing, as they might not have the same tastes in development as I do.</p>
<p>It would therefore be interesting to list the differences, objectively. So no "Python's lambdas sucks". Instead explain what Ruby's lambdas can do that Python's can't. No subjectivity. Example code is good!</p>
<p>Don't have several differences in one answer, please. And vote up the ones you know are correct, and down those you know are incorrect (or are subjective). Also, differences in syntax is not interesting. We know Python does with indentation what Ruby does with brackets and ends, and that @ is called self in Python.</p>
<p>UPDATE: This is now a community wiki, so we can add the big differences here.</p>
<h2>Ruby has a class reference in the class body</h2>
<p>In Ruby you have a reference to the class (self) already in the class body. In Python you don't have a reference to the class until after the class construction is finished.</p>
<p>An example:</p>
<pre><code>class Kaka
puts self
end
</code></pre>
<p>self in this case is the class, and this code would print out "Kaka". There is no way to print out the class name or in other ways access the class from the class definition body in Python (outside method definitions).</p>
<h2>All classes are mutable in Ruby</h2>
<p>This lets you develop extensions to core classes. Here's an example of a rails extension:</p>
<pre><code>class String
def starts_with?(other)
head = self[0, other.length]
head == other
end
end
</code></pre>
<p>Python (imagine there were no <code>''.startswith</code> method):</p>
<pre><code>def starts_with(s, prefix):
return s[:len(prefix)] == prefix
</code></pre>
<p>You could use it on any sequence (not just strings). In order to use it you should import it <em>explicitly</em> e.g., <code>from some_module import starts_with</code>.</p>
<h2>Ruby has Perl-like scripting features</h2>
<p>Ruby has first class regexps, $-variables, the awk/perl line by line input loop and other features that make it more suited to writing small shell scripts that munge text files or act as glue code for other programs.</p>
<h2>Ruby has first class continuations</h2>
<p>Thanks to the callcc statement. In Python you can create continuations by various techniques, but there is no support built in to the language.</p>
<h2>Ruby has blocks</h2>
<p>With the "do" statement you can create a multi-line anonymous function in Ruby, which will be passed in as an argument into the method in front of do, and called from there. In Python you would instead do this either by passing a method or with generators.</p>
<p>Ruby:</p>
<pre><code>amethod { |here|
many=lines+of+code
goes(here)
}
</code></pre>
<p>Python (Ruby blocks correspond to different constructs in Python):</p>
<pre><code>with amethod() as here: # `amethod() is a context manager
many=lines+of+code
goes(here)
</code></pre>
<p>Or</p>
<pre><code>for here in amethod(): # `amethod()` is an iterable
many=lines+of+code
goes(here)
</code></pre>
<p>Or</p>
<pre><code>def function(here):
many=lines+of+code
goes(here)
amethod(function) # `function` is a callback
</code></pre>
<p>Interestingly, the convenience statement in Ruby for calling a block is called "yield", which in Python will create a generator.</p>
<p>Ruby:</p>
<pre><code>def themethod
yield 5
end
themethod do |foo|
puts foo
end
</code></pre>
<p>Python:</p>
<pre><code>def themethod():
yield 5
for foo in themethod():
print foo
</code></pre>
<p>Although the principles are different, the result is strikingly similar.</p>
<h2>Ruby supports functional style (pipe-like) programming more easily</h2>
<pre><code>myList.map(&:description).reject(&:empty?).join("\n")
</code></pre>
<p>Python:</p>
<pre><code>descriptions = (f.description() for f in mylist)
"\n".join(filter(len, descriptions))
</code></pre>
<h2>Python has built-in generators (which are used like Ruby blocks, as noted above)</h2>
<p>Python has support for generators in the language. In Ruby 1.8 you can use the generator module which uses continuations to create a generator from a block. Or, you could just use a block/proc/lambda! Moreover, in Ruby 1.9 Fibers are, and can be used as, generators, and the Enumerator class is a built-in generator <a href="http://wiki.github.com/rdp/ruby_tutorials_core/enumerator" rel="nofollow">4</a></p>
<p><a href="http://docs.python.org/tutorial/classes.html#generators" rel="nofollow">docs.python.org</a> has this generator example:</p>
<pre><code>def reverse(data):
for index in range(len(data)-1, -1, -1):
yield data[index]
</code></pre>
<p>Contrast this with the above block examples.</p>
<h2>Python has flexible name space handling</h2>
<p>In Ruby, when you import a file with <code>require</code>, all the things defined in that file will end up in your global namespace. This causes namespace pollution. The solution to that is Rubys modules. But if you create a namespace with a module, then you have to use that namespace to access the contained classes.</p>
<p>In Python, the file is a module, and you can import its contained names with <code>from themodule import *</code>, thereby polluting the namespace if you want. But you can also import just selected names with <code>from themodule import aname, another</code> or you can simply <code>import themodule</code> and then access the names with <code>themodule.aname</code>. If you want more levels in your namespace you can have packages, which are directories with modules and an <code>__init__.py</code> file.</p>
<h2>Python has docstrings</h2>
<p>Docstrings are strings that are attached to modules, functions and methods and can be
introspected at runtime. This helps for creating such things as the help command and
automatic documentation.</p>
<pre><code>def frobnicate(bar):
"""frobnicate takes a bar and frobnicates it
>>> bar = Bar()
>>> bar.is_frobnicated()
False
>>> frobnicate(bar)
>>> bar.is_frobnicated()
True
"""
</code></pre>
<p>Ruby's equivalent are similar to javadocs, and located above the method instead of within it. They can be retrieved at runtime from the files by using 1.9's Method#source_location <a href="http://github.com/rdp/ri_for" rel="nofollow" title="example use">example use</a></p>
<h2>Python has multiple inheritance</h2>
<p>Ruby does not ("on purpose" -- see Ruby's website, <a href="http://codeidol.com/other/rubyckbk/Modules-and-Namespaces/Simulating-Multiple-Inheritance-with-Mixins/" rel="nofollow">see here how it's done in Ruby</a>). It does reuse the module concept as a type of abstract classes.</p>
<h2>Python has list/dict comprehensions</h2>
<p>Python:</p>
<pre><code>res = [x*x for x in range(1, 10)]
</code></pre>
<p>Ruby:</p>
<pre><code>res = (0..9).map { |x| x * x }
</code></pre>
<p>Python:</p>
<pre><code>>>> (x*x for x in range(10))
<generator object <genexpr> at 0xb7c1ccd4>
>>> list(_)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
</code></pre>
<p>Ruby:</p>
<pre><code>p = proc { |x| x * x }
(0..9).map(&p)
</code></pre>
<p>Python <strong>2.7+</strong>:</p>
<pre><code>>>> {x:str(y*y) for x,y in {1:2, 3:4}.items()}
{1: '4', 3: '16'}
</code></pre>
<p>Ruby:</p>
<pre><code>>> Hash[{1=>2, 3=>4}.map{|x,y| [x,(y*y).to_s]}]
=> {1=>"4", 3=>"16"}
</code></pre>
<h2>Python has decorators</h2>
<p>Things similar to decorators can also be created in Ruby, and it can also be argued that they aren't as necessary as in Python.</p>
<h2>Syntax differences</h2>
<p>Ruby requires "end" or "}" to close all of its scopes, while Python uses white-space only. There have been recent attempts in Ruby to allow for whitespace only indentation <a href="http://github.com/michaeledgar/seamless" rel="nofollow">http://github.com/michaeledgar/seamless</a></p>
| 264 | 2009-07-11T12:24:26Z | 1,113,765 | <p>While the functionalty is to a great extent the same (especially in the <a href="http://en.wikipedia.org/wiki/Turing%5Fcompleteness" rel="nofollow">Turing</a> sense), malicious tongues claim that Ruby was created for Pythonistas that could not split up with the Perlish coding style.</p>
| -4 | 2009-07-11T13:56:01Z | [
"python",
"ruby"
] |
What does Ruby have that Python doesn't, and vice versa? | 1,113,611 | <p>There is a lot of discussions of Python vs Ruby, and I all find them completely unhelpful, because they all turn around why feature X sucks in language Y, or that claim language Y doesn't have X, although in fact it does. I also know exactly why I prefer Python, but that's also subjective, and wouldn't help anybody choosing, as they might not have the same tastes in development as I do.</p>
<p>It would therefore be interesting to list the differences, objectively. So no "Python's lambdas sucks". Instead explain what Ruby's lambdas can do that Python's can't. No subjectivity. Example code is good!</p>
<p>Don't have several differences in one answer, please. And vote up the ones you know are correct, and down those you know are incorrect (or are subjective). Also, differences in syntax is not interesting. We know Python does with indentation what Ruby does with brackets and ends, and that @ is called self in Python.</p>
<p>UPDATE: This is now a community wiki, so we can add the big differences here.</p>
<h2>Ruby has a class reference in the class body</h2>
<p>In Ruby you have a reference to the class (self) already in the class body. In Python you don't have a reference to the class until after the class construction is finished.</p>
<p>An example:</p>
<pre><code>class Kaka
puts self
end
</code></pre>
<p>self in this case is the class, and this code would print out "Kaka". There is no way to print out the class name or in other ways access the class from the class definition body in Python (outside method definitions).</p>
<h2>All classes are mutable in Ruby</h2>
<p>This lets you develop extensions to core classes. Here's an example of a rails extension:</p>
<pre><code>class String
def starts_with?(other)
head = self[0, other.length]
head == other
end
end
</code></pre>
<p>Python (imagine there were no <code>''.startswith</code> method):</p>
<pre><code>def starts_with(s, prefix):
return s[:len(prefix)] == prefix
</code></pre>
<p>You could use it on any sequence (not just strings). In order to use it you should import it <em>explicitly</em> e.g., <code>from some_module import starts_with</code>.</p>
<h2>Ruby has Perl-like scripting features</h2>
<p>Ruby has first class regexps, $-variables, the awk/perl line by line input loop and other features that make it more suited to writing small shell scripts that munge text files or act as glue code for other programs.</p>
<h2>Ruby has first class continuations</h2>
<p>Thanks to the callcc statement. In Python you can create continuations by various techniques, but there is no support built in to the language.</p>
<h2>Ruby has blocks</h2>
<p>With the "do" statement you can create a multi-line anonymous function in Ruby, which will be passed in as an argument into the method in front of do, and called from there. In Python you would instead do this either by passing a method or with generators.</p>
<p>Ruby:</p>
<pre><code>amethod { |here|
many=lines+of+code
goes(here)
}
</code></pre>
<p>Python (Ruby blocks correspond to different constructs in Python):</p>
<pre><code>with amethod() as here: # `amethod() is a context manager
many=lines+of+code
goes(here)
</code></pre>
<p>Or</p>
<pre><code>for here in amethod(): # `amethod()` is an iterable
many=lines+of+code
goes(here)
</code></pre>
<p>Or</p>
<pre><code>def function(here):
many=lines+of+code
goes(here)
amethod(function) # `function` is a callback
</code></pre>
<p>Interestingly, the convenience statement in Ruby for calling a block is called "yield", which in Python will create a generator.</p>
<p>Ruby:</p>
<pre><code>def themethod
yield 5
end
themethod do |foo|
puts foo
end
</code></pre>
<p>Python:</p>
<pre><code>def themethod():
yield 5
for foo in themethod():
print foo
</code></pre>
<p>Although the principles are different, the result is strikingly similar.</p>
<h2>Ruby supports functional style (pipe-like) programming more easily</h2>
<pre><code>myList.map(&:description).reject(&:empty?).join("\n")
</code></pre>
<p>Python:</p>
<pre><code>descriptions = (f.description() for f in mylist)
"\n".join(filter(len, descriptions))
</code></pre>
<h2>Python has built-in generators (which are used like Ruby blocks, as noted above)</h2>
<p>Python has support for generators in the language. In Ruby 1.8 you can use the generator module which uses continuations to create a generator from a block. Or, you could just use a block/proc/lambda! Moreover, in Ruby 1.9 Fibers are, and can be used as, generators, and the Enumerator class is a built-in generator <a href="http://wiki.github.com/rdp/ruby_tutorials_core/enumerator" rel="nofollow">4</a></p>
<p><a href="http://docs.python.org/tutorial/classes.html#generators" rel="nofollow">docs.python.org</a> has this generator example:</p>
<pre><code>def reverse(data):
for index in range(len(data)-1, -1, -1):
yield data[index]
</code></pre>
<p>Contrast this with the above block examples.</p>
<h2>Python has flexible name space handling</h2>
<p>In Ruby, when you import a file with <code>require</code>, all the things defined in that file will end up in your global namespace. This causes namespace pollution. The solution to that is Rubys modules. But if you create a namespace with a module, then you have to use that namespace to access the contained classes.</p>
<p>In Python, the file is a module, and you can import its contained names with <code>from themodule import *</code>, thereby polluting the namespace if you want. But you can also import just selected names with <code>from themodule import aname, another</code> or you can simply <code>import themodule</code> and then access the names with <code>themodule.aname</code>. If you want more levels in your namespace you can have packages, which are directories with modules and an <code>__init__.py</code> file.</p>
<h2>Python has docstrings</h2>
<p>Docstrings are strings that are attached to modules, functions and methods and can be
introspected at runtime. This helps for creating such things as the help command and
automatic documentation.</p>
<pre><code>def frobnicate(bar):
"""frobnicate takes a bar and frobnicates it
>>> bar = Bar()
>>> bar.is_frobnicated()
False
>>> frobnicate(bar)
>>> bar.is_frobnicated()
True
"""
</code></pre>
<p>Ruby's equivalent are similar to javadocs, and located above the method instead of within it. They can be retrieved at runtime from the files by using 1.9's Method#source_location <a href="http://github.com/rdp/ri_for" rel="nofollow" title="example use">example use</a></p>
<h2>Python has multiple inheritance</h2>
<p>Ruby does not ("on purpose" -- see Ruby's website, <a href="http://codeidol.com/other/rubyckbk/Modules-and-Namespaces/Simulating-Multiple-Inheritance-with-Mixins/" rel="nofollow">see here how it's done in Ruby</a>). It does reuse the module concept as a type of abstract classes.</p>
<h2>Python has list/dict comprehensions</h2>
<p>Python:</p>
<pre><code>res = [x*x for x in range(1, 10)]
</code></pre>
<p>Ruby:</p>
<pre><code>res = (0..9).map { |x| x * x }
</code></pre>
<p>Python:</p>
<pre><code>>>> (x*x for x in range(10))
<generator object <genexpr> at 0xb7c1ccd4>
>>> list(_)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
</code></pre>
<p>Ruby:</p>
<pre><code>p = proc { |x| x * x }
(0..9).map(&p)
</code></pre>
<p>Python <strong>2.7+</strong>:</p>
<pre><code>>>> {x:str(y*y) for x,y in {1:2, 3:4}.items()}
{1: '4', 3: '16'}
</code></pre>
<p>Ruby:</p>
<pre><code>>> Hash[{1=>2, 3=>4}.map{|x,y| [x,(y*y).to_s]}]
=> {1=>"4", 3=>"16"}
</code></pre>
<h2>Python has decorators</h2>
<p>Things similar to decorators can also be created in Ruby, and it can also be argued that they aren't as necessary as in Python.</p>
<h2>Syntax differences</h2>
<p>Ruby requires "end" or "}" to close all of its scopes, while Python uses white-space only. There have been recent attempts in Ruby to allow for whitespace only indentation <a href="http://github.com/michaeledgar/seamless" rel="nofollow">http://github.com/michaeledgar/seamless</a></p>
| 264 | 2009-07-11T12:24:26Z | 1,113,875 | <p>I don't think "Ruby has X and Python doesn't, while Python has Y and Ruby doesn't" is the most useful way to look at it. They're quite similar languages, with many shared abilities. </p>
<p>To a large degree, the difference is what the language makes elegant and readable. To use an example you brought up, both do theoretically have lambdas, but Python programmers tend to avoid them, and constructs made using them do not look anywhere near as readable or idiomatic as in Ruby. So in Python, a good programmer will want to take a different route to solving the problem than he would in Ruby, just because it actually <em>is</em> the better way to do it.</p>
| 12 | 2009-07-11T14:52:21Z | [
"python",
"ruby"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.