Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Type hints and style
#1
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?
Reply
#2
What about
class MyClass:
    def __init__(self) -> None:
        pass
 
    def my_func(
        self,
        arg1: int = 10,
        arg2: List[int]
    ) -> Generator[int, None, None]:
        ...
?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  SQLAlchemy with type hints gontajones 1 6,668 Jun-17-2020, 06:52 PM
Last Post: gontajones
  Type hinting style and PEP8 hlovatt 2 2,782 May-07-2020, 08:12 PM
Last Post: hlovatt
  Type hinting - return type based on parameter micseydel 2 2,425 Jan-14-2020, 01:20 AM
Last Post: micseydel
  Should a function ever be more permissive than its type hints? Shay 1 1,906 Mar-13-2019, 05:36 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020