66

I was reading that Python does all its "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?

danronmoon
  • 3,814
  • 5
  • 34
  • 56
openfrog
  • 40,201
  • 65
  • 225
  • 373
  • 7
    http://stackoverflow.com/questions/1003841/how-do-i-move-the-turtle-in-logo – Skilldrick Dec 20 '09 at 16:02
  • 13
    In fact, Python supports curly braces, BEGIN/END, and almost any other language's block schemes: see http://www.python.org/doc/humor/#python-block-delimited-notation-parsing-explained! – Alok Singhal Dec 20 '09 at 16:07
  • 44
    "No question is newbie enough" (quote from SO FAQ). SO is about questions that can be answered. I believe both are true here. Perhaps for Pythoneers this is a trivial question, but so what? Others ask "how to get seconds out of a timestamp" or "what's a hex number" and nobody complains. – Abel Dec 20 '09 at 16:27
  • 16
    I agree this isn't a bad question. yes, the answer is available in the docs, etc, but so are the answers to many SO questions. People new to Python often wonder about the lack of braces, why not answer this question as a way to get the best answer out there? – Ned Batchelder Dec 20 '09 at 17:25
  • 6
    @Ned Batchelder: "Why" questions are rarely very helpful. In this case, however, it's simply a confirmation of a fact. Confirmation of fact questions are really a poor use of Stack Overflow. – S.Lott Dec 21 '09 at 01:52
  • 1
    I had the same question, having heard a rumour that it was possible to use braces. I thought perhaps there was an option to the interpreter or similar. I suspect the doc/humour reference above was the source of the rumour. Now I know. Decent question, good answer, thanks all. – yoyo Nov 03 '12 at 23:03
  • 2
    Yes it's true! This is one of the reason I hate Python and his indentation nonsense! – Marco Demaio Sep 18 '14 at 19:15

15 Answers15

100

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
Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589
  • 19
    and for anyone wondering, this important statement is an easter egg. The exception is the python devs saying "nope, never adding it" – Allison Jun 01 '17 at 01:14
44

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

a_dict = {
    'key': 'value',
}
starball
  • 20,030
  • 7
  • 43
  • 238
Paul D. Waite
  • 96,640
  • 56
  • 199
  • 270
30

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()
Lucas Jones
  • 19,767
  • 8
  • 75
  • 88
  • 12
    So how do you end a block? – Jonny Sep 02 '13 at 08:21
  • 2
    You might want to rewrite the function names to be PEP 8 compliant. Newbie questions should be answered with the best looking examples. – dnevins Sep 09 '13 at 06:55
  • 11
    @Jonny: Blocks are ended implicitly, by an outdent/dedent/unindent - i.e., when you reduce the indentation level by one. There is no explicit character that is used to mark the end of the block. This does mean that unlike in C, for example, you cannot have multiple blocks at the same level, as it would create ambiguity. – Lucas Jones Sep 15 '13 at 20:18
18

Python with Braces is a variant of python that lets you do exactly that. It's a project that I've been working on lately together with my friend.

eshirazi
  • 2,773
  • 1
  • 14
  • 13
  • 3
    The link doesn't work anymore. Is there any other link (or any other project you found that does the same thing but stable)? – Piyush Soni Mar 25 '22 at 03:01
14

Use Whyton:

http://writeonly.wordpress.com/2010/04/01/whython-python-for-people-who-hate-whitespace/

