Python From The PHP Perspective

Where I work, the decision has been made to use Python for all new projects. Up until this point, the vast majority of my coding experience has been in PHP. I had been reluctant to take the time to learn Python, because it did not give me anything that I needed, but I started reading the Python in a Nutshell book (BTW, since when were “nutshells” 700 pages?). I was pleased to read about the ability to compile Python code into .exe and .app files, because I have thought about the possibility of writing educational software some time in the future (meaning more than a year from now).

First, keep in mind that I am approaching Python from the web development perspective. PHP is basically designed for web development (though it can be used for other purposes, e.g., see PHP-GTK); Python is not designed for one specific purpose; web development is one of its capabilities. In many ways, the languages are similar (they are both VHLLs), but they definitely have their differences. Some of the differences are small (e.g., in PHP a set of key and value pairs is called an associative array and in Python is it called a dictionary, in PHP you use “null” for a null value and in Python you use “None,” etc.) and some are not (we’ll get there).

PHP Weaknesses
In my opinion, the three big problems/shortcomings of PHP are inconsistency (such as in function names, argument order, etc.), lack of namespaces, and lack of multiple inheritance (which is probably not a concern for most web apps). In order to get a better idea of what is supposed to be so great about Python, I did some searching and came up with a Python page that compares Python and PHP. You can easily see that is biased, because there is a list of a lot of things Python has that PHP doesn’t, yet most of those are inaccurate or incorrect in PHP5 (which came out 3.5 years ago). For example, the claim that references are “painful” in PHP5 when it takes just one character more than standard assignment (e.g., $b =& $a) or that “method chaining” is not in PHP. This is from my personal code:
$this->db->from('news')->orderby('datetime', 'desc')->limit($limit);).

Screenshot of PHP code in a terminalSome other common complaints with PHP are how easy it is to mistype a variable name, create ugly code, and that it is not object-oriented. With the first one, you simply turn on full error reporting and use of uninitialized variables is shown as a notice (and you should be creating code to strict standards on a dev server anyway, right?). As far as creating ugly code, I think that’s an opinion either because people don’t like braces or they base their claims on the fact that you have a lot of choice with PHP and so beginning programmers can make ugly code. The screenshot shows all of the code that is in the view file for my “recent-sites” page (something I threw together in just a few minutes last night). Python generally has one way of doing something or else one way that is preferred, so there is more consistency from one Python programmer to another, but only part of this is due to the language itself (I could write a Python script that uses 5 spaces for indentation instead of 4, but people would blame that inconsistency on me whereas a PHP programmer who puts a brace on the same line as an if statement vs. the next line is somehow demonstrating a flaw with PHP?). As far as OO goes, PHP5 does everything I need from an OO perspective quite nicely.

