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

前端 未结 9 1689
长发绾君心
长发绾君心 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.

    0 讨论(0)
  • 2021-02-19 06:17

    Is it absolutely necessary that it returns tuples, or will any iterable do?

    import collections
    def iterate(keywords):
        if not isinstance(keywords, collections.Iterable):
            yield keywords
        else:
            for keyword in keywords:
                yield keyword
    
    
    for keyword in iterate(library.get_keywords()):
        print keyword
    
    0 讨论(0)
  • 2021-02-19 06:22

    Your tuple_maker doesn't do what you think it does. An equivalent definition of tuple maker to yours is

    def tuple_maker(input):
        return input
    

    What you're seeing is that tuple_maker("a string") returns a string, while tuple_maker(["str1","str2","str3"]) returns a list of strings; neither return a tuple!

    Tuples in Python are defined by the presence of commas, not brackets. Thus (1,2) is a tuple containing the values 1 and 2, while (1,) is a tuple containing the single value 1.

    To convert a value to a tuple, as others have pointed out, use tuple.

    >>> tuple([1])
    (1,)
    >>> tuple([1,2])
    (1,2)
    
    0 讨论(0)
提交回复
热议问题