Syntax not understood

2QdxY4RzWzUUiLuE at potatochowder.com 2QdxY4RzWzUUiLuE at potatochowder.com
Thu Nov 4 15:21:58 EDT 2021


On 2021-11-04 at 14:36:48 -0400,
David Lowry-Duda <david at lowryduda.com> wrote:

> > x_increment, y_increment = (scale * i for i in srcpages.xobj_box[2:])
> > 
> > (scale * i for i in srcpages.xobj_box[2:]) is a generator, a single
> > object, it should not be possible to unpack it into 2 variables.
> 
> If you know the exact number of values in the generator, you can do 
> this. Here is an oversimplified example.
> 
>   l = [0, 1, 2, 3, 4, 5]
>   a, b = (elem * 10 for elem in l[:4])
>   print(a, b) # prints 40 50
> 
> This is very fragile code and I would recommend against using it.

How is that any more fragile than any other operation that destructs (or
doesn't) a tuple?

Is the following fragile:

    quotient, remainder = divmod(numerator, denominator)

Would you surround it with try/except, or always unpack it defensively?

    result = divmod(numerator, denominator)
    if len(result) == 2:
        quotient, remainder = result
    else:
        raise SomeException("divmod didn't work")

If I know where a generator (or an iterator, or a tuple, or a list) came
from, and it's documented to contain/yield a known quantity of values,
then why is it fragile to depend on that?

On the other hand, yes, if I build code that depends on a lot of
unstated relationships between values of questionable (or unknown)
origin, then I am definitely asking for trouble.


More information about the Python-list mailing list