MrJoe
MrJoe

Reputation: 445

Print items in *args

I am implementing decorators and am trying to get the output

Please can someone explain why the .format(i for i in args) doesn't iterate through John and Tom but instead prints the location of the variables args

def doDouble (func):
    def wrapper_doDouble (*args):
        func(*args)
        func(*args)
    return wrapper_doDouble

@doDouble
def functionToPrint(*args):
    print ("Hi {}".format(i for i in args))

functionToPrint("John", "Tom")

This is my current output:

Hi <generator object functionToPrint.<locals>.<genexpr> at 0x03CEFD80>
Hi <generator object functionToPrint.<locals>.<genexpr> at 0x03CDA1B0>

Upvotes: 0

Views: 100

Answers (2)

tarkmeper
tarkmeper

Reputation: 767

Your inline for loop is in slightly the wrong place. You want to call Hi format repeatedly, not pass a list into Hi. Since that will generate multiple values you need to join them back together.

def doDouble (func):
    def wrapper_doDouble (*args):
        func(*args)
        func(*args)
    return wrapper_doDouble

@doDouble
def functionToPrint(*args):
    print ("\n".join("Hi {}".format(i) for i in args))

functionToPrint("John", "Tom")

Upvotes: 3

blue note
blue note

Reputation: 29099

The problem is not in the decorator. It is in the format.

 "hi {}".format("john", "tom")

will only print "john", since you only use the first argument in your formatted string. Replace it with eg

print ("\n".join(len(args) *["Hi {}"])).format(*args))

Upvotes: 5

Related Questions