What's the best practice for handling single-value tuples in Python?

前端 未结 9 1720
长发绾君心
长发绾君心 2021-02-19 05:44

I am using a 3rd party library function which reads a set of keywords from a file, and is supposed to return a tuple of values. It does this correctly as long as there are at le

9条回答
  •  天涯浪人
    2021-02-19 06:16

    For your first problem, I'm not really sure if this is the best answer, but I think you need to check yourself whether the returned value is a string or tuple and act accordingly.

    As for your second problem, any variable can be turned into a single valued tuple by placing a , next to it:

    >>> x='abc'
    >>> x
    'abc'
    >>> tpl=x,
    >>> tpl
    ('abc',)
    

    Putting these two ideas together:

    >>> def make_tuple(k):
    ...     if isinstance(k,tuple):
    ...             return k
    ...     else:
    ...             return k,
    ... 
    >>> make_tuple('xyz')
    ('xyz',)
    >>> make_tuple(('abc','xyz'))
    ('abc', 'xyz')
    

    Note: IMHO it is generally a bad idea to use isinstance, or any other form of logic that needs to check the type of an object at runtime. But for this problem I don't see any way around it.

提交回复
热议问题