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
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(&amp;:description).reject(&amp;: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 &gt;&gt;&gt; bar = Bar() &gt;&gt;&gt; bar.is_frobnicated() False &gt;&gt;&gt; frobnicate(bar) &gt;&gt;&gt; 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>&gt;&gt;&gt; (x*x for x in range(10)) &lt;generator object &lt;genexpr&gt; at 0xb7c1ccd4&gt; &gt;&gt;&gt; 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(&amp;p) </code></pre> <p>Python <strong>2.7+</strong>:</p> <pre><code>&gt;&gt;&gt; {x:str(y*y) for x,y in {1:2, 3:4}.items()} {1: '4', 3: '16'} </code></pre> <p>Ruby:</p> <pre><code>&gt;&gt; Hash[{1=&gt;2, 3=&gt;4}.map{|x,y| [x,(y*y).to_s]}] =&gt; {1=&gt;"4", 3=&gt;"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,880
<p>Python has a "we're all adults here" mentality. Thus, you'll find that Ruby has things like constants while Python doesn't (although Ruby's constants only raise a warning). The Python way of thinking is that if you want to make something constant, you should put the variable names in all caps and not change it.</p> <p>For example, Ruby:</p> <pre><code>&gt;&gt; PI = 3.14 =&gt; 3.14 &gt;&gt; PI += 1 (irb):2: warning: already initialized constant PI =&gt; 4.14 </code></pre> <p>Python:</p> <pre><code>&gt;&gt;&gt; PI = 3.14 &gt;&gt;&gt; PI += 1 &gt;&gt;&gt; PI 4.1400000000000006 </code></pre>
19
2009-07-11T14:54:19Z
[ "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(&amp;:description).reject(&amp;: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 &gt;&gt;&gt; bar = Bar() &gt;&gt;&gt; bar.is_frobnicated() False &gt;&gt;&gt; frobnicate(bar) &gt;&gt;&gt; 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>&gt;&gt;&gt; (x*x for x in range(10)) &lt;generator object &lt;genexpr&gt; at 0xb7c1ccd4&gt; &gt;&gt;&gt; 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(&amp;p) </code></pre> <p>Python <strong>2.7+</strong>:</p> <pre><code>&gt;&gt;&gt; {x:str(y*y) for x,y in {1:2, 3:4}.items()} {1: '4', 3: '16'} </code></pre> <p>Ruby:</p> <pre><code>&gt;&gt; Hash[{1=&gt;2, 3=&gt;4}.map{|x,y| [x,(y*y).to_s]}] =&gt; {1=&gt;"4", 3=&gt;"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,898
<p>Ruby has sigils and twigils, Python doesn't.</p> <p><strong>Edit</strong>: And one very important thing that I forgot (after all, the previous was just to flame a little bit :-p):</p> <p>Python has a JIT compiler (<a href="http://psyco.sourceforge.net/" rel="nofollow">Psyco</a>), a sightly lower level language for writing faster code (<a href="http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/" rel="nofollow">Pyrex</a>) and the ability to add inline C++ code (<a href="http://www.scipy.org/Weave" rel="nofollow">Weave</a>).</p>
5
2009-07-11T15:01:16Z
[ "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(&amp;:description).reject(&amp;: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 &gt;&gt;&gt; bar = Bar() &gt;&gt;&gt; bar.is_frobnicated() False &gt;&gt;&gt; frobnicate(bar) &gt;&gt;&gt; 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>&gt;&gt;&gt; (x*x for x in range(10)) &lt;generator object &lt;genexpr&gt; at 0xb7c1ccd4&gt; &gt;&gt;&gt; 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(&amp;p) </code></pre> <p>Python <strong>2.7+</strong>:</p> <pre><code>&gt;&gt;&gt; {x:str(y*y) for x,y in {1:2, 3:4}.items()} {1: '4', 3: '16'} </code></pre> <p>Ruby:</p> <pre><code>&gt;&gt; Hash[{1=&gt;2, 3=&gt;4}.map{|x,y| [x,(y*y).to_s]}] =&gt; {1=&gt;"4", 3=&gt;"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,114,449
<p>Ruby has builtin continuation support using <code>callcc</code>.</p> <p>Hence you can implement cool things like the <a href="http://www.randomhacks.net/articles/2005/10/11/amb-operator" rel="nofollow">amb-operator</a></p>
6
2009-07-11T19:19:11Z
[ "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(&amp;:description).reject(&amp;: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 &gt;&gt;&gt; bar = Bar() &gt;&gt;&gt; bar.is_frobnicated() False &gt;&gt;&gt; frobnicate(bar) &gt;&gt;&gt; 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>&gt;&gt;&gt; (x*x for x in range(10)) &lt;generator object &lt;genexpr&gt; at 0xb7c1ccd4&gt; &gt;&gt;&gt; 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(&amp;p) </code></pre> <p>Python <strong>2.7+</strong>:</p> <pre><code>&gt;&gt;&gt; {x:str(y*y) for x,y in {1:2, 3:4}.items()} {1: '4', 3: '16'} </code></pre> <p>Ruby:</p> <pre><code>&gt;&gt; Hash[{1=&gt;2, 3=&gt;4}.map{|x,y| [x,(y*y).to_s]}] =&gt; {1=&gt;"4", 3=&gt;"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,114,453
<p>Python has an explicit, builtin syntax for list-comprehenions and generators whereas in Ruby you would use map and code blocks.</p> <p>Compare</p> <pre><code>list = [ x*x for x in range(1, 10) ] </code></pre> <p>to</p> <pre><code>res = (1..10).map{ |x| x*x } </code></pre>
11
2009-07-11T19:20:50Z
[ "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(&amp;:description).reject(&amp;: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 &gt;&gt;&gt; bar = Bar() &gt;&gt;&gt; bar.is_frobnicated() False &gt;&gt;&gt; frobnicate(bar) &gt;&gt;&gt; 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>&gt;&gt;&gt; (x*x for x in range(10)) &lt;generator object &lt;genexpr&gt; at 0xb7c1ccd4&gt; &gt;&gt;&gt; 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(&amp;p) </code></pre> <p>Python <strong>2.7+</strong>:</p> <pre><code>&gt;&gt;&gt; {x:str(y*y) for x,y in {1:2, 3:4}.items()} {1: '4', 3: '16'} </code></pre> <p>Ruby:</p> <pre><code>&gt;&gt; Hash[{1=&gt;2, 3=&gt;4}.map{|x,y| [x,(y*y).to_s]}] =&gt; {1=&gt;"4", 3=&gt;"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,114,457
<p>I'm unsure of this, so I add it as an answer first.</p> <h2>Python treats unbound methods as functions</h2> <p>That means you can call a method either like <code>theobject.themethod()</code> or by <code>TheClass.themethod(anobject)</code>.</p> <p>Edit: Although the difference between methods and functions is small in Python, and non-existant in Python 3, it also doesn't exist in Ruby, simply because Ruby doesn't have functions. When you define functions, you are actually defining methods on Object.</p> <p>But you still can't take the method of one class and call it as a function, you would have to rebind it to the object you want to call on, which is much more obstuse.</p>
8
2009-07-11T19:26:02Z
[ "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(&amp;:description).reject(&amp;: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 &gt;&gt;&gt; bar = Bar() &gt;&gt;&gt; bar.is_frobnicated() False &gt;&gt;&gt; frobnicate(bar) &gt;&gt;&gt; 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>&gt;&gt;&gt; (x*x for x in range(10)) &lt;generator object &lt;genexpr&gt; at 0xb7c1ccd4&gt; &gt;&gt;&gt; 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(&amp;p) </code></pre> <p>Python <strong>2.7+</strong>:</p> <pre><code>&gt;&gt;&gt; {x:str(y*y) for x,y in {1:2, 3:4}.items()} {1: '4', 3: '16'} </code></pre> <p>Ruby:</p> <pre><code>&gt;&gt; Hash[{1=&gt;2, 3=&gt;4}.map{|x,y| [x,(y*y).to_s]}] =&gt; {1=&gt;"4", 3=&gt;"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,114,487
<p><strong>Some others from:</strong></p> <p><a href="http://www.ruby-lang.org/en/documentation/ruby-from-other-languages/to-ruby-from-python/" rel="nofollow">http://www.ruby-lang.org/en/documentation/ruby-from-other-languages/to-ruby-from-python/</a></p> <p>(If I have misintrepreted anything or any of these have changed on the Ruby side since that page was updated, someone feel free to edit...)</p> <p>Strings are mutable in Ruby, not in Python (where new strings are created by "changes").</p> <p>Ruby has some enforced case conventions, Python does not.</p> <p>Python has both lists and tuples (immutable lists). Ruby has arrays corresponding to Python lists, but no immutable variant of them.</p> <p>In Python, you can directly access object attributes. In Ruby, it's always via methods.</p> <p>In Ruby, parentheses for method calls are usually optional, but not in Python.</p> <p>Ruby has public, private, and protected to enforce access, instead of Python’s convention of using underscores and name mangling.</p> <p>Python has multiple inheritance. Ruby has "mixins."</p> <p><strong>And another very relevant link:</strong></p> <p><a href="http://c2.com/cgi/wiki?PythonVsRuby" rel="nofollow">http://c2.com/cgi/wiki?PythonVsRuby</a></p> <p>Which, in particular, links to <strong>another good one by Alex Martelli</strong>, who's been also posting a lot of great stuff here on SO:</p> <p><a href="http://groups.google.com/group/comp.lang.python/msg/028422d707512283" rel="nofollow">http://groups.google.com/group/comp.lang.python/msg/028422d707512283</a></p>
9
2009-07-11T19:44:50Z
[ "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(&amp;:description).reject(&amp;: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 &gt;&gt;&gt; bar = Bar() &gt;&gt;&gt; bar.is_frobnicated() False &gt;&gt;&gt; frobnicate(bar) &gt;&gt;&gt; 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>&gt;&gt;&gt; (x*x for x in range(10)) &lt;generator object &lt;genexpr&gt; at 0xb7c1ccd4&gt; &gt;&gt;&gt; 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(&amp;p) </code></pre> <p>Python <strong>2.7+</strong>:</p> <pre><code>&gt;&gt;&gt; {x:str(y*y) for x,y in {1:2, 3:4}.items()} {1: '4', 3: '16'} </code></pre> <p>Ruby:</p> <pre><code>&gt;&gt; Hash[{1=&gt;2, 3=&gt;4}.map{|x,y| [x,(y*y).to_s]}] =&gt; {1=&gt;"4", 3=&gt;"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,114,551
<p>You can import only specific functions from a module in Python. In Ruby, you import the whole list of methods. You could "unimport" them in Ruby, but it's not what it's all about.</p> <p>EDIT:</p> <p>let's take this Ruby module :</p> <pre><code> module Whatever def method1 end def method2 end end </code></pre> <p>if you include it in your code :</p> <pre><code> include Whatever </code></pre> <p>you'll see that both <b>method1</b> and <b>method2</b> have been added to your namespace. You can't import only <b>method1</b>. You either import them both or you don't import them at all. In Python you can import only the methods of your choosing. If this would have a name maybe it would be called selective importing?</p>
18
2009-07-11T20:20:17Z
[ "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(&amp;:description).reject(&amp;: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 &gt;&gt;&gt; bar = Bar() &gt;&gt;&gt; bar.is_frobnicated() False &gt;&gt;&gt; frobnicate(bar) &gt;&gt;&gt; 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>&gt;&gt;&gt; (x*x for x in range(10)) &lt;generator object &lt;genexpr&gt; at 0xb7c1ccd4&gt; &gt;&gt;&gt; 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(&amp;p) </code></pre> <p>Python <strong>2.7+</strong>:</p> <pre><code>&gt;&gt;&gt; {x:str(y*y) for x,y in {1:2, 3:4}.items()} {1: '4', 3: '16'} </code></pre> <p>Ruby:</p> <pre><code>&gt;&gt; Hash[{1=&gt;2, 3=&gt;4}.map{|x,y| [x,(y*y).to_s]}] =&gt; {1=&gt;"4", 3=&gt;"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,114,627
<p>Ruby has a line by line loop over input files (the '-n' flag) from the commandline so it can be used like AWK. This Ruby one-liner: </p> <pre><code>ruby -ne 'END {puts $.}' </code></pre> <p>will count lines like the AWK one-liner:</p> <pre><code>awk 'END{print NR}' </code></pre> <p>Ruby gets feature this through Perl, which took it from AWK as a way of getting sysadmins on board with Perl without having to change the way they do things.</p>
5
2009-07-11T20:57:24Z
[ "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(&amp;:description).reject(&amp;: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 &gt;&gt;&gt; bar = Bar() &gt;&gt;&gt; bar.is_frobnicated() False &gt;&gt;&gt; frobnicate(bar) &gt;&gt;&gt; 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>&gt;&gt;&gt; (x*x for x in range(10)) &lt;generator object &lt;genexpr&gt; at 0xb7c1ccd4&gt; &gt;&gt;&gt; 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(&amp;p) </code></pre> <p>Python <strong>2.7+</strong>:</p> <pre><code>&gt;&gt;&gt; {x:str(y*y) for x,y in {1:2, 3:4}.items()} {1: '4', 3: '16'} </code></pre> <p>Ruby:</p> <pre><code>&gt;&gt; Hash[{1=&gt;2, 3=&gt;4}.map{|x,y| [x,(y*y).to_s]}] =&gt; {1=&gt;"4", 3=&gt;"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,117,852
<h2>Python Example</h2> <p>Functions are first-class variables in Python. You can declare a function, pass it around as an object, and overwrite it:</p> <pre><code>def func(): print "hello" def another_func(f): f() another_func(func) def func2(): print "goodbye" func = func2 </code></pre> <p>This is a fundamental feature of modern scripting languages. JavaScript and Lua do this, too. Ruby doesn't treat functions this way; naming a function calls it.</p> <p>Of course, there are ways to do these things in Ruby, but they're not first-class operations. For example, you can wrap a function with Proc.new to treat it as a variable--but then it's no longer a function; it's an object with a "call" method.</p> <h2>Ruby's functions aren't first-class objects</h2> <p>Ruby functions aren't first-class objects. Functions must be wrapped in an object to pass them around; the resulting object can't be treated like a function. Functions can't be assigned in a first-class manner; instead, a function in its container object must be called to modify them.</p> <pre><code>def func; p "Hello" end def another_func(f); method(f)[] end another_func(:func) # =&gt; "Hello" def func2; print "Goodbye!" self.class.send(:define_method, :func, method(:func2)) func # =&gt; "Goodbye!" method(:func).owner # =&gt; Object func # =&gt; "Goodbye!" self.func # =&gt; "Goodbye!" </code></pre>
28
2009-07-13T05:42:03Z
[ "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(&amp;:description).reject(&amp;: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 &gt;&gt;&gt; bar = Bar() &gt;&gt;&gt; bar.is_frobnicated() False &gt;&gt;&gt; frobnicate(bar) &gt;&gt;&gt; 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>&gt;&gt;&gt; (x*x for x in range(10)) &lt;generator object &lt;genexpr&gt; at 0xb7c1ccd4&gt; &gt;&gt;&gt; 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(&amp;p) </code></pre> <p>Python <strong>2.7+</strong>:</p> <pre><code>&gt;&gt;&gt; {x:str(y*y) for x,y in {1:2, 3:4}.items()} {1: '4', 3: '16'} </code></pre> <p>Ruby:</p> <pre><code>&gt;&gt; Hash[{1=&gt;2, 3=&gt;4}.map{|x,y| [x,(y*y).to_s]}] =&gt; {1=&gt;"4", 3=&gt;"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,118,120
<p>python has named optional arguments</p> <pre><code>def func(a, b=2, c=3): print a, b, c &gt;&gt;&gt; func(1) 1 2 3 &gt;&gt;&gt; func(1, c=4) 1 2 4 </code></pre> <p>AFAIK Ruby has only positioned arguments because b=2 in the function declaration is an affectation that always append.</p>
3
2009-07-13T07:33:41Z
[ "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(&amp;:description).reject(&amp;: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 &gt;&gt;&gt; bar = Bar() &gt;&gt;&gt; bar.is_frobnicated() False &gt;&gt;&gt; frobnicate(bar) &gt;&gt;&gt; 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>&gt;&gt;&gt; (x*x for x in range(10)) &lt;generator object &lt;genexpr&gt; at 0xb7c1ccd4&gt; &gt;&gt;&gt; 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(&amp;p) </code></pre> <p>Python <strong>2.7+</strong>:</p> <pre><code>&gt;&gt;&gt; {x:str(y*y) for x,y in {1:2, 3:4}.items()} {1: '4', 3: '16'} </code></pre> <p>Ruby:</p> <pre><code>&gt;&gt; Hash[{1=&gt;2, 3=&gt;4}.map{|x,y| [x,(y*y).to_s]}] =&gt; {1=&gt;"4", 3=&gt;"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,118,733
<p>"Variables that start with a capital letter becomes constants and can't be modified"</p> <p>Wrong. They can.</p> <p>You only get a warning if you do.</p>
11
2009-07-13T10:35:00Z
[ "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(&amp;:description).reject(&amp;: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 &gt;&gt;&gt; bar = Bar() &gt;&gt;&gt; bar.is_frobnicated() False &gt;&gt;&gt; frobnicate(bar) &gt;&gt;&gt; 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>&gt;&gt;&gt; (x*x for x in range(10)) &lt;generator object &lt;genexpr&gt; at 0xb7c1ccd4&gt; &gt;&gt;&gt; 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(&amp;p) </code></pre> <p>Python <strong>2.7+</strong>:</p> <pre><code>&gt;&gt;&gt; {x:str(y*y) for x,y in {1:2, 3:4}.items()} {1: '4', 3: '16'} </code></pre> <p>Ruby:</p> <pre><code>&gt;&gt; Hash[{1=&gt;2, 3=&gt;4}.map{|x,y| [x,(y*y).to_s]}] =&gt; {1=&gt;"4", 3=&gt;"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,119,232
<p>I would like to mention Python descriptor API that allows one customize object-to-attribute "communication". It is also noteworthy that, in Python, one is free to implement an alternative protocol via overriding the default given through the default implementation of the <code>__getattribute__</code> method. Let me give more details about the aforementioned. Descriptors are regular classes with <code>__get__</code>, <code>__set__</code> and/or <code>__delete__</code> methods. When interpreter encounters something like <code>anObj.anAttr</code>, the following is performed:</p> <ul> <li><code>__getattribute__</code> method of <code>anObj</code> is invoked</li> <li><code>__getattribute__</code> retrieves anAttr object from the class dict</li> <li>it checks whether abAttr object has <code>__get__</code>, <code>__set__</code> or <code>__delete__</code> callable objects</li> <li>the context (i.e., caller object or class, and value, instead of the latter, if we have setter) is passed to the callable object</li> <li>the result is returned.</li> </ul> <p>As was mentioned, this is the default behavior. One is free to change the protocol by re-implementing <code>__getattribute__</code>.</p> <p>This technique is lot more powerful than decorators.</p>
7
2009-07-13T12:46:18Z
[ "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(&amp;:description).reject(&amp;: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 &gt;&gt;&gt; bar = Bar() &gt;&gt;&gt; bar.is_frobnicated() False &gt;&gt;&gt; frobnicate(bar) &gt;&gt;&gt; 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>&gt;&gt;&gt; (x*x for x in range(10)) &lt;generator object &lt;genexpr&gt; at 0xb7c1ccd4&gt; &gt;&gt;&gt; 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(&amp;p) </code></pre> <p>Python <strong>2.7+</strong>:</p> <pre><code>&gt;&gt;&gt; {x:str(y*y) for x,y in {1:2, 3:4}.items()} {1: '4', 3: '16'} </code></pre> <p>Ruby:</p> <pre><code>&gt;&gt; Hash[{1=&gt;2, 3=&gt;4}.map{|x,y| [x,(y*y).to_s]}] =&gt; {1=&gt;"4", 3=&gt;"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,120,798
<p>Surprised to see nothing mentioned of ruby's "method missing" mechanism. I'd give examples of the find_by_... methods in Rails, as an example of the power of that language feature. My guess is that something similar could be implemented in Python, but to my knowledge it isn't there natively.</p>
3
2009-07-13T17:06:35Z
[ "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(&amp;:description).reject(&amp;: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 &gt;&gt;&gt; bar = Bar() &gt;&gt;&gt; bar.is_frobnicated() False &gt;&gt;&gt; frobnicate(bar) &gt;&gt;&gt; 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>&gt;&gt;&gt; (x*x for x in range(10)) &lt;generator object &lt;genexpr&gt; at 0xb7c1ccd4&gt; &gt;&gt;&gt; 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(&amp;p) </code></pre> <p>Python <strong>2.7+</strong>:</p> <pre><code>&gt;&gt;&gt; {x:str(y*y) for x,y in {1:2, 3:4}.items()} {1: '4', 3: '16'} </code></pre> <p>Ruby:</p> <pre><code>&gt;&gt; Hash[{1=&gt;2, 3=&gt;4}.map{|x,y| [x,(y*y).to_s]}] =&gt; {1=&gt;"4", 3=&gt;"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,138,535
<p>Ruby has embedded documentation:</p> <pre><code> =begin You could use rdoc to generate man pages from this documentation =end </code></pre>
2
2009-07-16T15:46:57Z
[ "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(&amp;:description).reject(&amp;: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 &gt;&gt;&gt; bar = Bar() &gt;&gt;&gt; bar.is_frobnicated() False &gt;&gt;&gt; frobnicate(bar) &gt;&gt;&gt; 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>&gt;&gt;&gt; (x*x for x in range(10)) &lt;generator object &lt;genexpr&gt; at 0xb7c1ccd4&gt; &gt;&gt;&gt; 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(&amp;p) </code></pre> <p>Python <strong>2.7+</strong>:</p> <pre><code>&gt;&gt;&gt; {x:str(y*y) for x,y in {1:2, 3:4}.items()} {1: '4', 3: '16'} </code></pre> <p>Ruby:</p> <pre><code>&gt;&gt; Hash[{1=&gt;2, 3=&gt;4}.map{|x,y| [x,(y*y).to_s]}] =&gt; {1=&gt;"4", 3=&gt;"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,139,232
<p>My python's rusty, so some of these may be in python and i just don't remember/never learned in the first place, but here are the first few that I thought of:</p> <h3>Whitespace</h3> <p>Ruby handles whitespace completely different. For starters, you don't need to indent anything (which means it doesn't matter if you use 4 spaces or 1 tab). It also does smart line continuation, so the following is valid:</p> <pre><code>def foo(bar, cow) </code></pre> <p>Basically, if you end with an operator, it figures out what is going on.</p> <h3>Mixins</h3> <p>Ruby has mixins which can extend instances instead of full classes:</p> <pre><code>module Humor def tickle "hee, hee!" end end a = "Grouchy" a.extend Humor a.tickle » "hee, hee!" </code></pre> <h3>Enums</h3> <p>I'm not sure if this is the same as generators, but as of Ruby 1.9 ruby as enums, so </p> <pre><code>&gt;&gt; enum = (1..4).to_enum =&gt; #&lt;Enumerator:0x1344a8&gt; </code></pre> <p>Reference: <a href="http://blog.nuclearsquid.com/writings/ruby-1-9-what-s-new-what-s-changed">http://blog.nuclearsquid.com/writings/ruby-1-9-what-s-new-what-s-changed</a></p> <h3>"Keyword Arguments"</h3> <p>Both of the items listed there are supported in Ruby, although you can't skip default values like that. You can either go in order</p> <pre><code>def foo(a, b=2, c=3) puts "#{a}, #{b}, #{c}" end foo(1,3) &gt;&gt; 1, 3, 3 foo(1,c=5) &gt;&gt; 1, 5, 3 c &gt;&gt; 5 </code></pre> <p>Note that c=5 actually assigns the variable c in the calling scope the value 5, and sets the parameter b the value 5.</p> <p>or you can do it with hashes, which address the second issue</p> <pre><code>def foo(a, others) others[:b] = 2 unless others.include?(:b) others[:c] = 3 unless others.include?(:c) puts "#{a}, #{others[:b]}, #{others[:c]}" end foo(1,:b=&gt;3) &gt;&gt; 1, 3, 3 foo(1,:c=&gt;5) &gt;&gt; 1, 2, 5 </code></pre> <p>Reference: The Pragmatic Progammer's Guide to Ruby</p>
5
2009-07-16T17:53:47Z
[ "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(&amp;:description).reject(&amp;: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 &gt;&gt;&gt; bar = Bar() &gt;&gt;&gt; bar.is_frobnicated() False &gt;&gt;&gt; frobnicate(bar) &gt;&gt;&gt; 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>&gt;&gt;&gt; (x*x for x in range(10)) &lt;generator object &lt;genexpr&gt; at 0xb7c1ccd4&gt; &gt;&gt;&gt; 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(&amp;p) </code></pre> <p>Python <strong>2.7+</strong>:</p> <pre><code>&gt;&gt;&gt; {x:str(y*y) for x,y in {1:2, 3:4}.items()} {1: '4', 3: '16'} </code></pre> <p>Ruby:</p> <pre><code>&gt;&gt; Hash[{1=&gt;2, 3=&gt;4}.map{|x,y| [x,(y*y).to_s]}] =&gt; {1=&gt;"4", 3=&gt;"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,139,857
<p>I'd like to suggest a variant of the original question, "What does Ruby have that Python doesn't, and vice versa?" which admits the disappointing answer, "Well, what can you do with either Ruby or Python that can't be done in Intercal?" Nothing on that level, because Python and Ruby are both part of the vast royal family sitting on the throne of being Turing approximant.</p> <p>But what about this:</p> <p><strong>What can be done gracefully and well in Python that can't be done in Ruby with such beauty and good engineering, or vice versa?</strong></p> <p>That may be much more interesting than mere feature comparison.</p>
12
2009-07-16T19:43:13Z
[ "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(&amp;:description).reject(&amp;: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 &gt;&gt;&gt; bar = Bar() &gt;&gt;&gt; bar.is_frobnicated() False &gt;&gt;&gt; frobnicate(bar) &gt;&gt;&gt; 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>&gt;&gt;&gt; (x*x for x in range(10)) &lt;generator object &lt;genexpr&gt; at 0xb7c1ccd4&gt; &gt;&gt;&gt; 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(&amp;p) </code></pre> <p>Python <strong>2.7+</strong>:</p> <pre><code>&gt;&gt;&gt; {x:str(y*y) for x,y in {1:2, 3:4}.items()} {1: '4', 3: '16'} </code></pre> <p>Ruby:</p> <pre><code>&gt;&gt; Hash[{1=&gt;2, 3=&gt;4}.map{|x,y| [x,(y*y).to_s]}] =&gt; {1=&gt;"4", 3=&gt;"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,302,166
<p>From Ruby's <a href="http://www.ruby-lang.org/en/documentation/ruby-from-other-languages/to-ruby-from-python/" rel="nofollow">website</a>:</p> <p>Similarities As with Python, in Ruby,...</p> <blockquote> <ul> <li>There’s an interactive prompt (called irb).</li> <li>You can read docs on the command line (with the ri command instead of pydoc).</li> <li>There are no special line terminators (except the usual newline).</li> <li>String literals can span multiple lines like Python’s triple-quoted strings.</li> <li>Brackets are for lists, and braces are for dicts (which, in Ruby, are called “hashes”).</li> <li>Arrays work the same (adding them makes one long array, but composing them like this <code>a3 = [ a1, a2 ]</code> gives you an array of arrays).</li> <li>Objects are strongly and dynamically typed.</li> <li>Everything is an object, and variables are just references to objects.</li> <li>Although the keywords are a bit different, exceptions work about the same.</li> <li>You’ve got embedded doc tools (Ruby’s is called rdoc).</li> </ul> </blockquote> <p>Differences Unlike Python, in Ruby,...</p> <blockquote> <ul> <li>Strings are mutable.</li> <li>You can make constants (variables whose value you don’t intend to change).</li> <li>There are some enforced case-conventions (ex. class names start with a capital letter, variables start with a lowercase letter).</li> <li>There’s only one kind of list container (an Array), and it’s mutable.</li> <li>Double-quoted strings allow escape sequences (like \t) and a special “expression substitution” syntax (which allows you to insert the results of Ruby expressions directly into other strings without having to "add " + "strings " + "together"). Single-quoted strings are like Python’s r"raw strings".</li> <li>There are no “new style” and “old style” classes. Just one kind.</li> <li>You never directly access attributes. With Ruby, it’s all method calls.</li> <li>Parentheses for method calls are usually optional.</li> <li>There’s public, private, and protected to enforce access, instead of Python’s <code>_voluntary_ underscore __convention__</code>.</li> <li>“mixin’s” are used instead of multiple inheritance.</li> <li>You can add or modify the methods of built-in classes. Both languages let you open up and modify classes at any point, but Python prevents modification of built-ins — Ruby does not.</li> <li>You’ve got true and false instead of True and False (and nil instead of None).</li> <li>When tested for truth, only false and nil evaluate to a false value. Everything else is true (including 0, 0.0, "", and []).</li> <li>It’s elsif instead of elif.</li> <li>It’s require instead of import. Otherwise though, usage is the same.</li> <li>The usual-style comments on the line(s) above things (instead of docstrings below them) are used for generating docs.</li> <li>There are a number of shortcuts that, although give you more to remember, you quickly learn. They tend to make Ruby fun and very productive.</li> </ul> </blockquote>
16
2009-08-19T19:32:19Z
[ "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(&amp;:description).reject(&amp;: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 &gt;&gt;&gt; bar = Bar() &gt;&gt;&gt; bar.is_frobnicated() False &gt;&gt;&gt; frobnicate(bar) &gt;&gt;&gt; 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>&gt;&gt;&gt; (x*x for x in range(10)) &lt;generator object &lt;genexpr&gt; at 0xb7c1ccd4&gt; &gt;&gt;&gt; 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(&amp;p) </code></pre> <p>Python <strong>2.7+</strong>:</p> <pre><code>&gt;&gt;&gt; {x:str(y*y) for x,y in {1:2, 3:4}.items()} {1: '4', 3: '16'} </code></pre> <p>Ruby:</p> <pre><code>&gt;&gt; Hash[{1=&gt;2, 3=&gt;4}.map{|x,y| [x,(y*y).to_s]}] =&gt; {1=&gt;"4", 3=&gt;"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,573,879
<p>Somewhat more on the infrastructure side:</p> <ul> <li><p>Python has much better integration with C++ (via things like <a href="http://www.boost.org/doc/libs/1%5F40%5F0/libs/python/doc/index.html" rel="nofollow">Boost.Python</a>, <a href="http://www.riverbankcomputing.com/software/sip/intro" rel="nofollow">SIP</a>, and <a href="http://www.language-binding.net/pyplusplus/pyplusplus.html" rel="nofollow">Py++</a>) than Ruby, where the options seem to be either write directly against the Ruby interpreter API (which you can do with Python as well, of course, but in both cases doing so is low level, tedious, and error prone) or use SWIG (which, while it works and definitely is great if you want to support many languages, isn't nearly as nice as Boost.Python or SIP if you are specifically looking to bind C++).</p></li> <li><p>Python has a number of web application environments (Django, Pylons/Turbogears, web.py, probably at least half a dozen others), whereas Ruby (effectively) has one: Rails. (Other Ruby web frameworks do exist, but seemingly have a hard time getting much traction against Rails). Is this aspect good or bad? Hard to say, and probably quite subjective; I can easily imagine arguments that the Python situation is better and that the Ruby situation is better.</p></li> <li><p>Culturally, the Python and Ruby communities seem somewhat different, but I can only hint at this as I don't have that much experience interacting with the Ruby community. I'm adding this mostly in the hopes that someone who has a lot of experience with both can amplify (or reject) this statement.</p></li> </ul>
11
2009-10-15T17:26:53Z
[ "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(&amp;:description).reject(&amp;: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 &gt;&gt;&gt; bar = Bar() &gt;&gt;&gt; bar.is_frobnicated() False &gt;&gt;&gt; frobnicate(bar) &gt;&gt;&gt; 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>&gt;&gt;&gt; (x*x for x in range(10)) &lt;generator object &lt;genexpr&gt; at 0xb7c1ccd4&gt; &gt;&gt;&gt; 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(&amp;p) </code></pre> <p>Python <strong>2.7+</strong>:</p> <pre><code>&gt;&gt;&gt; {x:str(y*y) for x,y in {1:2, 3:4}.items()} {1: '4', 3: '16'} </code></pre> <p>Ruby:</p> <pre><code>&gt;&gt; Hash[{1=&gt;2, 3=&gt;4}.map{|x,y| [x,(y*y).to_s]}] =&gt; {1=&gt;"4", 3=&gt;"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,981,429
<p>Another difference in lambdas between Python and Ruby is demonstrated by Paul Graham's <a href="http://www.paulgraham.com/accgen.html" rel="nofollow">Accumulator Generator</a> problem. Reprinted here:</p> <blockquote>Write a function foo that takes a number n and returns a function that takes a number i, and returns n incremented by i. Note: (a) that's number, not integer, (b) that's incremented by, not plus.</blockquote> <p>In Ruby, you can do this:</p> <pre><code>def foo(n) lambda {|i| n += i } end </code></pre> <p>In Python, you'd create an object to hold the state of n:</p> <pre><code>class foo(object): def __init__(self, n): self.n = n def __call__(self, i): self.n += i return self.n </code></pre> <p>Some folks might prefer the explicit Python approach as being clearer conceptually, even if it's a bit more verbose. You store state like you do for anything else. You just need to wrap your head around the idea of callable objects. But regardless of which approach one prefers aesthetically, it does show one respect in which Ruby lambdas are more powerful constructs than Python's.</p>
3
2009-12-30T17:45:19Z
[ "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(&amp;:description).reject(&amp;: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 &gt;&gt;&gt; bar = Bar() &gt;&gt;&gt; bar.is_frobnicated() False &gt;&gt;&gt; frobnicate(bar) &gt;&gt;&gt; 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>&gt;&gt;&gt; (x*x for x in range(10)) &lt;generator object &lt;genexpr&gt; at 0xb7c1ccd4&gt; &gt;&gt;&gt; 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(&amp;p) </code></pre> <p>Python <strong>2.7+</strong>:</p> <pre><code>&gt;&gt;&gt; {x:str(y*y) for x,y in {1:2, 3:4}.items()} {1: '4', 3: '16'} </code></pre> <p>Ruby:</p> <pre><code>&gt;&gt; Hash[{1=&gt;2, 3=&gt;4}.map{|x,y| [x,(y*y).to_s]}] =&gt; {1=&gt;"4", 3=&gt;"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
2,043,465
<p><a href="http://c2.com/cgi/wiki?PythonVsRuby" rel="nofollow">http://c2.com/cgi/wiki?PythonVsRuby</a><br> <a href="http://c2.com/cgi/wiki?SwitchedFromPythonToRuby" rel="nofollow">http://c2.com/cgi/wiki?SwitchedFromPythonToRuby</a><br> <a href="http://c2.com/cgi/wiki?SwitchedFromRubyToPython" rel="nofollow">http://c2.com/cgi/wiki?SwitchedFromRubyToPython</a><br> <a href="http://c2.com/cgi/wiki?UsingPythonDontNeedRuby" rel="nofollow">http://c2.com/cgi/wiki?UsingPythonDontNeedRuby</a><br> <a href="http://c2.com/cgi/wiki?UsingRubyDontNeedPython" rel="nofollow">http://c2.com/cgi/wiki?UsingRubyDontNeedPython</a> </p>
2
2010-01-11T17:13:23Z
[ "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(&amp;:description).reject(&amp;: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 &gt;&gt;&gt; bar = Bar() &gt;&gt;&gt; bar.is_frobnicated() False &gt;&gt;&gt; frobnicate(bar) &gt;&gt;&gt; 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>&gt;&gt;&gt; (x*x for x in range(10)) &lt;generator object &lt;genexpr&gt; at 0xb7c1ccd4&gt; &gt;&gt;&gt; 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(&amp;p) </code></pre> <p>Python <strong>2.7+</strong>:</p> <pre><code>&gt;&gt;&gt; {x:str(y*y) for x,y in {1:2, 3:4}.items()} {1: '4', 3: '16'} </code></pre> <p>Ruby:</p> <pre><code>&gt;&gt; Hash[{1=&gt;2, 3=&gt;4}.map{|x,y| [x,(y*y).to_s]}] =&gt; {1=&gt;"4", 3=&gt;"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
3,073,441
<p><sub>Shamelessly copy/pasted from: <a href="http://stackoverflow.com/users/95810/alex-martelli">Alex Martelli</a> answer on <em>"<a href="http://groups.google.com/group/comp.lang.python/msg/028422d707512283" rel="nofollow">What's better about Ruby than Python</a>"</em> thread from <a href="http://groups.google.com/group/comp.lang.python" rel="nofollow" title="comp.lang.python">comp.lang.python</a> mailing list. </sub></p> <blockquote> <p>Aug 18 2003, 10:50 am Erik Max Francis wrote:</p> <blockquote> <p>"Brandon J. Van Every" wrote:</p> <blockquote> <p>What's better about Ruby than Python? I'm sure there's something. What is it?</p> </blockquote> <p>Wouldn't it make much more sense to ask Ruby people this, rather than Python people?</p> </blockquote> <p>Might, or might not, depending on one's purposes -- for example, if one's purposes include a "sociological study" of the Python community, then putting questions to that community is likely to prove more revealing of information about it, than putting them elsewhere:-).</p> <p>Personally, I gladly took the opportunity to follow Dave Thomas' one-day Ruby tutorial at last OSCON. Below a thin veneer of syntax differences, I find Ruby and Python amazingly similar -- if I was computing the minimum spanning tree among just about any set of languages, I'm pretty sure Python and Ruby would be the first two leaves to coalesce into an intermediate node:-).</p> <p>Sure, I do get weary, in Ruby, of typing the silly "end" at the end of each block (rather than just unindenting) -- but then I do get to avoid typing the equally-silly ':' which Python requires at the <em>start</em> of each block, so that's almost a wash:-). Other syntax differences such as '@foo' versus 'self.foo', or the higher significance of case in Ruby vs Python, are really just about as irrelevant to me.</p> <p>Others no doubt base their choice of programming languages on just such issues, and they generate the hottest debates -- but to me that's just an example of one of Parkinson's Laws in action (the amount on debate on an issue is inversely proportional to the issue's actual importance).</p> <p><strong>Edit</strong> (by AM 6/19/2010 11:45): this is also known as "painting the bikeshed" (or, for short, "bikeshedding") -- the reference is, again, to Northcote Parkinson, who gave "debates on what color to paint the bikeshed" as a typical example of "hot debates on trivial topics". (end-of-Edit).</p> <p>One syntax difference that I do find important, and in Python's favor -- but other people will no doubt think just the reverse -- is "how do you call a function which takes no parameters". In Python (like in C), to call a function you always apply the "call operator" -- trailing parentheses just after the object you're calling (inside those trailing parentheses go the args you're passing in the call -- if you're passing no args, then the parentheses are empty). This leaves the mere mention of <em>any</em> object, with no operator involved, as meaning just a reference to the object -- in any context, without special cases, exceptions, ad-hoc rules, and the like. In Ruby (like in Pascal), to call a function WITH arguments you pass the args (normally in parentheses, though that is not invariably the case) -- BUT if the function takes no args then simply mentioning the function implicitly calls it. This may meet the expectations of many people (at least, no doubt, those whose only previous experience of programming was with Pascal, or other languages with similar "implicit calling", such as Visual Basic) -- but to me, it means the mere mention of an object may EITHER mean a reference to the object, OR a call to the object, depending on the object's type -- and in those cases where I can't get a reference to the object by merely mentioning it I will need to use explicit "give me a reference to this, DON'T call it!" operators that aren't needed otherwise. I feel this impacts the "first-classness" of functions (or methods, or other callable objects) and the possibility of interchanging objects smoothly. Therefore, to me, this specific syntax difference is a serious black mark against Ruby -- but I do understand why others would thing otherwise, even though I could hardly disagree more vehemently with them:-).</p> <p>Below the syntax, we get into some important differences in elementary semantics -- for example, strings in Ruby are mutable objects (like in C++), while in Python they are not mutable (like in Java, or I believe C#). Again, people who judge primarily by what they're already familiar with may think this is a plus for Ruby (unless they're familiar with Java or C#, of course:-). Me, I think immutable strings are an excellent idea (and I'm not surprised that Java, independently I think, reinvented that idea which was already in Python), though I wouldn't mind having a "mutable string buffer" type as well (and ideally one with better ease-of-use than Java's own "string buffers"); and I don't give this judgment because of familiarity -- before studying Java, apart from functional programming languages where <em>all</em> data are immutable, all the languages I knew had mutable strings -- yet when I first saw the immutable-string idea in Java (which I learned well before I learned Python), it immediately struck me as excellent, a very good fit for the reference-semantics of a higher level programming language (as opposed to the value-semantics that fit best with languages closer to the machine and farther from applications, such as C) with strings as a first-class, built-in (and pretty crucial) data type.</p> <p>Ruby does have some advantages in elementary semantics -- for example, the removal of Python's "lists vs tuples" exceedingly subtle distinction. But mostly the score (as I keep it, with simplicity a big plus and subtle, clever distinctions a notable minus) is against Ruby (e.g., having both closed and half-open intervals, with the notations a..b and a...b [anybody wants to claim that it's <em>obvious</em> which is which?-)], is silly -- IMHO, of course!). Again, people who consider having a lot of similar but subtly different things at the core of a language a PLUS, rather than a MINUS, will of course count these "the other way around" from how I count them:-).</p> <p>Don't be misled by these comparisons into thinking the two languages are <em>very</em> different, mind you. They aren't. But if I'm asked to compare "capelli d'angelo" to "spaghettini", after pointing out that these two kinds of pasta are just about undistinguishable to anybody and interchangeable in any dish you might want to prepare, I would then inevitably have to move into microscopic examination of how the lengths and diameters imperceptibly differ, how the ends of the strands are tapered in one case and not in the other, and so on -- to try and explain why I, personally, would rather have capelli d'angelo as the pasta in any kind of broth, but would prefer spaghettini as the pastasciutta to go with suitable sauces for such long thin pasta forms (olive oil, minced garlic, minced red peppers, and finely ground anchovies, for example - but if you sliced the garlic and peppers instead of mincing them, then you should choose the sounder body of spaghetti rather than the thinner evanescence of spaghettini, and would be well advised to forego the achovies and add instead some fresh spring basil [or even -- I'm a heretic...! -- light mint...] leaves -- at the very last moment before serving the dish). Ooops, sorry, it shows that I'm traveling abroad and haven't had pasta for a while, I guess. But the analogy is still pretty good!-)</p> <p>So, back to Python and Ruby, we come to the two biggies (in terms of language proper -- leaving the libraries, and other important ancillaries such as tools and environments, how to embed/extend each language, etc, etc, out of it for now -- they wouldn't apply to all IMPLEMENTATIONS of each language anyway, e.g., Jython vs Classic Python being two implementations of the Python language!):</p> <ol> <li><p>Ruby's iterators and codeblocks vs Python's iterators and generators;</p></li> <li><p>Ruby's TOTAL, unbridled "dynamicity", including the ability<br> to "reopen" any existing class, including all built-in ones, and change its behavior at run-time -- vs Python's vast but <em>bounded</em> dynamicity, which never changes the behavior of existing built-in classes and their instances.</p></li> </ol> <p>Personally, I consider <a href="http://stackoverflow.com/users/95810/alex-martelli">1</a> a wash (the differences are so deep that I could easily see people hating either approach and revering the other, but on MY personal scales the pluses and minuses just about even up); and <a href="http://groups.google.com/group/comp.lang.python/msg/028422d707512283" rel="nofollow">2</a> a crucial issue -- one that makes Ruby much more suitable for "tinkering", BUT Python equally more suitable for use in large production applications. It's funny, in a way, because both languages are so MUCH more dynamic than most others, that in the end the key difference between them from my POV should hinge on that -- that Ruby "goes to eleven" in this regard (the reference here is to "Spinal Tap", of course). In Ruby, there are no limits to my creativity -- if I decide that all string comparisons must become case-insensitive, <em>I CAN DO THAT</em>! I.e., I can dynamically alter the built-in string class so that a = "Hello World" b = "hello world" if a == b print "equal!\n" else print "different!\n" end WILL print "equal". In python, there is NO way I can do that. For the purposes of metaprogramming, implementing experimental frameworks, and the like, this amazing dynamic ability of Ruby is <em>extremely</em> appealing. BUT -- if we're talking about large applications, developed by many people and maintained by even more, including all kinds of libraries from diverse sources, and needing to go into production in client sites... well, I don't WANT a language that is QUITE so dynamic, thank you very much. I loathe the very idea of some library unwittingly breaking other unrelated ones that rely on those strings being different -- that's the kind of deep and deeply hidden "channel", between pieces of code that LOOK separate and SHOULD BE separate, that spells d-e-a-t-h in large-scale programming. By letting any module affect the behavior of any other "covertly", the ability to mutate the semantics of built-in types is just a BAD idea for production application programming, just as it's cool for tinkering.</p> <p>If I had to use Ruby for such a large application, I would try to rely on coding-style restrictions, lots of tests (to be rerun whenever ANYTHING changes -- even what should be totally unrelated...), and the like, to prohibit use of this language feature. But NOT having the feature in the first place is even better, in my opinion -- just as Python itself would be an even better language for application programming if a certain number of built-ins could be "nailed down", so I KNEW that, e.g., len("ciao") is 4 (rather than having to worry subliminally about whether somebody's changed the binding of name 'len' in the <strong>builtins</strong> module...). I do hope that eventually Python does "nail down" its built-ins.</p> <p>But the problem's minor, since rebinding built-ins is quite a deprecated as well as a rare practice in Python. In Ruby, it strikes me as major -- just like the <em>too powerful</em> macro facilities of other languages (such as, say, Dylan) present similar risks in my own opinion (I do hope that Python never gets such a powerful macro system, no matter the allure of "letting people define their own domain-specific little languages embedded in the language itself" -- it would, IMHO, impair Python's wonderful usefulness for application programming, by presenting an "attractive nuisance" to the would-be tinkerer who lurks in every programmer's heart...).</p> <p>Alex</p> </blockquote>
11
2010-06-18T22:24:35Z
[ "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(&amp;:description).reject(&amp;: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 &gt;&gt;&gt; bar = Bar() &gt;&gt;&gt; bar.is_frobnicated() False &gt;&gt;&gt; frobnicate(bar) &gt;&gt;&gt; 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>&gt;&gt;&gt; (x*x for x in range(10)) &lt;generator object &lt;genexpr&gt; at 0xb7c1ccd4&gt; &gt;&gt;&gt; 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(&amp;p) </code></pre> <p>Python <strong>2.7+</strong>:</p> <pre><code>&gt;&gt;&gt; {x:str(y*y) for x,y in {1:2, 3:4}.items()} {1: '4', 3: '16'} </code></pre> <p>Ruby:</p> <pre><code>&gt;&gt; Hash[{1=&gt;2, 3=&gt;4}.map{|x,y| [x,(y*y).to_s]}] =&gt; {1=&gt;"4", 3=&gt;"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
3,397,341
<blockquote> <p>In Ruby, when you import a file with require, all the things defined in that file will end up in your global namespace.</p> </blockquote> <p>With <a href="http://github.com/soveran/cargo" rel="nofollow">Cargo</a> you can "<em>require libraries without cluttering your namespace</em>".</p> <pre><code># foo-1.0.0.rb class Foo VERSION = "1.0.0" end # foo-2.0.0.rb class Foo VERSION = "2.0.0" end </code></pre> <pre> >> Foo1 = import("foo-1.0.0") >> Foo2 = import("foo-2.0.0") >> Foo1::VERSION => "1.0.0" >> Foo2::VERSION => "2.0.0" </pre>
2
2010-08-03T14:13:07Z
[ "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(&amp;:description).reject(&amp;: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 &gt;&gt;&gt; bar = Bar() &gt;&gt;&gt; bar.is_frobnicated() False &gt;&gt;&gt; frobnicate(bar) &gt;&gt;&gt; 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>&gt;&gt;&gt; (x*x for x in range(10)) &lt;generator object &lt;genexpr&gt; at 0xb7c1ccd4&gt; &gt;&gt;&gt; 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(&amp;p) </code></pre> <p>Python <strong>2.7+</strong>:</p> <pre><code>&gt;&gt;&gt; {x:str(y*y) for x,y in {1:2, 3:4}.items()} {1: '4', 3: '16'} </code></pre> <p>Ruby:</p> <pre><code>&gt;&gt; Hash[{1=&gt;2, 3=&gt;4}.map{|x,y| [x,(y*y).to_s]}] =&gt; {1=&gt;"4", 3=&gt;"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
3,473,981
<p>At this stage, Python still has better unicode support</p>
6
2010-08-13T04:50:20Z
[ "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(&amp;:description).reject(&amp;: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 &gt;&gt;&gt; bar = Bar() &gt;&gt;&gt; bar.is_frobnicated() False &gt;&gt;&gt; frobnicate(bar) &gt;&gt;&gt; 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>&gt;&gt;&gt; (x*x for x in range(10)) &lt;generator object &lt;genexpr&gt; at 0xb7c1ccd4&gt; &gt;&gt;&gt; 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(&amp;p) </code></pre> <p>Python <strong>2.7+</strong>:</p> <pre><code>&gt;&gt;&gt; {x:str(y*y) for x,y in {1:2, 3:4}.items()} {1: '4', 3: '16'} </code></pre> <p>Ruby:</p> <pre><code>&gt;&gt; Hash[{1=&gt;2, 3=&gt;4}.map{|x,y| [x,(y*y).to_s]}] =&gt; {1=&gt;"4", 3=&gt;"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
4,102,608
<p>Ultimately all answers are going to be subjective at some level, and the answers posted so far pretty much prove that you can't point to any one feature that isn't doable in the other language in an equally nice (if not similar) way, since both languages are very concise and expressive.</p> <p>I like Python's syntax. However, you have to dig a bit deeper than syntax to find the true beauty of Ruby. There is zenlike beauty in Ruby's consistency. While no trivial example can possibly explain this completely, I'll try to come up with one here just to explain what I mean.</p> <p>Reverse the words in this string: </p> <pre><code>sentence = "backwards is sentence This" </code></pre> <p>When you think about how you would do it, you'd do the following:</p> <ol> <li>Split the sentence up into words</li> <li>Reverse the words</li> <li>Re-join the words back into a string</li> </ol> <p>In Ruby, you'd do this:</p> <pre><code>sentence.split.reverse.join ' ' </code></pre> <p>Exactly as you think about it, in the same sequence, one method call after another. </p> <p>In python, it would look more like this:</p> <pre><code>" ".join(reversed(sentence.split())) </code></pre> <p>It's not hard to understand, but it doesn't quite have the same flow. The subject (sentence) is buried in the middle. The operations are a mix of functions and object methods. This is a trivial example, but one discovers many different examples when really working with and understanding Ruby, especially on non-trivial tasks.</p>
26
2010-11-05T00:24:23Z
[ "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(&amp;:description).reject(&amp;: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 &gt;&gt;&gt; bar = Bar() &gt;&gt;&gt; bar.is_frobnicated() False &gt;&gt;&gt; frobnicate(bar) &gt;&gt;&gt; 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>&gt;&gt;&gt; (x*x for x in range(10)) &lt;generator object &lt;genexpr&gt; at 0xb7c1ccd4&gt; &gt;&gt;&gt; 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(&amp;p) </code></pre> <p>Python <strong>2.7+</strong>:</p> <pre><code>&gt;&gt;&gt; {x:str(y*y) for x,y in {1:2, 3:4}.items()} {1: '4', 3: '16'} </code></pre> <p>Ruby:</p> <pre><code>&gt;&gt; Hash[{1=&gt;2, 3=&gt;4}.map{|x,y| [x,(y*y).to_s]}] =&gt; {1=&gt;"4", 3=&gt;"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
4,104,294
<p>I like the fundamental differences in the way that Ruby and Python method invocations operate.</p> <p>Ruby methods are invoked via a form "message passing" and need not be explicitly first-class functions (there are ways to <a href="http://stackoverflow.com/questions/1933390/getting-ruby-function-object-itself">lift methods</a> into "proper" function-objects) -- in this aspect Ruby is similar to Smalltalk.</p> <p>Python works much more like JavaScript (or even Perl) where methods <em>are</em> functions which are invoked directly (there is also stored context information, but...)</p> <p>While this might seem like a "minor" detail it is really just the surface of how <em>different</em> the Ruby and Python designs are. (On the other hand, they are also quite the same :-)</p> <p>One practical difference is the concept of <code>method_missing</code> in Ruby (which, for better or worse, seems to be used in some popular frameworks). In Python, one can (at least partially) emulate the behavior using _<em>getattr</em>_/_<em>getattribute</em>_, albeit non-idiomatically.</p>
1
2010-11-05T08:06:14Z
[ "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(&amp;:description).reject(&amp;: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 &gt;&gt;&gt; bar = Bar() &gt;&gt;&gt; bar.is_frobnicated() False &gt;&gt;&gt; frobnicate(bar) &gt;&gt;&gt; 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>&gt;&gt;&gt; (x*x for x in range(10)) &lt;generator object &lt;genexpr&gt; at 0xb7c1ccd4&gt; &gt;&gt;&gt; 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(&amp;p) </code></pre> <p>Python <strong>2.7+</strong>:</p> <pre><code>&gt;&gt;&gt; {x:str(y*y) for x,y in {1:2, 3:4}.items()} {1: '4', 3: '16'} </code></pre> <p>Ruby:</p> <pre><code>&gt;&gt; Hash[{1=&gt;2, 3=&gt;4}.map{|x,y| [x,(y*y).to_s]}] =&gt; {1=&gt;"4", 3=&gt;"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
4,840,551
<h2>Ruby gets inheritance right with Single Inheritance</h2> <p>Did I mention Ruby has an EPIC community of developers. Ninja theme inspired by <a href="http://techoctave.com/c7/posts/46-object-oriented-ruby-classes-mixins-and-jedi" rel="nofollow">Object Oriented Ruby: Classes, Mixins and Jedi</a>.</p> <p>Ruby gets inheritance right with Single Inheritance! Needing to use multiple inheritance to express domain relationships is a symptom of an improperly designed system. The confusion multiple inheritance creates isn't worth the added functionality.</p> <p>Say you have a method called kick:</p> <pre><code>def kick puts "kick executed." end </code></pre> <p>What if <em>kick</em> is defined in both class <em>Ninjutsu</em> and class <em>Shaolin</em>? Multiple Inheritance fails here and that's why Python fails:</p> <pre><code>class Mortal &lt; Ninjutsu, Shaolin def initialize puts "mortal pwnage." end end </code></pre> <p>In Ruby if you need a Ninja, you create an instance of the <em>Ninja</em> class. If you need a Shaolin master, you create an instance of the <em>Shaolin</em> class.</p> <pre><code>ninja = Ninjutsu.new ninja.kick or master = Shaolin.new master.kick </code></pre> <h2>Ruby gets inheritance right with Mixins</h2> <p>There might be the off chance that both a Ninja and a Shaolin master share the same kick technique. Read that again - both share the same behavior - nothing else! Python would encourage you to roll a whole new class. Not with Ruby! In Ruby you simply use a Mixin:</p> <pre><code>module Katas def kick puts "Temporal Whip Kick." end end </code></pre> <p>and simply Mixin the Katas module into your Ruby Class:</p> <pre><code>require 'Katas' class Moral &lt; Ninjutsu include Katas def initialize puts "mortal pwnage." end end </code></pre> <p>Then the behavior gets shared - which is what you were really going for. Not an entire class. That's the biggest difference between Ruby and Python - Ruby gets inheritance right!</p>
-3
2011-01-30T01:15:14Z
[ "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(&amp;:description).reject(&amp;: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 &gt;&gt;&gt; bar = Bar() &gt;&gt;&gt; bar.is_frobnicated() False &gt;&gt;&gt; frobnicate(bar) &gt;&gt;&gt; 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>&gt;&gt;&gt; (x*x for x in range(10)) &lt;generator object &lt;genexpr&gt; at 0xb7c1ccd4&gt; &gt;&gt;&gt; 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(&amp;p) </code></pre> <p>Python <strong>2.7+</strong>:</p> <pre><code>&gt;&gt;&gt; {x:str(y*y) for x,y in {1:2, 3:4}.items()} {1: '4', 3: '16'} </code></pre> <p>Ruby:</p> <pre><code>&gt;&gt; Hash[{1=&gt;2, 3=&gt;4}.map{|x,y| [x,(y*y).to_s]}] =&gt; {1=&gt;"4", 3=&gt;"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
4,916,756
<p>Syntax is not a minor thing, it has a direct impact on how we think. It also has a direct effect on the rules we create for the systems we use. As an example we have the order of operations because of the way we write mathematical equations or sentences. The standard notation for mathematics allows people to read it more than one way and arrive at different answers given the same equation. If we had used prefix or postfix notation we would have created rules to distinguish what the numbers to be manipulated were rather than only having rules for the order in which to compute values.</p> <p>The standard notation makes it plain what numbers we are talking about while making the order in which to compute them ambiguous. Prefix and postfix notation make the order in which to compute plain while making the numbers ambiguous. Python would already have multiline lambdas if it were not for the difficulties caused by the syntactic whitespace. (Proposals do exist for pulling this kind of thing off without necessarily adding explicit block delimiters.)</p> <p>I find it easier to write conditions where I want something to occur if a condition is <em>false</em> much easier to write with the unless statement in Ruby than the semantically equivalent "if-not" construction in Ruby or other languages for example. If most of the languages that people are using today are equal in power, how can the syntax of each language be considered a trivial thing? After specific features like blocks and inheritance mechanisms etc. syntax is the most important part of a language,hardly a superficial thing.</p> <p>What is superficial are the aesthetic qualities of beauty that we ascribe to syntax. Aesthetics have nothing to do with how our cognition works, syntax does.</p>
4
2011-02-06T22:49:27Z
[ "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(&amp;:description).reject(&amp;: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 &gt;&gt;&gt; bar = Bar() &gt;&gt;&gt; bar.is_frobnicated() False &gt;&gt;&gt; frobnicate(bar) &gt;&gt;&gt; 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>&gt;&gt;&gt; (x*x for x in range(10)) &lt;generator object &lt;genexpr&gt; at 0xb7c1ccd4&gt; &gt;&gt;&gt; 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(&amp;p) </code></pre> <p>Python <strong>2.7+</strong>:</p> <pre><code>&gt;&gt;&gt; {x:str(y*y) for x,y in {1:2, 3:4}.items()} {1: '4', 3: '16'} </code></pre> <p>Ruby:</p> <pre><code>&gt;&gt; Hash[{1=&gt;2, 3=&gt;4}.map{|x,y| [x,(y*y).to_s]}] =&gt; {1=&gt;"4", 3=&gt;"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
5,089,827
<p>I am surprised that no one has mentioned Singleton methods.</p> <pre><code>a=[] b=[] def b.some_method do ... end b.some_method #fine a.some_method #raises exception </code></pre> <p>It gives granular control over the open class concept. You can also use Eigenclasses to mixin a module into a specific object instead of all objects of a given class.</p> <pre><code>o=Object.new class &lt;&lt; o include SomeModule end </code></pre> <p>Python also doesn't have a switch statement without using ugly hacks which can decrease code readability.</p> <p>Ruby has no statements,only expressions. This add a lot of flexibility.</p> <p>You can get a reference to any method and pass that around.</p> <pre><code>a=[] m=a.method :map #m is now referencing an instance of Method and can be passed like any other reference to an object and is invoked with the call method and an optional block </code></pre> <p>Easy nested lexical scope giving controlled global variables.</p> <pre><code>lambda { global=nil def Kernel.some_global= val global||=val end def Kernel.some_global global end }.call </code></pre> <p>Once that lambda is invoked, global is out of scope, but you can set it(only once in this example) and then access it anywhere in your program. Hopefully the value of this is clear.</p> <p>Creating a DSL is much easier in Ruby than in Python. Creating something like Rake or RSpec in Python is possible but what a nightmare it would be. So to answer your question Ruby has much more flexibility than Python. It is not at the flexibility level of Lisp, but is arguably the most flexible OO language.</p> <p>Python is great and all but it is so stiff compared to Ruby. Ruby is less verbose, more readable(as in it reads much closer to a natural language), python reads like english translated to french.</p> <p>Python is also annoying in that its community is always in lock-step with Guido, if Guido says that you don't need feature X, everyone in the community believes it and parrots it. It leads to a stale community, kind of like the Java community that simply can't understand what anonymous functions and closures buy you. The Python community is not as annoying as Haskell's, but still. </p>
-2
2011-02-23T10:45:49Z
[ "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(&amp;:description).reject(&amp;: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 &gt;&gt;&gt; bar = Bar() &gt;&gt;&gt; bar.is_frobnicated() False &gt;&gt;&gt; frobnicate(bar) &gt;&gt;&gt; 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>&gt;&gt;&gt; (x*x for x in range(10)) &lt;generator object &lt;genexpr&gt; at 0xb7c1ccd4&gt; &gt;&gt;&gt; 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(&amp;p) </code></pre> <p>Python <strong>2.7+</strong>:</p> <pre><code>&gt;&gt;&gt; {x:str(y*y) for x,y in {1:2, 3:4}.items()} {1: '4', 3: '16'} </code></pre> <p>Ruby:</p> <pre><code>&gt;&gt; Hash[{1=&gt;2, 3=&gt;4}.map{|x,y| [x,(y*y).to_s]}] =&gt; {1=&gt;"4", 3=&gt;"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
5,109,018
<p>The nested lexical scope example that someone gave gives several benefits.</p> <ol> <li>"Safer" globals</li> <li>It is one method to embed DSL's into your program. </li> </ol> <p>I think that is a very good example of the differences between the two languages. Ruby is simply more flexible. Python can be flexible, but you often have to do extreme contortions to get there, which makes it not worth the hassle.</p> <p>Sorry for not posting under the original answer, I guess I don't have privileges to do that.</p>
0
2011-02-24T18:43:50Z
[ "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(&amp;:description).reject(&amp;: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 &gt;&gt;&gt; bar = Bar() &gt;&gt;&gt; bar.is_frobnicated() False &gt;&gt;&gt; frobnicate(bar) &gt;&gt;&gt; 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>&gt;&gt;&gt; (x*x for x in range(10)) &lt;generator object &lt;genexpr&gt; at 0xb7c1ccd4&gt; &gt;&gt;&gt; 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(&amp;p) </code></pre> <p>Python <strong>2.7+</strong>:</p> <pre><code>&gt;&gt;&gt; {x:str(y*y) for x,y in {1:2, 3:4}.items()} {1: '4', 3: '16'} </code></pre> <p>Ruby:</p> <pre><code>&gt;&gt; Hash[{1=&gt;2, 3=&gt;4}.map{|x,y| [x,(y*y).to_s]}] =&gt; {1=&gt;"4", 3=&gt;"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
5,560,856
<h2>More about Ruby's blocks</h2> <p>It has being suggested that Ruby's blocks may be "substituted" by Python's context managers. In fact, blocks allow more than Python's context managers can do.</p> <p>The receiving method of a block could execute the block within the context of some object, thus allowing the block to call methods otherwise unreacheable. Python's generators can't do that either. </p> <p>A simple example may help:</p> <pre><code>class Proxy attr_accesor :target def method &amp;block # Ruby 1.9 or in Rails 2.3 target.instance_exec &amp;block end end class C private def hello puts "hello" end end p = Proxy.new c = C.new p.target = c p.method { hello } </code></pre> <p>In this example the method call within the block <code>{ hello }</code> has it true meaning in the context of the target object <code>c</code>.</p> <p>This example is for illustrative purposes, only. Real working code that uses this kind of execute in the context of another object is not uncommon. The monitoring tool Godm for instance, uses it. </p>
0
2011-04-06T02:32:44Z
[ "python", "ruby" ]
Python/mod_wsgi server global data
1,113,736
<p>I have been looking into different systems for creating a fast cache in a web-farm running Python/mod_wsgi. Memcache and others are options ... But I was wondering:</p> <p>Because I don't need to share data across machines, wanting each machine to maintain a local cache ...</p> <p>Does Python or WSGI provide a mechanism for Python native shared data in Apache such that the data persists and is available to all threads/processes until the server is restarted? This way I could just keep a cache of objects with concurrency control in the memory space of all running application instances?</p> <p>If not, it sure would be useful</p> <p>Thanks!</p>
3
2009-07-11T13:36:58Z
1,113,984
<p>There's Django's thread-safe in-memory cache back-end, see <a href="http://code.djangoproject.com/browser/django/trunk/django/core/cache/backends/locmem.py" rel="nofollow">here</a>. It's cPickle-based, and although it's designed for use with Django, it has minimal dependencies on the rest of Django and you could easily refactor it to remove these. Obviously each process would get its own cache, shared between its threads; If you want a cache shared by all processes on the same machine, you could just use this cache in its own process with an IPC interface of your choice (domain sockets, say) or use <code>memcached</code> locally, or, if you might ever want persistence across restarts, something like <a href="http://tokyocabinet.sourceforge.net/" rel="nofollow">Tokyo Cabinet</a> with a Python interface like <a href="http://code.google.com/p/pytyrant/" rel="nofollow">this</a>.</p>
1
2009-07-11T15:45:03Z
[ "python", "apache", "caching", "mod-wsgi" ]
Python/mod_wsgi server global data
1,113,736
<p>I have been looking into different systems for creating a fast cache in a web-farm running Python/mod_wsgi. Memcache and others are options ... But I was wondering:</p> <p>Because I don't need to share data across machines, wanting each machine to maintain a local cache ...</p> <p>Does Python or WSGI provide a mechanism for Python native shared data in Apache such that the data persists and is available to all threads/processes until the server is restarted? This way I could just keep a cache of objects with concurrency control in the memory space of all running application instances?</p> <p>If not, it sure would be useful</p> <p>Thanks!</p>
3
2009-07-11T13:36:58Z
1,113,991
<p>This is thoroughly covered by the <a href="http://code.google.com/p/modwsgi/wiki/ProcessesAndThreading" rel="nofollow">Sharing and Global Data section</a> of the mod_wsgi documentation. The short answer is: No, not unless you run everything in one process, but that's not an ideal solution.</p> <p>It should be noted that <a href="http://beaker.groovie.org/" rel="nofollow">caching is <em>ridiculously</em> easy to do with Beaker middleware</a>, which supports multiple backends including memcache.</p>
2
2009-07-11T15:47:36Z
[ "python", "apache", "caching", "mod-wsgi" ]
Python/mod_wsgi server global data
1,113,736
<p>I have been looking into different systems for creating a fast cache in a web-farm running Python/mod_wsgi. Memcache and others are options ... But I was wondering:</p> <p>Because I don't need to share data across machines, wanting each machine to maintain a local cache ...</p> <p>Does Python or WSGI provide a mechanism for Python native shared data in Apache such that the data persists and is available to all threads/processes until the server is restarted? This way I could just keep a cache of objects with concurrency control in the memory space of all running application instances?</p> <p>If not, it sure would be useful</p> <p>Thanks!</p>
3
2009-07-11T13:36:58Z
6,079,193
<p>I realize this is an old thread, but here's another option for a "server-wide dict": <a href="http://poshmodule.sourceforge.net/posh/html/posh.html" rel="nofollow">http://poshmodule.sourceforge.net/posh/html/posh.html</a> (POSH, Python Shared Objects). Disclaimer: haven't used it myself yet.</p>
0
2011-05-21T02:15:52Z
[ "python", "apache", "caching", "mod-wsgi" ]
Is it possible to pass a variable out of a pdb session into the original interactive session?
1,114,080
<p>I am using pdb to examine a script having called <code>run -d</code> in an ipython session. It would be useful to be able to plot some of the variables but I need them in the main ipython environment in order to do that. </p> <p>So what I am looking for is some way to make a variable available back in the main interactive session after I quit pdb. If you set a variable in the topmost frame it does seem to be there in the ipython session, but this doesn't work for any frames further down.</p> <p>Something like <code>export</code> in the following:</p> <pre><code>ipdb&gt; myvar = [1,2,3] ipdb&gt; p myvar [1, 2, 3] ipdb&gt; export myvar ipdb&gt; q In [66]: myvar Out[66]: [1, 2, 3] </code></pre>
2
2009-07-11T16:37:10Z
1,114,472
<p>Per ipython's <a href="http://ipython.scipy.org/moin/Documentation" rel="nofollow">docs</a>, and also a <code>run?</code> command from the ipython prompt,</p> <blockquote> <p>after execution, the IPython interactive namespace gets updated with all variables defined in the program (except for <code>__name__</code> and sys.argv)</p> </blockquote> <p>By "defined in the program" (a slightly sloppy use of terms), it doesn't mean "anywhere within any nested functions found there" -- it means "in the <code>globals()</code> of the script/module you're <code>run</code>ning. If you're within any kind of nesting, <code>globals()['myvar'] = [1,2,3]</code> should still work fine, just like your hoped-for <code>export</code> would if it existed.</p> <p><strong>Edit</strong>: If you're in a different module, you need to set the name in the globals of your original one -- after an <code>import sys</code> if needed, <code>sys.modules["originalmodule"].myvar = [1, 2, 3]</code> will do what you desire.</p>
2
2009-07-11T19:37:58Z
[ "python", "debugging", "ipython" ]
How do I check if a process is alive in Python on Linux?
1,114,312
<p>I have a process id in Python. I know I can kill it with os.kill(), but how do I check if it is alive ? Is there a built-in function or do I have to go to the shell?</p>
1
2009-07-11T18:11:18Z
1,114,332
<p>Use <code>subprocess</code> module to spawn process. There is <strong>proc.poll()</strong> function - it returns <code>None</code> if process is still alive, otherwise it returns process returncode.</p> <p><strong><a href="http://docs.python.org/library/subprocess.html" rel="nofollow">http://docs.python.org/library/subprocess.html</a></strong></p>
14
2009-07-11T18:19:24Z
[ "python", "process" ]
How do I check if a process is alive in Python on Linux?
1,114,312
<p>I have a process id in Python. I know I can kill it with os.kill(), but how do I check if it is alive ? Is there a built-in function or do I have to go to the shell?</p>
1
2009-07-11T18:11:18Z
1,114,435
<p><code>os.kill</code> does not kill processes, it sends them signals (it's poorly named).</p> <p>If you send signal 0, you can determine whether you are allowed to send other signals. An error code will indicate whether it's a permission problem or a missing process.</p> <p>See <code>man 2 kill</code> for more info.</p> <p>Also, if the process is your child, you can get a <code>SIGCHLD</code> when it dies, and you can use one of the <code>wait</code> calls to deal with it.</p>
12
2009-07-11T19:12:22Z
[ "python", "process" ]
How to set default button in PyGTK?
1,114,568
<p>I have very simple window where I have 2 buttons - one for cancel, one for apply. How to set the button for apply as default one? (When I press enter, "apply" button is pressed)</p> <p>However, I want to set focus to the first input widget (I can't use grab_focus() on the button)</p> <p>Any suggestions?</p> <p><strong>Edit:</strong> After <em>wuub</em>'s answer it works visually good. However, when I press the button in different widget, it doesn't run callback of the default button.</p> <p>Example code:</p> <pre><code>import os, sys, pygtk, gtk def run(button, window): dialog = gtk.MessageDialog(window, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, gtk.BUTTONS_OK, "OK") dialog.run() dialog.destroy() window = gtk.Window() window.connect("destroy", gtk.main_quit) vbox = gtk.VBox(spacing = 10) entry = gtk.Entry() vbox.pack_start(entry) button = gtk.Button(stock = gtk.STOCK_SAVE) button.connect("clicked", run, window) button.set_flags(gtk.CAN_DEFAULT) window.set_default(button) vbox.pack_start(button) window.add(vbox) window.show_all() gtk.main() </code></pre> <p><strong>EDIT2</strong>: Every input which can activate default widget must be ran</p> <pre><code>widget.set_activates_default(True) </code></pre>
5
2009-07-11T20:30:34Z
1,114,892
<p><a href="http://www.pygtk.org/docs/pygtk/class-gtkdialog.html#method-gtkdialog--set-default-response" rel="nofollow">http://www.pygtk.org/docs/pygtk/class-gtkdialog.html#method-gtkdialog--set-default-response</a></p> <p><a href="http://www.pygtk.org/docs/pygtk/class-gtkwindow.html#method-gtkwindow--set-default" rel="nofollow">http://www.pygtk.org/docs/pygtk/class-gtkwindow.html#method-gtkwindow--set-default</a></p>
4
2009-07-11T23:12:19Z
[ "python", "user-interface", "pygtk" ]
Does main.py or app.yaml determine the URL used by the App Engine cron task in this example?
1,114,601
<p>In this sample code the URL of the app seems to be determined by this line within the app:</p> <pre><code>application = webapp.WSGIApplication([('/mailjob', MailJob)], debug=True) </code></pre> <p>but also by this line within the app handler of app.yaml:</p> <pre><code>- url: /.* script: main.py </code></pre> <p>However, the URL of the cron task is set by this line:</p> <pre><code>url: /tasks/summary </code></pre> <p>So it seems the cron utility will call "<code>/tasks/summary</code>" and because of the app handler, this will cause <code>main.py</code> to be invoked. Does this mean that, as far as the cron is concerned, the line in the app that sets the URL is extraneous:</p> <pre><code>application = webapp.WSGIApplication([('/mailjob', MailJob)], debug=True) </code></pre> <p>. . . since the only URL needed by the cron task is the one defined in app.yaml.</p> <pre><code>app.yaml application: yourappname version: 1 runtime: python api_version: 1 handlers: - url: /.* script: main.py cron.yaml cron: - description: daily mailing job url: /tasks/summary schedule: every 24 hours main.py #!/usr/bin/env python import cgi from google.appengine.ext import webapp from google.appengine.api import mail from google.appengine.api import urlfetch class MailJob(webapp.RequestHandler): def get(self): # Call your website using URL Fetch service ... url = "http://www.yoursite.com/page_or_service" result = urlfetch.fetch(url) if result.status_code == 200: doSomethingWithResult(result.content) # Send emails using Mail service ... mail.send_mail(sender="admin@gmail.com", to="someone@gmail.com", subject="Your account on YourSite.com has expired", body="Bla bla bla ...") return application = webapp.WSGIApplication([ ('/mailjob', MailJob)], debug=True) def main(): wsgiref.handlers.CGIHandler().run(application) if __name__ == '__main__': main() </code></pre>
1
2009-07-11T20:42:05Z
1,114,615
<p>Looks like you're reading <a href="http://basbrun.com/?p=101" rel="nofollow">this page</a> (even though you don't give us the URL). The configuration and code as presented won't run successfully: the cron task will try to visit URL path /tasks/summary, app.yaml will make that execute main.py, but the latter only sets up a handler for /mailjob, so the cron task's attempt will fail with a 404 status code.</p>
1
2009-07-11T20:48:59Z
[ "python", "google-app-engine", "cron", "url-routing" ]
Does main.py or app.yaml determine the URL used by the App Engine cron task in this example?
1,114,601
<p>In this sample code the URL of the app seems to be determined by this line within the app:</p> <pre><code>application = webapp.WSGIApplication([('/mailjob', MailJob)], debug=True) </code></pre> <p>but also by this line within the app handler of app.yaml:</p> <pre><code>- url: /.* script: main.py </code></pre> <p>However, the URL of the cron task is set by this line:</p> <pre><code>url: /tasks/summary </code></pre> <p>So it seems the cron utility will call "<code>/tasks/summary</code>" and because of the app handler, this will cause <code>main.py</code> to be invoked. Does this mean that, as far as the cron is concerned, the line in the app that sets the URL is extraneous:</p> <pre><code>application = webapp.WSGIApplication([('/mailjob', MailJob)], debug=True) </code></pre> <p>. . . since the only URL needed by the cron task is the one defined in app.yaml.</p> <pre><code>app.yaml application: yourappname version: 1 runtime: python api_version: 1 handlers: - url: /.* script: main.py cron.yaml cron: - description: daily mailing job url: /tasks/summary schedule: every 24 hours main.py #!/usr/bin/env python import cgi from google.appengine.ext import webapp from google.appengine.api import mail from google.appengine.api import urlfetch class MailJob(webapp.RequestHandler): def get(self): # Call your website using URL Fetch service ... url = "http://www.yoursite.com/page_or_service" result = urlfetch.fetch(url) if result.status_code == 200: doSomethingWithResult(result.content) # Send emails using Mail service ... mail.send_mail(sender="admin@gmail.com", to="someone@gmail.com", subject="Your account on YourSite.com has expired", body="Bla bla bla ...") return application = webapp.WSGIApplication([ ('/mailjob', MailJob)], debug=True) def main(): wsgiref.handlers.CGIHandler().run(application) if __name__ == '__main__': main() </code></pre>
1
2009-07-11T20:42:05Z
1,114,651
<p>You could do it like this:</p> <pre><code>app.yaml application: yourappname version: 1 runtime: python api_version: 1 handlers: - url: /tasks/.* script: main.py cron.yaml cron: - description: daily mailing job url: /tasks/summary schedule: every 24 hours main.py #!/usr/bin/env python import cgi from google.appengine.ext import webapp from google.appengine.api import mail from google.appengine.api import urlfetch class MailJob(webapp.RequestHandler): def get(self): # Call your website using URL Fetch service ... url = "http://www.yoursite.com/page_or_service" result = urlfetch.fetch(url) if result.status_code == 200: doSomethingWithResult(result.content) # Send emails using Mail service ... mail.send_mail(sender="admin@gmail.com", to="someone@gmail.com", subject="Your account on YourSite.com has expired", body="Bla bla bla ...") return application = webapp.WSGIApplication([ ('/tasks/summary', MailJob)], debug=True) def main(): wsgiref.handlers.CGIHandler().run(application) if __name__ == '__main__': main() </code></pre>
3
2009-07-11T21:15:13Z
[ "python", "google-app-engine", "cron", "url-routing" ]
Making a Makefile
1,114,667
<p>How I can make a Makefile, because it's the best way when you distribute a program by source code. Remember that this is for a C++ program and I'm starting in the C development world. But is it possible to make a Makefile for my Python programs?</p>
2
2009-07-11T21:23:09Z
1,114,683
<p>I use Makefiles for some Python projects, but this is highly dubious... I do things like:</p> <pre><code>SITE_ROOT=/var/www/apache/... site_dist: cp -a assets/css build/$(SITE_ROOT)/css cp -a src/public/*.py build/$(SITE_ROOT) </code></pre> <p>and so on. Makefile are nothing but batch execution systems (and fairly complex ones at that). You can use your normal Python tools (to generate .pyc and others) the same way you would use GCC.</p> <pre><code>PY_COMPILE_TOOL=pycompiler all: myfile.pyc cp myfile.pyc /usr/share/python/...wherever myfile.pyc: &lt;deps&gt; $(PY_COMPILE_TOOL) myfile.py </code></pre> <p>Then</p> <pre><code>$ make all </code></pre> <p>And so on. Just treat your operations like any other. Your <code>pycompiler</code> might be something simple like:</p> <pre><code>#!/usr/bin/python import py_compile py_compile.compile(file_var) </code></pre> <p>or some variation on </p> <pre><code>$ python -mcompileall . </code></pre> <p>It is all the same. Makefiles are nothing special, just automated executions and the ability to check if files need updating.</p>
6
2009-07-11T21:29:58Z
[ "c++", "python", "c", "makefile" ]
Making a Makefile
1,114,667
<p>How I can make a Makefile, because it's the best way when you distribute a program by source code. Remember that this is for a C++ program and I'm starting in the C development world. But is it possible to make a Makefile for my Python programs?</p>
2
2009-07-11T21:23:09Z
1,114,687
<p>A simple <code>Makefile</code> usually consists of a set of targets, its dependencies, and the actions performed by each target:</p> <pre><code>all: output.out output.out: dependency.o dependency2.o ld -o output.out dependency.o dependency2.o dependency.o: dependency.c gcc -o dependency.o dependency.c dependency2.o: dependency2.c gcc -o dependency2.o dependency2.c </code></pre> <p>The target <code>all</code> (which is the first in the example) and tries to build its dependencies in case they don't exist or are not up to date. will be run when no target argument is specified in the <code>make</code> command. </p>
4
2009-07-11T21:31:12Z
[ "c++", "python", "c", "makefile" ]
Making a Makefile
1,114,667
<p>How I can make a Makefile, because it's the best way when you distribute a program by source code. Remember that this is for a C++ program and I'm starting in the C development world. But is it possible to make a Makefile for my Python programs?</p>
2
2009-07-11T21:23:09Z
1,114,692
<p>From your question it sounds like a tutorial or an overview of what Makefiles actually do might benefit you.</p> <p>A good places to start is the <a href="http://www.gnu.org/software/make/manual/make.html" rel="nofollow">GNU Make</a> documentation.</p> <p>It includes the following overview "The make utility automatically determines which pieces of a large program need to be recompiled, and issues commands to recompile them."</p> <p>And its first three chapters covers:</p> <ol> <li>Overview of make</li> <li>An Introduction to Makefiles</li> <li>Writing Makefiles</li> </ol>
11
2009-07-11T21:34:01Z
[ "c++", "python", "c", "makefile" ]
Making a Makefile
1,114,667
<p>How I can make a Makefile, because it's the best way when you distribute a program by source code. Remember that this is for a C++ program and I'm starting in the C development world. But is it possible to make a Makefile for my Python programs?</p>
2
2009-07-11T21:23:09Z
1,114,730
<blockquote> <p>How i can make a MakeFile, because it's the best way when you distribuite a program by source code</p> </blockquote> <p>It's not. For example, KDE uses <a href="http://www.cmake.org/" rel="nofollow">CMake</a>, and Wesnoth uses <a href="http://www.scons.org/" rel="nofollow">SCons</a>. I would suggest one of these systems instead, they are easier and more powerful than make. CMake can generate makefiles. :-)</p>
4
2009-07-11T21:51:35Z
[ "c++", "python", "c", "makefile" ]
Making a Makefile
1,114,667
<p>How I can make a Makefile, because it's the best way when you distribute a program by source code. Remember that this is for a C++ program and I'm starting in the C development world. But is it possible to make a Makefile for my Python programs?</p>
2
2009-07-11T21:23:09Z
1,114,870
<p>If you are asking about a portable form of creating Makefiles you can try to look at <a href="http://www.cmake.org/cmake/project/about.html" rel="nofollow">http://www.cmake.org/cmake/project/about.html</a></p>
1
2009-07-11T22:58:09Z
[ "c++", "python", "c", "makefile" ]
Making a Makefile
1,114,667
<p>How I can make a Makefile, because it's the best way when you distribute a program by source code. Remember that this is for a C++ program and I'm starting in the C development world. But is it possible to make a Makefile for my Python programs?</p>
2
2009-07-11T21:23:09Z
1,115,223
<p>For Python programs, they're usually distributed with a <code>setup.py</code> script which uses <code>distutils</code> in order to build the software. <code>distutils</code> has extensive <a href="http://docs.python.org/distutils/" rel="nofollow">documentation</a> which should be a good starting point.</p>
3
2009-07-12T03:06:30Z
[ "c++", "python", "c", "makefile" ]
PyQt Automatic Repeating Forms
1,114,678
<p>I'm currently attempting to migrate a legacy VBA/Microsoft Access application to Python and PyQt. I've had no problems migrating any of the logic, and most of the forms have been a snap, as well. However, I've hit a problem on the most important part of the application--the main data-entry form.</p> <p>The form is basically a row of text boxes corresponding to fields in the database. The user simply enters data in to a fields, tabs to the next and repeats. When he comes to the end of the record/row, he tabs again, and the form automatically creates a new blank row for him to start entering data in again. (In actuality, it displays a "blank" row below the current new record, which the user can actually click in to to start a new records as well.) It also allows the user to scroll up and down to see all the current subset of records he's working on.</p> <p>Is there a way to replicate this functionality in PyQt? I haven't managed to find a way to get Qt to do this easily. Access takes care of it automatically; no code outside the form is required. Is it that easy in PyQt (or even close), or is this something that's going to need to be programmed from scratch?</p>
2
2009-07-11T21:27:16Z
1,115,236
<p>You should look into QSqlTableModel, and the QTableView Objects. QSqlTableModel offers an abstraction of a relational table that can be used inside on of the Qt view classes. A QTableView for example. The functionality you describe can be implemented with moderate effort just by using these two classes. </p> <p>The QSqlTableModel also supports editing on database fields.</p> <p>My guess the only functionality that you will have to manually implement is the "TAB" at the end of the table to create a new row if you want to keep that.</p> <p>I don't know much about Access, but using the ODBC-SQL driver you should be able use the actual access database for your development or testing there is some older information <a href="http://www.qtcentre.org/forum/f-qt-programming-2/t-odbc-and-ms-access-6485.html" rel="nofollow">here</a>, you might want to consider moving to Sqlite, Mysql or another actual SQL database.</p>
3
2009-07-12T03:18:32Z
[ "python", "qt", "qt4", "pyqt", "pyqt4" ]
Django Model Inheritance And Foreign Keys
1,114,767
<p>Basically, I have a model where I've created a superclass that many other classes share, and then each of those classes has some unique features that differ from each other. Let's say class A is the superclass, and class B, C, and D are children of that class.</p> <p>Both class B and class C can have multiples of class D, however I've seen that it's best to put the foreign key relationship in class D, which then refers to its parent class. Now in other languages, I could simply say it has a ForeignKey relationship to class A, and then the language recognizes the classes' true type. However, I don't think that's how it works with Python.</p> <p>What's the best recommended way of pursuing this issue?</p> <p>EDIT: Here is roughly what I mean...</p> <pre><code>class A(models.Model): field = models.TextField() class B(A): other = &lt;class specific functionality&gt; class C(A): other2 = &lt;different functionality&gt; class D(A): #I would like class D to have a foreign key to either B or C, but not both. </code></pre> <p>Essentially, class B and class C both have multiple class D's. But a particular class D only belongs to one of them.</p>
8
2009-07-11T22:03:55Z
1,114,806
<p>I see a problem here:</p> <pre><code>class D(A): #D has foreign key to either B or C, but not both. </code></pre> <p>Can't do it. You'll have to add both because in SQL columns must be defined exactly.</p> <p>Also even though inherited models like you have compile with <code>syncdb</code> - they don't seem to behave like you would expect - at least I could not make them work. I can't explain why.</p> <p>This is how FK works in Django</p> <pre><code>class A(models.Model): a = models.CharField(max_length=5) class B(models.Model): a = model.ForeignKey(A, related_name='A') b = models.CharField(max_length=5) class D(models.Model): a = model.ForeignKey(A, related_name='A') parent = model.ForeignKey(B, related_name='D') </code></pre> <p>this way you can effectively have multiples of D in B. </p> <p>Inheritance in models (e.g. class B(A)) doesn't work as I would expect it. Maybe someone else can explain it better.</p> <p>Take a look at <a href="http://www.djangoproject.com/documentation/models/many%5Fto%5Fone/" rel="nofollow">this doc</a> page. It's about many-to-one relationship in django.</p> <pre><code>b = B() b.D_set.create(...) </code></pre>
1
2009-07-11T22:25:30Z
[ "python", "django", "inheritance", "django-models", "foreign-keys" ]
Django Model Inheritance And Foreign Keys
1,114,767
<p>Basically, I have a model where I've created a superclass that many other classes share, and then each of those classes has some unique features that differ from each other. Let's say class A is the superclass, and class B, C, and D are children of that class.</p> <p>Both class B and class C can have multiples of class D, however I've seen that it's best to put the foreign key relationship in class D, which then refers to its parent class. Now in other languages, I could simply say it has a ForeignKey relationship to class A, and then the language recognizes the classes' true type. However, I don't think that's how it works with Python.</p> <p>What's the best recommended way of pursuing this issue?</p> <p>EDIT: Here is roughly what I mean...</p> <pre><code>class A(models.Model): field = models.TextField() class B(A): other = &lt;class specific functionality&gt; class C(A): other2 = &lt;different functionality&gt; class D(A): #I would like class D to have a foreign key to either B or C, but not both. </code></pre> <p>Essentially, class B and class C both have multiple class D's. But a particular class D only belongs to one of them.</p>
8
2009-07-11T22:03:55Z
1,115,171
<p>From the <a href="http://docs.djangoproject.com/en/dev/topics/db/models/#one-to-one-relationships" rel="nofollow">Django Docs</a>:</p> <blockquote> <p>For example, if you were building a database of "places", you would build pretty standard stuff such as address, phone number, etc. in the database. Then, if you wanted to build a database of restaurants on top of the places, instead of repeating yourself and replicating those fields in the Restaurant model, you could make Restaurant have a OneToOneField to Place (because a restaurant "is a" place; in fact, to handle this you'd typically use inheritance, which involves an implicit one-to-one relation).</p> </blockquote> <p>Normally, you would just have <code>Restaurant</code> inherit from <code>Place</code>. Sadly, you need what I consider a hack: making a one-to-one reference from subclass to superclass (<code>Restaurant</code> to <code>Place</code>)</p>
3
2009-07-12T02:19:31Z
[ "python", "django", "inheritance", "django-models", "foreign-keys" ]
Django Model Inheritance And Foreign Keys
1,114,767
<p>Basically, I have a model where I've created a superclass that many other classes share, and then each of those classes has some unique features that differ from each other. Let's say class A is the superclass, and class B, C, and D are children of that class.</p> <p>Both class B and class C can have multiples of class D, however I've seen that it's best to put the foreign key relationship in class D, which then refers to its parent class. Now in other languages, I could simply say it has a ForeignKey relationship to class A, and then the language recognizes the classes' true type. However, I don't think that's how it works with Python.</p> <p>What's the best recommended way of pursuing this issue?</p> <p>EDIT: Here is roughly what I mean...</p> <pre><code>class A(models.Model): field = models.TextField() class B(A): other = &lt;class specific functionality&gt; class C(A): other2 = &lt;different functionality&gt; class D(A): #I would like class D to have a foreign key to either B or C, but not both. </code></pre> <p>Essentially, class B and class C both have multiple class D's. But a particular class D only belongs to one of them.</p>
8
2009-07-11T22:03:55Z
1,116,508
<p>You could also do a generic relation <a href="http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#id1" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#id1</a> and check the types to constrain it to B or C when setting or saving. This is probably more work than figuring out the direct reference, but might feel cleaner.</p>
1
2009-07-12T17:43:32Z
[ "python", "django", "inheritance", "django-models", "foreign-keys" ]
Django Model Inheritance And Foreign Keys
1,114,767
<p>Basically, I have a model where I've created a superclass that many other classes share, and then each of those classes has some unique features that differ from each other. Let's say class A is the superclass, and class B, C, and D are children of that class.</p> <p>Both class B and class C can have multiples of class D, however I've seen that it's best to put the foreign key relationship in class D, which then refers to its parent class. Now in other languages, I could simply say it has a ForeignKey relationship to class A, and then the language recognizes the classes' true type. However, I don't think that's how it works with Python.</p> <p>What's the best recommended way of pursuing this issue?</p> <p>EDIT: Here is roughly what I mean...</p> <pre><code>class A(models.Model): field = models.TextField() class B(A): other = &lt;class specific functionality&gt; class C(A): other2 = &lt;different functionality&gt; class D(A): #I would like class D to have a foreign key to either B or C, but not both. </code></pre> <p>Essentially, class B and class C both have multiple class D's. But a particular class D only belongs to one of them.</p>
8
2009-07-11T22:03:55Z
4,004,118
<p>One way to do this is to add an intermediate class as follows:</p> <pre><code>class A(Model): class Meta(Model.Meta): abstract = True # common definitions here class Target(A): # this is the target for links from D - you then need to access the # subclass through ".b" or ".c" # (no fields here) class B(Target): # additional fields here class C(Target): # additional fields here class D(A): b_or_c = ForeignKey(Target) def resolve_target(self): # this does the work for you in testing for whether it is linked # to a b or c instance try: return self.b_or_c.b except B.DoesNotExist: return self.b_or_c.c </code></pre> <p>Using an intermediate class (Target) guarantees that there will only be one link from D to either B or C. Does that make sense? See <a href="http://docs.djangoproject.com/en/1.2/topics/db/models/#model-inheritance" rel="nofollow">http://docs.djangoproject.com/en/1.2/topics/db/models/#model-inheritance</a> for more information.</p> <p>In your database there will be tables for Target, B, C and D, but not A, because that was marked as abstract (instead, columns related to attributes on A will be present in Target and D).</p> <p>[Warning: I have not actually tried this code - any corrections welcome!]</p>
1
2010-10-23T13:15:07Z
[ "python", "django", "inheritance", "django-models", "foreign-keys" ]
Does "from-import" exec the whole module?
1,114,787
<p>OK, so I know that <code>from-import</code> is "exactly" the same as <code>import</code>, except that it's obviously not because namespaces are populated differently.</p> <p>My question is primarily motivated because I have a <code>utils</code> module which has one or two functions that are used by every other module in my app, and I'm working on incorporating the standard library <code>logging</code> module, which as far as I can tell I need to do sorta like this:</p> <pre><code>import logging logging.basicConfig(filename="/var/log") # I want file logging baselogger = logging.getLogger("mine") #do some customizations to baselogger </code></pre> <p>and then to use it in a different module I would import logging again:</p> <pre><code>import logging logger = logging.getlogger("mine") # log stuff </code></pre> <p>But what I want to know is if I do a <code>from utils import awesome_func</code> will my logger definitely be set up, and will the logging module be set up the way I want? </p> <p>This would apply to other generic set-ups as well.</p>
1
2009-07-11T22:15:28Z
1,114,809
<p>Yes, <code>from MODULE import OBJECT</code> executes everything in the module and then effectively does <code>OBJECT = MODULE.OBJECT</code>. You can tell that the module has already been loaded, in a sense, because now it resides in the <a href="http://www.diveintopython.org/file%5Fhandling/more%5Fon%5Fmodules.html" rel="nofollow"><code>sys.modules</code></a> dictionary.</p>
1
2009-07-11T22:25:47Z
[ "python", "logging", "import" ]
Does "from-import" exec the whole module?
1,114,787
<p>OK, so I know that <code>from-import</code> is "exactly" the same as <code>import</code>, except that it's obviously not because namespaces are populated differently.</p> <p>My question is primarily motivated because I have a <code>utils</code> module which has one or two functions that are used by every other module in my app, and I'm working on incorporating the standard library <code>logging</code> module, which as far as I can tell I need to do sorta like this:</p> <pre><code>import logging logging.basicConfig(filename="/var/log") # I want file logging baselogger = logging.getLogger("mine") #do some customizations to baselogger </code></pre> <p>and then to use it in a different module I would import logging again:</p> <pre><code>import logging logger = logging.getlogger("mine") # log stuff </code></pre> <p>But what I want to know is if I do a <code>from utils import awesome_func</code> will my logger definitely be set up, and will the logging module be set up the way I want? </p> <p>This would apply to other generic set-ups as well.</p>
1
2009-07-11T22:15:28Z
1,114,822
<p>Looks like like the answer is yes:</p> <pre><code>$ echo 'print "test" def f1(): print "f1" def f2(): print "f2" ' &gt; util.py $ echo 'from util import f1 f1() from util import f2 f2() ' &gt; test.py $ python test.py test f1 f2 $ </code></pre>
5
2009-07-11T22:30:21Z
[ "python", "logging", "import" ]
Does "from-import" exec the whole module?
1,114,787
<p>OK, so I know that <code>from-import</code> is "exactly" the same as <code>import</code>, except that it's obviously not because namespaces are populated differently.</p> <p>My question is primarily motivated because I have a <code>utils</code> module which has one or two functions that are used by every other module in my app, and I'm working on incorporating the standard library <code>logging</code> module, which as far as I can tell I need to do sorta like this:</p> <pre><code>import logging logging.basicConfig(filename="/var/log") # I want file logging baselogger = logging.getLogger("mine") #do some customizations to baselogger </code></pre> <p>and then to use it in a different module I would import logging again:</p> <pre><code>import logging logger = logging.getlogger("mine") # log stuff </code></pre> <p>But what I want to know is if I do a <code>from utils import awesome_func</code> will my logger definitely be set up, and will the logging module be set up the way I want? </p> <p>This would apply to other generic set-ups as well.</p>
1
2009-07-11T22:15:28Z
1,115,073
<p>The answer to your question is yes. </p> <p>For a good explanation of the import process, please see Frederik Lundh's "<a href="http://effbot.org/zone/import-confusion.htm" rel="nofollow">Importing Python Modules</a>". </p> <p>In particular, I'll quote the sections that answer your query.</p> <blockquote> <p><strong>What Does Python Do to Import a Module?</strong></p> <p>[...]</p> <ol> <li>Create a new, empty module object (this is essentially a dictionary)</li> <li>Insert that module object in the sys.modules dictionary</li> <li>Load the module code object (if necessary, compile the module first)</li> <li>Execute the module code object in the new module’s namespace. All variables assigned by the code will be available via the module object.</li> </ol> </blockquote> <p>and on the use of <code>from-import</code>:</p> <blockquote> <p><strong>There are Many Ways to Import a Module</strong></p> <p>[...]</p> <p><strong>from X import a, b, c</strong> imports the module X, and creates references in the current namespace to the given objects. Or in other words, you can now use a and b and c in your program.</p> </blockquote> <p>Note I've elided some matter. It's worth reading the entire document, it's actually quite short.</p>
6
2009-07-12T01:10:35Z
[ "python", "logging", "import" ]
Does "from-import" exec the whole module?
1,114,787
<p>OK, so I know that <code>from-import</code> is "exactly" the same as <code>import</code>, except that it's obviously not because namespaces are populated differently.</p> <p>My question is primarily motivated because I have a <code>utils</code> module which has one or two functions that are used by every other module in my app, and I'm working on incorporating the standard library <code>logging</code> module, which as far as I can tell I need to do sorta like this:</p> <pre><code>import logging logging.basicConfig(filename="/var/log") # I want file logging baselogger = logging.getLogger("mine") #do some customizations to baselogger </code></pre> <p>and then to use it in a different module I would import logging again:</p> <pre><code>import logging logger = logging.getlogger("mine") # log stuff </code></pre> <p>But what I want to know is if I do a <code>from utils import awesome_func</code> will my logger definitely be set up, and will the logging module be set up the way I want? </p> <p>This would apply to other generic set-ups as well.</p>
1
2009-07-11T22:15:28Z
1,115,552
<p>As mentioned above, yes. And you can write simple test to be sure:</p> <pre><code># file m.py import sys # define function def f(): pass #execute this when module is loaded (i.e. imported or run as script) print 'imported', __name__ # print all "exposed" variables to make sure that the f is visible print dir(sys.modules[__name__]) # file main.py from m import f print 'done' </code></pre> <p>I recommend writing such tests every time you're in doubt how some importing or subclassing or thomething else works.</p>
0
2009-07-12T08:19:33Z
[ "python", "logging", "import" ]
Python converts string into tuple
1,114,813
<p>Example:</p> <pre><code>regular_string = "%s %s" % ("foo", "bar") result = {} result["somekey"] = regular_string, print result["somekey"] # ('foo bar',) </code></pre> <p>Why <code>result["somekey"]</code> tuple now not string?</p>
3
2009-07-11T22:27:47Z
1,114,820
<p>Because of comma at the end of the line.</p>
16
2009-07-11T22:30:10Z
[ "python" ]
Python converts string into tuple
1,114,813
<p>Example:</p> <pre><code>regular_string = "%s %s" % ("foo", "bar") result = {} result["somekey"] = regular_string, print result["somekey"] # ('foo bar',) </code></pre> <p>Why <code>result["somekey"]</code> tuple now not string?</p>
3
2009-07-11T22:27:47Z
1,114,837
<p>When you write</p> <pre><code>result["somekey"] = regular_string, </code></pre> <p>Python reads</p> <pre><code>result["somekey"] = (regular_string,) </code></pre> <p><code>(x,)</code> is the syntax for a tuple with a single element. Parentheses are assumed. And you really end up putting a tuple, instead of a string there.</p>
9
2009-07-11T22:39:06Z
[ "python" ]
Determine proxy type
1,115,039
<p>I have the following code to download a URL through a proxy:</p> <pre><code>proxy_handler = urllib2.ProxyHandler({'http': p}) opener = urllib2.build_opener(proxy_handler) urllib2.install_opener(opener) req = urllib2.Request(url) sock = urllib2.urlopen(req) </code></pre> <p>How can I use Python to determine the type of proxy it is (transparent, anonymous, etc)? One solution would be to use an external server, but I want to avoid that kind of dependency if possible.</p>
3
2009-07-12T00:49:18Z
1,115,081
<blockquote> <p>One solution would be to use an external server</p> </blockquote> <p>You must have a server of some sort.</p> <p>The best option you can hope of doing is to host your own web server and print the headers to see if it is leaking any variables.</p>
1
2009-07-12T01:16:31Z
[ "python", "proxy", "anonymous" ]
Determine proxy type
1,115,039
<p>I have the following code to download a URL through a proxy:</p> <pre><code>proxy_handler = urllib2.ProxyHandler({'http': p}) opener = urllib2.build_opener(proxy_handler) urllib2.install_opener(opener) req = urllib2.Request(url) sock = urllib2.urlopen(req) </code></pre> <p>How can I use Python to determine the type of proxy it is (transparent, anonymous, etc)? One solution would be to use an external server, but I want to avoid that kind of dependency if possible.</p>
3
2009-07-12T00:49:18Z
1,115,871
<p>Do you mean retrieving the current proxy configuration?<br /> You can with urllib.getproxies:</p> <pre><code>import urllib urllib.getproxies() {'http': 'http://your_proxy_servername:8080'} </code></pre> <p>Note: I was not able to find any documentation about urllib.getproxies. I am using Python 2.5, and it just works.</p>
-1
2009-07-12T11:35:12Z
[ "python", "proxy", "anonymous" ]
Sorting disk I/O errors in Python
1,115,203
<p>How do I sort out (distinguish) an error derived from a "disk full condition" from "trying to write to a read-only file system"? I don't want to fill my HD to find out :) What I want is to know who to catch each exception, so my code can say something to the user when he is trying to write to a ReadOnly FS and another message if the user is trying to write a file in a disk that is full.</p>
2
2009-07-12T02:48:05Z
1,115,214
<p>On a read-only filesystem, the files themselves will be marked as read-only. Any attempt to <code>open</code> a read-only file for writing (<code>O_WRONLY</code> or <code>O_RDWR</code>) will fail. On UNIX-like systems, the errno <code>EACCES</code> will be set.</p> <pre> >>> file('/etc/resolv.conf', 'a') Traceback (most recent call last): File "", line 1, in IOError: [Errno 13] Permission denied: '/etc/resolv.conf' </pre> <p>In contrast, attempts to <code>write</code> to a full file may result in <code>ENOSPC</code>. <strong>May</strong> is critical; the error may be delayed until <code>fsync</code> or <code>close</code>.</p> <pre> >>> file(<a href="http://en.wikipedia.org/wiki//dev/full" rel="nofollow">/dev/full</a>, 'a').write('\n') close failed in file object destructor: IOError: [Errno 28] No space left on device </pre>
2
2009-07-12T02:59:58Z
[ "python", "exception" ]
Sorting disk I/O errors in Python
1,115,203
<p>How do I sort out (distinguish) an error derived from a "disk full condition" from "trying to write to a read-only file system"? I don't want to fill my HD to find out :) What I want is to know who to catch each exception, so my code can say something to the user when he is trying to write to a ReadOnly FS and another message if the user is trying to write a file in a disk that is full.</p>
2
2009-07-12T02:48:05Z
1,115,216
<p>Once you catch <code>IOError</code>, e.g. with an <code>except IOError, e:</code> clause in Python 2.*, you can examine <code>e.errno</code> to find out exactly what kind of I/O error it was (unfortunately in a way that's not necessarily fully portable among different operating systems).</p> <p>See the <a href="http://docs.python.org/library/errno.html">errno</a> module in Python standard library; opening a file for writing on a R/O filesystem (on a sensible OS) should produce <code>errno.EPERM</code>, <code>errno.EACCES</code> or better yet <code>errno.EROFS</code> ("read-only filesystem"); if the filesystem is R/W but there's no space left you should get <code>errno.ENOSPC</code> ("no space left on device"). But you will need to experiment on the OSes you care about (with a small USB key filling it up should be easy;-).</p> <p>There's no way to use different <code>except</code> clauses depending on errno -- such clauses must be distinguished by the <em>class</em> of exceptions they catch, not by attributes of the exception instance -- so you'll need an if/else or other kind of dispatching within a single <code>except IOError, e:</code> clause.</p>
7
2009-07-12T03:01:12Z
[ "python", "exception" ]
Django Model Sync Table
1,115,238
<p>If I change a field in a Django model, how can I synchronize it with the database tables? Do I need to do it manually on the database or is there a tool that does helps with the process?</p>
4
2009-07-12T03:21:13Z
1,115,252
<p>Alas, Django does not support any easy solution to this. </p> <p>The only thing django will do for you, is restart your database with new tables that match your new models:</p> <pre><code>$ #DON'T DO THIS UNLESS YOU CAN AFFORD TO LOSE ALL YOUR DATA! $ python PROJECT_DIR/manage.py syncdb </code></pre> <p>the next option is to use the various sql* options to manage.py to see what django would do to match the current models to the database, then issue your own <code>ALTER TABLE</code> commands to make everything work right. Of course this is error prone and difficult.</p> <p>The real solution is to use a database migration tool, such as <a href="http://south.aeracode.org/" rel="nofollow">south</a> to generate migration code.</p> <p>Here is a <a href="http://stackoverflow.com/questions/426378/what-is-your-favorite-solution-for-managing-database-migrations-in-django">similar question</a> with discussion about various database migration options for django.</p>
6
2009-07-12T03:33:47Z
[ "python", "database", "django", "django-models", "synchronization" ]
Django Model Sync Table
1,115,238
<p>If I change a field in a Django model, how can I synchronize it with the database tables? Do I need to do it manually on the database or is there a tool that does helps with the process?</p>
4
2009-07-12T03:21:13Z
1,115,271
<p><a href="http://code.google.com/p/django-evolution/" rel="nofollow">Django Evolution</a> can help, but the best option really is to plan out your schema in advance, or to make simple modifications manually. Or, to be willing to toast your test data by dropping tables and re-syncing.</p>
3
2009-07-12T03:48:49Z
[ "python", "database", "django", "django-models", "synchronization" ]
Django Model Sync Table
1,115,238
<p>If I change a field in a Django model, how can I synchronize it with the database tables? Do I need to do it manually on the database or is there a tool that does helps with the process?</p>
4
2009-07-12T03:21:13Z
1,115,369
<p>Django does not provide for this out of the box.</p> <p>Here's some information from the Django Book on <a href="http://www.djangobook.com/en/1.0/chapter05/" rel="nofollow">doing it by hand</a> (see Making Changes to a Database Schema). This works for straightforward, simple changes.</p> <p>Longer-term, you'll probably want to use a migration tool. There are three major options:</p> <ul> <li><a href="http://code.google.com/p/django-evolution/" rel="nofollow">django-evolution</a></li> <li><a href="http://code.google.com/p/dmigrations/" rel="nofollow">Dmigrations</a> (written by Simon Willison, one of the creators of Django) (works only with MySQL)</li> <li><a href="http://south.aeracode.org/" rel="nofollow">South</a></li> </ul> <p>EDIT: Looking through the question linked by TokenMacGuy, I'll add two more to the list for the sake of completeness:</p> <ul> <li><a href="http://bitbucket.org/DeadWisdom/migratory/" rel="nofollow">Migratory</a></li> <li><a href="http://github.com/ricardochimal/simplemigrations/tree/master" rel="nofollow">simplemigrations</a></li> </ul>
2
2009-07-12T05:17:00Z
[ "python", "database", "django", "django-models", "synchronization" ]
Django Model Sync Table
1,115,238
<p>If I change a field in a Django model, how can I synchronize it with the database tables? Do I need to do it manually on the database or is there a tool that does helps with the process?</p>
4
2009-07-12T03:21:13Z
1,117,089
<p>Just to throw in an extra opinion - dmigrations is pretty nice and clear to use, but I'd say South is your best bet. Again, it's easy to get into, but it's more powerful and also has support for more database backends than just MySQL. It even handles MSSQL, if that's your thing</p>
0
2009-07-12T22:24:36Z
[ "python", "database", "django", "django-models", "synchronization" ]
Django Model Sync Table
1,115,238
<p>If I change a field in a Django model, how can I synchronize it with the database tables? Do I need to do it manually on the database or is there a tool that does helps with the process?</p>
4
2009-07-12T03:21:13Z
1,232,838
<p>Can't seem to be able to add a comment to the marked answer, probably because I haven't got enough rep (be nice if SO told me so though).</p> <p>Anyway, just wanted to add that in the answered post, I believe it is wrong about syncdb - syncdb does <strong>not</strong> touch tables once they have been created and have data in them. You should <strong>not</strong> lose data by calling it (otherwise, how could you add new tables for new apps?)</p> <p>I believe the poster was referring to the reset command instead, which <strong>does</strong> result in data loss - it will drop the table and recreate it and hence it'll have all the latest model changes.</p>
4
2009-08-05T12:08:03Z
[ "python", "database", "django", "django-models", "synchronization" ]
Cost of len() function
1,115,313
<p>What is the cost of <a href="https://docs.python.org/2/library/functions.html#len"><code>len()</code></a> function for Python built-ins? (list/tuple/string/dictionary)</p>
106
2009-07-12T04:31:02Z
1,115,329
<p>It's <strong>O(1)</strong> (very fast) on every type you've mentioned, plus <code>set</code> and others such as <code>array.array</code>.</p>
109
2009-07-12T04:40:31Z
[ "python", "algorithm", "collections", "complexity-theory" ]
Cost of len() function
1,115,313
<p>What is the cost of <a href="https://docs.python.org/2/library/functions.html#len"><code>len()</code></a> function for Python built-ins? (list/tuple/string/dictionary)</p>
106
2009-07-12T04:31:02Z
1,115,349
<p>Calling len() on those data types is O(1) in <a href="http://www.python.org">CPython</a>, the most common implementation of the Python language. Here's a link to a table that provides the algorithmic complexity of many different functions in CPython:</p> <p><a href="http://wiki.python.org/moin/TimeComplexity">TimeComplexity Python Wiki Page</a> </p>
97
2009-07-12T04:59:44Z
[ "python", "algorithm", "collections", "complexity-theory" ]
Cost of len() function
1,115,313
<p>What is the cost of <a href="https://docs.python.org/2/library/functions.html#len"><code>len()</code></a> function for Python built-ins? (list/tuple/string/dictionary)</p>
106
2009-07-12T04:31:02Z
1,115,382
<p>The below measurements provide evidence that <code>len()</code> is O(1) for oft-used data structures. </p> <p>A note regarding <code>timeit</code>: When the <code>-s</code> flag is used and two strings are passed to <code>timeit</code> the first string is executed only once and is not timed.</p> <h3>List:</h3> <pre><code>$ python -m timeit -s "l = range(10);" "len(l)" 10000000 loops, best of 3: 0.0677 usec per loop $ python -m timeit -s "l = range(1000000);" "len(l)" 10000000 loops, best of 3: 0.0688 usec per loop </code></pre> <h3>Tuple:</h3> <pre><code>$ python -m timeit -s "t = (1,)*10;" "len(t)" 10000000 loops, best of 3: 0.0712 usec per loop $ python -m timeit -s "t = (1,)*1000000;" "len(t)" 10000000 loops, best of 3: 0.0699 usec per loop </code></pre> <h3>String:</h3> <pre><code>$ python -m timeit -s "s = '1'*10;" "len(s)" 10000000 loops, best of 3: 0.0713 usec per loop $ python -m timeit -s "s = '1'*1000000;" "len(s)" 10000000 loops, best of 3: 0.0686 usec per loop </code></pre> <h3>Dictionary (dictionary-comprehension available in 2.7+):</h3> <pre><code>$ python -mtimeit -s"d = {i:j for i,j in enumerate(range(10))};" "len(d)" 10000000 loops, best of 3: 0.0711 usec per loop $ python -mtimeit -s"d = {i:j for i,j in enumerate(range(1000000))};" "len(d)" 10000000 loops, best of 3: 0.0727 usec per loop </code></pre> <h3>Array:</h3> <pre><code>$ python -mtimeit -s"import array;a=array.array('i',range(10));" "len(a)" 10000000 loops, best of 3: 0.0682 usec per loop $ python -mtimeit -s"import array;a=array.array('i',range(1000000));" "len(a)" 10000000 loops, best of 3: 0.0753 usec per loop </code></pre> <h3>Set (set-comprehension available in 2.7+):</h3> <pre><code>$ python -mtimeit -s"s = {i for i in range(10)};" "len(s)" 10000000 loops, best of 3: 0.0754 usec per loop $ python -mtimeit -s"s = {i for i in range(1000000)};" "len(s)" 10000000 loops, best of 3: 0.0713 usec per loop </code></pre> <h3>Deque:</h3> <pre><code>$ python -mtimeit -s"from collections import deque;d=deque(range(10));" "len(d)" 100000000 loops, best of 3: 0.0163 usec per loop $ python -mtimeit -s"from collections import deque;d=deque(range(1000000));" "len(d)" 100000000 loops, best of 3: 0.0163 usec per loop </code></pre>
33
2009-07-12T05:34:28Z
[ "python", "algorithm", "collections", "complexity-theory" ]
Cost of len() function
1,115,313
<p>What is the cost of <a href="https://docs.python.org/2/library/functions.html#len"><code>len()</code></a> function for Python built-ins? (list/tuple/string/dictionary)</p>
106
2009-07-12T04:31:02Z
1,115,401
<p>All those objects keep track of their own length. The time to extract the length is small (O(1) in big-O notation) and mostly consists of [rough description, written in Python terms, not C terms]: look up "len" in a dictionary and dispatch it to the built_in len function which will look up the object's <code>__len__</code> method and call that ... all it has to do is <code>return self.length</code></p>
19
2009-07-12T06:17:13Z
[ "python", "algorithm", "collections", "complexity-theory" ]
Static methods and thread safety
1,115,420
<p>In python with all this idea of "Everything is an object" where is thread-safety?</p> <p>I am developing django website with wsgi. Also it would work in linux, and as I know they use effective process management, so we could not think about thread-safety alot. I am not doubt in how module loads, and there functions are static or not? Every information would be helpfull.</p>
2
2009-07-12T06:32:23Z
1,115,427
<p>Functions in a module are equivalent to static methods in a class. The issue of thread safety arises when multiple threads may be modifying shared data, or even one thread may be modifying such data while others are reading it; it's best avoided by making data be owned by ONE module (accessed via Queue.Queue from others), but when that's not feasible you have to resort to locking and other, more complex, synchronization primitives.</p> <p>This applies whether the access to shared data happens in module functions, static methods, or instance methods -- and the shared data is such whether it's instance variables, class ones, or global ones (scoping and thread safety are essentially disjoint, except that function-local data is, to a pont, intrinsically thread-safe -- no other thread will ever see the data inside a function instance, until and unless the function deliberately "shares" it through shared containers).</p> <p>If you use the <code>multiprocessing</code> module in Python's standard library, instead of the <code>threading</code> module, you may in fact not have to care about "thread safety" -- essentially because NO data is shared among processes... well, unless you go out of your way to change that, e.g. via <code>mmap</code>ped files;-).</p>
7
2009-07-12T06:40:47Z
[ "python", "django", "thread-safety" ]
Static methods and thread safety
1,115,420
<p>In python with all this idea of "Everything is an object" where is thread-safety?</p> <p>I am developing django website with wsgi. Also it would work in linux, and as I know they use effective process management, so we could not think about thread-safety alot. I am not doubt in how module loads, and there functions are static or not? Every information would be helpfull.</p>
2
2009-07-12T06:32:23Z
1,115,756
<p>See the <a href="http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock" rel="nofollow">python documentation</a> to better understand the general thread safety implications of Python.</p> <p>Django itself seems to be <a href="http://code.djangoproject.com/wiki/DjangoSpecifications/Core/Threading" rel="nofollow">thread safe</a> as of 1.0.3, but your code may not and you will have to verify that...</p> <p>My advice would be to simply don't care about that and serve your application with multiple processes instead of multiple threads (for example by using apache 'prefork' instead of 'worker' MPM).</p>
0
2009-07-12T10:33:33Z
[ "python", "django", "thread-safety" ]
Google App Engine: how to unescape POST body?
1,116,066
<p>Newbie question...</p> <p>I am using silverlight to POST data to my GAE application</p> <pre><code> class XmlCrud(webapp.RequestHandler): def post(self): body = self.request.body </code></pre> <p>The data comes in fine but it is escaped like this:</p> <pre><code>%3C%3Fxml+version=%221.0%22+encoding%3D%22utf-16%22%3F%3E%0D%0A%3CBosses+xmlns%3Axsi%3D%22http%3A%2F%2Fwww.w3.org%2F2001%2FXMLSchema-instance%22+xmlns%3Axsd </code></pre> <p>how do I unescape it?</p>
2
2009-07-12T13:44:24Z
1,116,109
<p>I'd recommend not encoding it in the first place if the body of the post is just an XML document.</p>
0
2009-07-12T14:18:41Z
[ "python", "google-app-engine" ]
Google App Engine: how to unescape POST body?
1,116,066
<p>Newbie question...</p> <p>I am using silverlight to POST data to my GAE application</p> <pre><code> class XmlCrud(webapp.RequestHandler): def post(self): body = self.request.body </code></pre> <p>The data comes in fine but it is escaped like this:</p> <pre><code>%3C%3Fxml+version=%221.0%22+encoding%3D%22utf-16%22%3F%3E%0D%0A%3CBosses+xmlns%3Axsi%3D%22http%3A%2F%2Fwww.w3.org%2F2001%2FXMLSchema-instance%22+xmlns%3Axsd </code></pre> <p>how do I unescape it?</p>
2
2009-07-12T13:44:24Z
1,116,119
<p>I agree with Hank.</p> <p>The answer to your actual question, though, is that your example is URL encoded. To decode, replace each %XX with the character having hex value 0xXX, and + with space.</p> <p><code>urllib.unquote_plus</code> does this, and according to the docs it's in App Engine</p> <p>urllib docs: <a href="https://docs.python.org/library/urllib.html" rel="nofollow">https://docs.python.org/library/urllib.html</a></p> <p>Statement that urllib is supported (there may be others): <a href="http://code.google.com/appengine/docs/python/urlfetch/overview.html" rel="nofollow">http://code.google.com/appengine/docs/python/urlfetch/overview.html</a></p>
3
2009-07-12T14:25:46Z
[ "python", "google-app-engine" ]
python windows directory mtime: how to detect package directory new file?
1,116,144
<p>I'm working on an auto-reload feature for WHIFF <a href="http://whiff.sourceforge.net" rel="nofollow">http://whiff.sourceforge.net</a> (so you have to restart the HTTP server less often, ideally never).</p> <p>I have the following code to reload a package module "location" if a file is added to the package directory. It doesn't work on Windows XP. How can I fix it? I think the problem is that getmtime(dir) doesn't change on Windows when the directory content changes? I'd really rather not compare an os.listdir(dir) with the last directory content every time I access the package...</p> <pre><code> if not do_reload and hasattr(location, "__path__"): path0 = location.__path__[0] if os.path.exists(path0): dir_mtime = int( os.path.getmtime(path0) ) if fn_mtime&lt;dir_mtime: print "dir change: reloading package root", location do_reload = True md_mtime = dir_mtime </code></pre> <p>In the code the "fn_mtime" is the recorded mtime from the last (re)load.</p> <p>... added comment: I came up with the following work around, which I think may work, but I don't care for it too much since it involves code generation. I dynamically generate a code fragment to load a module and if it fails it tries again after a reload. Not tested yet.</p> <pre><code>GET_MODULE_FUNCTION = """ def f(): import %(parent)s try: from %(parent)s import %(child)s except ImportError: # one more time... reload(%(parent)s) from %(parent)s import %(child)s return %(child)s """ def my_import(partname, parent): f = None # for pychecker parentname = parent.__name__ defn = GET_MODULE_FUNCTION % {"parent": parentname, "child": partname} #pr "executing" #pr defn try: exec(defn) # defines function f() except SyntaxError: raise ImportError, "bad function name "+repr(partname)+"?" partmodule = f() #pr "got", partmodule setattr(parent, partname, partmodule) #pr "setattr", parent, ".", partname, "=", getattr(parent, partname) return partmodule </code></pre> <p>Other suggestions welcome. I'm not happy about this...</p>
0
2009-07-12T14:43:28Z
1,116,166
<p>you can try using getatime() instead.</p>
0
2009-07-12T14:54:39Z
[ "python", "windows-xp" ]
python windows directory mtime: how to detect package directory new file?
1,116,144
<p>I'm working on an auto-reload feature for WHIFF <a href="http://whiff.sourceforge.net" rel="nofollow">http://whiff.sourceforge.net</a> (so you have to restart the HTTP server less often, ideally never).</p> <p>I have the following code to reload a package module "location" if a file is added to the package directory. It doesn't work on Windows XP. How can I fix it? I think the problem is that getmtime(dir) doesn't change on Windows when the directory content changes? I'd really rather not compare an os.listdir(dir) with the last directory content every time I access the package...</p> <pre><code> if not do_reload and hasattr(location, "__path__"): path0 = location.__path__[0] if os.path.exists(path0): dir_mtime = int( os.path.getmtime(path0) ) if fn_mtime&lt;dir_mtime: print "dir change: reloading package root", location do_reload = True md_mtime = dir_mtime </code></pre> <p>In the code the "fn_mtime" is the recorded mtime from the last (re)load.</p> <p>... added comment: I came up with the following work around, which I think may work, but I don't care for it too much since it involves code generation. I dynamically generate a code fragment to load a module and if it fails it tries again after a reload. Not tested yet.</p> <pre><code>GET_MODULE_FUNCTION = """ def f(): import %(parent)s try: from %(parent)s import %(child)s except ImportError: # one more time... reload(%(parent)s) from %(parent)s import %(child)s return %(child)s """ def my_import(partname, parent): f = None # for pychecker parentname = parent.__name__ defn = GET_MODULE_FUNCTION % {"parent": parentname, "child": partname} #pr "executing" #pr defn try: exec(defn) # defines function f() except SyntaxError: raise ImportError, "bad function name "+repr(partname)+"?" partmodule = f() #pr "got", partmodule setattr(parent, partname, partmodule) #pr "setattr", parent, ".", partname, "=", getattr(parent, partname) return partmodule </code></pre> <p>Other suggestions welcome. I'm not happy about this...</p>
0
2009-07-12T14:43:28Z
1,116,246
<p>I'm not understanding your question completely...</p> <p>Are you calling getmtime() on a directory or an individual file?</p>
0
2009-07-12T15:31:19Z
[ "python", "windows-xp" ]
python windows directory mtime: how to detect package directory new file?
1,116,144
<p>I'm working on an auto-reload feature for WHIFF <a href="http://whiff.sourceforge.net" rel="nofollow">http://whiff.sourceforge.net</a> (so you have to restart the HTTP server less often, ideally never).</p> <p>I have the following code to reload a package module "location" if a file is added to the package directory. It doesn't work on Windows XP. How can I fix it? I think the problem is that getmtime(dir) doesn't change on Windows when the directory content changes? I'd really rather not compare an os.listdir(dir) with the last directory content every time I access the package...</p> <pre><code> if not do_reload and hasattr(location, "__path__"): path0 = location.__path__[0] if os.path.exists(path0): dir_mtime = int( os.path.getmtime(path0) ) if fn_mtime&lt;dir_mtime: print "dir change: reloading package root", location do_reload = True md_mtime = dir_mtime </code></pre> <p>In the code the "fn_mtime" is the recorded mtime from the last (re)load.</p> <p>... added comment: I came up with the following work around, which I think may work, but I don't care for it too much since it involves code generation. I dynamically generate a code fragment to load a module and if it fails it tries again after a reload. Not tested yet.</p> <pre><code>GET_MODULE_FUNCTION = """ def f(): import %(parent)s try: from %(parent)s import %(child)s except ImportError: # one more time... reload(%(parent)s) from %(parent)s import %(child)s return %(child)s """ def my_import(partname, parent): f = None # for pychecker parentname = parent.__name__ defn = GET_MODULE_FUNCTION % {"parent": parentname, "child": partname} #pr "executing" #pr defn try: exec(defn) # defines function f() except SyntaxError: raise ImportError, "bad function name "+repr(partname)+"?" partmodule = f() #pr "got", partmodule setattr(parent, partname, partmodule) #pr "setattr", parent, ".", partname, "=", getattr(parent, partname) return partmodule </code></pre> <p>Other suggestions welcome. I'm not happy about this...</p>
0
2009-07-12T14:43:28Z
1,117,571
<p>long time no see. I'm not sure exactly what you're doing, but the equivalent of your code:</p> <pre><code>GET_MODULE_FUNCTION = """ def f(): import %(parent)s try: from %(parent)s import %(child)s except ImportError: # one more time... reload(%(parent)s) from %(parent)s import %(child)s return %(child)s """ </code></pre> <p>to be <code>exec</code>ed with:</p> <pre><code>defn = GET_MODULE_FUNCTION % {"parent": parentname, "child": partname} exec(defn) </code></pre> <p>is (per <a href="http://docs.python.org/library/functions.html?highlight=%5F%5Fimport%5F%5F#%5F%5Fimport%5F%5F" rel="nofollow">the docs</a>), assuming parentname names a package and partname names a module in that package (if partname is a top-level name of the parentname package, such as a function or class, you'll have to use a getattr at the end):</p> <pre><code>import sys def f(parentname, partname): name = '%s.%s' % (parentname, partname) try: __import__(name) except ImportError: parent = __import__(parentname) reload(parent) __import__(name) return sys.modules[name] </code></pre> <p>without exec or anything weird, just call this <code>f</code> appropriately.</p>
2
2009-07-13T03:11:17Z
[ "python", "windows-xp" ]
python windows directory mtime: how to detect package directory new file?
1,116,144
<p>I'm working on an auto-reload feature for WHIFF <a href="http://whiff.sourceforge.net" rel="nofollow">http://whiff.sourceforge.net</a> (so you have to restart the HTTP server less often, ideally never).</p> <p>I have the following code to reload a package module "location" if a file is added to the package directory. It doesn't work on Windows XP. How can I fix it? I think the problem is that getmtime(dir) doesn't change on Windows when the directory content changes? I'd really rather not compare an os.listdir(dir) with the last directory content every time I access the package...</p> <pre><code> if not do_reload and hasattr(location, "__path__"): path0 = location.__path__[0] if os.path.exists(path0): dir_mtime = int( os.path.getmtime(path0) ) if fn_mtime&lt;dir_mtime: print "dir change: reloading package root", location do_reload = True md_mtime = dir_mtime </code></pre> <p>In the code the "fn_mtime" is the recorded mtime from the last (re)load.</p> <p>... added comment: I came up with the following work around, which I think may work, but I don't care for it too much since it involves code generation. I dynamically generate a code fragment to load a module and if it fails it tries again after a reload. Not tested yet.</p> <pre><code>GET_MODULE_FUNCTION = """ def f(): import %(parent)s try: from %(parent)s import %(child)s except ImportError: # one more time... reload(%(parent)s) from %(parent)s import %(child)s return %(child)s """ def my_import(partname, parent): f = None # for pychecker parentname = parent.__name__ defn = GET_MODULE_FUNCTION % {"parent": parentname, "child": partname} #pr "executing" #pr defn try: exec(defn) # defines function f() except SyntaxError: raise ImportError, "bad function name "+repr(partname)+"?" partmodule = f() #pr "got", partmodule setattr(parent, partname, partmodule) #pr "setattr", parent, ".", partname, "=", getattr(parent, partname) return partmodule </code></pre> <p>Other suggestions welcome. I'm not happy about this...</p>
0
2009-07-12T14:43:28Z
1,121,799
<p>There are two things about your first code snippet that concern me:</p> <ul> <li><p>You cast the float from getmtime to int. Dependening on the frequency this code is run, you might get unreliable results.</p></li> <li><p>At the end of the code you assign dir_mtime to a variable md_mtime. fn_mtime, which you check against, seems not to be updated.</p></li> </ul>
0
2009-07-13T20:17:01Z
[ "python", "windows-xp" ]
python program choice
1,116,163
<p>My program is ICAPServer (similar with httpserver), it's main job is to receive data from clients and save the data to DB.</p> <p>There are two main steps and two threads:</p> <ol> <li>ICAPServer receives data from clients, puts the data in a queue (50kb &lt;1ms);</li> <li>another thread pops data from the queue, and writes them to DB SO, if 2nd step is too slow, the queue will fill up memory with those data.</li> </ol> <p>Wondering if anyone have any suggestion...</p>
0
2009-07-12T14:54:01Z
1,116,170
<p>Put an upper limit on the amount of data in the queue?</p>
0
2009-07-12T14:59:42Z
[ "python", "sqlalchemy", "twisted" ]
python program choice
1,116,163
<p>My program is ICAPServer (similar with httpserver), it's main job is to receive data from clients and save the data to DB.</p> <p>There are two main steps and two threads:</p> <ol> <li>ICAPServer receives data from clients, puts the data in a queue (50kb &lt;1ms);</li> <li>another thread pops data from the queue, and writes them to DB SO, if 2nd step is too slow, the queue will fill up memory with those data.</li> </ol> <p>Wondering if anyone have any suggestion...</p>
0
2009-07-12T14:54:01Z
1,116,224
<p>It is hard to say for sure, but perhaps using two processes instead of threads will help in this situation. Since Python has the Global Interpreter Lock (GIL), it has the effect of only allowing any one thread to execute Python instructions at any time. </p> <p>Having a system designed around processes might have the following advantages:</p> <ul> <li>Higher concurrency, especially on multiprocessor machines</li> <li>Greater throughput, since you can probably spawn multiple queue consumers / DB writer processes to spread out the work. Although, the impact of this might be minimal if it is really the DB that is the bottleneck and not the process writing to the DB.</li> </ul>
2
2009-07-12T15:22:35Z
[ "python", "sqlalchemy", "twisted" ]
python program choice
1,116,163
<p>My program is ICAPServer (similar with httpserver), it's main job is to receive data from clients and save the data to DB.</p> <p>There are two main steps and two threads:</p> <ol> <li>ICAPServer receives data from clients, puts the data in a queue (50kb &lt;1ms);</li> <li>another thread pops data from the queue, and writes them to DB SO, if 2nd step is too slow, the queue will fill up memory with those data.</li> </ol> <p>Wondering if anyone have any suggestion...</p>
0
2009-07-12T14:54:01Z
1,116,586
<p>One note: before going for optimizations, it is very important to get some good measurement, and profiling.</p> <p>That said, I would bet the slow part in the second step is database communication; you could try to analyze the SQL statement and its execution plan. and then optimize it (it is one of the <a href="http://www.sqlalchemy.org/features.html" rel="nofollow">features</a> of SQLAlchemy); if still it would be too slow, check about database optimizations.</p> <p>Of course, it is possible the bottleneck would be in a completely different place; in this case, you still have chances to optimize using C code, dedicated network, or more threads - just to give three possible example of completely different kind of optimizations.</p> <p>Another point: as I/O operations usually release the GIL, you could also try to improve performance just by adding another reader thread - and I think this could be a much cheaper solution.</p>
0
2009-07-12T18:16:55Z
[ "python", "sqlalchemy", "twisted" ]
Finding content between two words withou RegEx, BeautifulSoup, lXml ... etc
1,116,172
<p>How to find out the content between two words or two sets of random characters?</p> <p>The scraped page is not guaranteed to be Html only and the important data can be inside a javascript block. So, I can't remove the JavaScript.</p> <p>consider this:</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;div&gt;StartYYYY "Extract HTML", ENDYYYY &lt;/body&gt; Some Java Scripts code STARTXXXX "Extract JS Code" ENDXXXX. &lt;/html&gt; </code></pre> <p>So as you see the html markup may not be complete. I can fetch the page, and then without worrying about anything, I want to find the content called "Extract the name" and "Extract the data here in a JavaScript".</p> <p>What I am looking for is in python:</p> <p>Like this:</p> <pre><code>data = FindBetweenText(UniqueTextBeforeContent, UniqueTextAfterContent, page) </code></pre> <p>Where page is downloaded and data would have the text I am looking for. I rather stay away from regEx as some of the cases can be too complex for RegEx.</p>
1
2009-07-12T15:00:38Z
1,116,180
<p>Well, this is what it would be in PHP. No doubt there's a much sexier Pythonic way.</p> <pre><code>function FindBetweenText($before, $after, $text) { $before_pos = strpos($text, $before); if($before_pos === false) return null; $after_pos = strpos($text, $after); if($after_pos === false || $after_pos &lt;= $before_pos) return null; return substr($text, $before_pos, $after_pos - $before_pos); } </code></pre>
0
2009-07-12T15:04:39Z
[ "python", "screen-scraping", "fetch" ]
Finding content between two words withou RegEx, BeautifulSoup, lXml ... etc
1,116,172
<p>How to find out the content between two words or two sets of random characters?</p> <p>The scraped page is not guaranteed to be Html only and the important data can be inside a javascript block. So, I can't remove the JavaScript.</p> <p>consider this:</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;div&gt;StartYYYY "Extract HTML", ENDYYYY &lt;/body&gt; Some Java Scripts code STARTXXXX "Extract JS Code" ENDXXXX. &lt;/html&gt; </code></pre> <p>So as you see the html markup may not be complete. I can fetch the page, and then without worrying about anything, I want to find the content called "Extract the name" and "Extract the data here in a JavaScript".</p> <p>What I am looking for is in python:</p> <p>Like this:</p> <pre><code>data = FindBetweenText(UniqueTextBeforeContent, UniqueTextAfterContent, page) </code></pre> <p>Where page is downloaded and data would have the text I am looking for. I rather stay away from regEx as some of the cases can be too complex for RegEx.</p>
1
2009-07-12T15:00:38Z
1,116,219
<p>if you are sure your markers are unique, do something like this</p> <pre><code>s=""" &lt;html&gt; &lt;body&gt; &lt;div&gt;StartYYYY "Extract HTML", ENDYYYY &lt;/body&gt; Some Java Scripts code STARTXXXX "Extract JS Code" ENDXXXX. &lt;/html&gt; """ def FindBetweenText(startMarker, endMarker, text): startPos = text.find(startMarker) if startPos &lt; 0: return endPos = text.find(endMarker) if endPos &lt; 0: return return text[startPos+len(startMarker):endPos] print FindBetweenText('STARTXXXX', 'ENDXXXX', s) </code></pre>
2
2009-07-12T15:18:04Z
[ "python", "screen-scraping", "fetch" ]
Finding content between two words withou RegEx, BeautifulSoup, lXml ... etc
1,116,172
<p>How to find out the content between two words or two sets of random characters?</p> <p>The scraped page is not guaranteed to be Html only and the important data can be inside a javascript block. So, I can't remove the JavaScript.</p> <p>consider this:</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;div&gt;StartYYYY "Extract HTML", ENDYYYY &lt;/body&gt; Some Java Scripts code STARTXXXX "Extract JS Code" ENDXXXX. &lt;/html&gt; </code></pre> <p>So as you see the html markup may not be complete. I can fetch the page, and then without worrying about anything, I want to find the content called "Extract the name" and "Extract the data here in a JavaScript".</p> <p>What I am looking for is in python:</p> <p>Like this:</p> <pre><code>data = FindBetweenText(UniqueTextBeforeContent, UniqueTextAfterContent, page) </code></pre> <p>Where page is downloaded and data would have the text I am looking for. I rather stay away from regEx as some of the cases can be too complex for RegEx.</p>
1
2009-07-12T15:00:38Z
1,116,220
<p>[Slightly tested]</p> <pre><code>def bracketed_find_first(prefix, suffix, page, start=0): prefixpos = page.find(prefix, start) if prefixpos == -1: return None # NOT "" startpos = prefixpos + len(prefix) endpos = page.find(suffix, startpos) # DRY if endpos == -1: return None # NOT "" return page[startpos:endpos] </code></pre> <p>Note: the above returns only the first occurrence. Here is a generator which yields each occurrence.</p> <pre><code>def bracketed_finditer(prefix, suffix, page, start_at=0): while True: prefixpos = page.find(prefix, start_at) if prefixpos == -1: return # StopIteration startpos = prefixpos + len(prefix) endpos = page.find(suffix, startpos) if endpos == -1: return yield page[startpos:endpos] start_at = endpos + len(suffix) </code></pre>
0
2009-07-12T15:18:05Z
[ "python", "screen-scraping", "fetch" ]
Finding content between two words withou RegEx, BeautifulSoup, lXml ... etc
1,116,172
<p>How to find out the content between two words or two sets of random characters?</p> <p>The scraped page is not guaranteed to be Html only and the important data can be inside a javascript block. So, I can't remove the JavaScript.</p> <p>consider this:</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;div&gt;StartYYYY "Extract HTML", ENDYYYY &lt;/body&gt; Some Java Scripts code STARTXXXX "Extract JS Code" ENDXXXX. &lt;/html&gt; </code></pre> <p>So as you see the html markup may not be complete. I can fetch the page, and then without worrying about anything, I want to find the content called "Extract the name" and "Extract the data here in a JavaScript".</p> <p>What I am looking for is in python:</p> <p>Like this:</p> <pre><code>data = FindBetweenText(UniqueTextBeforeContent, UniqueTextAfterContent, page) </code></pre> <p>Where page is downloaded and data would have the text I am looking for. I rather stay away from regEx as some of the cases can be too complex for RegEx.</p>
1
2009-07-12T15:00:38Z
1,116,243
<p>Here's my attempt, this is tested. While recursive, there should be no unnecessary string duplication, although a generator might be more optimal</p> <pre><code>def bracketed_find(s, start, end, startat=0): startloc=s.find(start, startat) if startloc==-1: return [] endloc=s.find(end, startloc+len(start)) if endloc == -1: return [s[startloc+len(start):]] return [s[startloc+len(start):endloc]] + bracketed_find(s, start, end, endloc+len(end)) </code></pre> <p>and here is a generator version</p> <pre><code>def bracketed_find(s, start, end, startat=0): startloc=s.find(start, startat) if startloc==-1: return endloc=s.find(end, startloc+len(start)) if endloc == -1: yield s[startloc+len(start):] return else: yield s[startloc+len(start):endloc] for found in bracketed_find(s, start, end, endloc+len(end)): yield found </code></pre>
0
2009-07-12T15:29:56Z
[ "python", "screen-scraping", "fetch" ]
Retrieve cookie created using javascript in python
1,116,362
<p>I've had a look at many tutorials regarding cookiejar, but my problem is that the webpage that i want to scape creates the cookie using javascript and I can't seem to retrieve the cookie. Does anybody have a solution to this problem?</p>
1
2009-07-12T16:25:38Z
1,116,402
<p>Maybe you can execute the JavaScript code in a JavaScript engine with Python bindings (like <a href="http://github.com/davisp/python-spidermonkey/tree/master" rel="nofollow">python-spidermonkey</a> or <a href="http://code.google.com/p/pyv8/" rel="nofollow">pyv8</a>) and then retrieve the cookie. Or, as the javascript code is executed client side anyway, you may be able to convert the cookie-generating code to Python.</p>
0
2009-07-12T16:47:09Z
[ "python", "cookies", "urllib2", "cookiejar" ]
Retrieve cookie created using javascript in python
1,116,362
<p>I've had a look at many tutorials regarding cookiejar, but my problem is that the webpage that i want to scape creates the cookie using javascript and I can't seem to retrieve the cookie. Does anybody have a solution to this problem?</p>
1
2009-07-12T16:25:38Z
1,116,524
<p>You could access the page using a real browser, via <a href="http://pamie.sourceforge.net/" rel="nofollow">PAMIE</a>, <a href="http://sourceforge.net/projects/pywin32/" rel="nofollow">win32com</a> or similar, then the JavaScript will be running in its native environment.</p>
0
2009-07-12T17:52:35Z
[ "python", "cookies", "urllib2", "cookiejar" ]
Retrieve cookie created using javascript in python
1,116,362
<p>I've had a look at many tutorials regarding cookiejar, but my problem is that the webpage that i want to scape creates the cookie using javascript and I can't seem to retrieve the cookie. Does anybody have a solution to this problem?</p>
1
2009-07-12T16:25:38Z
1,116,535
<p>If all pages have the same JavaScript then maybe you could parse the HTML to find that piece of code, and from that get the value the cookie would be set to? </p> <p>That would make your scraping quite vulnerable to changes in the third party website, but that's most often the case while scraping. (Please bear in mind that the third-party website owner may not like that you're getting the content this way.)</p>
3
2009-07-12T17:55:59Z
[ "python", "cookies", "urllib2", "cookiejar" ]
Retrieve cookie created using javascript in python
1,116,362
<p>I've had a look at many tutorials regarding cookiejar, but my problem is that the webpage that i want to scape creates the cookie using javascript and I can't seem to retrieve the cookie. Does anybody have a solution to this problem?</p>
1
2009-07-12T16:25:38Z
1,118,077
<p>I responded to your <a href="http://stackoverflow.com/questions/1117491/fake-a-cookie-to-scrape-a-site-in-python/1118060#1118060">other question</a> as well: take a look at <a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow">mechanize</a>. It's probably the most fully featured scraping module I know: if the cookie is sent, then I'm sure you can get to it with this module.</p>
1
2009-07-13T07:19:38Z
[ "python", "cookies", "urllib2", "cookiejar" ]
Should I use Unicode string by default?
1,116,449
<p>Is it considered as a good practice to pick Unicode string over regular string when coding in Python? I mainly work on the Windows platform, where most of the string types are Unicode these days (i.e. .NET String, '_UNICODE' turned on by default on a new c++ project, etc ). Therefore, I tend to think that the case where non-Unicode string objects are used is a sort of rare case. Anyway, I'm curious about what Python practitioners do in real-world projects. </p>
17
2009-07-12T17:13:22Z
1,116,476
<p>From my practice -- use unicode. </p> <p>At beginning of one project we used usuall strings, however our project was growing, we were implementing new features and using new third-party libraries. In that mess with non-unicode/unicode string some functions started failing. We started spending time localizing this problems and fixing them. However, some third-party modules doesn't supported unicode and started failing after we switched to it (but this is rather exclusion than a rule). </p> <p>Also I have some experience when we needed to rewrite some third party modules(e.g. SendKeys) cause they were not supporting unicode. If it was done in unicode from beginning it will be better :) </p> <p>So I think today we should use unicode.</p> <p>P.S. All that mess upwards is only my hamble opinion :)</p>
17
2009-07-12T17:31:49Z
[ "python", "unicode" ]
Should I use Unicode string by default?
1,116,449
<p>Is it considered as a good practice to pick Unicode string over regular string when coding in Python? I mainly work on the Windows platform, where most of the string types are Unicode these days (i.e. .NET String, '_UNICODE' turned on by default on a new c++ project, etc ). Therefore, I tend to think that the case where non-Unicode string objects are used is a sort of rare case. Anyway, I'm curious about what Python practitioners do in real-world projects. </p>
17
2009-07-12T17:13:22Z
1,116,487
<p>If you are dealing with severely constrained memory or disk space, use ASCII strings. In this case, you should additionally write your software in C or something even more compact :)</p>
2
2009-07-12T17:38:16Z
[ "python", "unicode" ]
Should I use Unicode string by default?
1,116,449
<p>Is it considered as a good practice to pick Unicode string over regular string when coding in Python? I mainly work on the Windows platform, where most of the string types are Unicode these days (i.e. .NET String, '_UNICODE' turned on by default on a new c++ project, etc ). Therefore, I tend to think that the case where non-Unicode string objects are used is a sort of rare case. Anyway, I'm curious about what Python practitioners do in real-world projects. </p>
17
2009-07-12T17:13:22Z
1,116,546
<p>As you ask this question, I suppose you are using Python 2.x. </p> <p>Python 3.0 changed quite a lot in string representation, and all text now is unicode.<br /> I would go for unicode in any new project - in a way compatible with the switch to Python 3.0 (see <a href="http://docs.python.org/3.0/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit">details</a>).</p>
13
2009-07-12T17:59:19Z
[ "python", "unicode" ]
Should I use Unicode string by default?
1,116,449
<p>Is it considered as a good practice to pick Unicode string over regular string when coding in Python? I mainly work on the Windows platform, where most of the string types are Unicode these days (i.e. .NET String, '_UNICODE' turned on by default on a new c++ project, etc ). Therefore, I tend to think that the case where non-Unicode string objects are used is a sort of rare case. Anyway, I'm curious about what Python practitioners do in real-world projects. </p>
17
2009-07-12T17:13:22Z
1,116,549
<p>Additional to Mihails comment I would say: Use Unicode, since it is the future. In Python 3.0, Non-Unicode will be gone, and as much I know, all the "U"-Prefixes will make trouble, since they are also gone.</p>
4
2009-07-12T17:59:48Z
[ "python", "unicode" ]
Should I use Unicode string by default?
1,116,449
<p>Is it considered as a good practice to pick Unicode string over regular string when coding in Python? I mainly work on the Windows platform, where most of the string types are Unicode these days (i.e. .NET String, '_UNICODE' turned on by default on a new c++ project, etc ). Therefore, I tend to think that the case where non-Unicode string objects are used is a sort of rare case. Anyway, I'm curious about what Python practitioners do in real-world projects. </p>
17
2009-07-12T17:13:22Z
1,116,581
<p>It can be tricky to consistently use unicode strings in Python 2.x - be it because somebody inadvertently uses the more natural <code>str(blah)</code> where they meant <code>unicode(blah)</code>, forgetting the <code>u</code> prefix on string literals, third-party module incompatibilities - whatever. So in Python 2.x, use unicode only if you have to, and are prepared to provide good unit test coverage.</p> <p>If you have the option of using Python 3.x however, you don't need to care - strings will be unicode with no extra effort.</p>
5
2009-07-12T18:15:26Z
[ "python", "unicode" ]
Should I use Unicode string by default?
1,116,449
<p>Is it considered as a good practice to pick Unicode string over regular string when coding in Python? I mainly work on the Windows platform, where most of the string types are Unicode these days (i.e. .NET String, '_UNICODE' turned on by default on a new c++ project, etc ). Therefore, I tend to think that the case where non-Unicode string objects are used is a sort of rare case. Anyway, I'm curious about what Python practitioners do in real-world projects. </p>
17
2009-07-12T17:13:22Z
1,116,660
<p>Yes, use unicode. </p> <p>Some hints:</p> <ol> <li><p>When doing input output in any sort of binary format, decode directly after reading and encode directly before writing, so that you never need to mix strings and unicode. Because mixing that tends to lead to UnicodeEncodeDecodeErrors sooner or later.</p></li> <li><p>[Forget about this one, my explanations just made it even more confusing. It's only an issue when porting to Python 3, you can care about it then.]</p></li> <li><p>Common Python newbie errors with Unicode (not saying you are a newbie, but this may be read by newbies): Don't confuse encode and decode. Remember, UTF-8 is an ENcoding, so you ENcode Unicode to UTF-8 and DEcode from it.</p></li> <li><p>Do not fall into the temptation of setting the default encoding in Python (by setdefaultencoding in sitecustomize.py or similar) to whatever you use most. That is just going to give you problems if you reinstall or move to another computer or suddenly need to use another encoding. Be explicit.</p></li> <li><p>Remember, not all of Python 2s standard library accepts unicode. If you feed a method unicode and it doesn't work, but it should, try feeding it ascii and see. Examples: urllib.urlopen(), which fails with unhelpful errors if you give it a unicode object instead of a string.</p></li> </ol> <p>Hm. That's all I can think of now!</p>
13
2009-07-12T18:54:32Z
[ "python", "unicode" ]
What's the point of this code pattern?
1,116,693
<p>I was trying to create a python wrapper for an tk extension, so I looked at Tkinter.py to learn how to do it. </p> <p>While looking at that file, I found the following pattern appears a lot of times: an internal method (hinted by the leading "_" in the method name) is defined, then a public method is defined just to be the internal method. </p> <p>I want to know what's the benefit of doing this.</p> <p>For example, in the code for class Misc:</p> <pre><code>def _register(self, func, subst=None, needcleanup=1): # doc string and implementations is removed since it's not relevant register = _register </code></pre> <p>Thank you.</p>
3
2009-07-12T19:21:21Z
1,116,701
<p><a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">From PEP8</a></p> <p>In addition, the following special forms using leading or trailing underscores are recognized (these can generally be combined with any case convention):</p> <blockquote> <p>_single_leading_underscore: weak "internal use" indicator. E.g. "from M import *" does not import objects whose name starts with an underscore.</p> </blockquote>
2
2009-07-12T19:26:07Z
[ "python" ]
What's the point of this code pattern?
1,116,693
<p>I was trying to create a python wrapper for an tk extension, so I looked at Tkinter.py to learn how to do it. </p> <p>While looking at that file, I found the following pattern appears a lot of times: an internal method (hinted by the leading "_" in the method name) is defined, then a public method is defined just to be the internal method. </p> <p>I want to know what's the benefit of doing this.</p> <p>For example, in the code for class Misc:</p> <pre><code>def _register(self, func, subst=None, needcleanup=1): # doc string and implementations is removed since it's not relevant register = _register </code></pre> <p>Thank you.</p>
3
2009-07-12T19:21:21Z
1,116,702
<p>Well, I'm supposing, there could be <em>another</em> internal callable, that could've been used, it just didn't make it to the version you have. Generally, I think it is a good idea - you expose one symbol publically and internally it can be anything, a real method, a stubbed out method, a debug version of the method, anything.</p>
1
2009-07-12T19:26:10Z
[ "python" ]
What's the point of this code pattern?
1,116,693
<p>I was trying to create a python wrapper for an tk extension, so I looked at Tkinter.py to learn how to do it. </p> <p>While looking at that file, I found the following pattern appears a lot of times: an internal method (hinted by the leading "_" in the method name) is defined, then a public method is defined just to be the internal method. </p> <p>I want to know what's the benefit of doing this.</p> <p>For example, in the code for class Misc:</p> <pre><code>def _register(self, func, subst=None, needcleanup=1): # doc string and implementations is removed since it's not relevant register = _register </code></pre> <p>Thank you.</p>
3
2009-07-12T19:21:21Z
1,116,705
<p>Sometimes, you may want to change a method's behavior. For example, I could do this (hypothetically within the Misc class):</p> <pre><code>def _another_register(self, func, subst=None, needcleanup=1): ... def change_register(self): self.register = self._another_register def restore_register(self): self.register = self._register </code></pre> <p>This can be a pretty handy way to alter the behavior of certain pieces of code without subclassing (but it's generally not advisable to do this kind of thing except within the class itself).</p>
8
2009-07-12T19:27:26Z
[ "python" ]
Calculating formulae in Excel with Python
1,116,725
<p>I would like to insert a calculation in Excel using Python. Generally it can be done by inserting a formula string into the relevant cell. However, if i need to calculate a formula multiple times for the whole column the formula must be updated for each individual cell. For example, if i need to calculate the sum of two cells, then for cell C(k) the computation would be A(k)+B(k). In excel it is possible to calculate C1=A1+B1 and then automatically expand the calculation by dragging the mouse from C1 downwards. My question is: Is it possible to the same thing with Python, i.e. to define a formula in only one cell and then to use Excel capabilities to extend the calculation for the whole column/row?</p> <p>Thank you in advance, Sasha</p>
1
2009-07-12T19:36:54Z
1,116,782
<p>If you are using COM bindings, then you can simply record a macro in Excel, then translate it into Python code.<br /> If you are using xlwt, you have to resort to normal loops in python..</p>
0
2009-07-12T20:02:31Z
[ "python", "excel", "formula" ]
Calculating formulae in Excel with Python
1,116,725
<p>I would like to insert a calculation in Excel using Python. Generally it can be done by inserting a formula string into the relevant cell. However, if i need to calculate a formula multiple times for the whole column the formula must be updated for each individual cell. For example, if i need to calculate the sum of two cells, then for cell C(k) the computation would be A(k)+B(k). In excel it is possible to calculate C1=A1+B1 and then automatically expand the calculation by dragging the mouse from C1 downwards. My question is: Is it possible to the same thing with Python, i.e. to define a formula in only one cell and then to use Excel capabilities to extend the calculation for the whole column/row?</p> <p>Thank you in advance, Sasha</p>
1
2009-07-12T19:36:54Z
1,116,827
<p>As <a href="http://stackoverflow.com/questions/1116725/calculating-formulae-in-excel-with-python/1116782#1116782">Roberto </a> mentions, you can use <strong><a href="http://pypi.python.org/pypi/xlwt" rel="nofollow">xlwt</a></strong> and a trusty for-loop:</p> <pre><code>import xlwt w = xlwt.Workbook() ws = w.add_sheet('mysheet') for i in range(10): ws.write(i, 0, i) ws.write(i, 1, i+1) ws.write(i, 2, xlwt.Formula("$A$%d+$B$%d" % (i+1, i+1))) w.save('myworkbook.xls') </code></pre>
3
2009-07-12T20:19:39Z
[ "python", "excel", "formula" ]
Calculating formulae in Excel with Python
1,116,725
<p>I would like to insert a calculation in Excel using Python. Generally it can be done by inserting a formula string into the relevant cell. However, if i need to calculate a formula multiple times for the whole column the formula must be updated for each individual cell. For example, if i need to calculate the sum of two cells, then for cell C(k) the computation would be A(k)+B(k). In excel it is possible to calculate C1=A1+B1 and then automatically expand the calculation by dragging the mouse from C1 downwards. My question is: Is it possible to the same thing with Python, i.e. to define a formula in only one cell and then to use Excel capabilities to extend the calculation for the whole column/row?</p> <p>Thank you in advance, Sasha</p>
1
2009-07-12T19:36:54Z
1,183,609
<p>Sasha, </p> <p>Python code translated from your macro would look like this:</p> <pre><code>startCell = mySheet.Range("M6") wholeRange = mySheet.Range("M6:M592") startCell.FormulaR1C1 = "=R[-1]C[-7]/RC[-10]*R[-1]C" startCell.AutoFill(Destination=wholeRange) </code></pre> <p>Haven't tested it, but I write this often at work. Let me know if it doesn't work.</p>
0
2009-07-26T02:48:08Z
[ "python", "excel", "formula" ]