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)
7 Réponses
+ 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)!
+ 1
Thats just the syntax of how decorators were implemented in python. It's most commonly used with *args, **kwargs
+ 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
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
0
But why is num in wrap(num) being able to reference the argument in get_primes?
0
Would you mind explaining to me how those *args and **kwargs work? I went to the documentation, but I couldn't understand it.
0
Thanks, I think I get it now. Will mess around with code to make it sediment in my mind.