Using generator expressions

Jonathan Gossage jgossage at gmail.com
Mon Sep 25 10:15:56 EDT 2023


I am having a problem using generator expressions to supply the arguments
for a class instance initialization. The following example shows the
problem:

class test1(object):
    def __init__(self, a, b):

>         self.name = a

        self.value = b
st = 'Programming Renaissance, Any'.split(', ')
y = test1(a for a in st)
print(f'Object values are: {y._a}, {y._b}')

I would expect to get the values from the list generated by splitting the
string passed in as arguments to the new instance of test1, but instead
I get the generator expression by itself as a generator object. The
generator
expression is treated like a passive object instead of being run. If I had
wanted to pass the generator expression itself, I would have expected to
have
to use parentheses around the generator expression. Any suggestions on how
to
get the generator expression to run?
If I change the definition of the input arguments to *args I can capture the
arguments within __init__ but it is verbose and ugly. Also, I could accept
the
arguments from a Sequence and extract the Sequence members into the class
values. I would prefer my solution if I could get it to work.
Note that I tried generator expressions both inside parentheses and not,
without success.

-- 
Jonathan Gossage


More information about the Python-list mailing list