python - 有没有一种Python式的方法来处理可能是容器或字符串的参数?

标签 python

我经常同时遇到以下两个问题

  1. 我有一个带有参数的函数,该参数预计是字符串容器
  2. 我想通过向函数传递字符串容器或非单例列表的单个字符串来简化调用

我通常用类似下面的东西来处理这个问题,这对我来说似乎不是Pythonic(我不知道为什么)。有没有更Pythonic的方法来处理这种情况?这实际上是一个坏习惯吗?最合适的做法是要求像 my_func(['just_deal_with_it']) 这样的函数调用?

请注意,下面的函数 iterable_not_string 来自 sorin 对 another question 的回答。

from collections.abc import Iterable

def iterable_not_string(x):

    is_iter = isinstance(x, Iterable)
    is_not_str = (not isinstance(x, str))
    return (is_iter and is_not_str)

def my_func(list_or_string):

    if iterable_not_string(list_or_string):
        do_stuff(list_or_string)
    else:
        do_stuff([list_or_string])

最佳答案

我使用以下习惯用法,适用于任何灵活类型语言:

def my_func(arg):
    """arg can be a list, or a single string"""

    if isinstance(arg, str):
        arg = [ arg ]

    # the rest of the code can just treat `arg` as a list
    do_stuff_with_a_list(arg)

通过在开始时将参数规范化为列表,可以避免稍后的代码重复和类型检查......以及如果忘记检查就会出现随之而来的错误。

关于python - 有没有一种Python式的方法来处理可能是容器或字符串的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71149030/

相关文章:

javascript - 如何更改 Plone 中 'Print this' document_action 的 url 表达式以与 collective.documentviewer 一起使用?

python - 无效的十六进制值

python - NLTK MLE 模型澄清三元组及更多

python - 双击 PyQt4 QTableWidget 上的行将内容设置为 -1

python - 使用 Flask 通过 api_key POST 到 Elasticsearch 托管服务

python : Get Active Sheet in xlrd? 以及在 Python 中读取和验证 excel 文件的帮助

Python 和正则表达式

python - 如何从 tkinter 比例小部件显示中删除比例值?

python - 这是确保 python unicode "string"以 utf-8 编码的最佳方法吗?

python - 我如何将一个小部件添加到 FloatLayout 内 ScrollView 内的 StackLayout 中?