【问题标题】:Python type annotations style for functions with long arguments具有长参数的函数的 Python 类型注释样式
【发布时间】:2021-05-28 19:23:05
【问题描述】:

用长类型注解设置函数定义样式的规范(基于一些 PEP)方法是什么?

我能想到的一些替代方案:

  • 选项 1:
def my_long_function_name_super_important(
   first_long_argument_to_my_function: Union[int, str],
   second: Dict[int, str],
   third_arg: int = 0 ) -> (bool, int):
   
   return (True, 1)
  • 选项 2:
def my_long_function_name_super_important(
   first_long_argument_to_my_function: Union[int, str],
   second: Dict[int, str],
   third_arg: int = 0
) -> (bool, int):
   
   return (True, 1)
  • 选项 3:
def my_long_function_name_super_important(
   first_long_argument_to_my_function: Union[int, str],
   second: Dict[int, str],  third_arg: int = 0
) -> (bool, int):
   
   return (True, 1)
  • 选项 4:
def my_long_function_name_super_important(
   first_long_argument_to_my_function: Union[int, str],
   second: Dict[int, str],
   third_arg: int = 0,
   ) -> (bool, int):
   
   return (True, 1)

注意:以 Python 3.8+ 为目标以获得最新答案。

【问题讨论】:

  • 没有。 black 格式化程序似乎已经得到了认真的采用,但它仍然不是官方的,因此是“意见”。
  • 你能把它变成一个答案吗?也许显示black 推荐的格式?
  • 为什么要投反对票?至少发表评论:(我仍然认为这是一个完全有效的问题。否则,请评论它的缺陷
  • 要求编码风格可能是固执己见。不应要求基于批准的 PEP 的 canon 编码风格。

标签: python python-3.x python-3.8 type-hinting pep


【解决方案1】:

正如@MisterMiyagi 所暗示的,对于函数中的这些类型注释,没有基于 PEP 的官方编码风格

话虽如此,在尝试了一些不同的选项之后,我意识到选项 2 和 3 在一些 python 代码格式化程序中会产生一些小问题(例如:jupyter notebook 中函数中的代码折叠),因为缺少缩进关闭)。因此,为了寻求最高的可读性,我最终使用了类似于选项 2 的东西,但在函数定义的最后一行有一个小缩进(更容易发现),并且每行有一个参数(更容易阅读):

def my_long_function_name_super_important(
   first_long_argument_to_my_function: Union[int, str],
   second: Dict[int, str],
   third_arg: int = 0
  ) -> (bool, int):
   
   return (True, 1)

仅供参考,@MisterMiyagi 的 black 格式化程序似乎正是选项 2(可以试用 here

【讨论】:

猜你喜欢
  • 2020-01-28
  • 1970-01-01
  • 2023-03-09
  • 1970-01-01
  • 2018-05-26
  • 2020-09-01
  • 1970-01-01
  • 2022-06-16
  • 1970-01-01
相关资源
最近更新 更多