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

前端 未结 9 1695
长发绾君心
长发绾君心 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:02

    for your first problem you could check if the return value is tuple using

    type(r) is tuple
    #alternative
    isinstance(r, tuple)
    # one-liner
    def as_tuple(r): return [ tuple([r]), r ][type(r) is tuple]
    

    the second thing i like to use tuple([1]). think it is a matter of taste. could probably also write a wrapper, for example def tuple1(s): return tuple([s])

提交回复
热议问题