A PHP Developer Spends a Week with Python

Last week, I wrote about my discontent with PHP and why I chose to give Python a shot at becoming my new tool of choice. Since then, Python and I have spent a lot of time together getting acquainted. I’m finally becoming accustomed to the lack of semicolons and curly braces and have accepted Python’s whitespace neurosis. It hasn’t completely dethroned PHP yet because I am still evaluating which web framework I want to invest the time into learning first (Django, TurboGears, Pylons) and then picking my templating system (Kid, Myghty, Cheetah, Genshi, Clearsilver, etc.) But the more I use Python, the bigger fan I become. After only one week, I’m fluent enough to be writing useful stuff and I’m having more fun doing it. This is how I got started…

Snakes on my brain

First, I highly recommend picking up two books: Learning Python (ISBN: 0596002815) and Beginning Python (ISBN: 159059519X). Learning Python reads like a dry tome that would be right at home in an introductory CS class. It is very heavy on the theory (you don’t actually get to start doing anything until about page 60) and, being published almost five years ago, is somewhat outdated. However, it explains crucial details about how Python works under the hood. For example, unlike any language I’ve ever used, variables are simply references to objects. This might sound insignificant, but consider the following code and it’s output in a Python interactive prompt:

>>> languages = ["Pascal", "Python", "Perl", "PHP"]
>>> thepeas = languages
>>> print thepeas
['Pascal', 'Python', 'Perl', 'PHP']
>>> print languages.pop()
PHP
>>> print thepeas
['Pascal', 'Python', 'Perl']
>>> print thepeas.pop()
Perl
>>> print languages
['Pascal', 'Python']

As you can see, both languages and thepeas are two references to the same object, changing one affects the other. This would have been a very frustrating concept to initially encounter if I hadn’t read Learning Python first.

On the other hand, Beginning Python was published in only 2005 and seems to be better aimed at the self-instruction crowd. It moves along quite a bit faster and includes a greater number of examples. Plus, I find the author’s style of writing more approachable. However, pace and praticality comes at the cost of glazing over some rather important theory. I’ve been reading both books concurrently and find that this approach allows me to soak up more information and helps keep my attention. If you have to choose one book though, get Beginning Python.

Tale of two committees

Finallly getting into the mix; writing code, reading the online docs and my books, and browsing tutorials, I am immediately struck with a key difference in philosophy: PHP was created soley with web development in mind, while Python is a Swiss Army Knife. When using PHP, I just fire up my text editor, add a “<?php” and get cranking. Testing normally consists of FTPing or SCPing the .php file to my server and hitting “Reload” in my browser. Form data is easily accessable with $_POST['stuff'] and MySQL extensions are most likely installed too. PHP is preconfigured on almost every Apache web server and everything Just Works™–which is why I (and everyone else) learned PHP in the first place.

Python, however, doesn’t know what you want to do with it out of the box. It’s a very modular tool that feels right at home either crunching scientific data or processing HTML forms. Fitting with Python’s “batteries included” mantra, you can do almost all of these things without having to download any additional libraries (and if you can’t find a built-in library that does what you want, just head over to the Cheese Shop). However, because it would be hugely wasteful to automatically load every library into memory, Python does require this be done manually with the import statement: “import re” will get you regular expressions, “import pdfgen” will allow you to generate PDFs, “import this” will give you geek poetry (yes, really), etc. Using Python for web development will most likely entail installing and configuring mod_python on Apache, or using the CGI handler. Database interaction modules also have to be manually imported. Doing all of this isn’t difficult, or even time-comsuming, but it does require adapting to the Python way of thinking: “Batteries included… Some assembly required.”

Flexibility, thy name is Python!

If you have the patience to relearn a few things, Python can be very rewarding. I best learn by building stuff that I need, so I decided that my first project would be an offline web-browser / site cacher. It’s not the simplest thing to start with, but it would help me evaluate Python in a real-world application. The program would connect to a site, download the HTML document and its associated images and stylesheets, convert absolute URLs to relative URLs, and save everything to disk with the same directory structure. Having never used Python before, from start to finish, this project took me two days to complete. “Bah!,” I can hear the readers now, “I could have done the same thing in PHP in a quarter of the time and I wouldn’t have had to learn anything new!” While that may be true, four hours after finishing the initial version, I had also converted the crawler into a multithreaded application that improved its performance by a factor of ten. Try that with PHP.

