如何将单个对象或集合转换为集合?

huangapple go评论50阅读模式
英文:

How to convert a single object or a set into a set?

问题

以下是翻译好的代码部分,不包括问题的回答:

有以下方法

```python
def send_message(
    content: str,
    slack_conn_ids: Union[SlackConnection, Set[SlackConnection]],
    send_only_in_production: bool = True,
):
   ...
   if isinstance(slack_conn_ids, set):
      set_slack_conn_ids = slack_conn_ids
   elif isinstance(slack_conn_ids, SlackConnection):
      set_slack_conn_ids = {slack_conn_ids}
   else:
      raise ValueError("`slack_conn_ids`应该是`SlackConnection`或`Set[SlackConnection]`类型"
        )
   ...
这段代码是否可以更简化,更符合惯用法?

<details>
<summary>英文:</summary>

There&#39;s a method as follows:

def send_message(
content: str,
slack_conn_ids: Union[SlackConnection, Set[SlackConnection]],
send_only_in_production: bool = True,
):
...
if isinstance(slack_conn_ids, set):
set_slack_conn_ids = slack_conn_ids
elif isinstance(slack_conn_ids, SlackConnection):
set_slack_conn_ids = {slack_conn_ids}
else:
raise ValueError("slack_conn_ids should be of type SlackConnection or Set[SlackConnection]"
)
...


Can this code be simplified, implemented more idiomatically?

</details>


# 答案1
**得分**: 2

可以使用模式匹配。

```py
匹配 slack_conn_ids:
    情况 set():
        set_slack_conn_ids = slack_conn_ids
    情况 SlackConnection():
        set_slack_conn_ids = { slack_conn_ids }
    情况 _:
        引发 ValueError("‘slack_conn_ids’ 应该是 ‘SlackConnection’ 或 ‘Set[SlackConnection]’ 类型")
英文:

You can use pattern matching.

match slack_conn_ids:
    case set():
        set_slack_conn_ids = slack_conn_ids
    case SlackConnection():
        set_slack_conn_ids = { slack_conn_ids }
    case _:
        raise ValueError(&quot;`slack_conn_ids` should be of type `SlackConnection` or `Set[SlackConnection]`&quot;)

答案2

得分: 2

不。让调用方负责提供一个集合,即使该集合只包含一个连接。

def send_message(
    content: str,
    slack_conn_ids: Set[SlackConnection],
    send_only_in_production: bool = True,
):
   
   ...


s = SlackConnection(...)
send_message("hi", {s})
英文:

Don't. Let the caller be responsible for providing a set, even if that set only contains one connection.

def send_message(
    content: str,
    slack_conn_ids: Set[SlackConnection],
    send_only_in_production: bool = True,
):
   
   ...


s = SlackConnection(...)
send_message(&quot;hi&quot;, {s})

答案3

得分: -2

你的代码已经非常简化,很难再有什么改进的余地。

以下是我设计的代码:

if isinstance(slack_conn_ids, SlackConnection) or isinstance(slack_conn_ids, set):
    try:
        slack_conn_ids = {slack_conn_ids}
    except TypeError:
        pass
else:
    raise ValueError("‘slack_conn_ids’ 应该是 ‘SlackConnection’ 或 ‘Set[SlackConnection]’ 类型")
英文:

Your code is already very simplified, it is impossible to come out with something worth the difference.

Here is how I would design that code:

if isinstance(slack_conn_ids, SlackConnection) or isinstance(slack_conn_ids, set):
    try:
        slack_conn_ids = {slack_conn_ids}
    except TypeError:
        pass
else:
    raise ValueError(&quot;`slack_conn_ids` should be of type `SlackConnection` or `Set[SlackConnection]`&quot;)

Explanation:

  1. Check in one-line if input is approved.
  2. Change variable slack_conn_ids to set if object. If already set, everything okay. No need to waste memory creating new variables and assigning more than needed.

huangapple
  • 本文由 发表于 2023年3月3日 20:20:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/75627001.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定