0

Can someone please help me understand how iterations inside decorators work on the Python code below?

def decor(func): def wrap(num): [print(i) for i in func(num)] return wrap def is_prime(num): for i in range(2,num): if num % i == 0: return False return True @decor def get_primes(num): for i in range(num): if is_prime(i): yield i primes_up_to = int(input("You want primes up to what number? \n")) get_primes(primes_up_to)

10th Jul 2020, 9:57 PM
Falnésio Borges
Falnésio Borges - avatar
7 Respuestas
+ 1
DECORATION FUNCTIONS REPLACE THE ORIGINAL FUNCTION So if I return wrap and wrap is defined as having an argument, then get_primes(num) is just wrap(num)!
11th Jul 2020, 9:15 PM
Falnésio Borges
Falnésio Borges - avatar
+ 1
Thats just the syntax of how decorators were implemented in python. It's most commonly used with *args, **kwargs
11th Jul 2020, 2:36 AM
JME
+ 1
https://code.sololearn.com/cUhg2T9316g0/?ref=app *args is a way to pass any amount of arguments **kwargs is a way to pass any amount of key word arguments The words aren't important the asterisks are the signifiers
11th Jul 2020, 2:59 AM
JME
0
This looks like it's more about generators than decorator functions. decor runs wrap(num) Wrap runs get_primes(num) generator. Get_primes runs is_prime which yields a number if true Yielding a number causes wrap to print it
11th Jul 2020, 1:59 AM
JME
0
But why is num in wrap(num) being able to reference the argument in get_primes?
11th Jul 2020, 2:27 AM
Falnésio Borges
Falnésio Borges - avatar
0
Would you mind explaining to me how those *args and **kwargs work? I went to the documentation, but I couldn't understand it.
11th Jul 2020, 2:39 AM
Falnésio Borges
Falnésio Borges - avatar
0
Thanks, I think I get it now. Will mess around with code to make it sediment in my mind.
11th Jul 2020, 3:06 AM
Falnésio Borges
Falnésio Borges - avatar