Simple C#/Python Code Comparison

by Jeremy Jones

I'm trying to dig into C# a little more at work, so I decided to do something really easy and write a little code to grab an RSS feed and pull the enclosure data out of it. Before you look at the code, let me say that I don't have an objective point to make with this. I'm not trying to make sweeping judgments based on number of lines of code or anything else. I do have some subjective remarks to make at the end, however.

Here is the C# code:

using System;
using System.Xml;

namespace RssGrabber
{
class MainClass
{
public static void Main(string[] args)
{
string rssUrl = "http://geekmuse.dreamhosters.com/wp/?feed=rss2";
XmlTextReader reader = new XmlTextReader(rssUrl);
while(reader.Read())
{
if ((reader.IsStartElement()) && (reader.Name == "enclosure"))
{
while (reader.MoveToNextAttribute())
{
System.Console.WriteLine("{0} => {1}", reader.Name, reader.Value);
}
}
}
}
}
}


Here is the Python code:

from elementtree import ElementTree as ET
import StringIO
import urllib

rssUrl = "http://geekmuse.dreamhosters.com/wp/?feed=rss2"

et = ET.parse(StringIO.StringIO(urllib.urlopen(rssUrl).read()))
for elem in et.findall("//enclosure"):
for items in elem.attrib.items():
print "%s => %s" % items


Now, on to the subjective. Python just feels more manageable than C#. It feels friendlier. It didn't feel tedious to try to get data out of. That's it. That's my point. If your opinion varies from that, then that's OK. I'm not here to change your mind. And I'm definitely not here to try to offer up comprehensive language comparisons. I'm just expressing a little piece of an experience I just had which I thought was worth noting.

20 Comments

Dave Brondsema
2007-02-28 10:34:19
Why is your C# example formatted to use 8-wide tabs for indenting, while your python example has 4 spaces for indentation?
Jeremy Jones
2007-02-28 10:43:58
Uggh. That looks horrid. The reason for the indentation variation is that I used Monodevelop for the C# and vim for the Python example. I guess Monodevelop does tabs by default and my .vimrc does 4 spaces. I'll see if I can clean that up. I didn't get the full effect from the preview I had when writing this post. Thanks so much for pointing this out!
Tom
2007-02-28 12:25:58
To be fair -- not to start a flame war -- but to make the comparison as close as possible, we can drop the namespace and 3 more sets of parens that aren't needed.


Furthermore, anything but small scripts will likely require a class and method definition in the Python code as well. So at that point, let's just compare the "functional" code:

string rssUrl = "http://geekmuse.dreamhosters.com/wp/?feed=rss2";
XmlTextReader reader = new XmlTextReader( rssUrl );
while( reader.Read() )
  if( reader.IsStartElement() && (reader.Name == "enclosure") )
    while( reader.MoveToNextAttribute() )
      Console.WriteLine("{0} => {1}", reader.Name, reader.Value);


Now, that said... I'll still agree with you that the Python version is a bit cleaner.


It looks like the Python version reads the whole stream and tokenizes it ahead of time (just a guess based on the "parse" and "elem.attrib" list). The C# version is streaming. Using DOM/XPath might further clean up the C# code.


2007-02-28 12:32:37
Out of curiosity, why the StringIO stuff in the python example, and not just:


et = ET.parse(urllib.urlopen(rssUrl))

Reedo
2007-02-28 12:39:09
Have you tried IronPython, perchance?
Jeremy Jones
2007-02-28 14:08:13
@anonymous,


Doh! I started to miss what you were saying. The urllib.urlopen() provides a .read() method! I guess it was early and my brain wasn't working. Thanks so much for pointing that out. (Now I feel dumb.)

Jeremy Jones
2007-02-28 14:09:25
@Reedo,


Yes, I've tried IronPython. In fact, I was working on getting another example to post using the MS XML parsing library from Python code, which would really be a more fair example. Haven't gotten that working just yet, though.

Jeremy Jones
2007-02-28 14:11:42
@Tom,


In looking at the differences, I didn't really include the boilerplate stuff that Monodevelop included. A lot of it was the clunkiness of the C# language compared to Python. I figured that there were effectively 6 lines of C# and 5 lines of Python (if memory serves). It was really all about the subjective "feel". Thanks for posting the cleaned up C# code, though!

