Authored by Dan Thomson

Creating an entrypoint in a Python script

Scripting languages like Python often allow you to just "go" by executing the first available function or method as soon as possible. This can be a convenience for just writing simple one or two-liner scripts to accomplish a simple task, but larger jobs often end up looking messy and are hard to follow without following some basic conventions. Many compiled languages like Java/Scala/Kotlin, C, Haskell, etc. force the programmer to define a standard entrypoint function which provides a clear starting point for your program. This forces coders into a common standard and makes it generally understood where to look for a program's entrypoint.

I recommend following this standard in Python. This snippet shows you how you can provide similar behaviour in your Python programs and includes the argparse library for parsing command-line arguments at the same time.

As an added bonus, Python provides a special variable called __name__ which defines the name of the module being run or executed. If the current source file is being executed as a program, __name__ is set to __main__. Otherwise, if the Python file is being imported as a separate module, __name__ is set to the name of the module. This allows you to both execute a script when run directly (this is often used as a way of executing tests for a module) and not execute anything if you just want to import function/method/class definitions from a separate file and run them elsewhere. 897 Bytes
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment