What is the syntax rule for having trailing commas in tuple definitions?

前端 未结 10 1457
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 05:54

In the case of a single element tuple, the trailing comma is required.

a = (\'foo\',)

What about a tuple with multiple elements? It seems t

10条回答
  •  隐瞒了意图╮
    2020-11-22 06:24

    Another reason that this exists is that it makes code generation and __repr__ functions easier to write. For example, if you have some object that is built like obj(arg1, arg2, ..., argn), then you can just write obj.__repr__ as

    def __repr__(self):
        l = ['obj(']
        for arg in obj.args: # Suppose obj.args == (arg1, arg2, ..., argn)
            l.append(repr(arg))
            l.append(', ')
        l.append(')')
        return ''.join(l)
    

    If a trailing comma wasn't allowed, you would have to special case the last argument. In fact, you could write the above in one line using a list comprehension (I've written it out longer to make it easier to read). It wouldn't be so easy to do that if you had to special case the last term.

提交回复
热议问题