Levi Cook
2007-03-01 07:51:19
Interesting. For what it's worth, here's a ruby version to ponder. IMO, it doesn't look a whole lot different than the python version. The do/end blocks add a bit of line noise, but the string interpolation is nice and legible.



require 'open-uri'
require 'rexml/document'


rss_url = 'http://geekmuse.dreamhosters.com/wp/?feed=rss2'


doc = REXML::Document.new(open(rss_url).read())
doc.elements.each('//enclosure') do |elem|
  elem.attributes.each do |name, value|
    puts "#{name} => #{value}"
  end
end

Josh Peters
2007-03-01 14:06:20
here's a php example with simplexml:
$rssUrl = 'http://geekmuse.dreamhosters.com/wp/?feed=rss2';
$xml = simplexml_load_file($rssUrl);
foreach ($xml->xpath('//enclosure') as $elem) {
foreach ($elem->attributes() as $key => $value) {
printf("%s => %s\n", $key, $value);
}
}
Josh Peters
2007-03-01 14:08:17
D'oh! I shoulda used a pre tag...
Jeremy Jones
2007-03-01 16:18:51
@Levi,


Thanks so much for posting a Ruby example! I started trying to hammer this out, but became impatient with my inexperience with Ruby. You're right - it does look a whole lot like the Python version. Thanks again!

Jeremy Jones
2007-03-01 16:21:34
@Josh,


Thank you for posting a PHP example! I should have figured PHP would have good support for XML out of the box.


2007-03-02 08:45:42
Let's face it, you can do the same thing in any of these languages. It's all preference and infrastructure requirements. Of course we're all going to think whatever we program with on a daily basis is the easiest read and ones we don't use are more tedious.
Josh Peters
2007-03-02 13:23:28
@Jeremy
Actually prior to PHP 5, the XML support was pretty sketchy. PHP 4 had a DOM package that wasn't 100% in line with other implementations.


PHP 5 is quite nice for XML manipulation these days with its SimpleXML, DOM, and SOAP classes built in.

Rob Hudson
2007-03-05 17:57:56
I recently asked a local Python group of whether naive string concatenation was less efficient than something like StringIO. I was happy to see the response I got:
http://euglug.org/pipermail/python/2007-February/000557.html
Dave Turvene
2007-03-08 05:55:17
So you demonstrated Python is less wordy and "more manageable" than C# and commentors demonstrated that Ruby, PHP, etc. are all more or less equally less wordy and more manageable. And all pretty much have a large set of standard libraries (e.g. XML) to feed from.


To me, the big advantage to Python cannot be demonstrated in ten line programs but in large, long-lived software systems. The OO nature of Python (including introspection, class hierarchies, decorators, etc.) really demonstrate your point: "Python just feels more manageable.." In some ways, I think it is more difficult to write a ten line program in Python than in other dynamic languages because of this (e.g. Perl or Bash).


I have done a lot of Perl and some PHP systems. Large systems based on these languages require a much larger degree of centralized, proactive supervision on the code base to avoid a spaghetti mess.


I'm not familiar with Ruby and haven't seen any large systems based on it. Does anyone know of any large Ruby projects?

Jeremy Jones
2007-03-08 06:14:22
@Dave Turvene,


Very well said. I definitely prefer Python to other languages. And I've looked into quite a few of them. What I was hoping to accomplish with this post is exactly what you observed - the "feel" of the language.


Regarding Ruby, I would suspect that Rails itself is probably a decent place to look for a large-ish code base, but that's just a guess.

Asim Jalis
2008-02-25 21:00:01
The Python and C# samples are not equivalent because Python is using XPath while the C# code is doing raw DOM walking. The C# code can become shorter if you create an XmlDocument and then call SelectNodes("//enclosure") on it. Still, I agree with the general sentiment here: Python is just beautiful.
Jordan Callicoat
2008-07-02 07:26:17
I also agree that python is generally more elegant. But C# is not without it's nifty features too (check out the DateTime.Parse static method for example, gotta love it). For a more python-ish experience on .NET (well apart from actually using python with IronPython ;P), check out Boo. It takes alot of queues from python and ruby, and adds some nifty stuff from c# and VB.NET. :)