Python Docstrings (με παραδείγματα)

Σε αυτό το σεμινάριο, θα μάθουμε για τα Python docstrings. Πιο συγκεκριμένα, θα μάθουμε πώς και γιατί τα docstrings χρησιμοποιούνται με τη βοήθεια παραδειγμάτων.

Τα Python docstrings είναι οι κυριολεκτικές συμβολοσειρές που εμφανίζονται αμέσως μετά τον ορισμό μιας συνάρτησης, μεθόδου, κλάσης ή λειτουργικής μονάδας. Ας πάρουμε ένα παράδειγμα.

Παράδειγμα 1: Docstrings

 def square(n): '''Takes in a number n, returns the square of n''' return n**2

Εδώ, η κυριολεκτική συμβολοσειρά:

 '' Λαμβάνει έναν αριθμό n, επιστρέφει το τετράγωνο του n '' '

Μέσα στα τριπλά εισαγωγικά υπάρχει το docstring της συνάρτησης square()όπως εμφανίζεται αμέσως μετά τον ορισμό της.

Σημείωση: Μπορούμε επίσης να χρησιμοποιήσουμε τριπλά """εισαγωγικά για τη δημιουργία εγγράφων.

Σχόλια Python vs Docstrings

Σχόλια Python

Τα σχόλια είναι περιγραφές που βοηθούν τους προγραμματιστές να κατανοήσουν καλύτερα την πρόθεση και τη λειτουργικότητα του προγράμματος. Αγνοούνται πλήρως από τον διερμηνέα Python

Στο Python, χρησιμοποιούμε το σύμβολο κατακερματισμού #για να γράψουμε ένα σχόλιο μίας γραμμής. Για παράδειγμα,

 # Program to print "Hello World" print("Hello World") 

Σχόλια Python χρησιμοποιώντας συμβολοσειρές

Εάν δεν αντιστοιχίσουμε συμβολοσειρές σε καμία μεταβλητή, ενεργούν ως σχόλια. Για παράδειγμα,

 "I am a single-line comment" ''' I am a multi-line comment! ''' print("Hello World")

Σημείωση: Χρησιμοποιούμε τριπλά εισαγωγικά για συμβολοσειρές πολλαπλών γραμμών.

Pstron docstrings

Όπως αναφέρθηκε παραπάνω, οι συμβολοσειρές Python είναι συμβολοσειρές που χρησιμοποιούνται αμέσως μετά τον ορισμό μιας συνάρτησης, μεθόδου, κλάσης ή λειτουργικής μονάδας (όπως στο Παράδειγμα 1 ). Χρησιμοποιούνται για την τεκμηρίωση του κωδικού μας.

Μπορούμε να έχουμε πρόσβαση σε αυτά τα έγγραφα χρησιμοποιώντας το __doc__χαρακτηριστικό.

Python __doc__ χαρακτηριστικό

Κάθε φορά που υπάρχουν γραμματοσειρές συμβολοσειρών αμέσως μετά τον ορισμό μιας συνάρτησης, μιας ενότητας, μιας τάξης ή μιας μεθόδου, συνδέονται με το αντικείμενο ως __doc__χαρακτηριστικό τους. Μπορούμε αργότερα να χρησιμοποιήσουμε αυτό το χαρακτηριστικό για να ανακτήσουμε αυτό το έγγραφο.

Παράδειγμα 2: Εκτύπωση εγγράφων

 def square(n): '''Takes in a number n, returns the square of n''' return n**2 print(square.__doc__)

Παραγωγή

 Παίρνει έναν αριθμό n, επιστρέφει το τετράγωνο του n

Εδώ, square()μπορείτε να αποκτήσετε πρόσβαση στην τεκμηρίωση της λειτουργίας μας χρησιμοποιώντας το __doc__χαρακτηριστικό.

Τώρα, ας δούμε docstrings για την ενσωματωμένη συνάρτηση print():

Παράδειγμα 3: Έγγραφα για την ενσωματωμένη λειτουργία εκτύπωσης ()

 print(print.__doc__)

Παραγωγή

εκτύπωση (τιμή,…, sep = '', end = ' n', file = sys.stdout, flush = False) Εκτυπώνει τις τιμές σε μια ροή ή στο sys.stdout από προεπιλογή. Προαιρετικά ορίσματα λέξεων-κλειδιών: αρχείο: ένα αντικείμενο που μοιάζει με αρχείο (ροή); προεπιλογές στο τρέχον sys.stdout. sep: συμβολοσειρά που παρεμβάλλεται μεταξύ τιμών, προεπιλογή διαστήματος. end: string που επισυνάπτεται μετά την τελευταία τιμή, προεπιλογή μια νέα γραμμή. flush: εάν πρέπει να ξεπλύνετε με βία τη ροή.

Εδώ, μπορούμε να δούμε ότι η τεκμηρίωση της print()συνάρτησης υπάρχει ως __doc__χαρακτηριστικό αυτής της συνάρτησης.

Docstrings μίας γραμμής στο Python

Τα έγγραφα μιας γραμμής είναι τα έγγραφα που ταιριάζουν σε μία γραμμή.

Τυπικές συμβάσεις για τη σύνταξη εγγράφων μονής γραμμής:

  • Ακόμα κι αν είναι μονής επένδυσης, εξακολουθούμε να χρησιμοποιούμε τα τριπλά εισαγωγικά γύρω από αυτά τα έγγραφα, καθώς μπορούν να επεκταθούν εύκολα αργότερα.
  • Τα εισαγωγικά κλεισίματος είναι στην ίδια γραμμή με τα εισαγωγικά.
  • Δεν υπάρχει κενή γραμμή είτε πριν είτε μετά το docstring.
  • Δεν πρέπει να είναι περιγραφικά, αλλά πρέπει να ακολουθούν τη δομή "Κάντε αυτό, επιστρέψτε" που τελειώνει με μια τελεία.

Ας πάρουμε ένα παράδειγμα.

Παράδειγμα 4: Γράψτε μια σειρά εγγράφων για μια συνάρτηση

 def multiplier(a, b): """Takes in two numbers, returns their product.""" return a*b

Docstrings πολλαπλών γραμμών στο Python

Τα έγγραφα πολλαπλών γραμμών αποτελούνται από μια σύνοψη γραμμής όπως μια μονή γραμμή εγγράφων, ακολουθούμενη από μια κενή γραμμή, ακολουθούμενη από μια πιο περίπλοκη περιγραφή.

Το έγγραφο PEP 257 παρέχει τις τυπικές συμβάσεις για τη σύνταξη εγγράφων πολλαπλών γραμμών για διάφορα αντικείμενα.

Μερικά αναφέρονται παρακάτω:

1. Docstrings για Python Modules

  • Τα έγγραφα για Python Modules θα πρέπει να απαριθμούν όλες τις διαθέσιμες τάξεις, συναρτήσεις, αντικείμενα και εξαιρέσεις που εισάγονται κατά την εισαγωγή της μονάδας.
  • 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

Μπορούμε επίσης να δημιουργήσουμε τεκμηρίωση από docstrings χρησιμοποιώντας εργαλεία όπως το Sphinx. Για να μάθετε περισσότερα, επισκεφθείτε την Επίσημη τεκμηρίωση Sphinx

ενδιαφέροντα άρθρα...