I am working through Mastering Matplotlib and in chapter two they introduce the following code snippet:
#! /usr/bin/env python3.4 import matplotlib.pyplot as plt def main () -> None: plt.plot([1,2,3,4]) plt.ylabel('some numbers') plt.savefig('simple-line.png') if __name__ == '__main__': main()
This can be seen in this notebook, cell 10. I have never seen a main method defined this way, what is the function of -> None
? My only thought so far is that this may be similar to def main(argv=None)
?
Beyond that, what is ->
in Python? I can't find it in this list of Python operators.
The None keyword is used to define a null value, or no value at all. None is not the same as 0, False, or an empty string. None is a data type of its own (NoneType) and only None can be None.
The main function in Python acts as the point of execution for any program. Defining the main function in Python programming is a necessity to start the execution of the program as it gets executed only when the program is run directly and not executed when imported as a module.
Conclusion. The -> (arrow) is used to annotate the return value for a function in Python 3.0 or later. It does not affect the program but is intend to be consumed by other users or libraries as documentation for the function.
Functions often print None when we pass the result of calling a function that doesn't return anything to the print() function. All functions that don't explicitly return a value, return None in Python.
As is, it does absolutely nothing. It is a type annotation for the main
function that simply states that this function returns None
. Type annotations were introduced in Python 3.5
and are specified in PEP 484
.
Annotations for the return value of a function use the symbol ->
followed by a type. It is completely optional and if you removed it, nothing would change.
This will have absolutely no effect on execution, it is only taken under consideration if you use it with a type checking tool like mypy
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With