Python boilerplate keyboard shortcut
Reviewing my Python template for scripts
One thing I strive for is optimization. Every language has code you have to repeat time and time again. When programming, I want to get to the interesting parts of the code and not have to stress or remember the boilerplate code.
My solution is a keyboard shortcut. Quickly and easily, I can get a Python script template in my editor. An added benefit, I get consistency among my Python scripts.
I assign it to the typed shortcut ;;pytm (Python template) to expand into:
#!/usr/bin/env python3
""""""
def main():
pass
if __name__ == "__main__":
main()
Let's explain each part for better understanding.
Shebang
#!/usr/bin/env python3
When executing a Python script, the shebang (#!) is used to tell your system what interpreter to use. Used in Unix/Linux-based operating systems. For more information please visit: Shebang
Regardless of the operating system, I add in the shebang at the top of the Python script.
Empty docstring
""""""
When creating modules in Python, it is good practice to add a docstring. Documentation is important in explaining your codeindent.
There is a Python Enhancement Proposals (PEP) about docstrings. PEP 257 -- Docstring Conventions
Main function
def main():
pass
I define a main function for the module. This clearly indicates to the code reader this is the entry point to the script/program. Most times that reader is me in the future. Although this function could be named anything, many other languages use main as the entry point, so I follow that same convention in my Python scripts. Why reinvent the wheel, right?
name == “main”
if __name__ == "__main__":
main()
Part is Python syntax. This tells the interpreter if this module is executed, run all the statements in this if block. For more information, check out What does the if name == “main”: do?
myscript example
Here is a myscript.py example:
#!/usr/bin/env python3
"""Myscript - prints "Hello, World." to the terminal."""
def main():
print("Hello, World.")
if __name__ == "__main__":
main()
Enjoy and happy coding!
References: