[Tutor] Named function in a single line
Cameron Simpson
cs at cskk.id.au
Thu Sep 10 19:06:51 EDT 2020
On 10Sep2020 23:04, Manprit Singh <manpritsinghece at gmail.com> wrote:
>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 ?
In addition to the other comments, let me sidestep PEP 8 and point you
to a specific part of the Zen. Like the Pirate Code, it is more of a
guideline.
Run the command "import this" in the interactive interpreter:
>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
In particular, "Readability counts."
When we write code, it almost always requires maintenance. Sometimes
that is bugfixes, sometimes that is changes for new circumstances.
Regardless, the more readable the code, the easier such maintenance is.
The purpose of PEP 8 is to mandate style rules for the standard library
which ships with Python. The objective is readable, maintainable code.
The PEP is to provide some concrete specific practices which give (a)
consistent looking code and (b) generally readable code. It is required
for new code for the standard library, and is also a reasonable starting
point for code style in other projects.
But remember the objective: to make code easy to work with.
Cheers,
Cameron Simpson <cs at cskk.id.au>
More information about the Tutor
mailing list