How can a class be used to define function args in Python?

I’m wondering if it’s possible to use a class to define function args in pure Python, or maybe by using a package.

For example:

class FunArgs:
    first: int
    second: str

def my_fun(FunArgs):
    pass

if __name__ == "__main__":
    my_fun(first=1, second="OK")

The reason to use that syntax is just its simplicity.

Often we tend to add too much of args in functions and also put notes about them, which reduce its readability.

The example is very simple, but in general those types are longer and more complex, which reduce readability more.

8

I won’t go too much into details about the appropriateness of such an approach to class design (after all, Python’s philosophy is basically “do whatever you want as long as you know what you are doing”).

The simplest way you can get to such a syntax is using dataclass.

from dataclasses import dataclass

@dataclass
class FunArgs:
    first: int
    second: int

def my_fun(fun_args: FunArgs):
    print(f'This is first: {fun_args.first}')
    print(f'This is second: {fun_args.second}')

if __name__ == "__main__":
    my_fun(FunArgs(1, "OK"))

3

This isn’t a recommendation, but if you’re looking to increase the readability in your codebase, consider using a decorator that validates **kwargs based on a provided dataclass. This way, you can avoid passing a dataclass instance when calling your function. Instead, the dataclass serves solely for validating that the correct arguments are passed, similar to how a Python function with named arguments would behave if an argument is missing. You define the decorator once (in this case args_with_class) and then you can reuse it on all your functions. You are free to change the name to something that makes sense for you.

This validation in the decorator is just an example, Pydantic might be a good option here.

from dataclasses import dataclass, fields
from typing import Callable, Type

@dataclass
class FunArgs:
    first: int
    second: str

def args_with_class(dataclass_type: Type):
    def decorator(func: Callable):
        def wrapper(*args, **kwargs):
            # Extract dataclass fields
            required_fields = {f.name for f in fields(dataclass_type)}
            
            # Check if all required fields are present in kwargs
            missing_fields = required_fields - kwargs.keys()
            if missing_fields:
                raise TypeError(f"Missing required arguments: {', '.join(missing_fields)}")

            # Call the actual function
            return func(*args, **kwargs)

        return wrapper
    return decorator



@args_with_class(FunArgs)
def my_fun(**kwargs):
    print(f'This is first: {kwargs["first"]}')
    print(f'This is second: {kwargs["second"]}')

if __name__ == "__main__":
    # Correct usage
    my_fun(first=1, second=2)

    # Example with incorrect types
    try:
        my_fun(first=1, second="OK")
    except TypeError as e:
        print(e)

    # Example with missing arguments
    try:
        my_fun(first=1)
    except TypeError as e:
        print(e)

4

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật