我经常同时遇到以下两个问题
- 我有一个带有参数的函数,该参数预计是字符串容器
- 我想通过向函数传递字符串容器或非单例列表的单个字符串来简化调用
我通常用类似下面的东西来处理这个问题,这对我来说似乎不是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/