Pysertive : การออกแบบ Python แบบแน่วแน่โดยสัญญา (DBC) Toolkit
Pysertive เป็นห้องสมุด Python ที่จัดให้มีการตกแต่งสำหรับการออกแบบตามหลักการสัญญา (DBC) มันช่วยลดความซับซ้อนของเงื่อนไข postconditions และค่าคงที่ในรหัสของคุณ Pysertive มีจุดมุ่งหมายที่จะเป็นเครื่องมือที่ทรงพลังในการสร้างความมั่นใจว่าพฤติกรรมและข้อ จำกัด ของรหัสส่งเสริมการพัฒนาซอฟต์แวร์ที่ปลอดภัยบำรุงรักษาและมีประสิทธิภาพใน Python
สิ่งที่ pysertive ทำได้ดี:
Pysertive ได้รับการออกแบบด้วยความเรียบง่ายและความยืดหยุ่นในใจช่วยให้คุณสามารถรวมสัญญาที่เข้มงวดในการตรวจสอบรหัส Python ของคุณได้อย่างง่ายดายซึ่งช่วยในการดีบักและรักษาระบบที่ซับซ้อน
ในการติดตั้ง pysertive เพียงใช้ PIP:
pip install pysertiveนี่คือวิธีเริ่มต้นอย่างรวดเร็วด้วย pysertive:
from pysertive import pre_condition , post_condition , invariant
@ pre_condition ( lambda x : x > 0 , exception_type = ValueError , message = "Input must be positive" )
def sqrt ( x ):
return x ** 0.5
@ post_condition ( lambda result : result != None , exception_type = AssertionError , message = "Result cannot be None" )
def fetch_data ():
return { "data" : "Here is your data" }
@ invariant ( lambda self : self . balance >= 0 , exception_type = RuntimeError , message = "Insufficient funds" )
class BankAccount :
def __init__ ( self , balance ):
self . balance = balance
def deposit ( self , amount ):
self . balance += amount
def withdraw ( self , amount ):
self . balance -= amount # No need to manually check for negative balance ตรวจสอบให้แน่ใจว่าอินพุตไปยังฟังก์ชั่นของคุณถูกต้อง:
@ pre_condition ( lambda age : age >= 18 , exception_type = ValueError , message = "Must be 18 or older" )
def sign_contract ( age ):
print ( f"Contract signed by individual aged { age } " )ตรวจสอบความถูกต้องของผลลัพธ์หลังจากฟังก์ชั่นของคุณดำเนินการ:
@ post_condition ( lambda result : result > 0 , exception_type = AssertionError , message = "Profit must be positive" )
def calculate_profit ( revenue , costs ):
return revenue - costsบังคับใช้รัฐในชั้นเรียนยังคงสอดคล้อง:
@ invariant ( lambda self : self . inventory_count >= 0 , exception_type = RuntimeError , message = "Inventory count cannot be negative" )
class Warehouse :
def __init__ ( self , inventory_count ):
self . inventory_count = inventory_count
def add_stock ( self , number ):
self . inventory_count += number
def remove_stock ( self , number ):
self . inventory_count -= number สำหรับตัวอย่างรายละเอียดเพิ่มเติมเกี่ยวกับวิธีการใช้ pysertive ลองดูตัวอย่างไฟล์ examples.py ในที่เก็บ ไฟล์นี้มีตัวอย่างของวิธีการใช้เงื่อนไขล่วงหน้า postconditions และค่าคงที่ในรหัส Python ของคุณ
ยินดีต้อนรับ! หากคุณต้องการมีส่วนร่วมโปรดตรวจสอบคู่มือที่มีส่วนร่วมและอย่าลังเลที่จะเปิดปัญหาหรือคำขอดึง
Pysertive เปิดตัวภายใต้ใบอนุญาต MIT ดูไฟล์ใบอนุญาตสำหรับรายละเอียดเพิ่มเติม
ไปด้านบน