Search code examples
pythonprogram-entry-pointtype-hinting

Should the "main function" (if __name__ == "__main__") have a type hint?


I understand that it is good practice to add a type hint to functions in my Python code. This helps when reading the code to clarify what type of value gets returned, and this metadata can also be verified in unit tests.

However, I am not sure whether I should add type hints to my "main" function.

I tried searching for "type hint for main python" and "does the main function have a type hint python", but I wasn't able to find the answer to my question. Maybe I'm just missing something obvious.

My question is this: should if __name__ == "__main__": in Python have the type hint -> None added to it?

In other words, should it look like this:

if __name__ == "__main__" -> None:

Solution

  • The critical point is that the Python "main" ["function"] is not a function (as discussed in many other Q&As on Stack Overflow). Instead, it is an if clause. You can use type hints only in functions, not in if clauses.

    Type hints help provide a quick overview of what gets returned, and they can be used for unit tests. Neither are feasible in the case of "main", which cannot return anything.

    Proof by example: if you try it, VSCode/Codium for example shows a red arrow:

    If you try to run the code, the interpreter throws a bunch of IndentationError: unexpected indent errors.


    NOTE: An important exception to this is the main() function that you use in a Python Google Cloud Function (CF) since that gets passed a response parameter and is therefore a function. This CF main() can have a return, and you should give it a type hint like with any other function. The same of course for similar code not in a CF.