Programming
Article

A PHP Guy’s Look At Python

By Kevin Yank

Against all odds, I found myself with a little spare time this week. Rather than do something sensible like clean the garage or get some exercise, I took the opportunity to learn a new programming language: Python.

Like may SitePoint readers, I cut my teeth on PHP. I’ve become very comfortable with it over the years, warts and all. PHP continues to be a dependable choice, but PHP hasn’t changed a whole lot lately. Meanwhile, the kinds of applications I’ve been working on have been growing dramatically in both size and complexity.

Python has a lot in common with PHP: it’s a dynamically typed, open source scripting language with excellent documentation and a thriving community around it. Both languages are also a little quirky when it comes to their handling of Unicode text.

Unlike PHP, Python wasn’t originally designed as a language for Web development—it’s a general programming language that just happens to have some excellent libraries and frameworks for building web sites, like Django. This may sound like an argument against Python, but it turns out that when you start writing bigger web applications, most of your code has nothing to do with HTML, and PHP’s HTML-friendly features just seem to get in the way.

Enough Hand-waving! What’s The Code Like?

Let’s look at some of the neat features of Python code.

The most distinguishing feature of Python code is the lack of braces or other delimiters around code blocks. Instead, Python uses the indenting of your code to indicate blocks:

print "Let's count to ten!"
for i in range(10):
  number = i + 1
  print number
print "All done!"

The above code includes a for loop that will run ten times. The two lines following the for statement are indented to indicate they’re within the for loop. The last line isn’t indented, so Python knows the for loop is finished.

At first it feels frighteningly fragile to trust indentation to describe the structure of your code; but once you get used to it, you’ll notice that your code looks less cluttered. Even better, you’ll find it easier to read Python code written by others, because developers are forced to indent their code neatly and consistently.

Python has a number of convenient, little features that make common tasks less cumbersome than in other languages. Take multiple assignment, for example, which lets you avoid creating temporary variables:

a = 1
b = 2
print a, b     # prints '1 2'
a, b = b, a+b
print a, b     # prints '2 3'

Python also has a number of slick features for dealing with what it calls sequences. These let you split and combine lists (the equivalent of PHP arrays) and text strings using simple, consistent syntax, instead of having to remember obscure function names for each.

Python’s list comprehensions let you quickly build complex lists out of simple lists with a minimum of code. They’re a little hard to understand at first glance, but they quickly become indispensable:

me = 'Kevin Yank'
range(5)                                 # [0, 1, 2, 3, 4]
[me[x] for x in range(5)]                # ['K', 'e', 'v', 'i', 'n']
[x for x in range(10) if x % 2 == 0]     # [0, 2, 4, 6, 8]
[me[x] for x in range(10) if x % 2 == 0] # ['K', 'v', 'n', 'Y', 'n']

But all that syntactic sugar aside, the biggest feature of Python that I appreciate after years of coding PHP is its sensible system of modules and packages for organizing code into multiple files. In PHP, when one script includes (or requires) another script, it runs the risk of having its own variable, function, and class names clobbered by the script that it is including.

Python automatically sets up a separate namespace for each file (called a module) that your program imports, so that naming conflicts are naturally avoided. This frees you up to choose shorter, more natural names (especially for classes in big projects), while at the same time forcing you to give more thought to the structure of your code.

Where to Begin?

There is little sense in learning a new language unless you have a reason to use it. For the past couple of years, that reason for many web developers has been Django. The best place to start, therefore, is probably SitePoint’s Django Djumpstart article.

More recently, a lot of developers are taking renewed interest in Python because it is the development language for Google App Engine. It’s worth having a look at App Engine before diving into Python.

