DEV Community

xtofl
xtofl

Posted on

Local functions to structure code

Oftentimes I encounter lengthy methods, structured into parts by comments.

def threaded_needle(url, needle, thread):
  # get the haystack
  response = requests.get(url)
  if response.code == ...:
    ...

  # find the needle
  ...
  # thread the needle
  ...
Enter fullscreen mode Exit fullscreen mode

It doesn't work on me: I need visual hints, indentation, modular design, to understand the function's flow.

Also, I'm a top-down thinker: details are wasted on me until I understand
the structure. So I prefer the highest level information first, i.e.
the main functionality.

Therefore my python modules are typically structured so:

def main():  # will be called at the bottom of the file
  detail()
  other_detail()

def detail():
  ...

def other_detail():
  ...

# traditional unsurprising boilerplate at the bottom of the module
if __name__ == "__main__":
  main()
Enter fullscreen mode Exit fullscreen mode

Two things make it easier for me to understand the code:

  1. high level structure (main) first
  2. named functions to identify functional blocks of code

So we can apply this to (lengthy) functions, too.

def threaded_needle(url, needle, thread):

  def main():
    return threaded(find(needle, haystack()))

  def haystack():
    response = ...
    ...

  def find(needle, haystack):
    ...

  def threaded(found_needle):
    ...

  return main()
Enter fullscreen mode Exit fullscreen mode

I agree the def main() on top and the obligatory main() call at the bottom look a bit unfamiliar at first. It's just a convention - once you know it, you won't be surprised anymore.

The other surprising thing: the function body does not get longer by this technique: the comment lines are replaced by function signatures.

I like it. Do you?

Top comments (0)