Cover photo for post Python. Good, bad, evil -1-: Missing braces

Python. Good, bad, evil -1-: Missing braces

Every programmer should learn a new programming language once in a while. Be it for inspiration or just for fun. After some homework in C# some years ago and quite some Java at university (again), Python was my language of choice. This is the first article in a series I plan to write about what I like in Python, what is disturbing but works out and what is really evil. In this article I give a short overview on my motivation to dig into Python and start with a first topic: The missing braces.

This entry is part of my series Python. Good, bad, evil, where I discuss my experiences with Python from a PHP developers point of view. Find references to the successor episodes in the trackbacks of this post.

Learning a language just for the sake of doing so is cumbersome. My motivation for it was, that I needed a well established and responsible ID3 tagging library. Neither a PHP lib nor extension, nor any shell tool I found satisfied my needs, but Pythons mutagen did.

After having tagged my MP3 collection quite well using Musicbrainz Picard, I wanted to have reasonable genre tags for this, too. There is a plug-in for Picard, which tries to determine genres from Last.FM tags for a specific title by a specific artist. I liked the idea, but the plug-in has some serious drawbacks. So I finally decided to take the jump into Python and started with Pagger, a semi-automatic solution for genre tagging on the shell.

Beside the very nice mutagen library, Python is one of the most used scripting languages nowadays. As PHP does, Python allows you to code object oriented, procedural and functional. In this sense it is quite similar to my favorite language. However, Python has some fundamental differences in respect to syntax and semantics, which I found interesting to experience. In addition, learning about different approaches from outside ones own community is always a good idea.

In each article in this series, I will tackle another feature I found interesting while working with and reading about Python. I will show you some small examples to illustrate the discussed feature, discuss the pros and cons I see and conclude with an opinion if I would like to see such an approach in PHP or not. I'd love to read your opinion in the comments, so feel free to discuss your own and my views.

Pagger

This should not be an article about Pagger, but once mentioned, I'd like to give a short overview on what it does: Pagger runs on the shell and receives a config file and a directory with MP3s as parameters. The config file determines the genres you want to be used, mappings between tags and genres, ignore patterns for tags and some more configuration.

Pagger now tries to determine suitable genres for an MP3 from Last.FM tags and from Freebase. If it recognizes all of these genres, it automatically assigns them without interaction. If there are unrecognized genres for a file or none at all, it offers an interactive shell to add new genres, new mappings, ignores regex and more. Learning iteratively this way, Pagger has the goal to assign tags more and more sensible automatically with each tagged file.

You can find the Pagger source code on github. Feedback and contributions are very welcome. But beware, this stuff is below alpha state by now.

The no-brace approach

In contrast to many other languages, Python does not use braces of any kind for syntactical code structure. Don't be too shocked, when comparing the following two code pieces, that perform equivalent operations in PHP and Python:

<?php for ($i = 1; $i <= 10; $i++) { if ($i % 2 === 0) { echo "$i is even\n"; } } ?>

In Python one could achieve the same thing like this:

for i in range(1, 11): if i % 2 == 0: print i, u" is even"

I know that there are more elegant ways to achieve this in both languages, but examples should be simple and stupid.

Cons

I'll start with the cons of such an approach: First, Python code looks simply ugly for programmers that are used to common languages like PHP, Java, C and many others. Braces are the most common approach for structuring source code at all. Therefore, many many coders out there are highly used to that way and are pretty irritated by Python code missing them. It takes quite a while to get used to it, which keeps you from efficient coding at first.

Second, problems occur easily here, when inconsistent indentation is used. Python only looks for the indentation in number of space characters. This might be blanks, but also tabs (and maybe other space chars?). You need to stick carefully to your style of indentation, otherwise your code will break, not only the optical appearance. However, this can also be considered a pro in terms of coding style, as you will see in the next section. And a sensible editor will fix the issues for you automatically.

Braces produce many blank lines in your code. While this might sound senseless at a first glance, this allows you to visually detect mating structures more easily. Python code looks generally more compact, if you do not introduce blank lines by intention. Having to use braces forces a developer to do so, which helps the readability of code.

Pros

No matter in which language you program, sticking to a common coding style throughout a project or maybe even a whole community provides only advantages. Digging into code which looks like it could be your own (from an optical perspective) makes you feel comfortable and therefore eases the process of analyzing the code. Enforcing a common coding style is therefore a goal in many programming communities. Python simply ensures that every code piece at least appears highly similar to every Python programmer.

Typing braces over and over again is cumbersome. Although most developers won't even notice any more, every brace costs a little bit of time. In addition, some keyboard layouts make typing braces hard: For example on a German keyboard, you need to type <Alt-Gr> + <7> to achieve a {. Removing the need to type braces therefore reduces time and non-productive effort while coding. Although both affect you only a very little.

Conclusion

Code without braces looks and feels strange to many programmers, but having the compiler enforce a certain coding style is cool. However, beside the fact that it won't happen, I also would not want PHP to loose its braces. What I would like to see is a common coding standard which can be enforced by PHP using an INI setting.

Naturally, this would be the coding standard I am using, just for clarity. ;)

I will continue this series whenever I find some time to blog and no hot topic is in the pipe. This won't happen before March 1st, since I'm on vacation for a week now. Read you in a bit! :)

Comments

