检测序列参数的正确方法? [英] Correct way to detect sequence parameter?

查看:39
本文介绍了检测序列参数的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个函数,该函数接受一个可以是序列或单个值的参数.值的类型是 str、int 等,但我希望将其限制为硬编码列表.换句话说,我想知道参数 X 是序列还是我必须转换为序列以避免以后出现特殊情况的东西.我可以做

I want to write a function that accepts a parameter which can be either a sequence or a single value. The type of value is str, int, etc., but I don't want it to be restricted to a hardcoded list. In other words, I want to know if the parameter X is a sequence or something I have to convert to a sequence to avoid special-casing later. I could do

type(X) in (list, tuple)

但可能还有其他我不知道的序列类型,并且没有通用的基类.

but there may be other sequence types I'm not aware of, and no common base class.

-N.

编辑:请参阅下面的答案",了解为什么大多数这些答案对我没有帮助.也许你有更好的建议.

Edit: See my "answer" below for why most of these answers don't help me. Maybe you have something better to suggest.

推荐答案

以上所有问题提到的方法是 str 是被认为是一个序列(它是可迭代的,有 getitem 等)但它是通常被视为单个项目.

The problem with all of the above mentioned ways is that str is considered a sequence (it's iterable, has getitem, etc.) yet it's usually treated as a single item.

例如,一个函数可以接受一个可以是文件名的参数或文件名列表.是什么函数的最 Pythonic 方式从后者中检测第一个?

For example, a function may accept an argument that can either be a filename or a list of filenames. What's the most Pythonic way for the function to detect the first from the latter?

根据修改后的问题,听起来您想要的更像是:

Based on the revised question, it sounds like what you want is something more like:

def to_sequence(arg):
    ''' 
    determine whether an arg should be treated as a "unit" or a "sequence"
    if it's a unit, return a 1-tuple with the arg
    '''
    def _multiple(x):  
        return hasattr(x,"__iter__")
    if _multiple(arg):  
        return arg
    else:
        return (arg,)

>>> to_sequence("a string")
('a string',)
>>> to_sequence( (1,2,3) )
(1, 2, 3)
>>> to_sequence( xrange(5) )
xrange(5)

这不能保证处理所有类型,但它可以很好地处理您提到的情况,并且应该对大多数内置类型做正确的事情.

This isn't guaranteed to handle all types, but it handles the cases you mention quite well, and should do the right thing for most of the built-in types.

在使用它时,确保接收到它的输出的任何东西都可以处理迭代.

When using it, make sure whatever receives the output of this can handle iterables.

这篇关于检测序列参数的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