V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
frankyzf
V2EX  ›  Python

程序运行时怎么能做到如果返回值和注解中的类型不匹配则报错?

  •  
  •   frankyzf · 297 天前 · 901 次点击
    这是一个创建于 297 天前的主题,其中的信息可能已经有所发展或是发生改变。

    不熟悉 python ,想问下程序运行时怎么能做到如果返回值和注解中的类型不匹配则报错?

    现在的情况如下:一个方法返回值有类型注解(比如 List<float>),具体的功能是从一个 API 里拿到后进行加工后返回。麻烦问下有什么插件或方法能做到在运行时,如果返回值的类型和类型注解不匹配 (比如返回值是 List<List<float>>)则报错?先谢谢了。

    3 条回复    2023-07-05 19:52:31 +08:00
    lsongzhi
        1
    lsongzhi  
       297 天前   ❤️ 1
    运行时类型检查用 pydantic ,https://github.com/pydantic/pydantic
    lisongeee
        2
    lisongeee  
       297 天前   ❤️ 1
    应该是 https://docs.pydantic.dev/latest/usage/validation_decorator/

    使用它的 `@validate_call` 装饰器放在你需要类型校验的函数上就行
    frankyzf
        3
    frankyzf  
    OP
       297 天前
    谢谢 @lisongeee @lsongzhi 的回复,我试下
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2543 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 15:56 · PVG 23:56 · LAX 08:56 · JFK 11:56
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.