pythonfunctiondocstringno-op

Why is a docstring sufficient to satisfy a python's definition of a function when its body is empty?


I discovered this fun feature of Python, where this:

def do_nothing():
    """Does nothing."""

is the same as this:

def do_nothing():
    ...

I found someone commented this here: "If you give your function a docstring, you don't even need to put any statement after the line with the docstring."

Could someone explain why the docstring acts as a no-op?

I have searched through the python language reference, and I see that python's function definition requires the body to have a statement. I looked at the statement definition in CPython, and I don't see any references to an Ellipsis or docstring as a valid statement: https://docs.python.org/3/reference/compound_stmts.html


Solution

  • A function does require a body. In your first example, the body is a string literal. That it's "a docstring" isn't a matter of formal syntax, but of context-dependent conventional interpretation. In your second example, the body is an Ellipsis object

    >>> ...
    Ellipsis
    >>> type(_)
    <class 'ellipsis'>
    

    For exactly the same reason, these are also valid function definitions:

    def f(): {}
    def f(): 88
    def f(): 3.14159
    def f(): 1 < 2
    def f(): pass
    

    A statement of any kind is necessary and sufficient, even if executing the statement has no effect. The latter is a matter of semantics rather than of syntax. The syntax doesn't (and can't) enforce that the code will do something sensible.