Curia

Python as a PHP replacement?

by Seth on Nov.30, 2009, under Python, Web Development

I recently sat down to coffee with a new acquaintance of mine who spends much of his time implementing F/OSS projects at non-profit organizations, and who had just stepped into a lead web developer position using PHP. After sharing pleasantries we began trading stories and talking about each of our “tools of the trade.” When I mentioned that I used to do most of my web development in PHP, but have spent the past year or so trying to move as completely as possible to Python, his response was: “Huh, I have never really thought of Python as a PHP replacement.”

Now, this guy hasn’t exactly been living under a rock for the past 10 years—his resume was quite impressive and included projects in a number of different programming languages; But as you can imagine, I was rather surprised by his response, and it made me wonder: Has the Python community really been that bad at promoting the strengths of Python for web development? Or, does the nirvana experienced by switching from a language like PHP to Python just make us so at peace with the world that we forget the hordes of developers still stuck with C-style syntax? Either way, it got me thinking about a few of the reasons why I decided to switch from PHP to Python; and why I not only see Python as an excellent PHP replacement, but am surprised it is such a “best-kept secret” for web development.

There are already plenty of pages out there discussing Python vs. PHP as a language, so I probably won’t get too technical here. I also want to try avoid turning this into a “Python is better than PHP because…” rant (for more on that, please see the end of this post), so I will simply share with you a few of the main reasons why I decided to replace PHP with Python as my primary language for web development:

» Python is more flexible than PHP

Python was engineered from the beginning to be a general purpose programming language. PHP on the other hand was written to overcome many of the “limitations” of the cgi-bin. This should say a lot about the “soul” of each language, but the conclusion I have come to is:

  • PHP is meant to do web things really well
  • Python is meant to do most things really well

Sure, these days you could write a desktop GUI in PHP, but it would most likely not be the right tool for the job (and you’d probably get laughed at). On a somewhat related note: many PHP developers I know find themselves switching between PHP for their website tasks, and a variety of other languages for other tasks (Shell Scripting for command-line scripts, Perl for text processing, etc.). As a Python programmer, I can typically stick to one programming language no matter what the task at hand requires (especially when armed with iPython).

Now, the obvious argument for PHP at this point is: “But wait, since PHP was written specifically for the web, shouldn’t that actually give it more credibility as the right tool for the web job?” Well, 5 or 10 years ago I might have agreed with you, but web development has changed a lot in the past few years (not to mention the introduction of Python’s WSGI spec).

The internet as a platform has grown and mutated drastically and now requires much more than “a server-side extension to HTML.” We are now in an age of full-blown internet applications, which require a true “application-level” language. In my opinion, PHP has only recently begun to move in that direction with the v5.3 release (as well as updates expected in PHP 6). That alone should give you pause when pondering PHP’s ability to “keep up” with the growth of the web.

In short, the internet continues to transform into an arena that is much less of a website platform, and much more of an application platform. To me, this makes a general purpose language such as Python the obvious choice for “future-proof” internet development.

» Python is typically faster than PHP, even especially on the web

You might find PHP beating out Python in a simple “hello world”-type test, but “real-world” applications will typically run much faster in Python. In a Web 2.0 world where everyone has broadband, speed is now an important factor in keeping your visitors happy.

In addition to “raw, under-the-hood” speed, Python’s language philosophy means it will typically scale better than PHP (although this can be argued a million different ways, since scalability usually involves much more than the language).

I’ve already done benchmarks comparing a few popular web frameworks, but if you’re still curious I’d suggest you dig around with Google for a while.

» Python is easier to read and maintain than PHP

Any veteran programmer will tell you that code readability plays a huge factor in code maintainability. With that in mind, Python was designed with some pretty strict syntax rules in regards to code-blocks and whitespace. While this may initially frustrate programmers who are used to a looser “bracket-encapsulated” language, it actually forces you to write more readable (and therefore, more maintainable) code.

