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 để cung cấp một tài liệu cho các 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']}
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ó.