Python “Issues”
Python is mostly consistent, but there are some things you have to learn (e.g., you don’t do str.len() when you want to get the length of a string, instead you do len(str); for counting the times a character, say x, appears in a string, you would do str.count(’x') though). One of the “nice” things is not using dollar signs for variables/objects, but that also means you have to know every reserved keyword (easy enough for a programmer, but potentially problematic to someone without programming experience) because they appear the same (e.g., del = 'blah' produces an error but delete = 'blah' does not). Fortunately, those are very minor issues and not real problems.

One of the first things that I noticed that annoyed me was the handling of whitespace when concatenating. Assuming “x” is a variable with a value of “7″ that we have already declared:
print "there are many (", x, ") parts"
Produces: there are many ( 7 ) parts

Where did the spaces come from? The answer is that Python inserts them automatically. I guess that’s supposed to be a nice thing, but look how ugly the code ends up being to do the same thing without the automatic spaces (note the “backticks”):
print "there are many (" + `x` + ") parts"

Maybe some people like the language to work that way, because it is convenient, but then why are class methods in Python so inconvenient? Specifically, why do you have to pass “self” to every single method so that the method can actually affect things from the class that it is part of? Even the __init__ methods require self, but I can’t imagine an __init__ method (the equivalent to a PHP __construct method) that would exist for a purpose other than to affect the class…

Comparisons
PHP is inconsistant with function names, but it does have excellent documentation. Compare PHP’s “print” documentation to that of Python’s “print” documentation, especially the number of examples. After that, feel free to do a search for “string word count” (so that you can find out how to count the number of words within a string, such as for determining the length of a blog post).

In PHP you would do:
str_word_count($werdz);
In Python (found nothing in the documentation, so I came up with):
len(werdz.split(None))

Hopefully I missed some clearer way of doing word counts in Python, because I can assure you that a programming newcomer would not easily understand the Python statement. Personally, I think Python appears to be a good language, but it isn’t the “language of God” as so many users seem to think. For someone who wanted to get into web development with no past programming experience, I would still have to suggest PHP first. The documentation is far superior to Python’s (which has actually been around longer…) and the support is better (not comparing communities, but PHP is more likely to be installed on a shared server and the tech support is more likely to be able to provide some help). Also, most shared hosts aren’t on the latest version of Python (2.5.1, which came out in April, 2007). For example, Dreamhost is on version 2.3.5, which is over a year old and doesn’t even support ternary expressions. DH has version 5.2.3 of PHP (latest version is 5.2.5).

I’m going to try to stick with Python and learn a little each day, but I’m not wow’ed like I had hoped to be. If anyone has any thoughts or can present better code samples (especially a Python example of the code from the screenshot), please share. I am certainly not an expert of either language (especially not Python), but I like to learn. If you have any thoughts on other shortcomings of either language in the context of web development, feel free to voice them as well, but please note the difference between a problem with a language and a problem with programming habits.


7 Responses to “Python From The PHP Perspective”

  1. 1 Josh Schumacher
    #!/usr/bin/python
    
    import sys
    import web
    from web import *
    import magic
    from magic import OCR
    
    class CodeSample:
        def __init__(self):
            myCode = magic.OCR.ReadFromWeb('http://blog.gordaen.com/wp-content/uploads/2007/12/recent_sites.png')
            print myCode
    
  2. 2 Josh Schumacher

    crap, forgot to wrap my code in a pre tag, guess it won’t compile now.

  3. 3 Gordaen

    LOL! I added the pre tag so we can marvel at your awesomeness :D

    For anyone interested, the Python FAQ has a few answers to some of my problems. Each of the answers generally is not so much of a “that’s because it makes sense for the coder” answer as a “that’s how it has always been” or “it’s because of the way Python is implemented” answer.

  4. 4 Mason

    If this is messing you up:

    print “there are many (”, x, “) parts”

    You could try:

    print “there are many (%d) parts” % x

    or used named tokens:

    tokens = {’part_count’:34}
    print “there are many (%(part_count)) pargs” % tokens

    Also lends a bit to clarity.

  5. 5 Mason

    Additionally, you may find this entertaining: http://xkcd.com/353/

    I have a heavy PHP background as well… Python didn’t really fascinate me until I really started exploring… Ruby lent a helping hand.

    If you want a super-sweet reference on all the little sweet things Python can do, pick up Python in a Nutshell.

    If you want a Pythonic web framework, check out Django. Holovaty and JKM just released a great reference on it.

  6. 6 Mason

    Additionally (and sorry for repeatedly spamming your blog… I’m kind of replying as I read), you can install Python under your Dreamhost user account if you have issue with the version they provide. Just install from source, making sure to specify your install path during configuration. Then just make sure that directory is in your PATH, and you’ll be able to soar with your own wings.

  7. 7 Gordaen

    The advantage of the backtick method is that you don’t have to know if the variable is an int or a string. I was aware of the %d, %s, etc. method, but I did not know about the tokens, so thanks for sharing that. Apparently you can use %s with non-strings just fine, so maybe that’s the method of choice.

    Haha, I love xkcd. I decided to actually finally go through all of the archives a month or two ago and have been keeping up via RSS since.

    The Python in a Nutshell book is great as a reference, though I find that Dive into Python has better examples in many cases (more “real world” as opposed to just demonstrating what a statement looks like). Funny that you should mention Django, as that’s pretty much been the reason for the change to Python at my work. Python, by itself, is not great for web projects, but Django is a very good framework.

    As far as installing a “personal” Python (or anything else for that matter) at Dreamhost, that’s the way to go. Even installing a personal copy of PHP lets you better configure the software, but the problem is that many hosts won’t let you do that. Then you’re stuck with whatever version they have (if any at all). I’ll likely be going to a VPS solution within the next 4 or so months, so that won’t be a worry for me. It’s more of a consideration for the new programmer who only wants to shell out a few bucks for some web space.

Leave a Reply