3 ms·
> Python has an even closer relationship between comments and string literals: its multiline comments are just string literals that get never used. That's not
by hermitdev 7y ago
> Python has an even closer relationship between comments and string literals: its multiline comments are just string literals that get never used.
That's not entirely true. A literal string immediately following a class or function is inspectable via its __doc__ member.
E.g.
class Foo:
"I am Foo."
def bar(self):
"I am Foo.bar"
Foo.__doc__ will have "I am Foo.", and Foo.bar.__doc__ will have "I am Foo.bar".
This is rarely used programattically, but at least one standard module uses this for running tests: doctest
Edit: not sure why it's not formatting correctly, as I am spacing the code a 4 space indent, but at least on my phone, it is not properly formatting as code. I apologize.
- est31 7y agoCool, didn't know about that!
- rat87 7y agoThese are used by python's documentation tools to extract documentation from running objects by importing and examining __doc__ of objects, instead of extracting docs from comments like Java or c++ doxygen. It also makes it easier to document python modules written in c since you just attach their docstrings and examine them at runtime same as any python module Either pythons stdlib crappy pydoc module `python -m pydoc -w ModuleName` the simple pdoc tool `/path/to/pdoc --html ModuleName` or the complicated and fully featured sphinx (too complicated for a single command `sphinx-apidoc ModuleName` to generate a default project and `make`/`make.bat` to run it ) They are also useful print help in repl (with `help(obj)` or `obj?` in IPython) Also in python comments are everything after a hash # till end of line. Non assigned Literal strings in python are just literal objects not comments. If they are the first thing in a class/function they become the class/function/method __doc__ attribute. If they aren't they have no use but are simply created and then garbage collected because there are no references pointing to them(cpython the default python implementation uses reference counting and the occasional cleanup of unreachable cycles so it would be deleted right after creation). Its the same with literal numbers or dictionaries. def a(): 5 [] "whoop de do" is a legal (and totally pointless) python function that will do nothing(other then allocate then cleanup some objects).