Clean Python: Make Sure Your Code Reads From Top to Bottom

David Kuda
1 min readJan 25, 2023

--

When you read a document, you read it from top to bottom.

You start by reading a summary, and you get a feel for what is inside the document from reading the table of contents.

Then you naturally expect the content to be listed according to the table of content.

Why not follow the same pattern for your code?

Your main function can be the same as a table of content. It can list the content of your code in a linear way and help to summarise what is happening.

So a very simple way to make your code easier to understand is to put your main at the top, and then define all functions according to the order they are called in the main function. And define your functions according to that order.

Let’s see the following example to make the point clear:

def main():
"""This app gets metadata from links and persists them"""
html_text = get_html("www.kuda.ai")
meta_data = parse_meta_data(html_text)
persist(meta_data)

def get_html(url: string) -> HTMLText:
...

def parse_meta_data(content: HTMLText) -> MetaData:
...

def persist(data: MetaData):
...

if __name__ == "__main__":
main()

I published this text originally on my website https://www.kuda.ai/blog/code-top-to-bottom

--

--

David Kuda

Software Engineer from Berlin | builds and learns in public | www.kuda.ai