Issue
I'm adding a docstring under my function just to see what's going to happen. When I run it, it returns the docstring instead of my function result. I thought docstring just like the comment that won't affect my result.
Remove the docstring and my function works again. Why is that happening?
Solution
You should use a normal comment #
for this, not a docstring """
.
Some tools (like PyCharm or the Sphinx library) docstrings on variables will be respected, but this is not actually built into Python. It is imaginable that in the future Jupyter Notebooks will allow this, but for now they do not, so you should avoid them.
In the official language, docstrings are only used in functions, classes and methods for setting the __doc__
attribute on an object. Regular comments aren't picked up by the interpreter, but strings are. A docstring is just a normal string, but it is parsed differently depending on where it is used. In functions, classes, and methods, they must be the first statement in the block.
For example, in these functions, both foo
and bar
have proper docstrings, but fizz
does not:
def foo():
"foo"
def bar():
"""bar"""
def fizz():
# fizz
pass
print(foo.__doc__)
print(bar.__doc__)
print(fizz.__doc__)
foo
bar
None
Answered By - flakes
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.