Documentation and Metadata
In Python, functions are not just blocks of code; they are objects that carry metadata about themselves. We can use this metadata for debugging, documentation generation, and introspection.
Docstrings
A Docstring is a multi-line string literal placed as the first statement in a function. It is used to explain what the function does, its parameters, and its return value.
def gen_bill(chai=0, samosa=0) -> tuple[int, str]:
"""
Calculate total bill for chai & samosa.
:param chai: Number of chai cups (10/cup)
:param samosa: Number of samosa (15/per)
:return: (total amount, thanks message)
"""
total = chai * 10 + samosa * 15
return total, "Thanks for eating!"
# Accessing the docstring
print(gen_bill.__doc__)
Introspection with Dunder Attributes
Python attaches special "dunder" (double underscore) attributes to function objects.
__doc__: Returns the function's docstring.__name__: Returns the string name of the function.
def greet():
"""Returns a simple hello."""
return "Hello"
print(greet.__name__) # 'greet'
print(greet.__doc__) # 'Returns a simple hello.'
The help() Function
The built-in help() function is a powerful tool that reads a function's signature and docstring to provide a formatted manual.
help(greet)
Output:
Help on function greet in module __main__:
greet()
Returns a simple hello.