I have the following generator:
import random
import string
def random_string_generator(size = 10, chars = string.ascii_lowercase + string.digits):
return "".join(random.choice(chars) for _ in range(size))
When I use interactive mode to inspect the generator, I get the following:
In [30]: random_string_generator()
Out[30]: '6v0vhljxac'
However, I do not understand how it works.
From what I've found so far:
_
has no special meaning in the grammar of Python_
isn't in thechars
list
- The generator works like
(expression(x) for x in iterator)
I have tried to further decompose the code in interactive mode and this is what I've found:
In [38]: chars=string.ascii_lowercase + string.digits
In [39]: size=10
In [40]: (random.choice(chars) for _ in range(size))
Out[40]: <generator object <genexpr> at 0x10bc6b258>
In [41]: list( (random.choice(chars) for _ in range(size))
...: )
Out[41]: ['6', 'v', '3', 'd', 'm', 'c', 'h', '1', 'v', 'n']
So my question is how does the random.choice(chars)
portion of the generator communicate with the iterative part for _ in range(size)
when they have no apparent connection to each other?