![](/img/trans.png)
[英]How to annotate function that takes a tuple of variable length? (variadic tuple type annotation)
[英]How to type annotate length of string?
我想在 python 中键入一个只接受单个字符的函数,举个例子: (s: str) -> int
由于 Python 没有单个字符的类型,因此您不能只执行(s: char) -> int
之类的操作。
有什么方法可以让s: str
只能是一个字符吗?
我可以看到这在编写代码时的提示中很有用。
这是我的完整示例:
import unicodedata
roman_numeral_lookup = {"I": 1, "V": 5, "X": 10, ...}
def exact_roman_numeral(s: str) -> int:
"""Return the value of a single Roman numeral. Dosen't support multicharacter roman numerals such as 'XII' or Apostrophus."""
# Convert Unicode Roman numerals into to their normalised text version. e.g. Ⅹ -> X, ⅰ -> I
s = unicodedata.normalize("NFKC", s).upper()
if s in roman_numeral_lookup:
return roman_numeral_lookup[s]
else: # Some form of invalid value.
if not isinstance(s, str):
raise TypeError("Argument must be of type str.")
elif len(s) != 1:
raise ValueError("Must be a single Roman numeral.")
else:
raise ValueError("Not a valid/supported Roman numeral.")
(我知道错误不是最好的)
好吧,理论上不应像您希望的那样使用类型注释 - 意思是,并非代码中的每个约束都应由类型注释表示。
现在,要回答您的问题,您当然可以构建自己的类型注释,但 IMO 工作量太大,结果太少。
SO上有其他答案描述了如何定义自定义注释
您可以随时:
原生地,没有。 注释无法满足您的要求。 但...
您可以创建一个新类型来支持您的字符串长度等规则,然后在您的注释中使用该类型。
class MyStringThatShouldOnlyBeOneCharacter:
def __init__(self, text):
self.text = text
# put your value checking here
return
def exact_roman_numeral(s: MyStringThatShouldOnlyBeOneCharacter) -> int:
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.