التلميحات توثيق تستطيع الأدوات فحصه
بايثون ديناميكي الأنواع: يمكن لمتغير أن يحمل أي شيء، ولا يظهر النوع الخاطئ إلا عند تشغيل السطر، ربما وسط يوم التداول. وتلميحات الأنواع تتيح كتابة ما تتوقعه الدالة وما ترجعه: def mid_price(bid: float, ask: float) -> float. وبايثون نفسها تتجاهلها عند التشغيل. قيمتها أن المحرر والمدقق الساكن مثل mypy أو pyright يقرؤها وينبهك إلى نداء خاطئ قبل تشغيل الشيفرة أصلًا، وأنها توثّق الدالة أفضل من تعليق يتقادم.
# Hints describe the function; Python does not enforce them when it runs
def mid_price(bid: float, ask: float) -> float:
return (bid + ask) / 2
print(mid_price(100.0, 100.5)) # 100.25
print(mid_price.__annotations__) # {'bid': <class 'float'>, 'ask': <class 'float'>, 'return': <class 'float'>}
print(mid_price(10, 12)) # 11.0 an int is accepted where float is hinted
try:
mid_price("a", "b") # a checker flags this line before the code runs
except TypeError as error:
print("only fails when it runs:", error) # only fails when it runs: unsupported operand type(s) for /الحاويات وNone والاتحادات
تأخذ الحاويات المدمجة أنواع عناصرها بين أقواس: list[float] وdict[str, float] وtuple[str, float] (نوع لكل موضع). والقيمة التي قد تغيب هي float | None ما يُلزم المستدعي بمعالجة None؛ ويشكو المدقق إن استعمل الناتج رقمًا دون فحص. وداخل الدالة يقوم if x is None: return بـتضييق النوع فيعرف الباقي أنه float. وللوسائط التي تُقرأ فقط فضّل نوعًا عامًا مثل Sequence[float] (قوائم، وtuples) على list[float] لتناسب مستدعين أكثر؛ وأرجع نوعًا محددًا مثل list[float].
# Containers, an optional result, and narrowing with an is None check
def best_quote(quotes: list[tuple[str, float]]) -> tuple[str, float] | None:
if not quotes:
return None
return min(quotes, key=lambda quote: quote[1])
def describe(quotes: list[tuple[str, float]]) -> str:
best = best_quote(quotes)
if best is None: # after this check the checker knows best is a tuple
return "no quotes"
venue, price = best
return f"{venue} at {price:.2f}"
print(describe([("XNAS", 100.02), ("ARCX", 100.01)])) # ARCX at 100.01
print(describe([])) # no quotesأشكال البيانات والمدقق وهو يعمل
القاموس ذو المفاتيح الثابتة، كأمر مثلًا، يفضَّل وصفه لا تركه dict. يسمّي TypedDict أو dataclass كل حقل ونوعه فيصير خطأ مطبعي مثل order["quantiy"] خطأً في المحرر لا KeyError عند 15:59. وتشغَّل أداة الفحص من سطر الأوامر (mypy main.py)؛ تطبع كل موضع تناقض فيه الشيفرة تلميحاتها وتخرج برمز غير صفري فتنسجم مع الفحوص الآلية التي ستراها لاحقًا. ويمكن إضافة التلميحات تدريجيًا: Any يوقف الفحص لقيمة، والشيفرة بلا أنواع تُتخطى. والتلميحات بيانات أيضًا تقرؤها الأدوات وقت التشغيل بـ typing.get_type_hints وهكذا يفحصها هذا المختبر.
# A TypedDict names the fields of an order; the checker would flag order["quantiy"]
from typing import TypedDict
class Order(TypedDict):
symbol: str
quantity: int
price: float
def notional(order: Order) -> float:
return order["quantity"] * order["price"]
order: Order = {"symbol": "AAPL", "quantity": 100, "price": 184.5}
print(notional(order)) # 18450.0
print(Order.__annotations__) # {'symbol': <class 'str'>, 'quantity': <class 'int'>, 'price': <class 'float'>}# The hints can be read at run time, which is how tools (and this lab) inspect a function
import typing
def apply_fee(prices: typing.Sequence[float], fee_rate: float = 0.001) -> list[float]:
return [price * (1 + fee_rate) for price in prices]
hints = typing.get_type_hints(apply_fee)
print(hints["fee_rate"], hints["return"]) # <class 'float'> list[float]
print(typing.get_origin(hints["prices"]).__name__) # Sequence
print(apply_fee((100.0, 200.0))) # a tuple is accepted: [100.1, 200.2]- التلميحات (
bid: floatو-> float) توثّق الدالة وتُتجاهل عند التشغيل؛ ويقرؤها مدقق مثل mypy. - تأخذ الحاويات أنواع العناصر (
list[tuple[str, float]])؛ والقيمة الغائبة هيfloat | None؛ ويمكن أن تكون الوسائط للقراءة فقطSequence[float]عامًا. - استعمل
TypedDictأوdataclassللسجلات، وشغّل المدقق في فحوصك الآلية، وتحقق من البيانات الخارجية واختبر الأرقام.
التالي: الاختبار باستخدام pytest، والـ fixtures والحالات المعلمَّة والفحوص التي تُبقي الاستراتيجية صادقة.
المختبر: ما الذي يُقيَّم
- أضف تلميحات الأنواع للأرقام في
mid_price25 نقطة - حدّد نوع حاوية في
best_quote25 نقطة - اسمح بقيمة غائبة في
safe_ratio25 نقطة - اقبل أي متتالية في
apply_fee25 نقطة