if statement - use of parentheses

Asked

Viewed 258 times

1

Using parentheses with if, alters code performance or modifies something?

Example, this:

if (1 != 2): print('É True')

compared to:

if 1 != 2: print('É True')

If it is only aesthetic, which form is more recurrent to use?

2 answers

3


The use of parentheses, in particular for ifandwhile, in Python, it is more a decision of software engineering and maintainability, this having no relation to the performance of execution. 3

Clean, clear and correct code principles important to the software quality, are affected by this decision.

Therefore, you should use parentheses when these will help in reading and understanding the code. 5

One detachable point here is to say about the precedence of operators, and in these cases, the programmer must/must use the parentheses to control the order of execution of the evaluations.

Like:

print(1 + 1 * 2, (1 + 1) * 2)  # print 3 4

0

There is no gain or loss in using extra parentheses in expressions like if and while. They are not mandatory in the language precisely to simplify the reading of the expressions. o : at the end of the commands does the separation of the expression to the block contained in the command - so there is no potential ambiguity that exists in C and the languages that copied its syntax requiring parentheses in the if.

Extra parentheses are automatically removed at the build stage of the program (remembering that the Python build is automatic). See as a function that uses parentheses and another that are not identical after compiled:

In [15]: def a():
    ...:     if qualquer_coisa == 1:
    ...:         pass
    ...:     

In [16]: def b():
    ...:     if (qualquer_coisa == 1):
    ...:         pass
    ...:     

In [17]: import dis

In [18]: dis.dis(a)
  2           0 LOAD_GLOBAL              0 (qualquer_coisa)
              2 LOAD_CONST               1 (1)
              4 COMPARE_OP               2 (==)
              6 POP_JUMP_IF_FALSE        8

  3     >>    8 LOAD_CONST               0 (None)
             10 RETURN_VALUE

In [19]: dis.dis(b)
  2           0 LOAD_GLOBAL              0 (qualquer_coisa)
              2 LOAD_CONST               1 (1)
              4 COMPARE_OP               2 (==)
              6 POP_JUMP_IF_FALSE        8

  3     >>    8 LOAD_CONST               0 (None)
             10 RETURN_VALUE

That is, the parentheses is not even indicated in the bytecode, which is what is actually executed - the "decompilation" process of dis.dis there’s no way of knowing it existed in the source code.

Note that this does not prevent you from using parentheses for improve on the readability of the code, especially in complex expressions of a if which may have to be broken into more than one line. In such cases, even, parentheses are preferable to the line continuation indicator \ .

Browser other questions tagged

You are not signed in. Login or sign up in order to post.