我想限制可以作为参数传递给另一个函数的函数范围。例如,将函数限制为两个指定的函数中的一个,或者来自特定模块,或者通过签名。我尝试了下面的代码,但是现在有一些限制: as参数可以被传递给任何函数。
这在Python中是可能的吗?
def func_as_param():
print("func_as_param called")
def other_func():
print("other_func called")
def func_with_func_arg(func: func_as_param): # this is not giving restrictions
# def func_with_func_arg(func: type(func_as_param)): # this is also not giving restrictions
print("func_with_func_arg called")
func()
def test_func_with_func_arg():
print("test_func_with_func_arg")
func_with_func_arg(func_as_param)
func_with_func_arg(other_func) # <- here IDE must complain that only func_as_param is expected
发布于 2022-10-07 18:29:50
期望特定签名的回调函数的
框架可能会使用
Callable[[Arg1Type, Arg2Type], ReturnType]
暗示类型。
您可能需要使用可调用类型。这可能对https://docs.python.org/3/library/typing.html#callable有帮助
注意事项
Python中的类型注释与C中的类型注释不同,它们是可选的语法块,我们可以添加这些代码以使代码更加明确。错误的类型注释只会在我们的代码编辑器中突出显示不正确的注释--不会因为注释而引发错误。如果有必要的话,你必须自己做检查。
发布于 2022-10-07 18:29:28
通常这是通过创建您自己的类型(类)来完成的。然后,任何其他函数都可以从它继承,并将是相同的“类型”。
class my_functions:
pass
class func_as_param_class(my_functions):
@staticmethod
def __call__():
print("func_as_param called")
func_as_param = func_as_param_class() # create the callable function ....
def other_func():
print("other_func called")
def func_with_func_arg(func: my_functions): # only my_functions are accepted.
# def func_with_func_arg(func: type(func_as_param)):
print("func_with_func_arg called")
func()
def test_func_with_func_arg():
print("test_func_with_func_arg")
func_with_func_arg(func_as_param)
func_with_func_arg(other_func) # <- here IDE must complain that only func_as_param is expected
在上面的代码中,我的IDE (py魅力)确实抱怨other_func
是错误的类型,但是这并不在运行时执行任何限制,它只允许IDE linter和mypy发出违规警告。
编辑:通过将调用函数声明为静态来删除参数。
发布于 2022-10-07 18:09:12
我不知道Python不对类型注释做任何更改是不是只有我一个人
语法:
def greeting(name: str) -> str:
return 'Hello ' + name
您可以在这里找到更多信息:https://docs.python.org/3/library/typing.html
https://stackoverflow.com/questions/73991045
复制相似问题