英文:
Python defining range of input parameter for methode
问题
你能否在方法声明中定义特定的数值范围?考虑到一个如下的函数:
def methode_range(value: int):
print(str(int))
你如何在方法参数输入字段中指定一个范围?
目前我的代码是:
def methode_range(value: int):
if (value > 0) & (value < 5):
print(str(int))
else:
raise Exception("输入值范围错误")
但现在我在思考:是否有更好的方法?就像你可以定义值的输入类型一样,你可以指定一个范围吗?
英文:
Can I define a specific value range in a methode declaration? given a function like:
def methode_range(value: int):
print(str(int))
how can I specify a range in the methode parameter input field?
currently my code would be:
def methode_range(value: int):
if (value > 0) & (value < 5):
print(str(int))
else:
raise Exception("Input value range")
but now I'm asking myself: is there a better way? Like the same way you can define the input type for the value, you can specify a range?
答案1
得分: 1
Strictly speaking, no. That said, you might want to use typing.Annotated
to simulate this sort of refinement type.
from typing import Annotated, get_type_hints, get_args
def foo(x: Annotated[int, range(1, 6)]):
x_hint = get_type_hints(foo, include_extras=True)['x']
rng = get_args(x_hint)[1]
if x not in rng:
raise ValueError("x out of range")
print(str(x))
Annotated
itself has no built-in semantics, so the arguments can be used for whatever you like. Keep in mind, though, that while you can attach any number of annotations to a type, finding the annotation that you want from among various other annotations added for other tools might be challenging. For example, you might have something like Annotated[x, foo, bar, baz]
. You might have to search through the list returned by get_args
to find the particular expression needed for any particular use-case.
英文:
Strictly speaking, no. That said, you might want to use typing.Annotated
to simulate this sort of refinement type.
from typing import Annotated, get_type_hints, get_args
def foo(x: Annotated[int, range(1, 6)]):
x_hint = get_type_hints(foo, include_extras=True)['x']
rng = get_args(x_hint)[1]
if x not in rng:
raise ValueError("x out of range")
print(str(x))
Annotated
itself has no built-in semantics, so the arguments can be used for whatever you like. Keep in mind, though, that while you can attach any number of annotations to a type, finding the annotation that you want from among various other annotations added for other tools might be challenging. For example, you might have something like Annotated[x, foo, bar, baz]
. You might have to search through the list returned by get_args
to find the particular expression needed for any particular use-case.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论