fj1*_*23x 19 python type-hinting python-3.x nonetype
def foo(
hello: str='world', bar: str=None,
another_string_or_None: str|????=None):
pass
Run Code Online (Sandbox Code Playgroud)
我试图在函数中设置Python中的类型提示,你可以添加多个类型提示something: str|bool='default value'
,但是,提示的类型是None
什么?:/
mbd*_*vpl 27
从你的例子:
def foo(
hello: str='world', bar: str=None,
another_string_or_None: str|????=None):
...
Run Code Online (Sandbox Code Playgroud)
我注意到你的用例是"某事或无".
从3.5版开始,Python通过typing
模块支持类型注释.在您的情况下,推荐的注释方法是使用typing.Optional[something]
提示.这有你正在寻找的确切含义.
因此提示another_string_or_None
将是:
import typing
def foo(
hello: str='world', bar: str=None,
another_string_or_None: typing.Optional[str]=None):
...
Run Code Online (Sandbox Code Playgroud)
只是None
!
>>> def nothing(nun: None) -> None:
... return nun
...
>>> nothing(None)
>>>
Run Code Online (Sandbox Code Playgroud)
或至少可以如此。
由于这些注释对Python而言,除了采用正确的语法/正确的语法外,没有其他意义,因此取决于工具。
例如,如果使用typecheck-decorator,则需要使用type(None)
:
>>> import typecheck as tc
>>>
>>> @tc.typecheck
>>> def nothing(nun: type(None)) -> type(None):
... return nun
...
>>> nothing(None)
>>> nothing(0)
typecheck.framework.InputParameterError: nothing() has got an incompatible value for nun: 0
>>> nothing(False)
typecheck.framework.InputParameterError: nothing() has got an incompatible value for nun: False
Run Code Online (Sandbox Code Playgroud)
Typecheck还使您可以更清楚地使用tc.any()
(OR),tc.all()
(AND)和“ AND ”添加更多的类型提示。
当心这tc.none()
是一个类似于NAND的谓词;而不是您要查找的内容-不带任何参数,它将接受等于或更apt的任何类型。tc.all()
tc.anything
由于@mbdevpl,我知道这个问题被认为得到了回答,但是,我想补充一点,这type(None)
就是您获得 None 类型实际值的方式,例如,这可能很有用if statement check
:
if isinstance(x_var, type(None)):
pass
Run Code Online (Sandbox Code Playgroud)
并且因为python3.5
,您还可以使用Union
无的一堆类型,如下所示:
x_var: typing.Union[str, None]
y_var: typing.Union[Dict, List, None]
Run Code Online (Sandbox Code Playgroud)
这相当于:
x_var: typing.Optional[str]
y_var: typing.Optional[typing.Union[Dict, List]]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7510 次 |
最近记录: |