OddThinking

A blog for odd things and odd thoughts.

Why the Python Main area should be small

Today, I am justifying a particular personal coding standard rule. If I explicitly argue the case, I hope I will conform to it more.

Consider a Python module:


from blah import Blah
from foo import Foo

# Lots of useful declarations in this area.
#
# Traditionally, nothing that would actively run without being called,
# just declarations.
#
# Let's call it the Decl Area.

if __name__ == '__main__':
# This code will only be seen if the package is directly run.
# Not if it is merely imported.
#
# Code that will actually run presumably calling the code in the
# Decl Area.
#
# Let's call this the Main Area.

Code in the Main Area suffers from three short-comings.

  • It cannot be re-used by another module.
  • It cannot be exercised by a unit test.
  • It declares globals, and therefore should use the awkward GLOBALS_NAMING_STANDARD. Oh, and be indented, because it inside an if statement.

Conclusion: Move as much code as possible out of the main area and into the declaration area.

Examples of what I am happy to leave inside the main area:

  • Calls to unit-test framework for self-testing modules. The unit-tests themselves should not be here, so they can be called by others.
  • Calls to functions to set the Window title (Windows only). That should not apply when the code is re-used.
  • Calls to a main() function in the declaration area if this is actually a script that does anything.
1 CommentCategories: S/W Dev
Tags: Python

Comment

  1. Sounds about right to me, except the bit about a “delcaration”. [Fixed. Thanks – Ed.]

Leave a comment

You must be logged in to post a comment.