没有Python 3类型提示?

新手上路,请多包涵
def foo(
        hello: str='world', bar: str=None,
        another_string_or_None: str|????=None):
    pass

我正在尝试在函数中的 Python 中设置类型提示,您可以使用 something: str|bool='default value' None 类型提示是什么? :/

原文由 fj123x 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 414
1 个回答

从你的例子:

 def foo(
        hello: str='world', bar: str=None,
        another_string_or_None: str|????=None):
    ...

我注意到您的用例是“某物或无”。

从 3.5 版开始,Python 通过 typing 模块 支持类型注释。在您的情况下,推荐的注释方式是使用 typing.Optional[something] hint 。这具有您正在寻找的确切含义。

因此 another_string_or_None 的提示是:

 import typing

def foo(
        hello: str='world', bar: str=None,
        another_string_or_None: typing.Optional[str]=None):
    ...

原文由 mbdevpl 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题