Other than readability, Python’s clean syntax also means:

  • You can write more code with less errors (because they’re so easy to spot). This often comes as a pleasant surprise to programmers migrating from C-style languages (take Eric Raymond for example).
  • You end up typing less — No more semicolons or brackets, and fewer parentheses.
  • Your eyes don’t have to move around as much to figure out what’s going on.
  • Your first guess about what’s happening in a code-block is usually correct.

When you have time to kill, I’d recommend a stroll through Rosetta Code to compare how different languages “look” when tackling the same problem. Unless you just love brackets, I think you’ll find the non C-style syntaxes much easier to read.

» Python is more consistent than PHP

Continuing somewhat in the vein of readability is the topic of consistency. Since PHP’s lack of consistency has already been studied exhaustively by the Perl folks, I will spare you my rant and suggest you read theirs.

As a side note on this topic: I often hear PHP programmers talk about how awesome PHP’s documentation is in that you can open a web browser and just type “php.net/some_function” to get help. Well, documentation recall usually isn’t that big of a deal for me (because I have a somewhat photographic memory), but I will say that after switching to Python I found myself turning to its documentation significantly less than I had with PHP, simply because I didn’t have to keep reminding myself whether that infrequently used function was named some_function or somefunction. With Python, the function/method I need is usually named exactly what I expect it to be named, and returns exactly what I expect it to return.

Oh, and don’t even get me started on PHP’s recent namespace decision.

 

» However, PHP still excels in a few areas «

Having said all of that, there are a few areas where I believe PHP may still shine brighter than Python:

» PHP hosting support is may be more prevalent than Python

It’s practically unheard of to find yourself on a web host that doesn’t support PHP out of the box. However, this is becoming less and less of an issue since most Python web applications can now be deployed using tools such as FastCGI or mod_proxy (as opposed to the popular mod_wsgi setup, which often requires root access to configure). These days any “reputable” web host is probably going to support some sort of strategy for deploying Python web applications. Of course, this only really applies to shared hosting environments without root access. If you’ve got a VPS or dedicated server you’re fine.

» PHP is arguably “more seasoned” on the web than Python

The communities behind projects like Drupal and WordPress really stand out to me as examples of the maturity of PHP on the web. Although similar Python web projects have been slowly emerging (and Plone has been around for years, if that’s your cup of tea), they don’t really compete yet in my opinion.

Of course, I am only talking about specific web projects here. Language wise, Python has been around longer than PHP. Web 2.0 framework wise, Python’s offerings have been around about as long as PHP’s (pretty much every language had its own answer to Ruby on Rails in 2005).

» PHP seems easier than Python at first (and might be for simple deployments)

There’s something magical about throwing together a few quick index.php/about.php/contact.php files and uploading them to the httpdocs directory of your webserver and it “just working.” A lot of simple websites have no need for acronyms like MVC, ORM, and DRY, and in those cases PHP is an excellent “server-side extension” to HTML. However, if and when you begin to scale, you’ll either find yourself switching to a full-blown framework, or throwing one together to help facilitate your growth. At that point, you’ll probably begin discovering the “dark corners” of PHP, and may find yourself wishing you had “done it right” the first time.

 

» So, which is better? «

Remember, the point of this post is to solidify the fact that Python can be an excellent PHP replacement. When it comes to programming languages, “better” is often more a case of personal preference than anything else. However, to me the points discussed above make Python the better choice when it comes to what I like in a web development language.

So, is Python a better web development language than PHP?
Well, does Nike make a better shoe than Adidas?

The most honest answer is probably: “It depends.” Python definitely has some significant advantages over PHP in certain circumstances, but the same could probably be said of PHP in other circumstances (although limited to the web I imagine).

 

I hope this post has encouraged you PHP programmers out there to take another look at Python. It may take some getting used to (Python’s way of doing things is inherently quite different than PHP’s), but you will probably find yourself thanking me later.

:, , ,

