【问题标题】:DataType of Arguments for Function in PythonPython中函数参数的数据类型
【发布时间】:2021-06-11 08:23:42
【问题描述】:

这是一件事 我想在 python 中预定义函数接受的任何参数的 DataType,就像我们在 C 或 C++ 中所做的那样。

# For Example
def maw(x, y):
  return x+y # I want to predefine this x and y to be integer-type

就像

// This is C-Program which accepts only integer as a parameter
int main(int x, int y){
return x+y;
}

我不想用另一行代码过滤这个参数,比如

if 'int' in type(x):
  pass
else:
  return False

【问题讨论】:

标签: python function filter arguments


【解决方案1】:

不幸的是,类型注释仍然只是一种方便,尽管通过 Python 解释器标志强制启用它们会很好。

但是,它们可用于mypy 的静态分析或ensure 的动态运行时分析(与单元测试结合运行非常有效)。

取自ensure的文档:

from ensure import ensure_annotations

@ensure_annotations
def f(x: int, y: float) -> float:
    return x + y

或在您的 DateType 情况下:

>>> from ensure import ensure_annotations
>>> from datetime import datetime, timedelta
>>> @ensure_annotations
... def myfunc(param: datetime) -> datetime:
...     return 123
... 
>>> @ensure_annotations
... def mycorrectfunc(param: datetime) -> datetime:
...     return param + timedelta(days=1)
... 
>>> myfunc(datetime.now())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File ".../lib/python3.8/site-packages/ensure/main.py", line 855, in __call__
    raise EnsureError(msg.format(
ensure.main.EnsureError: Return value of <function myfunc at 0x7f28325d7310> of type <class 'int'> does not match annotation type <class 'datetime.datetime'>
>>> mycorrectfunc(datetime.now())
datetime.datetime(2021, 3, 15, 10, 53, 37, 888834)
>>> 

这适用于所有其他类或type aliases(非常!)大致以类似的方式使用typedef或更确切地说assert isinstance(...)

【讨论】:

    【解决方案2】:

    没有办法在 Python 中声明变量,因为 C 意义上的“声明”和“变量”都不存在。

    reference

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-24
      • 1970-01-01
      • 2023-03-26
      • 2022-01-07
      • 2020-01-28
      • 2021-05-16
      • 1970-01-01
      相关资源
      最近更新 更多