Python Forum

Full Version: Type hints and style
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
So, I am struggeling with type hints in function definitions. Annotated function definitons cause formatting issues in the simplest cases. They force one to line break the definition, which is, however, only possible within the argument list. The result is IMAO very ugly code, as in the following example:

class MyClass:
    def __init__(self) -> None:
        pass

    def my_func(self, arg1: int = 10, arg2: List[int]) -> Generator[int, None, None]
        ...
This function has only two arguments. But In order to restict myself to 79 columns and to stay PEP8 conform, I have to insert a line break definition somewhere inside the argument list. So, where is the best place for that? I'd say it's nowhere, because

class MyClass:
    ...
    def my_func(self, arg1: int = 10, arg2: List[int]
                ) -> Generator[int, None, None]
        ...
really just breaks the visual flow and

class MyClass:
    ...
    def my_func(self, arg1: int = 10,
                arg2: List[int]) -> Generator[int, None, None]
        ...
is not PEP8 conform since the second line of the definition exceeds the 79th column. Ok, I could assign the return type to another variable, but that doesn't make things much better. Just replace the generic variable names in the above with some more realistic ones ...

I think the rule that argumets in a multi-line function definition have to be indented to until the left parenthesis generally conflicts with annotations. Just have a look at the best practice example on Flake8's website. I mean, what's the point of introducing so much whitspace on left, so that there is no more room for annotations?

Do you face similar problems? How do you go about formatting long function definitions?
What about
class MyClass:
    def __init__(self) -> None:
        pass
 
    def my_func(
        self,
        arg1: int = 10,
        arg2: List[int]
    ) -> Generator[int, None, None]:
        ...
?