'Python type annotations style for functions with long arguments
What is the canon (based on some PEP) way to style a function definition with long type annotations?
Some alternatives I can conceive:
- Option 1:
def my_long_function_name_super_important(
first_long_argument_to_my_function: Union[int, str],
second: Dict[int, str],
third_arg: int = 0 ) -> (bool, int):
return (True, 1)
- Option 2:
def my_long_function_name_super_important(
first_long_argument_to_my_function: Union[int, str],
second: Dict[int, str],
third_arg: int = 0
) -> (bool, int):
return (True, 1)
- Option 3:
def my_long_function_name_super_important(
first_long_argument_to_my_function: Union[int, str],
second: Dict[int, str], third_arg: int = 0
) -> (bool, int):
return (True, 1)
- Option 4:
def my_long_function_name_super_important(
first_long_argument_to_my_function: Union[int, str],
second: Dict[int, str],
third_arg: int = 0,
) -> (bool, int):
return (True, 1)
Note: targeting Python 3.8+ to get an up-to-date answer.
Solution 1:[1]
As hinted by @MisterMiyagi, there is no official coding style based on a PEP for these type annotations in functions.
That being said, after playing a bit with the different options, I realized options 2 and 3 generate some minor problems in some python code formatters (e.g.: code folding in functions in jupyter notebook) due to the lack of indentation in the closing ). As such, and in search of the highest readability, I ended up using something similar to option 2, but with a small indentation at the last line of the function definition (easier to spot), and with one argument per line (easier to read):
def my_long_function_name_super_important(
first_long_argument_to_my_function: Union[int, str],
second: Dict[int, str],
third_arg: int = 0
) -> (bool, int):
return (True, 1)
F.Y.I., the black formatter of @MisterMiyagi seems to be exactly Option 2 (can be tried out here)
edit: from @pabouk 's comment, Google style seems to lean towards options 2-3.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