You can skip braces in PHP example too, because blocks consist only of one command. So this is not very good example (-;

php at 2010-02-21

Braces save you, if a file is kind of broken. If python file is broken you have no chance to see where indentation goes wrong (very bad)

php5 at 2010-02-21

May be you'll write also about module organization. In php you have usually one (may be more) classes per file. But in python you have variables, constants, functions in one file! That is really cumbersome. You have often a python class and inside of class some other definitions (property) or whatever. IMO very chaotic. They should be at least sort functions and classes in module...

php6 at 2010-02-21

@php6

Python has had module support since forever. PHP just started using namespaces. See the Python documentation or Google for a tutorial if you don't believe me ;)

And: of course you have fields, functions etc. inside your PHP classes as well. That's how you do OOP!

trond at 2010-02-21

When I first looked into Python, I really welcomed the no braces approach - I think it makes code much more easily readable. And given the legacy codebases I've been subjected to recently, it would be a true blessing if PHP scripts would simply break if someone got the indentation wrong (shudder).

Also, I find when reading books on software development, I can read the Python examples more easily, because it is much clearer which code belongs to which block even when the example spans over more than one page.

Regarding detecting mating structures more easily when using braces, I have to disagree as well... when I was wearing braces as a teenager, I feld that this highly impaired my ability to take part in any kind of mating structures, since braces are mostly not considered very attractive. Imagine how mysterious and interesting I would've been if I actually had a Python instead.... uhm, am I still on-topic here? ;-)

Markus Wolff at 2010-02-21

@trond

You've misunderstood me. In PHP you just use classes. In python you don't know if you should/could classes or function inside module. What I mean, that after php it looks like cumbersome, because it is mix of functions and classes in module. In well written php you never see such organization of files. There is strict separation between functions and classes. Usually, you have some script.php which instantiate classes, but you never see functions definitions inside of some Foo.class.php

module.py

php6 at 2010-02-21

http://code.google.com/p/mock/source/browse/trunk/mock.py

as an example. There are more of course.

IMO python is more strict (=stable) language as php, because of better type ckeking etc. etc. My point is, if you switch from php you see many strange things...

On the other side, there are no really private, protected members of classes, no comfortable (elegant?) type checking of passed classes

php6 at 2010-02-21

@php6 I am afraid you are mistaking "can" for "must" in Python's "code organization" (and PHP's for that sake).

Your examples are just examples of how you MAY choose to do it. You don't /have/ to organize your Python code in such a way. And: you MAY use the same approach in PHP, if you really want to. Try it for yourself (PHP):

Perfectly valid PHP5.

You can organize your PHP and/or Python code this way. Generally, I wouldn't recommend it, but you can. Nothing special about Python there. So there is no "flaw" in Python's code organization capabilities here.

I bet there are tons of horrendous PHP scripts out there, if you want to look into bad PHP code organization.

(I'm more of a PHPer than Python'er myself, and have seen my share of crappy PHP code).

Of course, you'll observe differences when moving from one language to another. If you only know Lisp or Prolog you might feel that there are strange things going on in PHP as well. Or you may not.

In any case, I believe we should listen to Uncle Bob's advice: "Languages are tools not religions. Superior attitudes taken by language zealots ring hollow before the craftsman's toolbox."

http://twitter.com/unclebobmartin/statuses/9180866711

trond at 2010-02-21

well see here

as you can see php can be "no-brace". And this approve that your equivalent is wrong.

From my view point, here code with brace look more logical for third party.. Just image if you have multiple logical blocks without brace.

Alexandr Kosarev at 2010-02-21

python is more clear,simply,unified than php. PHP is a tool. Python is a language.

cottage at 2010-02-22

Tobias, thanks for offering to write a series, I'd like to offer my (vocal) support and tell you that for me, your series will really hit the spot.

I am someone who wants to learn Python but the reasons to do so need to become more concrete because I simply have so much work to do.

I have to know WHY I should learn it, I've asked this question time and again all over the web and the answers seem to provide an all too fleeting glimpse - but never the solid examples which cause me to go - crikey, thats something I could be doing in Python, if only I could programme in it.

In this post for example you explain not only the differences we will experience with the loss of curly braces, but that you get access to the Pagger library, which is cool.

Maybe further on in this series you could explore and explain how for a PHPer Python is better suited to some tasks than for others - and continue to give examples of what you mean.

Hope it goes well, and you have at least one avid follower.

Go Tobias.

PaulG at 2010-02-24

I am also looking forward to your articles in this series - learning Python is something I have been planning on doing for some time to inject some freshness into my PHP world.

Robert at 2010-02-24

Ich bin auch mal auf den Rest gespannt, wobei ich zur Diskussion zum Coding-Style nur sagen kann, dass man sich auf eins einigen sollte, und die dann enforcen sollte, ob per commit Hooks in einem Repository oder was anderem ist dann egal.

Zum Thema "wo schreibt's sich am Schönsten" möchte ich noch Ruby erwähnen ;-) :

/me räumt seinen möglichen Flamewar wieder ein und verzieht sich ^_^

Felix at 2010-03-01

(Oh, und ich sehe gerade ich hab's mal wieder geschafft die Bounds falsch zu lesen, wenn man im Beispiel oben die 11 durch eine 10 ersetzt macht es auch genau das gleiche wie deine Beispiele…)

Felix at 2010-03-01