Hướng dẫn python docstring for class variables - chuỗi tài liệu python cho các biến lớp

Ban đầu tôi đã viết một câu trả lời (xem bên dưới) nơi tôi nói điều này là không thể. Đó là sự thật vào năm 2012 nhưng Python đã tiếp tục. Hôm nay bạn có thể cung cấp tương đương với một tài liệu cho một biến toàn cầu hoặc một thuộc tính của một lớp hoặc thể hiện. Bạn sẽ cần phải chạy ít nhất Python 3.9 để hoạt động này:

from __future__ import annotations
from typing import Annotated

Feet = Annotated[float, "feet"]
Seconds = Annotated[float, "seconds"]
MilesPerHour = Annotated[float, "miles per hour"]

day: Seconds = 86400
legal_limit: Annotated[MilesPerHour, "UK national limit for single carriageway"] = 60
current_speed: MilesPerHour

def speed(distance: Feet, time: Seconds) -> MilesPerHour:
    """Calculate speed as distance over time"""
    fps2mph = 3600 / 5280  # Feet per second to miles per hour
    return distance / time * fps2mph

Bạn có thể truy cập các chú thích khi chạy bằng cách sử dụng

Python 3.9.1 (default, Jan 19 2021, 09:36:39) 
[Clang 10.0.1 (clang-1001.0.46.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import calc
>>> from typing import get_type_hints
>>> hints = get_type_hints(calc, include_extras=True)
>>> hints
{'day': typing.Annotated[float, 'seconds'], 'legal_limit': typing.Annotated[float, 'miles per hour', 'UK national limit for single carriageway'], 'current_speed': typing.Annotated[float, 'miles per hour']}
1:

Python 3.9.1 (default, Jan 19 2021, 09:36:39) 
[Clang 10.0.1 (clang-1001.0.46.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import calc
>>> from typing import get_type_hints
>>> hints = get_type_hints(calc, include_extras=True)
>>> hints
{'day': typing.Annotated[float, 'seconds'], 'legal_limit': typing.Annotated[float, 'miles per hour', 'UK national limit for single carriageway'], 'current_speed': typing.Annotated[float, 'miles per hour']}

Trích xuất thông tin về các biến bằng cách sử dụng các gợi ý cho mô -đun hoặc lớp nơi chúng được khai báo. Lưu ý cách các chú thích kết hợp khi bạn làm tổ chúng:

>>> hints['legal_limit'].__metadata__
('miles per hour', 'UK national limit for single carriageway')
>>> hints['day']
typing.Annotated[float, 'seconds']

Nó thậm chí còn hoạt động cho các biến có chú thích loại nhưng chưa được gán giá trị. Nếu tôi đã cố gắng tham chiếu calc.cien_speed, tôi sẽ gặp lỗi thuộc tính nhưng tôi vẫn có thể truy cập siêu dữ liệu của nó:

>>> hints['current_speed'].__metadata__
('miles per hour',)

Loại gợi ý cho một mô -đun chỉ bao gồm các biến toàn cầu, để đi sâu vào bạn cần gọi lại

Python 3.9.1 (default, Jan 19 2021, 09:36:39) 
[Clang 10.0.1 (clang-1001.0.46.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import calc
>>> from typing import get_type_hints
>>> hints = get_type_hints(calc, include_extras=True)
>>> hints
{'day': typing.Annotated[float, 'seconds'], 'legal_limit': typing.Annotated[float, 'miles per hour', 'UK national limit for single carriageway'], 'current_speed': typing.Annotated[float, 'miles per hour']}
2 trên các chức năng hoặc các lớp:

>>> get_type_hints(calc.speed, include_extras=True)
{'distance': typing.Annotated[float, 'feet'], 'time': typing.Annotated[float, 'seconds'], 'return': typing.Annotated[float, 'miles per hour']}

Tôi chỉ biết một công cụ cho đến nay có thể sử dụng

Python 3.9.1 (default, Jan 19 2021, 09:36:39) 
[Clang 10.0.1 (clang-1001.0.46.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import calc
>>> from typing import get_type_hints
>>> hints = get_type_hints(calc, include_extras=True)
>>> hints
{'day': typing.Annotated[float, 'seconds'], 'legal_limit': typing.Annotated[float, 'miles per hour', 'UK national limit for single carriageway'], 'current_speed': typing.Annotated[float, 'miles per hour']}
0 để lưu trữ tài liệu về một biến và đó là Pydantic. Nó phức tạp hơn một chút so với việc chỉ lưu trữ một tài liệu mặc dù nó thực sự mong đợi một ví dụ là
Python 3.9.1 (default, Jan 19 2021, 09:36:39) 
[Clang 10.0.1 (clang-1001.0.46.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import calc
>>> from typing import get_type_hints
>>> hints = get_type_hints(calc, include_extras=True)
>>> hints
{'day': typing.Annotated[float, 'seconds'], 'legal_limit': typing.Annotated[float, 'miles per hour', 'UK national limit for single carriageway'], 'current_speed': typing.Annotated[float, 'miles per hour']}
4. Đây là một ví dụ:

from typing import Annotated
import typing_extensions
from pydantic import Field
from pydantic.main import BaseModel
from datetime import date

# TypeAlias is in typing_extensions for Python 3.9:
FirstName: typing_extensions.TypeAlias = Annotated[str, Field(
        description="The subject's first name", example="Linus"
    )]

class Subject(BaseModel):
    # Using an annotated type defined elsewhere:
    first_name: FirstName = ""

    # Documenting a field inline:
    last_name: Annotated[str, Field(
        description="The subject's last name", example="Torvalds"
    )] = ""

    # Traditional method without using Annotated
    # Field needs an extra argument for the default value
    date_of_birth: date = Field(
        ...,
        description="The subject's date of birth",
        example="1969-12-28",
    )

Sử dụng lớp mô hình:

>>> guido = Subject(first_name='Guido', last_name='van Rossum', date_of_birth=date(1956, 1, 31))
>>> print(guido)
first_name='Guido' last_name='van Rossum' date_of_birth=datetime.date(1956, 1, 31)

Các mô hình Pydantic có thể cung cấp cho bạn một lược đồ JSON:

>>> from pprint import pprint
>>> pprint(Subject.schema())
{'properties': {'date_of_birth': {'description': "The subject's date of birth",
                                  'example': '1969-12-28',
                                  'format': 'date',
                                  'title': 'Date Of Birth',
                                  'type': 'string'},
                'first_name': {'default': '',
                               'description': "The subject's first name",
                               'example': 'Linus',
                               'title': 'First Name',
                               'type': 'string'},
                'last_name': {'default': '',
                              'description': "The subject's last name",
                              'example': 'Torvalds',
                              'title': 'Last Name',
                              'type': 'string'}},
 'required': ['date_of_birth'],
 'title': 'Subject',
 'type': 'object'}
>>> 

Nếu bạn sử dụng lớp này trong ứng dụng Fastapi, thông số kỹ thuật OpenAPI có ví dụ và mô tả cho cả ba trong số này được lấy từ trường liên quan.

Và đây là câu trả lời ban đầu đã đúng lúc đó nhưng không đứng trước thử thách của thời gian:

Không, không thể và nó sẽ không hữu ích nếu bạn có thể.

DocString luôn là một thuộc tính của một đối tượng (mô -đun, lớp hoặc hàm), không được gắn với một biến cụ thể.

Điều đó có nghĩa là nếu bạn có thể làm:

t = 42
t.__doc__ = "something"  # this raises AttributeError: '__doc__' is read-only

Bạn sẽ đặt tài liệu cho số nguyên 42 không dành cho biến

Python 3.9.1 (default, Jan 19 2021, 09:36:39) 
[Clang 10.0.1 (clang-1001.0.46.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import calc
>>> from typing import get_type_hints
>>> hints = get_type_hints(calc, include_extras=True)
>>> hints
{'day': typing.Annotated[float, 'seconds'], 'legal_limit': typing.Annotated[float, 'miles per hour', 'UK national limit for single carriageway'], 'current_speed': typing.Annotated[float, 'miles per hour']}
5. Ngay khi bạn tái lập
Python 3.9.1 (default, Jan 19 2021, 09:36:39) 
[Clang 10.0.1 (clang-1001.0.46.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import calc
>>> from typing import get_type_hints
>>> hints = get_type_hints(calc, include_extras=True)
>>> hints
{'day': typing.Annotated[float, 'seconds'], 'legal_limit': typing.Annotated[float, 'miles per hour', 'UK national limit for single carriageway'], 'current_speed': typing.Annotated[float, 'miles per hour']}
5, bạn sẽ mất tài liệu. Các đối tượng bất biến như số lượng chuỗi đôi khi có một đối tượng được chia sẻ giữa những người dùng khác nhau, vì vậy trong ví dụ này, có lẽ bạn thực sự đã đặt DocString cho tất cả các sự cố của
Python 3.9.1 (default, Jan 19 2021, 09:36:39) 
[Clang 10.0.1 (clang-1001.0.46.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import calc
>>> from typing import get_type_hints
>>> hints = get_type_hints(calc, include_extras=True)
>>> hints
{'day': typing.Annotated[float, 'seconds'], 'legal_limit': typing.Annotated[float, 'miles per hour', 'UK national limit for single carriageway'], 'current_speed': typing.Annotated[float, 'miles per hour']}
7 trong suốt chương trình của bạn.

print(42 .__doc__) # would print "something" if the above worked!

Đối với các đối tượng có thể thay đổi, nó sẽ không nhất thiết phải có hại nhưng vẫn sẽ bị hạn chế nếu bạn phản bác đối tượng.

Nếu bạn muốn ghi lại một thuộc tính của một lớp thì hãy sử dụng tài liệu của lớp để mô tả nó.

DocString của lớp là gì?

DocString là một chuỗi theo nghĩa đen xảy ra như là câu lệnh đầu tiên trong một mô -đun, hàm, lớp hoặc định nghĩa phương thức. Một tài liệu như vậy trở thành thuộc tính đặc biệt của __doc__ của đối tượng đó. Tất cả các mô -đun thường có tài liệu, và tất cả các chức năng và lớp được xuất bằng một mô -đun cũng nên có tài liệu.a string literal that occurs as the first statement in a module, function, class, or method definition. Such a docstring becomes the __doc__ special attribute of that object. All modules should normally have docstrings, and all functions and classes exported by a module should also have docstrings.

Có nên bắt đầu có một tài liệu?

Phương pháp __init__ có thể được ghi lại trong tài liệu cấp lớp hoặc như một tài liệu trên chính phương thức __init__.Một trong hai hình thức được chấp nhận, nhưng cả hai không nên được trộn lẫn.Chọn một quy ước để ghi lại phương thức __init__ và phù hợp với nó.. Either form is acceptable, but the two should not be mixed. Choose one convention to document the __init__ method and be consistent with it.

__ Doc __ có nghĩa là gì trong Python?

Thuộc tính __doc__ Mỗi đối tượng Python (hàm, lớp, biến, ...) cung cấp (nếu lập trình viên đã điền vào nó) một tài liệu ngắn mô tả các tính năng của nó.Bạn có thể truy cập nó bằng các lệnh như in myObject.provides (if programmer has filled it) a short documentation which describes its features. You can access it with commands like print myobject.

Mục đích của __ doc_string __ là gì?

DocString Python là một chuỗi được sử dụng để ghi lại mô -đun Python, lớp, chức năng hoặc phương thức, vì vậy các lập trình viên có thể hiểu những gì nó làm mà không cần phải đọc chi tiết về việc triển khai.Ngoài ra, đó là một thực tế phổ biến để tạo tài liệu trực tuyến (HTML) tự động từ các tài liệu.to document a Python module, class, function or method, so programmers can understand what it does without having to read the details of the implementation. Also, it is a common practice to generate online (html) documentation automatically from docstrings.