Project Hub
Some things I learned in the yocto-pi-vm project
Python is a very flexible language. We frequently see simple scripts where the program structure is minimal. These are often the learning exercises or tutorial snippets that first expose us to Python programming.
Instead of:
# initialize globals
server = "192.168.1.100"
...
# body of the code
# a list of statements to be executed sequentially
# along with branching and looping
...
# helper functions called from the body
def helper():
pass
...
Do this:
# initialize globals
server = "192.168.1.100"
...
# body of the code wrapped in the main() function
# a list of statements to be executed sequentially
# along with branching and looping
def main():
...
# helper functions called from the body
def helper():
pass
...
# execute only if run as a script
if __name__ == "__main__":
main()
The main() function collects the top-level control flow of the program. There shouldn’t be any global statements following it. The invocation of main() is at the very end. This ensures that any forward references can be resolved before it’s invoked.
Instead of
def main():
if not condition:
print("condition not met")
exit(1)
do_something()
def do_something():
...
Do this:
def main():
try:
check_condition()
do_something()
except Exception as err:
print("ERROR: {}".err)
exit(1)
def check_condition():
if not condition:
raise Exception("condition not met")
def do_something():
...
You could use a pattern like ‘validate_xxx()’ or ‘assert_xxx()’ instead of ‘check_xxx(), However, the latter two give a stronger sense that an exception needs to be handled.
It may be noted that this results in more lines of code. However, consider the case where there are several conditions to be checked. It the first case, there would be a clutter of control flow - if statements, print statements, and exit() calls - before the real body of the function. In the second case, within the try block, there’s no control flow regarding the conditions. Indeed, it looks almost like a declarative list of the required conditions. Also in the second case, the name of each condition can express its intent, while in the first case there is only the logic, which would need to be studied to understand its intent as well as cluttering the intent of the top level control flow.