maldun
  • 149
  • 1
  • 2
  • 1
    Do note that you can't nest statements to arbitrary depth in Whython. An if block, for example, can't contain another if block. – Asad Saeeduddin Sep 17 '13 at 13:23
  • @AsadSaeeduddin Which is a good thing. From the [Zen of Python](https://www.python.org/dev/peps/pep-0020/): "Flat is better than nested." – Joschua Jun 24 '16 at 21:29
  • 1
    @Joschua I still wish you could nest statements – Benj May 19 '19 at 15:21
12

Yes, it's true.

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

starball
  • 20,030
  • 7
  • 43
  • 238
cwap
  • 11,087
  • 8
  • 47
  • 61
  • 7
    Highly recommended to uses 4 spaces over tab too, so please change old habits if you currently use tabs :) – Jordan Messina Dec 20 '09 at 17:17
  • 16
    No way I'm gonna change tab for spaces. All other code I've written for 10 years use tab indentation without any problems. – Jonny Sep 02 '13 at 08:22
  • 14
    @Jordan Messina I disagree, and strongly so. For indentation purposes, tabs are hugely superior to spaces. I know that Python officially recommends using spaces, but I wish it didn't. – antred Oct 15 '15 at 14:42
  • 4
    @JordanMessina using 4 spaces increases the file size 4 times more than tabs... Also using tabs works everywhere, you don't need to use a configured editor that will replace a tab keypress with 4 spaces. These are good reasons to use tabs instead of spaces for indentation. – baptx Jan 21 '19 at 15:13
  • Only noobs indent with spaces. Soon enough you will realize that file size is smaller and code navigation is faster with tabs. – ekerner Nov 23 '20 at 12:30
8
>>> 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.

Benj
  • 736
  • 7
  • 21
7

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.

Skilldrick
  • 69,215
  • 34
  • 177
  • 229
  • There is nothing "natural" about the inability to easily cut-n-paste, automatically reindent and move by code blocks. Required indentation is a disability. Diagnosing accidental indentation is much more difficult than locating brace mismatches because any typical code editor can make brace errors obvious via properly automatible re-indentation. Indentation is also easy to break and difficult to debug. Removing semi-colons was enough to enforce readable code. Rant rant. – Paul Jul 18 '23 at 15:45
6

Python does not use curly braces for code blocks:

>>> while True {
  File "<stdin>", line 1
    while True {
               ^
SyntaxError: invalid syntax

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

(Notice the "not a chance" message – this is an Easter egg reflecting this design decision.)

As a language designed to be easy to use and read, Python uses colons and indentation to designate code blocks. Defining code blocks by indentation is unusual and can come as a surprise to programmers who are used to languages like C++ and C# because these (and many other languages) don't care about extra whitespace or indentation. This rule is intended to increase readability of Python code, at the cost of some of the programmer's freedom to use varying amounts of whitespace.

An increase in the indentation level indicates the start of a code block, while a decrease indicates the end of the code block. By convention, each indentation is four spaces wide.

Here's a simple example which sums all the integers from 0 to 9. Note that ranges in Python include the first value, up to but not including the last value:

j = 0
for i in range(0, 10):
    j += i
print(j)
bwDraco
  • 2,514
  • 2
  • 33
  • 38
6

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)])
Fernando Cesar
  • 131
  • 2
  • 6
  • 6
    Unfortunately, that project is dead as of 2018. The following is currently active. https://github.com/raptor4694/PyJava – Damian Jan 03 '20 at 20:38
3

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.

miya
  • 1,059
  • 1
  • 11
  • 20
2

Yes, code blocks in Python are defined by their indentation. The creators of Python were very interested in self-documenting code. They included indentation in the syntax as a way of innately enforcing good formatting practice.

I programmed in Python for a few years and became quite fond of its code structure because it really is easier. Have you ever left out a closing curly brace in a large program and spent hours trying to find it? Not a problem in Python. When I left that job and had to start using PHP, I really missed the Python syntax.

  • 18
    "Have you ever left out a closing curly brace in a large program and spent hours trying to find it?" No, never. But I have had tools or editors screw up the whitespace on a couple of occasions and had no way to disambiguate the result. – alexh Feb 11 '15 at 02:20
  • 1
    @alexh Times really have changed! Back in the B.C. days (before cell-phones) we didn't always have text editors capable of auto-matching or auto-inserting braces, parens, etc. I believe your experience shows that development of the whitespace detection feature has generally lagged behind bracket matching. There are text editors specifically designed for Python which don't screw up the whitespace. Tip: make sure you have your editor set to identify spaces and tabs. – Code Cavalier Aug 25 '15 at 17:49
1

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.

Sraw
  • 18,892
  • 11
  • 54
  • 87
  • @Benj Whatever, it doesn't matter. The idea is that with or without braces and semicolons, we will always use indentation. – Sraw Sep 17 '19 at 16:18
0

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

RBT
  • 24,161
  • 21
  • 159
  • 240
0

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