Is it true that I can't use curly braces in Python?

Viewed 77900

I was reading that Python does all it's "code blocks" by indentation, rather than with curly braces. Is that right? So functions, if's and stuff like that all appear without surrounding their block with curly braces?

15 Answers

You can try to add support for braces using a future import statement, but it's not yet supported, so you'll get a syntax error:

>>> from __future__ import braces
  File "<stdin>", line 1
SyntaxError: not a chance

Correct for code blocks. However, you do define dictionaries in Python using curly braces:

a_dict = {
    'key': 'value',
}

Ahhhhhh.

Yes. Curly braces are not used. Instead, you use the : symbol to introduce new blocks, like so:

if True:
    do_something()
    something_else()
else:
    something()

Yup :)

And there's (usually) a difference between 4 spaces and a tab, so make sure you standardize the usage ..

Yes.

if True:
    #dosomething
else:
    #dosomething else

#continue on with whatever you were doing

Basically, wherever you would've had an opening curly brace, use a colon instead. Unindent to close the region. It doesn't take long for it to feel completely natural.

>>> from __future__ import braces
  File "<stdin>", line 1
SyntaxError: not a chance

Well that explains a lot.
Note however, that Python does natively support curly brace-d code blocks! Take a look at below:

if x: #{
    x += 1
#}

For Ada or Pascal programmers, I take delight in revealing to you:

if x: #BEGIN
    ...
#END

Taken from the docs:

Python's parser is also sophisticated enough to recognize mixed notations, and it will even catch missing beginning or end delimiters and correct the program for the user. This allows the following to be recognized as legal Python:

if x: #BEGIN
     x = x + 1
#}

And this, for Bash users:

if x:
    x=99
#fi

Even better, for programmers familiar with C, C++, etc. you can omit the curly braces completely for only one statement:

if x:
    do_stuff()

Beautiful. As mentioned before, Python can also automatically correct code with incorrect delimiters, so this code is also legal:

if x:
    do_a_hundred_or_more_statements()
    x = x + 1
    print(x)



As this must make you love Python even more, I send you off with one last quote from the docs.

Now as you can see from this series of examples, Python has advanced the state of the art of parser technology and code recognition capabilities well beyond that of the legacy languages. It has done this in a manner which carefully balances good coding style with the need for older programmers to feel comfortable with look of the language syntax.

The only limitation is that these special delimiters be preceded by a hashtag symbol.

Yes you can use this library/package { Py } Use curly braces instead of indenting, plus much more sugar added to Python's syntax.

https://pypi.org/project/brackets/

// Use braces in Python!

def fib(n) {
  a, b = 0, 1
  while (a < n) {
    print(a, end=' ')
    a, b = b, a+b
  }
  print()
}

/*
  Powerful anonymous functions
*/

print([def(x) {
  if(x in [0, 1]) {
    return x
  };
  while (x < 100) {
    x = x ** 2
  };
  return x
}(x) for x in range(0, 10)])

As others have mentioned, you are correct, no curly braces in Python. Also, you do not have no end or endif or endfor or anything like that (as in pascal or ruby). All code blocks are indentation based.

I will give some thoughts about this question.

Admittedly at first I also thought it is strange to write code without curly braces. But after using Python for many years, I think it is a good design.

First, do we really need curly braces? I mean, as a human. If you are allowed to use curly braces in Python, won't you use indentation anymore? Of course, you will still use indentation! Because you want to write readable code, and indentation is one of the key points.

Second, when do we really need curly braces? As far as I think, we only strictly need curly braces when we need to minify our source code files. Like minified js files. But will you use Python in a situation that even the size of source code is sensitive? Also as far as I think, you won't.

So finally, I think curly braces are somehow like ;. It is just a historical issue, with or without it, we will always use indentation in Python.

In Python, four spaces() are used for indentation in place of curly braces ({). Though, curly braces are used at few places in Python which serve different purpose:

  1. Initialize a non-empty set (unordered collection of unique elements):

    fuitBasket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
    

    Citation

  2. Initialize an empty dictionary (key-value pairs):

    telephoneNumbers = {}
    
  3. Initialize a non-empty dictionary (key-value pairs):

    telephoneNumbers = {'jack': 4098, 'sape': 4139}
    

    Citation

In relation to format string, curly braces take on a different meaning. See https://docs.python.org/3/library/string.html?highlight=curly :

Format strings contain “replacement fields” surrounded by curly braces {}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}.

Related