Curia

Why I’ve fallen in love with Python

by on Jul.27, 2009, under F/OSS, Python

In a previous post, I briefly mentioned falling in love with Python. Now that I’m finally using Python for a large percentage of my development and am more than “casually acquainted” with its toolset, I thought it would be fun to highlight a few reasons why Python has become my new language of choice.

In an effort to help you understand where I’m coming from, let me (briefly) rehash some of my programming history: I spent much of the 90′s doing dynamic web development using Perl (weren’t those the days!). I eventually migrated to PHP which usually made things much easier on the web; and subsequently replaced most of my console scripting with BASH [shell scripting]. However, I’m kind of a hack and love languages so I have occasionally been known to write something in C; and although I’m not a complete stranger to Java and Ruby, I never really felt like I “clicked” with either of those languages.

Ok, now that I’ve hopefully convinced you that I’m not just a fly-by-night programmer, let me show you some Python code. Brace yourself, as this article is bound to get lengthy…

Reason #1: “Whitespace done right” is actually a good thing

The first thing that people either absolutely love or adamantly hate about Python is the fact that code blocks are heavily tied to proper usage of whitespace. At first glance, this causes many curious onlookers from other languages to shy away from Python and continue in their bracket-encapsulated bondage. I’ll admit, at first I wasn’t too wild about these new restrictions either (I’m a programmer—I should be able to do my code how I want!); but the first time I had to go back to doing something in PHP for a client, I quickly realized I didn’t ever want to put anything inside brackets again:

# A sample function that's free from brackets, parenthesis, and semicolons!
def check_number(x):
    if type(x) != type(0):
        return "That isn't a number!"
    elif x % 2:
        return "This number is odd"
    else:
        return "This number is even"

Not only does this make Python source code incredibly readable, but you also end up typing less!

Reason #2: I almost always know what type of object I’m working with

One thing that always annoyed me about Perl was that you set an array or hash using the ‘@’ or ‘%’ sigils, but typically accessed them using the ‘$’ sigil. PHP simplified this a bit, but “$array = array();” could be a simple list or an associative array (known as a dictionary in Python). With Python on the other hand, the enclosure defines the type (for most built-in types at least), and since everything is an object there’s no need for silly sigils:

# the type of enclosure makes a distinction between a string , a list, and a dictionary
string = 'This is a string'
print string # prints 'This is a string'
 
list = ['This', 'is', 'a', 'list']
print list[0] # prints 'This'
 
dict = {'first_key': 'This', 'second_key': 'is', 'third_key': 'a', 'fourth_key': 'dictionary'}
print dict['fourth_key'] # prints 'dictionary'

On a somewhat related note, you can use these objects on-the-fly in your scripts without even having to assign them to a name. This isn’t usually practical of course (and may not be recommended), but it is possible:

print ['This', 'is', 'a', 'list'][1] # prints 'is'
print {'first_key': 'This', 'second_key': 'is', 'third_key': 'a', 'fourth_key': 'dictionary'}['first_key'] # prints 'This'

Reason #3: I can throw practically any type of object almost anywhere I want

Ok, so that might be a slight exaggeration; but the truth is that since Python treats everything as an object, you’re free to pack things away in the strangest places. A great way of demonstrating the power and flexibility of Python is in an example showing a few ways different types of objects can be stored and accessed:

# create a function
def hello_function():
    return 'Hello world!'
 
# create a file handle
hello_file = open('~/hello.txt', 'r')
 
# create a list with the function, the file handle, and a string
list = [hello_function, hello_file, 'Hello world!']
print list[0]() # prints 'Hello world!'
print list[1].read() # prints 'Hello world!\n'
print list[2] # prints 'Hello world!'
 
# or how about a dictionary?
dict = {'function': hello_function, 'file_object': hello_file, 'string': 'Hello world!'}
print dict['function']() # prints 'Hello world!'
print dict['file_object'].read() # prints 'Hello world!\n'
print dict['string'] # prints 'Hello world!'
 
# print types
print type(list[0]) # prints <type 'function'>
print type(dict['file_object']) # prints <type 'file'>
print type(list[2]) # prints <type 'str'> (str for string)

The shelve and pickle modules are also work a look if you like what you’ve just seen here.

Reason #4: The “in” operator simplifies sequences and makes membership testing a breeze

To explain the power of “in”, it’s probably easier to just show you a few examples:

'p' in "spam" # == True
'item1' in ['item1', 'item2'] # == True
'key' in {"key": 'value'} # == True
 
# prints anchor tags for a navigation
for title, link in {'Home': 'index.html', 'About': 'about.html', 'Contact': 'contact.html'}.iteritems():
    print '<a href="%s">%s</a>' % (link, title)

Reason #5: Slicing, stepping, and striding are a walk in the park

Probably my most-hated function in PHP is the substr() function. It should just be easier to access a parts of a string. Thankfully, in Python it’s a piece of cake:

#string slices and stepping/striding
string = 'This is a string'
 
print string[3] # prints 's'
print string[5:9] # prints 'is a'
print string[::2] # prints 'Ti sasrn' (a stride of 2 means print every other item)
 
# works on lists and dictionaries as well
list = ['This', 'is', 'a', 'list']
 
print list[::2] # prints ['This', 'a']

Reason #6-XX: Python makes programming fun again!

I could go on and on, but this post would be endless. As you can see, Python is a flexible, powerful, and fun programming language. For more Python concepts (I didn’t have time here to go into list comprehensions, generators, decorators, etc), I’d suggest you take a gander at Wikipedia’s page on Python syntax and semantics.

Finally, I’ll leave you with a few relevant links that are worth taking the time to check out:

:

2 Comments for this entry

Leave a Reply

*

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...