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.

97 thoughts on “Python With Braces

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

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

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

    1. 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);

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

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

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

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

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

    1. Do you have an example you’d like me to try translating? Admittedly I’m not an expert, but I’m reasonably sure it is possible in Python.

      1. For anything but Python, I’ve always loved a bastardized Allman/GNU style where blocks are indented by two instead of four spaces; braces are indented by one; and functions following the same indentation rules unlike GNU. Example probably won’t space correctly.

        if ($x == 1)
        {
        print “abc”;
        }
        else
        {
        print “xyz”;
        }

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

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

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

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

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

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

      1. I prefer code outlines over scrolling past various function entries in a horribly long file. I also personally believe that if your file is very large, its a code smell that signals that you’ve been doing something wrong with how you are breaking down the problem.

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

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

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

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

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

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

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

    ###

    1. I’m an experienced programmer and I prefer what they seem to call 1TBS :P
      My only beef with the strict spacing requirements in python is that it makes reusing/distributing code a bit difficult. Some people use tab, some use 2 spaces, some use 4 spaces, etc.

      1. In any language that doesn’t enforce indentation you should still be matching the style of whatever code you’re editing. Python will happily accept different intent levels across modules (heck even in the same file it’s okay, just blocks have to equal)

      2. The problem is that people didn’t read the guideline (PEP8):
        “Use 4 spaces per indentation level.”
        “Spaces are the preferred indentation method. Tabs should be used solely to remain consistent with code that is already indented with tabs.”

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

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

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

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

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

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

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

    1. 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…)

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

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

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

  15. 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 ;).

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

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

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

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

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

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

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