Python’s Empty Function Does Not Require A Pass Statement?
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 liter
Solution 1:
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:
deffunc():
# 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:
deffunc():
"""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.
Post a Comment for "Python’s Empty Function Does Not Require A Pass Statement?"