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

前端 未结 9 1685
长发绾君心
长发绾君心 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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
    

提交回复
热议问题