Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Improving Python readability?

I've been really enjoying Python programming lately. I come from a background of a strong love for C-based coding, where everything is perhaps more complicated than it should be (but puts hair on your chest, at least). So switching from C to Python for more complex things that don't require tons of speed has been more of a boon than a bane in writing projects.

However, coming from this land of brackets and parentheses and structs as far as the naked eye can see, I come across a small problem: I find Python difficult to read.

For example, the following block of text is hard for me to decipher unless I stare at it (which I dislike doing):

if foo:
   bar = baz
   while bar not biz:
      bar = i_am_going_to_find_you_biz_i_swear_on_my_life()

did_i_not_warn_you_biz()
my_father_is_avenged()

The problem occurs at the end of that if block: all the tabbing and then suddenly returning to a jarring block feels almost disturbing. As a solution, I've started coding my Python like this:

if foo:
   bar = baz
   while bar not biz:
      bar = i_am_going_to_find_you_biz_i_swear_on_my_life()
   #-- while --
#-- if --

did_i_not_warn_you_biz()
my_father_is_avenged()

And this, for some odd reason, makes me more able to read my own code. But I'm curious: has anyone else with my strange problem found easier ways to make their tabbed-out code more readable? I'd love to find out if there's a better way to do this before this becomes a huge habit for me.

like image 748
verix Avatar asked Nov 26 '22 21:11

verix


2 Answers

Part of learning a new programming language is learning to read code in that language. A crutch like this may make it easier to read your own code, but it's going to impede the process of learning how to read anyone else's Python code. I really think you'd be better off getting rid of the end of block comments and getting used to normal Python.

like image 194
Chris Upchurch Avatar answered Nov 29 '22 12:11

Chris Upchurch


I like to put blank lines around blocks to make control flow more obvious. For example:

if foo:
   bar = baz

   while bar not biz:
      bar = i_am_going_to_find_you_biz_i_swear_on_my_life()

did_i_not_warn_you_biz()
my_father_is_avenged()
like image 33
Will Harris Avatar answered Nov 29 '22 11:11

Will Harris