19 Replies to “A PHP Developer Spends a Week with Python”

  1. Yep python is neat. Django is a neat little web framework.
    Though I’m a bit more in love with ruby at the moment. It doesn’t have python’s speed but it has grace going for it. And rails is living testimate to the flexability of ruby.

  2. As far as webapp frameworks go, I can’t recommend Django highly enough. It’s got a lot of attention in the Python community and it has an absolutely great community of its own.

    The best part, though, is the documentation. The djangoproject.com website has the main documentation, but they’re also writing djangobook.com. It’s just like Dive Into Python (http://diveintopython.org/), but specifically for Django.

    Oh, and about the whitespace… You were going to indent anyway, right? Except now it has to be perfectly consistent. You really start to love it after a while. It starts to change the way you look at other languages. They seem dirty with all the curly braces crap and weird, one-line code blocks.

  3. Django is the framework I’ve spent the most time with. Even being new to Python, I’ve found it extremely easy to use. The djangobook.com website is quite helpful, I especially like the AJAX annotation feature.

    However, one thing that I really like about Pylons is the heavy focus on WSGI and the interchangeable nature of its components. Want to use Cheetah instead of Myghty? Fine. I know TubroGears is also somewhat “pluggable”, and I’d like to compare the two frameworks on that matter. Django might also support swapping its components, but from my understanding, it uses its own templating system.

    Zope is the most mature of the bunch, but it also seems to be heavily focused on CMS applications. At least for now, I’d prefer to learn something more generalized.

  4. Python is an interesting language to work with. However, it is for hackers who want to do little magic thing with a very short code line. Python structure is not suitable for big projects and it is not suitable for web too. Working with Zope in a team is a nightmare.

    Python is multithreading. PHP has forks too. Not the same concept but the same effect.

    PHP is much greater especially when you work with PHPSavant, SolarPHP or Zend Framework

  5. pcdinh,

    Feel free to disagree with me, but please tell me why. Simply asserting that “PHP is much greater” doesn’t tell me a whole lot.

    Ditto when you say that “Python structure is not suitable for big projects or the the web”. I a previous post, I explained why I find Python’s syntax and philosophy more practical than either PHP or Ruby on large projects. Having a consistent and agreed upon way of doing things makes a project much more maintainable and scalable; esp. when you have mulitple developers. And why would Python be any less suitable for the web than PHP? Python Server Pages can be used very similiarly to PHP. But even better, there are a number of rapidly evolving Python web frameworks out there.


  6. @ pcdinh:

    “”””Python structure is not suitable for big projects and it is not suitable for web too.”””

    Really ? maybe you should explain that to folks at Google, YouTube, etc 😉
    http://www.python.org/about/quotes/

    @ avr

    “”” what about Zope ?”””

    I’ve read that Zope 2 is “heavy” and complex (Zope 3 seems better now) but Guido Van Rossum, the father of Python working at Google, now backs Django.
    http://video.google.com/videoplay?docid=-70449010942275062&q=django

    Concerning books I like “Dive into Python” (also freely available online):
    http://www.diveintopython.org/

    “Core Python programming” also have a very good review:
    http://starship.python.net/crew/wesc/cpp/

    Personally I now try to use more and more the introspection capabilities of Python to search for docs:
    http://techkr.blogspot.com/2006/12/python-introspection-tools.html

  7. Pingback: PHPDeveloper.org
  8. As a web developer also trying to transition to more Python and less PHP, I have to take great issue with pcdinh’s characterisation. Python’s structure is vastly more suitable for big projects – for the module/namespacing issues alone. I have no experience with Zope but purely as a language find Python much less hacky than PHP. Maybe pcdinh is getting Perl and Python mixed up 🙂

    Actually, it sounds more like a case of using simple PHP frameworks (Solar, ZF) and comparing them to using a large CMS application like Zope… Stay away from Zope for simple website dev and any of the frameworks mentioned (Pylons,TurboGears, DJango) is likely to be an equal or superior choice to the PHP frameworks.

  9. Re: References.

    That’s actually sort of true in PHP as well. Variables are actually just handles to a data structure. If you assign $a = $b in PHP, both variables will point to $b’s data structure until either variable is modified, at which point a copy is made and $a and $b would point to separate data structures. If you assigned $a =& $b, both variables will always point to the same data structure, even if you modify either variable, until you unset() one of them.

  10. A tp.

    You being new to Python and getting something out of it; just remember NEVER to mix tabs and spaces for indentation. You might have read about this Python wart in your books.
    I get along happily using spaces for indentation throughout and either use two spaces or four space indentation consistently in a file (depending on external factors). If I were to cut-n-paste a code snippet that used tabs for indentation then I would immediately change the indentation to spaces.

    – Paddy.

  11. Python is great. However, I find working with PHP on web projects lot easier than Python. Python is a general language and PHP is optimized for web applications.

    What I don’t like from Python is that it does not really support access scope with public, private and protected, provides support of open classes which can be considered evil, support of multi-inheritance which is harmful in big projects. Python code block is truly a nightmare. Python is really a great language for hackers and hobbists.

    It is interesting to see the combination of PHP and Python (for backend processing) in YouTube because there is a lot of the PHP and Java marriage out there.

    Does anyone know a web site that use the combination of PHP and Ruby?

  12. Yes, I could’nt agree more.

    I learned Python from “Learning Python” & “Beginning Python”, and anybody who asks me where to start, I lend them those books.

    Python is a great language to know, you might think you dont need to learn it. But it comes in handy in the weirdest situations.

    great Post.

  13. However, it is for hackers who want to do little magic thing with a very short code line. Python structure is not suitable for big projects and it is not suitable for web too.

    That’s the most ill-informed comment to this post, period.

    Large project support is vastly superior with Python over PHP because Python has namespaces, if for no other reason.

    “short code line” – that’s just too foolish to even bother commenting on.

    “not suitable for the web” – do not confuse flexibility with unsuitability. PHP is at its core a web application language and less so a general purpose language. Python is a general purpose language which happens to be an excellent tool for web applications, and now with many remarkable Python-based web frameworks available, you can write for the web and be ultra-productive at the same time.

    Python has long supported the web in meaningful ways far better than PHP. Unicode? Excellent (and soon to be even better) support for Unicode has been a feature of Python for years. How can PHP claim to be web friendly without a coherent unicode solution, today?

  14. While I would agree that Python is the best language I have had to learn and work with so far, when it comes to web development I feel sad. I live in a place where Internet connection is so broken that to even begin thinking of downloading django and Turbogears is a pain and believe me I have tried! Even where I could find a zip file it was so huge that I never succeeded in downloading the whole Turbogears package.

    Hey, I wish someone just packaged django and Turbogears for Windows and is willing to share the knowledge. We get a lot of Windows (pirated) and Linux software in Jos, Nigeria–shrink-wrapped…why not Python django and Turbogears?

    This is why in frustration I am turning to PHP for web stuff. At least there are shrink-wrapped versions I can buy.

  15. What about Ruby? I am a PHP developer checking out Ruby (for Rails). Man, the language has a lot of common sense. Give it a try – and blog about it. 🙂

  16. “Python structure is not suitable for big projects”

    PHP is *better* for big projects?

    Bwuhahahahahaha….

    Python has a clean and readable syntax, consistent naming, decent object orientation and a powerful namespace system (modules) *especially* for proper separation of code.

    I can’t imagine tackling any maintainable large project with PHP, my goodness.

    There are *many* examples of large projects in Python – Eve online, gentoo portage, Bzr source code control (or any of the Canonical projects) to name but a few off the top of my head.

    The comapny I work for (Resovler Systems) are creating a spreadsheet-like application development tool called Resolver (see http://www.resolverhacks.net/ ).

    It is still in beta and it consists of about 25000 lines of Python code and 85000 lines of code in the test framework. Structure and code readability are *very* important to us.

    Creating well structured code is made a great deal *easier* by using Python – to say otherwise is a bizarre fantasy (have you used Python?).

Comments are closed.