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.


Asked by: Dainton894 | Posted: 24-09-2021






Answer 1

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.

Answered by: Fenton885 | Posted: 25-10-2021



Answer 2

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()

Answered by: Sydney854 | Posted: 25-10-2021



Answer 3

You could try increasing the indent size, but in general I would just say, relax, it will come with time. I don't think trying to make Python look like C is a very good idea.

Answered by: Roman534 | Posted: 25-10-2021



Answer 4

Rather than focusing on making your existing structures more readable, you should focus on making more logical structures. Make smaller blocks, try not to nest blocks excessively, make smaller functions, and try to think through your code flow more.

If you come to a point where you can't quickly determine the structure of your code, you should probably consider refactoring and adding some comments. Code flow should always be immediately apparent -- the more you have to think about it, the less maintainable your code becomes.

Answered by: Kristian680 | Posted: 25-10-2021



Answer 5

Perhaps the best thing would be to turn on "show whitespace" in your editor. Then you would have a visual indication of how far in each line is tabbed (usually a bunch of dots), and it will be more apparent when that changes.

Answered by: Julian920 | Posted: 25-10-2021



Answer 6

from __future__ import braces

Need I say more? :)

Seriously, PEP 8, 'Blank lines', ยง4 is the official way to do it.

Answered by: Sydney736 | Posted: 25-10-2021



Answer 7

I would look in to understanding more details about Python syntax. Often times if a piece of code looks odd, there usually is a better way to write it. For example, in the above example:

bar = foo if baz else None
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()

While it is a small change, it might help the readability. Also, in all honesty, I've never used a while loop, so there is a good change you would end up with a nice concise list comprehension or for loop instead. ;)

Answered by: Kelvin617 | Posted: 25-10-2021



Similar questions

python - Improving readability of pandas chains

I am used to writing one-liners for whatever pandas operations/changing I have, and it is a bit difficult for me to read/understand after I've come back to it (similar to writing one long SQL statement...). What are some ways to improve readability on chained operations? Right now I was trying something like: res = ( # (1) we filter on new__status_group = 'Unknown' df[df['new__status_group'] == 'UNKN...


python - Improving readability of pandas chains

I am used to writing one-liners for whatever pandas operations/changing I have, and it is a bit difficult for me to read/understand after I've come back to it (similar to writing one long SQL statement...). What are some ways to improve readability on chained operations? Right now I was trying something like: res = ( # (1) we filter on new__status_group = 'Unknown' df[df['new__status_group'] == 'UNKN...


python - Optimal tab size for code readability

Closed. This question is opinion-based. It is not c...


Python code readability

I have a programming experience with statically typed languages. Now writing code in Python I feel difficulties with its readability. Lets say I have a class Host: class Host(object): def __init__(self, name, network_interface): self.name = name self.network_interface = network_interface I don't understand from this definition, what "network_interface" should be...


Condense this Python statement without destroying readability

I'm pretty new to Python still, so I'm trying to figure out how to do this and need some help. I use return codes to verify that my internal functions return successfully. For example (from internal library functions): result = some_function(arg1,arg2) if result != OK: return result or (from main script level): result = some_function(arg1,arg2) if result != OK: abor...


coding style - Should I make my python code less fool-proof to improve readability?

I try to make my code fool-proof, but I've noticed that it takes a lot of time to type things out and it takes more time to read the code. Instead of: class TextServer(object): def __init__(self, text_values): self.text_values = text_values # <more code> # <more methods> I tend to write this: class TextServer(object): def __in...


Python readability hints for a Java programmer

I'm a java programmer, but now entering the "realm of python" for some stuff for which Python works better. I'm quite sure a good portion of my code would look weird for a Python programmer (e.g. using parenthesis on every if). I know each language has its own conventions and set of "habits". So, from a readability standpoint what are conventions and practices which is "the way to go" in Java, but are not really th...


Python readability through descriptive naming


Is there a way to use readability (text extraction algorithm) and a custom algorithm in python to extract links from text?

Is there a way to use readability (text extraction algorithm) and a custom algorithm in python to extract links from text? I'd like to figure out a way of extracting links that are in the body of text. 1.) I use readability in python https://github.com/gfxmonk/python-readability 2.) I'd like to somehow compare the extracted t...


code readability - Python Shelve Module Memory Consumption

I have been assigned the task of reading a .txt file which is a log of various events and writing some of those events into a dictionary. The problem is that the file can sometimes get bigger than 3GB in size. This means that the dictionary gets too big to fit into main memory. It seems that Shelve is a good way to solve this problem. However, ...


python - Readability and efficiency, Which is better? Numpy, tuple, etc?

I'm working with xyz vectors a lot in my program. I'm using them enough that giving each one a variable (such as offset_x, offset_y, etc) is becoming tedious and cluttering code-wise. Now, I could put each set of x, y, and into tupples (such as offset = (x,y,z) ) , But I've found that doing stuff like offset[0] everywhere makes the code not quite as readable as I would like, Using a dict seems too inefficient. Numpy is ano...


python - Preserve code readability while optimising

I am writing a scientific program in Python and C with some complex physical simulation algorithms. After implementing algorithm, I found that there are a lot of possible optimizations to improve performance. Common ones are precalculating values, getting calculations out of cycle, replacing simple matrix algorithms with more complex and other. But there arises a problem. Unoptimized algorithm is much slower, but its logic...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top