Trung BìnhPython iconPython

`*args` và `**kwargs` là gì? Khi nào dùng?

args cho phép nhận bất kỳ số positional arguments — nhóm thành tuple. *kwargs nhận bất kỳ số keyword arguments — nhóm thành dict.

python
def log(level, *args, **kwargs):
    print(f"[{level}]", *args)
    for k, v in kwargs.items():
        print(f"  {k}: {v}")

log("INFO", "Server started", port=8080, debug=True)
# [INFO] Server started
#   port: 8080
#   debug: True

# Unpacking khi gọi function
def create_user(name, email, age):
    ...

data = {"name": "Alice", "email": "a@b.com", "age": 25}
create_user(**data)  # Unpack dict thành kwargs

Thứ tự params: def fn(pos, /, normal, args, kw_only, *kwargs).

Pitfall: args*kwargs không giữ type information — dùng overloads hoặc TypedDict cho strict typing.

Xem toàn bộ Python cùng filter theo level & chủ đề con.

Mở danh sách Python