推荐学习书目
› 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 · Jul 5, 2023 · 2205 views
    This topic created in 1177 days ago, the information mentioned may be changed or developed.

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

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

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

    使用它的 `@validate_call` 装饰器放在你需要类型校验的函数上就行
    frankyzf
        3
    frankyzf  
    OP
       Jul 5, 2023
    谢谢 @lisongeee @lsongzhi 的回复,我试下
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   993 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 23:07 · PVG 07:07 · LAX 16:07 · JFK 19:07
    ♥ Do have faith in what you're doing.