Python With Braces

python

If there’s one thing about Python that’s slightly disconcerting, it’s the complete lack of braces, or as they’re called in American English, suspenders. A feature of every variety of C, Java, PHP, Perl, and a whole bunch of other very powerful languages, braces make things more legible and don’t rely on precise indentation. [Ruby] and [Eran] have come up with a way to use these punctuation marks with Python in a project they call Python with Braces.

As its name implies, Python with Braces doesn’t care about indentation: you’re free to make you code extremely ugly, or write your code properly in K&R style. Each line is terminated in a semicolon, and blocks of code with only one statement don’t require curly braces, just like C and Java.

Right now [Ruby] and [Eran] have a Windows installer with an OS X package on its way. Executing a Python with Braces script only requires executing it with a ‘pythonb’ executable instead of the normal ‘python’ executable.

Comments

  1. msieneb says:

    Meaningless whitespace in python?

    Heresey!

    The point is to make code easier to understand. If you don’t, then all you will get in the end is a bug ridden mess that is impossible to support. Python specializes in readability as well as development speed. This project takes out both of the only advantages python has. Might as well make C a runtime language that can’t use libraries while they are at it.

    • Pixel Pirate says:

      Just because they added braces doesn’t mean it will become a unreadable mess. I don’t use C just so I can throw indentation everywhere, I still like having it neat and tidy as well as using braces.

      • MrP says:

        Braces in Python, heresy!
        The lack of braces keeps the code clean, pure, good.

        People abuse braces, and as a guy who often deals with others code, I hate the idea of encountering braces in python…

  2. opikalo says:

    You can already do it with `from __future__ import braces`

  3. finally, python has caught up to civilized languages like C and java

  4. teanau says:

    really? I find indention infinitely more descriptive of code structure than the occasional little squiggle

    • Rob says:

      Me to, so much so that place an opening brace indented on a line of its own and have the closing brace on a line of its own at the same indentation.

      I started VHDL recently and it’s quite odd –
      Wrong – process (statement; statement; statement;)
      Wrong – process (statement; statement; statement)
      Right – process (statement; statement; statement);

  5. Franklin says:

    Also let’s go back to 1989 where there’s no internet and computers are slower than toy keyboards.

  6. Travis K says:

    Why… My head hurts.

  7. Rob says:

    Dammit! I thought I had done ALL the ‘curly bracket’ languages.

    • Erik Johnson says:

      I’ve never heard of these called suspenders, I always said curly braces or curly bracket. Born and raised in north america.

      • andarb says:

        That was Brian being silly. Besides, braces =/= suspenders anyway. Suspenders have clips, braces BUTTON to your trousers.

      • furiousd says:

        Same, unless he’s referring to the type used on trousers. Trained in the US, always heard them called brackets or curly braces, never heard the term suspenders even suggested

        • angierhafai says:

          American here and I’ve also always called { and } ‘brackets’ and [ and ] ‘square brackets,’ probably because I first started using both when I first started programming C# when I was 10 and I used { and } far more than [ and ].

          When I had to help some friends learn Java freshman year about two years ago it caused some issues though because for most of them [ and ] were brackets and { and } were curly brackets.

  8. T.M. says:

    Significant whitespace is the bigger annoyance by far.

    • dhon_ says:

      I usually see significant whitespace as a huge advantage to pointing out errors (such as having two indented lines after an if statement with no braces). Could you provide some examples of where it is a source of frustration?

      One area I can see is mixed tabs and spaces looking the same but being treated differently. Perhaps Python should have just banned tabs for indenting.

      • Marco says:

        They finally made that the default. Shame half the community isn’t upgrading due to the lack of backwards compatibility.

      • Andrew Jones says:

        “Could you provide some examples of where it is a source of frustration?”
        Sure – leading tabs and leading spaces may LOOK the same, but they are not treated the same. No, I don’t really find ignoring the tab key entirely a viable option, either.

  9. David Hagler says:

    I prefer the inline callback syntax. A language that has demarcations for beginning and ending a block can do this, python cannot. I know I can declare my function, but I just prefer it the other way around – I would find it a nice change to the language, if this allowed that feature.

  10. Brian says:

    Is that opening line supposed to be a joke… http://www.sadtrombone.com/

  11. Luke Keyes says:

    I wouldn’t necessarily say that K&R is the “proper” brace style. I’m much bigger fan of Allman myself. http://en.wikipedia.org/wiki/Indent_style

  12. slim.w says:

    So, this is perl, then? A big improvement!

  13. Zack Kummer says:

    I’ve always hated how Python uses indentation; black should be code, white should be nothingness. Plus I like to compact my code so functions composed of numerous basic commands are on one line. It lets me see more of the code at once. In non-computer terms, it is like being able to spell out “The brown cow jumped over the blue moon” instead of
    “The
    Brown
    Cow
    Jumped
    Over
    The
    Blue
    Moon”

    • msieneb says:

      More like

      the=brown.cow.jumped(){over(the=bluemoon)}

      versus

      the=brown.cow.jumped()
      over( the = bluemoon )

      See how much easier it is to interpret the second one? Which one do you think is more prone to bugs? Fun fact: only 26% of coders know anything about writing secure, robust software and of those that do, 59% don’t care enough to do it. No wonder why software is so terrible and needs daily patching eh?

      Fun fact reference:
      Rotibi, Bola, “Failure to invest in secure software delivery puts businesses at risk,” Creative Intellect Consulting, Feb 21, 2011.

      The posting system sometimes swallows links so I will just leave it at that.

      • Greg Kennedy says:

        The best part of your comment is how the web software ate your preceding spaces on
        over(the=bluemoon)
        leading to precisely the bug that the curly-brace version fixes. I would use more Python if the webpages I posted it on didn’t destroy it all the time.

    • mb says:

      And on behalf of those of us who inherit this style of code, I just want to say I hate your damn guts. I freely admit I’m not as smart as you are, please stop making my life more difficult.

  14. Is not one advantage of a “brace-based” syntax the ability to condense things on to one line? For example in C –

    if(a==5){waffle1;}else{waffle2;}

    Presumably this isn’t possible with a language that relies on whitespace? (I’ve never used Python)

    I admit it doesn’t help with readability, but occasionally you have some complicated if…then…else structure or something that looks much better “out of the way” on a single line.

    • Doug Ballance says:

      It doesn’t help readability, and any semi-modern editor supports code folding which allows you to get it out of the way without sacrificing readability if you do need to work with it.

      I work with python daily, and cringe with the braces and semicolons when working with some of the other languages. The formality of the whitespace in python means I can pop open any random python module and -read/scan- it rather than parse it. The difference is huge once you get used to it.

      Adding braces to python is about like adding a humidifier to a toaster.

    • Javier says:

      You chose the wrong example. In python,
      if(a==5){waffle1;}else{waffle2;}
      becomes
      waffle1 if a == 5 else waffle2
      A one-liner that is easier to read than the C equivalent.

  15. somwonw says:

    The better way would have been end-tags. They would make Python parseable without intendation AND would be faster to write on non-English keyboard layouts (which is one of the original reasons for Python’s design). Like “if a==b: print ‘hjelp’ endif” or just ‘end’ would be ok as well.

    • Robert Wood says:

      I agree, end tags would be perfect. While I don’t mind forced indentation, when its the only indentation tool it can make it easier to make mistakes, especially when copying blocks of code. Whitespace isn’t necessarily too bad when working with “my own code” but not so obvious when trying to understand someone else’s or copy a block of sample code. I started forcing myself to explicitly add end comments (#endif, #endwhile, etc.) which is kind of a pain, but does a wonderful job of providing visual closure especially in some of the more deeply nested pieces of code… especially when coming back to something after a few months or a year.

      While I acknowledge that multiple levels of nested indentation isn’t a great way to code, most non-trivial problems I deal with end up that way at least until the flow is proven and can be properly refactored.

  16. Darren says:

    The worst part of using python is the stupid indentation. Even COBOL did away with indentation requirements.

    • cantido says:

      The indentation is annoying at times.. I like using tabs but konsole replaces tabs with spaces when I use “highlight, middle button paste”.. but I think more than formatting the worst things about python is the things it has in common with other scripting languages like perl etc; Stuff that works differently between versions, multiple alternatives for doing the same thing in the standard library (because the original tries were half baked so someone came along and added another half baked version) and then multiple third party modules for doing some common task like parsing a specific file format that all manage to do one part of the task well but not one of them does all parts of the task well.
      Python is the only scripting language aside from shell/bash that I use nowadays but I find it can often take longer to hack up a quick little tool in Python than it would have to do it in C or Java because of getting stuck with some shitty bug in a module.

    • Required indentation is brilliant when you often have to look through other people’s code. No more discussions about K&R or Allman or any other crazy form people use. No long one liners.

      Forcing a generally accepted best practice eliminates one of the deterrents to readability, a property arguably most important for code quality.

      • Alex Umrysh says:

        I agree. Reading python code where you CAN do things a number of ways but SHOULD do things a certain way makes reading the code of someone else so much easier.

        I converted a C sockets server to python and was able to reduce the LOC to about a quarter of what I started with. The significant whitespace is actually a good thing in python, and those who hate it are, in my opinion, also likely to be the sort of people who cram incomprehensible uncommented jibberish on a single line in C-style languages which require hours to interpret (not that I’m bitter).

        The truth is, as a computer scientist, I don’t care if it’s indents or brackets, as long as I can write the code that gets the job done.

        Additionally, Python is not C, and trying to make it so is going to give you a lot of headaches when you can’t do the sort of low level trickery you can do in C (you can, but it’s not the same). I find it helpful to have different syntax between languages in that it allows me to fall into a programming style that is different between languages.

        Perhaps brackets in python will allow you to write a DSL that compiles to Python more easily, but if you’re trying to do that you should be using something like PLY or pyparsing.

  17. Significantly more hackish was the original implementation of this idea, pybraces

    http://timhatch.com/projects/pybraces/

    It used the -*- encoding: braces _*_ to effectively pre-process the python and convert brace-style blocks into indented blocks.

  18. Otto says:

    see https://en.wikipedia.org/wiki/Indent_style

    Allman, Whitesmith, Gnu, Horstman are all acceptable styles to an
    old programmer who has had to read hundreds of thousands of lines of
    code. (C, C++, Python, Java, Rexx, TeX, Fortran, Algol, Cobol,
    Snobol, Lisp, Scheme, Perl (a pigs breakfast), Basic (RIP), and many
    others including assembly languages etc.)

    Python syntax is helpful in that we don’t have to run it through a
    style checker or formatter in order to make it readable. The compiler
    catches most of the stupid errors. Python allows both object oriented
    and functional styles of programming. It also integrates nicely with
    C and C++ routines so we can get speed when we need it. If one really
    wants to write obtuse unreadable code, it is still possible.

    Java is an anal retentive language where everything is crammed into an
    object in a class structure.

    C and C++ are evolved and evolving languages designed as workhorses.

    But in any language it is possible to write good readable code, or stupid
    obscure code. One can make a program class heavy or object sparse or
    functionally elegant and to a degree the choice is simply one of style.
    Adding braces and semi’s to Python is silly. It will not improve anyone’s
    code or coding style. Programmers will still be able to write elegant
    clear code or awkward difficult to maintain code. If brackets and semi’s
    make some some programmer feel more secure they are welcome to them,
    but IMHO they are just clutter in an already well designed and substantial
    language.

    ###

  19. Mark Sherman says:

    I would prefer if/ end if, like BASIC, or begin/end, like Pascal. Isn’t whole point of python to break away from curly-brace-land?

  20. TheInternet says:

    Wow, welcome to the modern world python.
    Finally possible to have readable code, and no longer so impossibly brittle. No more source formatting ruining an entire script or a simple extra tab breaking everything.

    This should be rolled into the language.

    Only the most backwards language would rely on formatting to decide program flow.

    • Of the points you have mentioned: readable code speaks *for* and not against strict whitespacing.

      Also, can you show a use case where a formatting not following python’s rules would be beneficial?

    • redxine says:

      When I forget to close a curly brace on line 10, perl and C helpfully inform me that it expected ‘}’ on line 1000.

      If I forget an indent in a python block, it’s painfully obvious, and even throws an IndentationError on a line number that’s at least close to the actual problem.

  21. Stan says:

    Have you ever accidentally deleted a curly brace? I did today and was alerted to it by the script that enforces coding conventions on save. A whole block of code jumped to the right, and my problem was immediately obvious.

    If convention says I have to indent to show scopes, using curly braces just forces me to repeat myself for the sake of the compiler. Don’t repeat yourself; write your code for people. The compiler can figure things out for itself.

    Besides, any loss of conciseness is more than made up for by list/dict comprehensions, imho.

  22. j says:

    Which compilers are letting you get away without semicolons in C and Java? They’re statement terminators. you need them.

    In perl they’re statement seperators, and you can elide them at the ends of blocks, since you’re out of statements to separate.

  23. j says:

    woops. read “don’t require semicolons” instead of “don’t require curly braces”.

  24. MarkS says:

    Kill me now… :( Some people are just to stupid to even try to think differently.
    Seriously.. that’s enough…

  25. Whatnot says:

    YES, let’s take the good stuff from python, and destroy it with the poor stuf from other languages!!!
    It’s what bill gates would do.

  26. “You know that thing that makes Python what it is? Why don’t we just screw it?!”

    • Cld says:

      Well, if for you the only thing that make Python is block indentation, you really don’t know the language.
      Python is a fucking awesome object (and not class) oriented language with dynamic and duck-typing and powerful metaclass.

      (But yes, even if I don’t really fond of python block syntax I really don’t see the interest to change it…)

  27. sss says:

    if you want curly braces, write in C/C++/Java/C#/JavaScript, if you want “end” write in Ruby,otherwise leave Python alone.

  28. garganzuul says:

    {} isn’t easily accessed on my country’s keyboard. Hence, Python.

  29. nanicoar says:

    {} isn’t easily accessed on my country’s keyboard. Hence, Python.

  30. This is totally regressive.
    What’s the use-case, use python in illegible one-line scripts? LOL, Civillized? To compare it to old c-syntax copy cats like Java etc won’t do. Are you guys melancholic? Are we going to revere Perl or PHP next too? No wait, they’re already mentioned!

    Really, indentation is mandatory in our company code style guidelines.
    I cannot imagine it different elsewhere.
    So why type extra characters.. or try find matching braces across closures of multiple screens of code, or having to check semicolons.

    To witness: I’m trying to switch from JavaScript to CoffeeScript for personal and I wish I could use it at work. The is far too much unneeded cruft in these languages.

    Perhaps, regard it as some kind of preference, like vim or emacs, tabs or spaces.
    But don’t tell me typing and reading more == better.

    So it sure it the most hacky thing I’ve seen for a while.

    No.. really, try CoffeeScript now, and if you don’t get it, try again in half a year or so. And type JavaScript daily! Backbone, jQuery plugins, etc. Then tell to me again whats “distressing”.

  31. AnarKIT says:

    I honestly dont get why so many people have issues with python’s significant whitespace. Are people so inflexible that they cannot adapt to different syntaxes.

    I use both C and Python and I never want for curly braces in python, nor do I hate them in C. Honestly, python looks much cleaner without them, adding the braces really is just extra code cruft that takes away from one of the big points of python in that its easy to read and doesnt rely on fiddly syntax elements that arent apparent to beginners.

  32. peter says:

    60 comments about curly braces vs whitespace. Wow. Let me try to put out this flamewars before it gets out of hand.

    vi vs emacs?

  33. JimBob says:

    I always heard them called braces or curly brackets, and I’m as American as John Wayne.

  34. vi vi vi viva las vegas! No really I like braces too it allows compactness when you want and you can auto indent the code with many available tools for that if you want … Indeed it doesn’t break when copy-pasting or when you accidently have a tabs or spaces setting in vim. So yes: I see python with braces becoming popular ;).

  35. mb says:

    Actually I need to apologize: Python supports any number of indentation style. I just found the reference for it.

  36. vindolin says:

    Most accurate comment on reddit:

    tonnynerd [+1] 10 points 1 day ago (12|3)
    Reminded me of this: http://news.bbcimg.co.uk/media/images/62450000/jpg/_62450357_restoredfresco.jpg%5B1%5D

  37. wade says:

    Does anyone really call them suspenders? I’ve never heard them called that. I refer to them as “curly brackets”.

    • It’s a joke. The british english word for those things that go over your shoulder to hold your pants up is ‘braces’. Likewise, these characters: “{ and }” are called either braces (british english) or curly brackets.

      I judge the success of my jokes on how many people it confuses. So far, this is the best joke ever.

  38. Sam says:

    Been staying the hell away from Python. If it’s one thing I can’t stand, it’s linguistic proscriptivists.

  39. qwerty says:

    about
    effing
    time

  40. Alex Umrysh says:

    This is cool and all, but what’s the real point? You aren’t going to be converting JS, C, or Java to python just by adding braces.

    If you’re hung up on the braces you’re missing the beauty of Python. It’s not about syntax, it’s about using the tools you have at your disposal to do your tasks more easily.

    It’s great that someone added curly brace blocks to python, but (admittedly without looking) I bet they just compile to indented “vanilla” python.

    The reason Python uses ‘significant whitespace’ is that it makes the code more readable. I’m able to compartmentalize different language syntaxes into different ways of thinking, perhaps I’m biased in that way.

  41. I find Python code very legible due to it’s succinctness. There is less distraction through useless characters such as braces. Saying that “braces make things more legible and don’t rely on precise indentation” is absurd, sorry.

    Before I started coding Python, the forced indentation and lack of braces actually kept me away from it, but since I started appreciating its elegance and got used to it I didn’t look back. That said it is very much a matter of habits as so many things in life.

  42. thejaundicedmonocle says:

    Why would any sane person do such a thing? The last thing the world needs is another braced language. And, to add insult to injury, (as if those filthy braces weren’t bad enough) you just had to just go ahead and add those fowl little semi-colon line endings as well. I wish upon you a very slow painful death.

  43. Andrew says:

    Wait, so now your Python source (with its lovely new curly brackets) won’t run with the standard Python interpreter? Great job, guys.

  44. David says:

    If it were only true. I have just recently taken up Python (having been an old Perl hacker) and, except for the spaces problem (yes, it is a problem), it’s really a pretty good language.

    If there were *only* a braces “option”, and source level debugging/ability to include standard Python modules, great!

    Now make the new variable scoping work with the debugger (pwbdb?:-), and have all symbols available when the debugger enters a source file, and make sure -m pwbdb does not lose the __file__ variable, and voila!

  45. Jerry Spicklemire says:

    Ironically, all of this discussion seems to be about the use of braces, not their complete absence. In Python, historically, the “shark jaws” {} (see a picture of trophy shark jaws, and you’ll see why I call them that) indicate a very handy data structure, called the ‘dictionary’. Other languages have similar features, but in Python when the shark shows up, you (used to) know there’s a dictionary involved. Still, there has been a glaring inconsistency that causes confusion, especially for newbies, that could have been easily prevent simply by extending the use of {}, like so. To create a dictionary you just:

    myDictionary = {}

    Oddly, to add data to the dictionary you don’t:

    myDictionary{‘key’} = ‘value’

    Instead, you use the same notation that is used for some other data structures, such as:

    myDictionary['key'] = ‘value’

    Clearly this was an error, the only mystery is why it persists, especially since the Python 3 project was famously undertaken to clean up Python inconsistencies, among other things.

    The confusion arises when you have to look carefully at what is contained in the [], in order to figure out what type of [] it is. Obviously, myDictionary{} clues you in instantly, or would if it didn’t result in a ‘syntax error’. Isn’t it obvious that these container, wrapper, bookendish things are meant to tell you, at a glance, precisely what they contain, rather than requiring you to open the package first, before you can figure out what to expect?

    Fixing this now would require substantial fortitude on the Prevailing Python Powers that be, but it would be well worth it, for all of the budding Pythonistas to come.

    Now back to the ‘used to ‘ part, mentioned above. Python has had another glaring wart for a long time, the C like string substitution syntax, using the % symbol. This ugly vestigial organ is a carry over from the fact that Python itself was first coded in C, so all of the core developers found this anomoly ‘familiar’. One might be grateful to learn that in Python 3, the % is gone. Except for the fact that it has been replaced with (can you guessed?) ‘shark jaws’. So, now you don’t see {} where you should, but also do see them where you shouldn’t. How could this have happened?

    In Python culture much is made of ‘readability’, but sometimes the blinders seem to take over, leaving those of us who depend on true readability wondering why the Emperor is traipsing around in his undies …

    In simplest terms, Python should have, and only one obvious use of {}, to make a dictionary, and manipulate it.

    Giving credit where it is due, the very cool Dictionary Comprehension gets it exactly right. Maybe soon, we can get the rest of it straightened out.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 94,439 other followers