Python 确保函数参数始终是字符串

Syt*_*tze 3 python string types casting assertion

我正在尝试编写一个带有仅接受字符串的函数的程序。如何使 python 函数参数始终为字符串,如果不是则抛出错误?

我正在寻找类似的东西:

def foo(i: int): 
       return i  
foo(5) 
foo('oops')
Run Code Online (Sandbox Code Playgroud)

但这不会引发错误。

Sul*_*yev 5

一个非常基本的方法可能是检查参数是否是以下实例str

def f(x):
   assert isinstance(x, str), "x should be a string"
   # rest of the logic
Run Code Online (Sandbox Code Playgroud)

如果不需要运行时检查,则实现此目的的另一种方法是使用mypy添加类型提示并进行后续检查。这看起来像这样:

def f(x: str) -> str:
   # note: here the output is assumed to be a string also
Run Code Online (Sandbox Code Playgroud)

一旦带有类型提示的代码准备就绪,就可以运行它mypy并检查是否有任何可能的错误。

解决此问题的更高级方法包括定义一个包含断言的特定类(或通过尝试转换输入来强制类型),或使用一些第三方库:我想到的是param,但肯定还有其他库。