และ ช่วยให้ฟังก์ชันรับ argument ได้ใน จะเก็บ argument แบบ ที่เกินมาไว้ใน tuple ส่วน จะเก็บ argument แบบ ที่เกินมาไว้ใน dict (ชื่อเป็นเพียงข้อตกลงร่วม — สิ่งที่สำคัญคือ และ )
และ ช่วยให้ฟังก์ชันรับ argument ได้ใน จะเก็บ argument แบบ ที่เกินมาไว้ใน tuple ส่วน จะเก็บ argument แบบ ที่เกินมาไว้ใน dict (ชื่อเป็นเพียงข้อตกลงร่วม — สิ่งที่สำคัญคือ และ )
*args**kwargs*args**kwargs***def total(*args): # collects all positional args into a tuple
print(args) # e.g. (1, 2, 3)
return sum(args)
total(1, 2, 3) # 6
total(1, 2, 3, 4, 5) # 15 — any number of args
def configure(**kwargs): # collects keyword args into a dict
print(kwargs) # e.g. {"host": "localhost", "port": 8080}
for key, value in kwargs.items():
print(f"{key} = {value}")
configure(host="localhost", port=8080, debug=True)
def func(a, b, *args, **kwargs):
# a, b → required positional
# args → extra positional (tuple)
# kwargs → extra keyword (dict)
...
func(1, 2, 3, 4, x=5, y=6)
# a=1, b=2, args=(3, 4), kwargs={"x": 5, "y": 6}
ลำดับที่จำเป็นต้องเป็นคือ: parameter ปกติ จากนั้น *args แล้วตามด้วย **kwargs
# `*` and `**` also UNPACK collections INTO arguments at the call site
numbers = [1, 2, 3]
total(*numbers) # same as total(1, 2, 3)
settings = {"host": "x", "port": 80}
configure(**settings) # same as configure(host="x", port=80)
ไวยากรณ์เดียวกันนี้ใช้แตก (unpack) list/dict ออกเป็น argument แบบ positional/keyword — สะดวกสำหรับการส่งต่อ argument
def wrapper(*args, **kwargs):
# accept ANY arguments and pass them through unchanged
return original_func(*args, **kwargs)
รูปแบบการส่งผ่าน (pass-through) นี้คือวิธีที่ decorator และฟังก์ชัน wrapper ใช้จัดการกับ signature ของฟังก์ชันใด ๆ
*args/**kwargs ช่วยให้สร้าง signature ของฟังก์ชันที่ยืดหยุ่นซึ่งรับ argument ได้ทุกจำนวน — จำเป็นอย่างยิ่งสำหรับการเขียน utility อเนกประสงค์ wrapper และโดยเฉพาะอย่างยิ่ง decorator (ซึ่งต้องห่อหุ้มฟังก์ชันที่ไม่ทราบ signature ผ่าน *args, **kwargs)
ทิศทางการ unpack (*list, **dict) ก็มีประโยชน์เท่ากันสำหรับการส่งต่อหรือกระจาย argument
การเข้าใจทั้งการเก็บรวบรวม (collecting) และการ unpacking เป็นกุญแจสำคัญในการเขียนโค้ด Python ที่นำกลับมาใช้ใหม่และเป็นแบบทั่วไป รวมถึงการอ่าน API และ decorator ของไลบรารีจำนวนมากที่พึ่งพาฟีเจอร์เหล่านี้