Speaking of diving into Python, Mark Pilgrim’s book Dive Into Python is available to read online for free, and is a great way to learn the language from scratch. If you’re after something with more depth and detail, the official Python Tutorial is a rewarding read, if a bit dry. It’s also significantly more up to date.

  • http://ricksweb.info deuce868

    I’d completely disagree that
    “There is little sense in learning a new language unless you have a reason to use it…”

    There are a ton of ideas and lessons that can be learned from other languages you can take back to the old regular language.

    I’m a bit biased though. I got into programming via PHP and find myself wishing I could do more and more Python. I find myself using it for all my shell/cron scripting needs and just finished up the Django book and an initial bit of code with it.

    With all the libraries available for things, using it for quickie script jobs is just awesome. Worth the learning curve.

  • http://www.sourceomnimedia.com PHPCamp.com

    I actually agree. Unless it’s part of your overall career plan learning a language just because it’s there is just intellectual curiosity. Seeing how the PHP forums have 640K posts and the Perl/Python one has 12K it’s clear which one dominates the industry. I have seen some developers embrace Python for back-end tasks but I would lose my lunch if I ever had to support a large web site front-end using it. PHP with all its quirks still rocks.

  • Martin

    If your career plan doesn’t involve improving yourself as a programmer then, indeed, don’t bother learning new languages for the “intellectual curiosity”. However, if your plan doesn’t involve improving yourself you should get out of the business. Period.

    If the only thing your plan involves is having a career and making money you will NEVER be better than an adequate programmer.

    As for 640k posts versus 12k, I suggest that the difference isn’t industry dominance, rather it’s programmer competence. I would say that if they’re asking soooo many questions, perhaps it’s because they simply can’t get it right.

  • Kevin

    “Seeing how the PHP forums have 640K posts and the Perl/Python one has 12K it’s clear which one dominates the industry.”

    Not sure about Perl, but most Python community exists on the mailing lists. My Python mailing lists get about 20x the traffic of all of my PHP mailing lists combined (this includes everything from wordpress and roundcube to the zend framework lists).

    As to the reason to learn alternate programming languages… It’s because it makes you a better programmer. Period. If you can’t see this as a valid reason then you’ll never understand.

    Kevin

  • Larry Anderson

    When I started my transition away for FoxBase/Pro & Chipmunk BASIC (I’m in a Mac shop) I did a lot of looking at multi-platform languages and whittled down my language choices to PHP and Python, currently I am doing just PHP work because that’s whats needed but if I were to do something desktop centric I’d be pulling out my Python books and diving in.

    Both have a similar syntax, very flexible, cross platform and are visually friendly (you can understand the code written). PHP has the advantage of being web based and also on a lot of ISPs support it. Python gives you all the direct desktop resource access that PHP does not, but also doesn’t require a massive overhead of requirements to install.

  • http://www.pixelsoul.net pixelsoul

    So umm besides name spacing, which we will get in PHP 6 there is no real benefit ?

  • hlellelid

    I’m not sure who’s writing website _frontends_ in PHP (or Python) at all anymore. That’s definitely going the way of dinosaurs and CRT monitors, so being “better” at this (whatever that means) isn’t much of a selling point for using PHP in new development. Honestly, I’ve spent most of my development career with PHP, but Python is hands-down a better language. Cleaner, simpler, …. SO much more consistent. It might lack some of the web-focus that PHP has, but -like I said- the world is changing. Yesterday’s idea of web applications is not today’s — and certainly not tomorrow’s.

    pixelsoul: the ability to distribute modules and package software is actually a HUGE problem for PHP that will not be solved by namespaces (though granted, it’ll get slightly better). That said, Python has lots of linguistic advantages — the list manipulation is incredibly powerful, functions/methods are first-class citizens making callbacks and closures possible, there’s multiple inheritance, … and the list obviously goes on.

  • phpimpact

    Python is a nice language to learn, it’s very simple and if you have some experience with PHP, Perl or Ruby, it shouldn’t take you more than 3 or 4 weeks to learn.

  • Anonymous

    I would be interested to see what PHP does in the future, I think its clear that the divide between website and application is closing, PHP will need to face some of the problems inherent in its design otherwise it will end up being a has been. As much as I love PHP 5 I wouldn’t want to embark on a web 2.0 app with it anymore, I will have to look into PHP6.

    As for Python I picked it up in a matter of minutes, although I cant say that im an expert yet.

    I think PHP is probably the best of the scripting bunch but at some point technologies such as .net and java will come back to the fore.

  • http://www.xixblog.com banago

    This is a good discussion on PHP and Python comparison. I do not have an interest right now on Python as I am on the precess of learning PHP, but I would like to look around it in the future and see how it can help my current PHP coding and other Python project pieces.

    Last Word, good post!

  • pritambarhate

    Good post. Python is indeed a clean language but for web I think PHP will still rule for quite a few years. I tried Python around 3-4 years ago liked the language but never quite got hang of its features like tuples. Anyway I was just toying with it. My first love was Java and that’s what I program everyday. Actually I came to PHP just because of its availability on shared hosting. One area where JEE is difficult to find.

    And I think coding in PHP won’t be that dirty in future since the rise of the ‘frameworks’ (mainly MVC). There a quite a few of them out there (May be a lot more than needed. But then in open source choice is good. :-) ) And with the use of these frameworks along with some good coding guidelines, I really think that clean code can be written in PHP. But yes Python makes it mandatory (at least on the surface, if one intentionally wants to write clumsy code no language can prevent it).

    Pritam Barhate
    ————————————–
    WebDesignStudent.net

  • phirate

    My company won’t even accept new contracts for PHP anymore, we consider it that badly out of touch with the state of the art as far as web development goes.

    The essential problem is that web applications are no longer simple. There was a time when the height of web app complexity was having a pile of includes and finding yourself needing memcached. Today even mid-range sites demand vastly smarter methods of dealing with data.

    Web user expectations have risen dramatically as well. Forms must validate and pre-fill intelligently – to do otherwise is basically an unforgivable crime. Long sequences of Click->load->edit->load->response are no longer acceptable, rapid out of band responses, ajax and comet communication, the requirement for effective ORM and a dizzying array of support libraries for everything from RSS consumption to elegant charting has flipped the balance from a need to do primarily HTML, with some application logic, to a complete and dramatic reverse – it is not possible to deliver a modern web app in any kind of competitive timeframe if you’re spending all your time fiddling with HTML, there’s just way too much other stuff to do.

    Ruby and Python stepped up to this challenge to a degree that PHP simply never has – and probably never will. There are no PHP frameworks that can hold a torch to Rails or Turbogears – they are a fundamental expression of their respective language platforms with the web as the interface, not a method for generating HTML with a variety of support libraries.

    I understand that at this point there will be a pile of old school, die-hard PHP geeks shaking their heads and saying “Hasn’t he heard of Cake or …”. If you haven’t already seen the writing on the wall, there’s probably nothing I can say to convince you. I did PHP commercially for years, but I stopped two years ago when it became clear that times have moved on – just as they did for perl when PHP arrived on the scene.

    Change is good, I’m delighted with Turbogears, it takes a clean language and grants it an unparalleled ability to bring a task to the web with a fraction of the code – and a hundred times the readability and manageability – of its nearest competitors on other platforms. I have successfully turned this into a major advantage for my company, and we have been cheerfully stealing contracts out from other firms to the point where we had to boost our price and we still have a month and a half wait time for anyone who wants new work done.

    I cannot bring myself to work with PHP code anymore. It feels like going backwards – from a spreadsheet to a calculator, from the ball point pen to the hammer and chisel. Those who sit there cherrypicking features and saying “PHP 6 will have this too!” have no idea how insane they sound. You could write a book with a hammer and chisel too, but the time it would take! and who would even want it? Get moving now people, and shift to a modern platform. Change comes fast and it’s far better to be leading the wave than lost in the wash.

    Hell, it’s more fun as well, I can spend my time on the fun, challenging parts of the work rather than mucking around with crap.

  • Mike

    I did experiment a bit with Django, trying to create a simple website, and boy there are a lot of settings and files to be configured only to get a simple output.

    From my side, a MVC PHP framework, like CodeIgniter, it’s way more simple and a natural approach to develop a web application.

    And, just like a detail, having identation instead of curly braces it maked difficult to see “for” loops or “if” conditions, especially when they contain a long code.

  • http://www.sourceomnimedia.com PHPCamp.com

    Ha ha, there’s never just a “Period” in a debate about programming so I’ll keep it going. Nice try though.

    I’ve been programming for just about 30 years and I’ve learned more languages than I care to remember. I know some Python but I would still never choose it for a front end. Most languages suck and there’s almost nothing that improved my skills by half of them. All I care about is what’s going to make me the most money and be fun. Python isn’t fun for me.

    We all get out of the business eventually, gotta think diversification of income. I got out of being an employee for about 6 years then I got bored and threw a resume out there asking for a ridiculous sum and darned if they didn’t beat it. So, right now PHP makes me money and I made a commitment so I can’t leave just yet.

    See at some point in your career, if you’re diligent and follow a plan, you’ll have broad experience and be a master at one or just a few skills. I’ve been in management at a fortune 500 company, 6 different kind of engineers (h/w and s/w), worked with customers, production and engineering and also run a couple side businesses. My only point is that this broad experience has helped me more than being good at PERL, PHP, (definitely VB), C++ or anything else.

    You know how it goes. When you’re just starting out people tell you to learn it all. You buy into the job postings that want you to be a master at 10 different languages, 3 different databases, you can fly and work 80 hour weeks and they’ll pay you a measly 5 figure salary. That’s total B.S. Many of us have been there done that. It will take time to understand that’s not how you get ahead and be seen by the industry as a highly valued scarce resource. Supply and demand rules and patience is rewarded. Maybe telling you will help you understand but most likely you’ll just have to figure it out yourself 10-20 years from now.

    We should be proud if we don’t just focus on learning as many languages or functions as we can because it lets us focus more on business, marketing and distribution. You know, the rest of the skills a successful company needs other than just Engineering. Engineers are everywhere. People who understand niche skills and broader skills are much harder to find.

    Not sure why someone would think Python isn’t dominated by PHP but I suppose they would have the numbers to back up that suggestion. So I still agree with the author.

    Good luck in all that you do. Cheers.

  • Anonymous

    @phirate

    I understand that at this point there will be a pile of old school, die-hard PHP geeks shaking their heads and saying “Hasn’t he heard of Cake or …”

    Die-hard PHP geeks don’t have time for your rants.

  • ringobob

    phirate, you’re probably right about where the industry is headed, and I’m glad you have more work than you can handle. That said, the market isn’t ready for everyone to go that way yet. You’re way ahead of the game, and PHP has not yet been left behind, and it may not ever be depending on how languages and applications (and the ever elusive “popularity”) evolve.

  • Thomas

    Feel free to turn down PHP contracts, and I’ll happily sweep them up. PHP isn’t an ivory tower language, it’s a tool to get things done. There are many things wrong with it, but there are also many things right with it. While language aficionados will point out inconsistent naming practices and return values amongst similar functions, a good PHP developer will point out that other languages like Java are far more consistent and would seem to be better designed, yet they’re getting pounded by PHP. Unless someone can manage to make Python easy to deploy and suited for rapid prototyping, PHP will be on top for a while. Ruby is the flavor of the week, and will probably not even be considered in five years for new projects.

    Required reading: http://terrychay.com/blog/article/php-ruby-evil-good.shtml

  • sempsteen

    Sticking to a programming language and avoiding others is not a good idea. I’m a PHP programmer. But the way i learned MVC consept was by reading JAVA documents and studying RubyOnRails. I would like to look at Pyhton if i have time. Also believe or not MSDN has some interesting articles about MVC consept.

  • oddz

    PHP is like that ugly girl friend. She may be ugly but she’s so damn useful. She cooks, cleans and does everything else without a word. Python is fun but isn’t nearly as useful as PHP in my opinion.

  • mikemike

    I agree

  • Jimbo Quimby

    I’ve been looking into Python, but I don’t really have a need to learn it currently, it seems, though it seems like a great language. A bit uninspiring, really. It might be too straightforward.

    I get all my work done in PHP and Javascript, and my serious programming kicks come from javascript at this point.

    I’ve looked into Ruby on Rails, and if you want to talk about “spend my time on the fun, challenging parts of the work rather than mucking around with crap”, that’s exactly what learning rails and deploying it and working with it in general felt like to me – mucking around instead of getting things done. I don’t like frameworks where I don’t know what all of the code is doing. For instance, I was looking at ‘The Rails Way’ and a note mentioned that, to paraphrase, the routing code has been so convoluted that for a long time only one person could change that section of the source, and ‘most developers still don’t understand’ the routing. But ‘you don’t need to’. Wow, that sounds great.

    Ruby seems cool, though. I’d consider writing a site in erb. I don’t really think MVC is appropriate for web applications. I’m going to check out django and turbogears, I guess.

    I think, though, knowing enough about PHP and Javascript and seeing that Ruby and Python aren’t much different, my quest to expand my programming methods is leading to strange languages like Haskell. Now THAT’s different.

  • Robert Idenpidi

    Well i would say take a look at PHP V/s Python: Analysis and you will know there are lots of stuff which PHP can’t do and Python can but there are also many aspects where PHP is winning the race.
    Both the languages have their advantages and disadvantages, you may choose depending upon your need rather than hype.

Recommended
Sponsors
Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in Front-end, once a week, for free.