[Tutor] Named function in a single line
Mats Wichmann
mats at wichmann.us
Thu Sep 10 14:09:08 EDT 2020
On 9/10/20 11:34 AM, Manprit Singh wrote:
> Dear sir ,
>
> I have seen at so many places that smaller named functions are written in a
> single line . For example ;
>
> def multiply(a, b): # a function definition for multiplication of 2
> numbers
> return a * b
>
> The function definitions which are very small , normally which contain
> only a single line statement, like that one given above , are being found
> written in a single line at so many places . If I write the function given
> above in a single line , it would be written like this :
>
> def multiply(a, b) : return a * b
>
> PEP 8 allows us to write such small functions in a single line ?
Quick note about PEP 8: it's "the law" for new content for the Python
standard library. Whether anyone else follows it is up to them - follow
existing project conventions if you're contributing to a project. Since
most checkers check for PEP8 you kind of get pushed that way, however.
The answer is yes... it's okay with PEP 8. When it makes sense and
doesn't impede readability.
There's a specific fuzzy statement like this:
"While sometimes it's okay to put an if/for/while with a small body on
the same line, never do this for multi-clause statements."
it appears to apply to a def statement as well (I recall an example of
that usage)
If you try to use the currently very popular code formatter Black, it
will always split function definitions if you put them on one line. So
that's their interpretation.
Recall that when people are writing examples for display, space matters
- number of lines on the screen of a tutorial tool, for example, is a
big deal, and people will cram to get it all in the same view, this
might be part of the reason you see lots of these!
More information about the Tutor
mailing list