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

15

70

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?

Admiralty answered 20/12, 2009 at 15:57 Comment(8)
#1004341Trigg
In fact, Python supports curly braces, BEGIN/END, and almost any other language's block schemes: see python.org/doc/humor/…!Slaveholder
"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.Clyte
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?Digged
@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.Humanly
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.Sheathing
Yes it's true! This is one of the reason I hate Python and his indentation nonsense!Florist
Check this out: github.com/mathialo/bython :D you're welcomeEdgar
K
104

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
Kaenel answered 20/12, 2009 at 16:7 Comment(1)
and for anyone wondering, this important statement is an easter egg. The exception is the python devs saying "nope, never adding it"Lianne
B
44

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

a_dict = {
    'key': 'value',
}
Blackboard answered 20/12, 2009 at 16:1 Comment(0)
B
31

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()
Bridges answered 20/12, 2009 at 16:0 Comment(3)
So how do you end a block?Hellenic
You might want to rewrite the function names to be PEP 8 compliant. Newbie questions should be answered with the best looking examples.Sheelah
@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.Bridges
A
20

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.

Another interesting project, is Bython.

Asthma answered 9/2, 2014 at 21:37 Comment(2)
The link doesn't work anymore. Is there any other link (or any other project you found that does the same thing but stable)?Barkentine
github.com/mathialo/bython probably? However all such preprocessors have a big issue - impossibility to define braced dicts (although it is basically pretty simple to distinguish from the code scope).Scanner
P
14

Use Whyton:

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

Pandean answered 10/6, 2011 at 11:24 Comment(3)
Do note that you can't nest statements to arbitrary depth in Whython. An if block, for example, can't contain another if block.Languorous
@AsadSaeeduddin Which is a good thing. From the Zen of Python: "Flat is better than nested."Rusel
@Rusel I still wish you could nest statementsTwopenny
S
13

Yes, it's true.

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

Sacrilege answered 20/12, 2009 at 15:59 Comment(6)
Highly recommended to uses 4 spaces over tab too, so please change old habits if you currently use tabs :)Minardi
No way I'm gonna change tab for spaces. All other code I've written for 10 years use tab indentation without any problems.Hellenic
@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.Aigrette
@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.Psalterium
Only noobs indent with spaces. Soon enough you will realize that file size is smaller and code navigation is faster with tabs.Vilberg
I've been on the 4-space indent team for a long time and although I still indent like that for compatibility, in recent years I came to the understanding that the advice, although well meaning, was myopic. Tabs and spaces have semantics attached to them and code editors can be configured accordingly. You can make a tab look like x spaces. So while google recommends 2 spaces for a tab and the rest of the python world works on 4, if everybody just went with an actual tab, you could then set your editor to "stretch" the tab to make anyone's code look however you want on your screen.Azoic
T
10
>>> 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.

Twopenny answered 18/5, 2019 at 14:49 Comment(2)
Very funny. Not.Skittle
That was Snarkoverflow.Paratrooper
T
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.

Trigg answered 20/12, 2009 at 15:59 Comment(1)
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.Ulda
L
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)
Liripipe answered 27/2, 2014 at 6:5 Comment(0)
P
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)])
Perfumery answered 22/5, 2019 at 20:44 Comment(1)
Unfortunately, that project is dead as of 2018. The following is currently active. github.com/raptor4694/PyJavaChud
P
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.

Pachyderm answered 20/12, 2009 at 17:10 Comment(0)
E
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.

Essy answered 2/3, 2013 at 0:12 Comment(2)
"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.Konstance
@Konstance 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.Essy
O
1

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

Octavla answered 1/8, 2018 at 3:34 Comment(2)
Actually, for the set you need to use square brackets ([ and ].Obligee
I think you might be talking about lists. Lists -> [], Tuples -> (), Sets -> {} and Dictionaries -> {}Crept
L
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.

Laud answered 27/3, 2019 at 2:3 Comment(1)
@Twopenny Whatever, it doesn't matter. The idea is that with or without braces and semicolons, we will always use indentation.Laud
M
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 }}.

Montreal answered 27/3, 2019 at 1:23 Comment(1)
They are also used for dictionaries.Obligee

© 2022 - 2024 — McMap. All rights reserved.