在Python中获取参数类型

问题描述 投票:0回答:5

我正在学习Python。我喜欢使用 help() 或 interinspect.getargspec 来获取 shell 中函数的信息。但无论如何我可以获得函数的参数/返回类型。

python types arguments
5个回答
10
投票

在 3.4.2 文档中https://docs.python.org/3/library/inspect.html,提到了您确切需要的内容(即获取函数参数的类型)。

您首先需要像这样定义您的函数:

def f(a: int, b: float, c: dict, d: list, <and so on depending on number of parameters and their types>):

然后你可以使用

formatargspec(*getfullargspec(f))
它会返回一个很好的散列,如下所示:

(a: int, b: float)

8
投票

formatargspec
自 3.5 版本起已弃用。更喜欢
signature

>>> from inspect import signature
>>> def foo(a, *, b:int, **kwargs):
...     pass

>>> sig = signature(foo)

>>> str(sig)
'(a, *, b:int, **kwargs)'

注意:在 Python 的某些实现中,某些可调用对象可能无法自省。例如,在 CPython 中,C 中定义的一些内置函数不提供有关其参数的元数据。


5
投票

如果你的意思是在函数的某个调用期间,函数本身可以通过对每个参数调用

type
来获取其参数的类型(并且肯定会知道它返回的类型)。

如果您的意思是从函数外部,则不:可以使用任何类型的参数调用该函数 - 某些此类调用会产生错误,但无法先验地知道它们会是哪些错误。

在 Python 3 中可以选择修饰参数,这种修饰的一种可能用途是表达有关参数类型(和/或对其的其他约束)的信息,但语言和标准库没有提供有关此类修饰如何进行的指导使用。您不妨采用一个标准,在函数的文档字符串中以结构化方式表达此类约束,这将具有适用于任何版本的 Python 的优点。


0
投票

最佳、最短的答案:

使用 inspect 库和 getfullargspec(function).annotations 请注意,您必须显式地对函数参数进行类型转换。

import inspect

def my_func(arg_1:str="One", arg_2:bool=False):
    pass

spec = inspect.getfullargspec(my_func).annotations

print(spec)

>>> {'arg_1': <class 'str'>, 'arg_2': <class 'bool'>}

从中您可以使用

spec.values()
获取每个参数的数据类型。


-2
投票

有一个函数叫

type()

这里是文档

你无法提前知道函数将返回什么类型

>>> import random
>>> def f():
...  c=random.choice("IFSN")
...  if c=="I":
...   return 1
...  elif c=="F":
...   return 1.0
...  elif c=="S":
...   return '1'
...  return None
... 
>>> type(f())
<type 'float'>
>>> type(f())
<type 'NoneType'>
>>> type(f())
<type 'float'>
>>> type(f())
<type 'int'>
>>> type(f())
<type 'str'>
>>> type(f())
<type 'float'>
>>> type(f())
<type 'float'>
>>> type(f())
<type 'NoneType'>
>>> type(f())
<type 'str'>

从函数中只返回一种类型的对象通常是一个好习惯,但 Python 不会强迫你这样做

© www.soinside.com 2019 - 2024. All rights reserved.