5 Comments for this entry

  • Dave

    Nice summary. How do I use python directly as a scripting language? Is there something similar to having PHP run by apache, or is there a little more to it?

  • Seth

    Dave,

    Thank you. Good question, and perhaps I will do a “part 2″ of this post going into more detail about that.

    In short I would suggest you check out a simple Python framework (Bottle is a great option) to familiarize yourself with how Python does things differently.

    Like PHP, the Python interpreter process can be run with Apache (using mod_wsgi). However, unlike PHP you will typically separate your “controller” and “view” code instead of writing HTML around <? and ?> type tags. While this may seem complicated at first, it actually lends itself to a better code layout. In PHP terms, it’s much like the process of using Smarty templates (PHP-only files as your “business” code, which then process and render your Smarty “presentation” code).

    Several Python template options exist, with the most popular ones probably being Mako (super-fast), Jinja (quick & simple), and Genshi (slower but XML-based).

    There are of course many options for deploying Python web applications, with mod_wsgi only being one of them. Typically during the building & testing phase, you will run your Python web app on some sort of built-in WSGI implementation and load it locally (if you’re familiar with Rails, it’s like running your Rails app locally and loading it on port 3000).

    Hope this helps!

  • V

    Interesting post.

    I’ve been interested in Python for a while now, having spent almost a decade with PHP. Seems a rather nice language and I can certainly see its benefits over PHP.

    However, I wonder about some things, for instance:

    1. Being developed for web, PHP has some inherent solutions for common requirements like session management, fcgi interfacing. Those are done in C, in the core of PHP, while Python requires middleware written in Python (e.g Beaker, Paster’s HTTP server or wsgi/fastcgi implementation).

    I wonder if there is a significant performance hit for Python because of that.

    It is true that there exists some theoretical threshold of app complexity above which PHP’s requirement to bootstrap entire application (the part thereof required to process the request) becomes significant performance bottleneck compared to load-once apps like those written in Python, which offsets any speed benefits of C code inside PHP. But I wonder how significant this is in practice? Even the most complex app has little to do in PHP. They all wait on I/O of whatever sort, even if the request generates dozens or more queries (take Drupal modules for example, at some point there can be over a hundred of queries per request). It is the stateless nature of HTTP that brings all languages to the same level requiring “third party” intervention like memory cached session management or data layers, database I/O, etc…, and number crunching algorithms can anyways be moved to C both in Python and in PHP. That being the common denominator, the true differences are then shown in parts that are done in the language itself: in this case the aforementioned session management, fastcgi interfacing (or in Python, entire HTTP server written in Python — Paster’s), etc…

    2. GIL worries me. While it is true that, especially for web applications, threads usually wait on I/O so GIL is not that much of a problem, I am not so convinced for practical implementations of apps that require performance and cache data wherever possible (reducing I/O wait). There, the GIL definitely impairs performance, but I wonder how significant?

    Also, SMP deployment with PHP is as simple as instructing PHP to spawn more processes. I’m assuming fastcgi implementation since Apache (and it’s mod_php) should not coexist with “performance” in the same sentence. :)

    It is as easy with Python (for instance using Paster), but each of those instances is interfaced with the web server through Python code, not C implemented code. Evenmoreso if proxying is used for load balancing.

    So if syntactic sugar present in Python is not sufficient to move us from PHP to Python (and in my case, I can name two: decorators and indentation/lack-of-$;{}, everything else is more or else the same), is there anything else that Python can offer?

  • Nilesh

    Thank you for this summary, I was searching for something like this – step wise differences between PHP and Python. I am a PHP Programmer but something clicked my mind that Python may be faster than PHP in webdev. And finally it is true what I thought :) Thanks again.

  • Julius H from San Jose, ca

    Wow! Thanks for the thorough explanation! Personally I am a bit of a newbie and was teaching myself python for application development, but wanted to eventually learn web developmen. So I thought I would have to eventually have to learn PHP to do this, reading this makes me more confident in Python and will save me time since I will not spend hours and hours of grueling study learning PHP. I will start from scratch figuring out how to deploy Python and hopefully by then the community will be bigger so I can ask around for meticulous question.
    THANKS A BUNCH!!!! =D

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...

Archives

All entries, chronologically...