Do python's variable length arguments (*args) expand a generator at function call time?

后端 未结 3 1257
别那么骄傲
别那么骄傲 2020-12-11 03:50

Consider the following Python code:

def f(*args):
    for a in args:
        pass

foo = [\'foo\', \'bar\', \'baz\']

# Python generator expressions FTW
gen          


        
相关标签:
3条回答
  • 2020-12-11 04:17

    Why not look and see what gen is in f()? Add print args as the first line. If it's still a generator object, it'll tell you. I would expect the argument unpacking to turn it into a tuple.

    0 讨论(0)
  • 2020-12-11 04:24

    Your don't really need

    gen = (f for f in foo)
    

    Calling

    f(*foo)
    

    will output

    ('foo', 'bar', 'baz')
    
    0 讨论(0)
  • 2020-12-11 04:34

    The generator is expanded at the time of the function call, as you can easily check:

    def f(*args):
        print(args)
    foo = ['foo', 'bar', 'baz']
    gen = (f for f in foo)
    f(*gen)
    

    will print

    ('foo', 'bar', 'baz')
    
    0 讨论(0)
提交回复
热议问题