无需调用即可检查Python函数签名 [英] Check python function signature without a call

查看:148
本文介绍了无需调用即可检查Python函数签名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序从用户输入中得到一个序列 args 和一个映射 kwargs 。我想检查这个输入,然后将它转发给一个python函数 f (这是根据用户输入选择的)。在这种情况下, f [kw] args 之间的函数签名不匹配是输入错误;我必须在 f 的实现中将它与可能的编程错误区分开来,即使它们都可能引发 TypeError

所以我想在尝试函数调用之前检查签名。除了手动比较 [kw] args inspect.getargspec (或 .getfullargspec .signature 在后面的python版本中)?



相关问题: 有没有办法在Python中检查函数的签名?

解决方案

使用 inspect 可能是最直接的方式 - 这不是人们通常期望在Python中执行的操作。



(通常,允许最终用户使用任意输入调用任意函数并不是程序员想要的。)


My program derives a sequence args and a mapping kwargs from user input. I want to check that input, and then forward it to a python function f (which is chosen based on user input). In this case, a function signature mismatch between f and [kw]args is an input error; I must distinguish it from possible programming errors within the implementation of f, even though they might both raise TypeError.

So I want to check the signature before attempting the function call. Is there a way to do this other than to manually compare [kw]args to the result of inspect.getargspec (or .getfullargspec or .signature in later python versions)?

Related questions: Is there a way to check a function's signature in Python?

解决方案

The method using inspect is probably the most straightforward way of doing this that exists - it's not something one would normally expect to be doing in Python.

(Typically, allowing end users to call arbitrary functions with arbitrary inputs is not what a programmer wants.)

这篇关于无需调用即可检查Python函数签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