In deze tutorial leren we over Python-docstrings. Meer specifiek zullen we leren hoe en waarom docstrings worden gebruikt met behulp van voorbeelden.
Python-docstrings zijn de letterlijke tekenreeksen die direct na de definitie van een functie, methode, klasse of module verschijnen. Laten we een voorbeeld nemen.
Voorbeeld 1: Docstrings
def square(n): '''Takes in a number n, returns the square of n''' return n**2
Hier de letterlijke tekenreeks:
'' 'Neemt een getal n op, geeft het kwadraat van n terug' ''
Binnen de drievoudige aanhalingstekens staat de docstring van de functie square()
zoals deze direct na de definitie wordt weergegeven.
Opmerking: we kunnen ook drievoudige """
aanhalingstekens gebruiken om docstrings te maken.
Python-opmerkingen versus Docstrings
Python-opmerkingen
Opmerkingen zijn beschrijvingen die programmeurs helpen de bedoeling en functionaliteit van het programma beter te begrijpen. Ze worden volledig genegeerd door de Python-interpreter.
In Python gebruiken we het hash-symbool #
om een commentaar van één regel te schrijven. Bijvoorbeeld,
# Program to print "Hello World" print("Hello World")
Python-opmerkingen met behulp van strings
Als we geen strings aan een variabele toewijzen, fungeren ze als commentaar. Bijvoorbeeld,
"I am a single-line comment" ''' I am a multi-line comment! ''' print("Hello World")
Opmerking: we gebruiken drievoudige aanhalingstekens voor strings met meerdere regels.
Python-docstrings
Zoals hierboven vermeld, zijn Python-docstrings strings die direct na de definitie van een functie, methode, klasse of module worden gebruikt (zoals in Voorbeeld 1 ). Ze worden gebruikt om onze code te documenteren.
We hebben toegang tot deze docstrings met behulp van het __doc__
attribuut.
Python __doc__ kenmerk
Wanneer letterlijke tekenreeksen aanwezig zijn net na de definitie van een functie, module, klasse of methode, worden ze als __doc__
attribuut aan het object gekoppeld . We kunnen dit kenmerk later gebruiken om deze docstring op te halen.
Voorbeeld 2: Docstring afdrukken
def square(n): '''Takes in a number n, returns the square of n''' return n**2 print(square.__doc__)
Uitvoer
Neemt een getal n op, geeft het kwadraat van n terug
Hier is de documentatie van onze square()
functie toegankelijk via het __doc__
attribuut.
Laten we nu eens kijken naar docstrings voor de ingebouwde functie print()
:
Voorbeeld 3: Docstrings voor de ingebouwde print () functie
print(print.__doc__)
Uitvoer
print (waarde,…, sep = '', end = ' n', file = sys.stdout, flush = False) Drukt de waarden standaard af naar een stream of naar sys.stdout. Optionele trefwoordargumenten: bestand: een bestandachtig object (stream); standaard ingesteld op het huidige sys.stdout. sep: string ingevoegd tussen waarden, standaard een spatie. end: string toegevoegd na de laatste waarde, standaard een nieuwe regel. doorspoelen: of de stroom met geweld moet worden doorgespoeld.
Hier kunnen we zien dat de documentatie van de print()
functie aanwezig is als het __doc__
attribuut van deze functie.
Enkele regel docstrings in Python
Enkele regel docstrings zijn de documenten die op één regel passen.
Standaardconventies om docstrings met één regel te schrijven:
- Hoewel ze enkelvoudig zijn, gebruiken we nog steeds de drievoudige aanhalingstekens rond deze docstrings, omdat ze later gemakkelijk kunnen worden uitgebreid.
- De afsluitende aanhalingstekens staan op dezelfde regel als de openingsaanhalingstekens.
- Er is geen lege regel voor of na de docstring.
- Ze moeten niet beschrijvend zijn, maar moeten de structuur "Doe dit, retourneren" volgen en eindigen met een punt.
Laten we een voorbeeld nemen.
Voorbeeld 4: Schrijf documentstrings met één regel voor een functie
def multiplier(a, b): """Takes in two numbers, returns their product.""" return a*b
Meerregelige Docstrings in Python
Meerregelige docstrings bestaan uit een samenvattingsregel, net als een docstring van één regel, gevolgd door een lege regel, gevolgd door een meer uitgebreide beschrijving.
Het PEP 257-document biedt de standaardconventies om meerregelige docstrings voor verschillende objecten te schrijven.
Sommige zijn hieronder opgesomd:
1. Docstrings voor Python-modules
- De docstrings voor Python-modules moeten alle beschikbare klassen, functies, objecten en uitzonderingen vermelden die worden geïmporteerd wanneer de module wordt geïmporteerd.
- They should also have a one-line summary for each item.
They are written at the beginning of the Python file.
Let's look at the docstrings for the builtin module in Python called pickle
.
Example 4: Docstrings of Python module
import pickle print(pickle.__doc__)
Output
Create portable serialized representations of Python objects. See module copyreg for a mechanism for registering custom picklers. See module pickletools source for extensive comments. Classes: Pickler Unpickler Functions: dump(object, file) dumps(object) -> string load(file) -> object loads(string) -> object Misc variables: __version__ format_version compatible_formats
Here, we can see that the docstring written at the beginning of the pickle.py module file can be accessed as its docstring.
2. Docstrings for Python Functions
- The docstring for a function or method should summarize its behavior and document its arguments and return values.
- It should also list all the exceptions that can be raised and other optional arguments.
Example 5: Docstrings for Python functions
def add_binary(a, b): ''' Returns the sum of two decimal numbers in binary digits. Parameters: a (int): A decimal integer b (int): Another decimal integer Returns: binary_sum (str): Binary string of the sum of a and b ''' binary_sum = bin(a+b)(2:) return binary_sum print(add_binary.__doc__)
Output
Returns the sum of two decimal numbers in binary digits. Parameters: a (int): A decimal integer b (int): Another decimal integer Returns: binary_sum (str): Binary string of the sum of a and b
As you can see, we have included a short description of what the function does, the parameter it takes in and the value it returns. The string literal is embedded to the function add_binary
as its __doc__
attribute.
3. Docstrings for Python Classes
- The docstrings for classes should summarize its behavior and list the public methods and instance variables.
- The subclasses, constructors, and methods should each have their own docstrings.
Example 6: Docstrings for Python class
Suppose we have a Person.py file with the following code:
class Person: """ A class to represent a person.… Attributes ---------- name : str first name of the person surname : str family name of the person age : int age of the person Methods ------- info(additional=""): Prints the person's name and age. """ def __init__(self, name, surname, age): """ Constructs all the necessary attributes for the person object. Parameters ---------- name : str first name of the person surname : str family name of the person age : int age of the person """ self.name = name self.surname = surname self.age = age def info(self, additional=""): """ Prints the person's name and age. If the argument 'additional' is passed, then it is appended after the main info. Parameters ---------- additional : str, optional More info to be displayed (default is None) Returns ------- None """ print(f'My name is (self.name) (self.surname). I am (self.age) years old.' + additional)
Here, we can use the following code to access only the docstrings of the Person class:
print(Person.__doc__)
Output
A class to represent a person.… Attributes ---------- name : str first name of the person surname : str family name of the person age : int age of the person Methods ------- info(additional=""): Prints the person's name and age
Using the help() Function for Docstrings
We can also use the help()
function to read the docstrings associated with various objects.
Example 7: Read Docstrings with the help() function
We can use the help()
function on the class Person
in Example 6 as:
help(Person)
Output
Help on class Person in module __main__: class Person(builtins.object) | Person(name, surname, age) | | A class to represent a person. | |… | | Attributes | ---------- | name : str | first name of the person | surname : str | family name of the person | age : int | age of the person | | Methods | ------- | info(additional=""): | Prints the person's name and age. | | Methods defined here: | | __init__(self, name, surname, age) | Constructs all the necessary attributes for the person object. | | Parameters | ---------- | name : str | first name of the person | surname : str | family name of the person | age : int | age of the person | | info(self, additional='') | Prints the person's name and age. | | If the argument 'additional' is passed, then it is appended after the main info. | | Parameters | ---------- | additional : str, optional | More info to be displayed (default is None) | | Returns | ------- | None | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined)
Here, we can see that the help()
function retrieves the docstrings of the Person
class along with the methods associated with that class.
4. Docstrings for Python Scripts
- The docstrings for Python script should document the script's functions and command-line syntax as a usable message.
- It should serve as a quick reference to all the functions and arguments.
5. Docstrings for Python Packages
The docstrings for a Python package is written in the package's __init__.py file.
- It should contain all the available modules and sub-packages exported by the package.
Docstring Formats
We can write docstring in many formats like the reStructured text (reST) format, Google format or the NumPy documentation format. To learn more, visit Popular Docstring Formats
We kunnen ook documentatie genereren van docstrings met behulp van tools zoals Sphinx. Ga voor meer informatie naar de officiële Sphinx-documentatie