[英]How to restrict a parameter of python function must be string or a function like lambda expression
For example, the following, the first parameter should be restricted to a string, and the second parameter should be a function. 例如,以下内容,第一个参数应限制为字符串,第二个参数应为函数。 However, this is wrong syntax for both.
但是,这两者的语法都是错误的。 Anyone can help suggest the correct syntax to impose the type restriction?
任何人都可以帮助建议正确的语法来强加类型限制?
def GetArg(msg:String, converter:lambda, default):
print("{}, the default is '{}':".format(msg, default))
return converter(stdin.readline().strip())
It gives error 它给出了错误
Traceback (most recent call last):
File "E:/stdin_ext.py", line 4, in <module>
def GetArg(msg:String, converter, default:String):
NameError: name 'String' is not defined
and 和
File "E:/stdin_ext.py", line 4
def GetArg(msg:String, converter:lambda, default:String):
^
SyntaxError: invalid syntax
You can use the typing module. 您可以使用输入模块。
from typing import Callable
def get_arg(msg: str, converter: Callable[[str], str], default) -> str:
print(f"{msg}, the default is '{default}':")
return converter(stdin.readline().strip())
assuming your function converter
takes a string
a returns a string
, and that get_arg
returns a string
. 假设你的函数
converter
接受一个string
a返回一个string
,并且get_arg
返回一个string
。 Note the code has also been modified to follow python's naming convention and uses f strings
over older style format strings. 请注意,代码也已修改为遵循python的命名约定,并使用
f strings
不是旧样式格式字符串。
Also note that these type hints
are just that, hints . 另请注意,这些
type hints
只是提示 。 They are not checked statically or at runtime. 它们不会静态检查或在运行时检查。 Although, certain IDE's will help you ensure they are correct.
虽然,某些IDE会帮助您确保它们是正确的。
You should use str
instead of String
and Callable
instead of lambda: 您应该使用
str
而不是String
和Callable
而不是lambda:
from typing import Callable
def GetArg(msg:str, converter:Callable, default):
print("{}, the default is '{}':".format(msg, default))
return converter(stdin.readline().strip())
That is, unless you have a specific class called String
and you are expecting an argument of its type. 也就是说,除非你有一个名为
String
的特定类,并且你期望它的类型参数。
When you write lambda
you are defining a new lambda, not specifying a type for a function, whence the error. 当你编写
lambda
你正在定义一个新的lambda,而不是为函数指定一个类型,从而产生错误。
I believe it is also important to point out that types in python are only a useful notation but it does not raise any error by itself, for example I could still call GetArg(1,2,3)
and don't get any error just by the type hinting (of course I would get an error trying to pass an argument to an int afterwards). 我相信这是同样重要的是指出,类型蟒蛇只是一个有用的格式,但它本身并不能提高任何错误,例如我仍然可以称之为
GetArg(1,2,3)
并没有得到任何错误只是通过类型提示 (当然我会在尝试将参数传递给int之后得到错误)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.