Python 规则:带默认值的参数必须放在不带默认值的后面

Python 规则:带默认值的参数必须放在不带默认值的后面

python 复制代码
# 需求:查询新闻 -> 分页, skip: 跳过的记录数, limit: 返回的记录数 10
@app.get("/news/news_list")
async def get_news_list(
        skip: int = 0,
        limit: int # 错误示例
):
    return {"skip": skip, "limit": limit}

上面这段编译代码报错如下:

text 复制代码
SyntaxError: non-default argument follows default argument

原因:

Python 语法规定:带默认值的参数,必须放在 不带默认值的参数 后面!

正确写法(两种方案)

方案 1:给 limit 也加默认值(最常用、最推荐)

python 复制代码
@app.get("/news/news_list")
async def get_news_list(
    skip: int = 0,
    limit: int = 10  # 加个默认值
):
    return {"skip": skip, "limit": limit}

方案 2:把无默认值的放前面

python 复制代码
@app.get("/news/news_list")
async def get_news_list(
    limit: int,       # 无默认值放前面
    skip: int = 0     # 有默认值放后面
):
    return {"skip": skip, "limit": limit}

总结

有默认值的参数 → 必须放后面

无默认值的参数 → 必须放前面

FastAPI 接口参数也必须遵守这个 Python 基础语法

相关推荐
susplus17 分钟前
【linux应用软件编程】进程间的通信方式1【管道&IPC】
linux·进程通信·管道·ipc
月光船幽幽3 小时前
检测用户意图复杂性的关键方法
人工智能·python
AlfredZhao4 小时前
用 crontab 给 LLM 使用量装上“监控眼”
linux
DogDaoDao6 小时前
Windows 开发提效工具全景指南:60+ 工具的工程化分层配置
windows·git·程序员·开发工具·powershell·everything·msys2
刃神太酷啦6 小时前
Linux 系统 MySQL 完整安装配置教程:从卸载 MariaDB 到优化 my.cnf----《Hello MySQL!》(1)
android·linux·c语言·c++·mysql·leetcode·mariadb
威联通网络存储6 小时前
TS-h3087XU-RP 汽车零部件质检追溯部署
python·汽车
你驴我6 小时前
WhatsApp 多账号场景下的会话归档与历史消息检索优化实践
后端·python
IT毕设实战小研7 小时前
基于安卓的空气质量查询系统
android·大数据·vue.js·爬虫·python·django·课程设计
赵文宇(温玉)7 小时前
OpenEuler24.03 SP4 系统安装(欧拉/麒麟V10)
linux·openeuler·欧拉
harmful_sheep7 小时前
java group by常见用法
java·开发语言·python