I'm trying to find a way to document my functions a bit, i.e. I use VS Code and when you use a native Python function (and have the Python package installed) and hover over the function, a small window appears explaining briefly what the functions do and describe the parameters a little, I would like to be able to achieve the same effects with functions that I can create (if possible).
The format doesn't really matter to me, in some editors I see that the same window is shown with a different format, they even put a box and so on. I don't really care much about the format, although if I could also modify the format it would be excellent, I just need to be able to document the functions, if someone could help me I would be very grateful.
In Python the simplest way to document code is with
docstrings
. Simply open quotes after the function and write its description. It doesn't matter which quotes, they just have to be the same opening and closing quotes. So:But if you want the documentation to be multi-line you must use 3 quotes to open and close. For example:
Something that will help when programming is to indicate the type that the function expects each parameter to have.
You can do this by typing a colon and the type it should receive after the parameter name. So:
You can also indicate the type that the function can return if you add
->
after the parameters and the type in question. For example:You can see that it is quite limited. That is why there are special types:
Any
, literally any type is valid.NoReturn
, unlikeAny
, indicates that the function does not return a value. It can only be used to indicate the return type.Optional
, means that it may or may not be of the specified type. For example:Optional[int]
.Union
, allows you to combine types by listing them separated by commas and enclosed in square brackets. Suppose now you want the function tosuma
accept parameters and be able to return a value of typefloat
as well. You would do it like this:Callable
, expect a function. It is used in a similar way toUnion
. In square brackets you receive a list of the types of the parameters and the return type. For example:There are more special types. They are all in the module
typing
. So don't forget to import them before using them.