I stumbled upon an interesting and unexpected feature of Python:
def fun():
"""Foo’s docstring"""
is a valid function? According to PEP 257, “A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition” meaning that the docstring itself is considered a statement?
I would have expected that at least a pass
statement is required here. The above example contradicts the Python Zen of “explicit is better than implicit” as pass
states an explicit intent, and a docstring does not.
Can anybody shed some light on the intent?
Empty statement is pass statement. Whenever Python encounters a pass statement, Python does nothing and moves to the next statement in the flow of control.
A pass statement is an empty/null statement that is considered as a placeholder for future code. When a user doesn't want to write a code, or is not able to write a code under a particular class or function, the user can apply a pass statement.
In Python, to write empty functions, we use pass statement. pass is a special statement in Python that does nothing. It only works as a dummy statement. We can use pass in empty while statement also.
In Python, pass is a null statement. The interpreter does not ignore a pass statement, but nothing happens and the statement results into no operation. The pass statement is useful when you don't write the implementation of a function but you want to implement it in the future.
A string literal is just like any other literal. It also works if you just put in an integer:
def func():
1
However, it doesn't work if you only use a comment:
def func():
# test
# IndentationError: expected an indented block
Even though it's also added as docstring (saved in the __doc__
attribute) it's also a function level constant:
def func():
"""I'm a function"""
>>> func.__code__.co_consts
("I'm a function", None)
So the presence of a string literal as only content of a function doesn't change how the function is actually "parsed" and "compiled" itself. Well, apart from the fact that it also got a not-None __doc__
attribute.
It's actually very handy for abstractmethod
s (see for example "Body of abstract method in Python"), where you don't need an actual function body.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With