Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python’s empty function does not require a pass statement? [closed]

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?

like image 320
Jens Avatar asked Sep 10 '17 22:09

Jens


People also ask

Is pass an empty statement in Python?

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.

Is Pass statement an empty statement?

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.

How do you pass an empty function in Python?

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.

Is pass necessary in Python?

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.


1 Answers

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 abstractmethods (see for example "Body of abstract method in Python"), where you don't need an actual function body.

like image 160
MSeifert Avatar answered Nov 14 '22 21:11

MSeifert