You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Python函数接收特定组合的必填参数?

Python函数参数:实现"二选一必填"逻辑

针对你需求的场景,有两种实用的实现方式,既避免全可选参数的松散性,又能满足用户只需提供id或username其一的要求:

方法一:参数默认值+内部校验

把所有参数设为None(可选),然后在函数内部做校验,确保每个用户的id和username至少提供一个,也可以选择是否限制同时提供两者:

def get_chat(first_id=None, first_username=None, second_id=None, second_username=None):
    """Returns chat between first and second"""
    # 校验第一个用户的身份参数
    if first_id is None and first_username is None:
        raise ValueError("必须提供first_id或first_username中的一个")
    # 可选:如果不允许同时传id和username,添加以下校验
    # if first_id is not None and first_username is not None:
    #     raise ValueError("first_id和first_username不能同时提供")
    
    # 校验第二个用户的身份参数
    if second_id is None and second_username is None:
        raise ValueError("必须提供second_id或second_username中的一个")
    # 可选:同样限制第二个用户的参数冲突
    # if second_id is not None and second_username is not None:
    #     raise ValueError("second_id和second_username不能同时提供")
    
    # 这里编写获取聊天记录的业务逻辑
    # ...

方法二:用数据类封装用户标识

通过数据类把每个用户的id和username打包成一个对象,在数据类的初始化阶段完成校验,让函数参数更规整,逻辑更清晰:

from dataclasses import dataclass

@dataclass
class UserIdentifier:
    user_id: int | None = None
    username: str | None = None
    
    def __post_init__(self):
        # 初始化后自动校验
        if self.user_id is None and self.username is None:
            raise ValueError("必须提供user_id或username中的一个")
        # 可选:限制同时提供id和username
        # if self.user_id is not None and self.username is not None:
        #     raise ValueError("不能同时提供user_id和username")

def get_chat(first_user: UserIdentifier, second_user: UserIdentifier):
    """Returns chat between first and second"""
    # 业务逻辑中直接通过first_user.user_id或first_user.username获取标识
    # ...

# 调用示例
get_chat(UserIdentifier(user_id=1001), UserIdentifier(username="user_alice"))
get_chat(UserIdentifier(username="user_bob"), UserIdentifier(user_id=1002))

两种方式对比

  • 方法一:无需额外依赖,代码简洁,适合简单场景;
  • 方法二:结构更清晰,参数传递更规范,适合需要复用用户标识逻辑的复杂项目。

内容的提问来源于stack exchange,提问作者Matvey_coder3

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 21:52:38