It's very common in C: hacking 'empty if statement' like this:
if(mostlyhappencondition) ;#empty statement else{ dosomething; }
It's working in Python? I mean, can we improve the app's performance by using that? I'd also like to know why.
Empty If Statement finds instances where a condition is checked but nothing is done about it.
Empty Statement: A statement which does nothing is called empty statement in Python. Empty statement is pass statement. Whenever Python encounters a pass statement, Python does nothing and moves to the next statement in the flow of control.
Empty lists are considered False in Python, hence the bool() function would return False if the list was passed as an argument. Other methods you can use to check if a list is empty are placing it inside an if statement, using the len() methods, or comparing it with an empty list.
There is a performance improvement if there isn't an else case in the "if", since the bytecodes don't pass execution into the "if" case.
Here's some functions and the output of dis.dis(foo)
The following sample app:
def foo(x): if x: pass else: return x+2
Disassembles to:
5 0 LOAD_FAST 0 (x) 3 POP_JUMP_IF_FALSE 9 6 6 JUMP_FORWARD 8 (to 17) 8 >> 9 LOAD_FAST 0 (x) 12 LOAD_CONST 1 (2) 15 BINARY_ADD 16 RETURN_VALUE >> 17 LOAD_CONST 0 (None) 20 RETURN_VALUE
The following
def foo(x): if not x: return x+2
Disassembles to:
11 0 LOAD_FAST 0 (x) 3 POP_JUMP_IF_TRUE 14 12 6 LOAD_FAST 0 (x) 9 LOAD_CONST 1 (2) 12 BINARY_ADD 13 RETURN_VALUE >> 14 LOAD_CONST 0 (None)
I can only guess you're looking for the pass
statement, sometimes needed to create an empty code block to prevent a syntax error.
if mostlyhappencondition: pass else: do_something()
It would be much more usual to just do this, which is logically equivalent:
if not mostlyhappencondition: do_something()
There are no significant performance gains to be found here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With