Reputation: 113
I was researching how to use pass statements in python. I have looked at (How to use the pass statement in Python) and while reading answers came up with some questions concerning other uses of the pass statement...
Should I use the pass statement in python for making my code more readable?
and
Would using the pass statement in this way potantially cause me any issues?
For example:
Below is a super simple program that basically says if someone is less than or is equal to 30 years old, don't do anything (pass). I know that if I wouldn't put pass, I would get an indentation error. Then after that I have my elif that'll print out "You are older than 30" if age is greater than 30.
age = 32
if age <= 30:
pass
elif age > 30:
print("You are older than 30")
Now I could've just written this code like this:
age = 32
if age > 30:
print("You are older than 30")
However, in terms of code readability, does adding a little more code and making things explicitly clear overall help me others who might go into the code in the future? Would coding in this way cause me any issues? Is there anything about using the pass statement in this way that could cause me some hiccups?
Upvotes: 1
Views: 3894
Reputation: 149
The pass
keyword was used for the language lexer. The indentation of a block is deducted from the first line after every colon :
. Without pass
, the following code would be ambiguous.
if condition:
do_something()
As for your question, I suggest only using pass
where it is needed. Having shorter code is better.
Upvotes: 0
Reputation: 569
Hiccups and slowdowns will be thrown if the code of yours is using unnecessary statements or loops, exceptions handling, more variables, etc ... You could use a linter for that issue, for example pylint
From The Zen of Python, by Tim Peters
Simple is better than complex.
Readability counts.
You could rewrite the code you posted like the snippet below, in order to keep it simple, avoid unnecessary checks if age <= 30
for example, and keep it more readable
age = 32
if age > 30:
print("You are older than 30")
else:
pass
As for the code in a better scale and the readability among others, you could use the pass
statement of course, comments, OOP, etc ...
Of course there are plenty of other techniques to follow these terms that I didn't mention.
Upvotes: 1
Reputation: 36
the pass
instruction will be justified in something like this:
class MyException(Exception):
pass
Or when writing tests, while the functionality is not yet ready. In my opinion, for readability, you always need to get rid of unnecessary branches. And the code:
age = 32
if age > 30:
print("You are older than 30")
looks much better and more readable.
Upvotes: 2