Help with generators outside of loops.

Christopher J. Bottaro cjbottaro at alumni.cs.utexas.edu
Wed Dec 8 17:11:25 CET 2004


Steven Bethard wrote:
> I don't do much with SQL/databases stuff, but if you really know the
> result will be a single row, you can take advantage of tuple unpacking
> and do something like:
> 
> row, = obj.ExecSQLQuery(sql, args)
> 
> or
> 
> [row] = obj.ExecSQLQuery(sql, args)
> 
> This has the advantage that you'll get a ValueError if you happen to be
> wrong (and there are more or fewer values in the generator).
> 
>  >>> def g(n):
> ...     for i in range(n):
> ...         yield i
> ...
>  >>> x, = g(1)
>  >>> x
> 0
>  >>> x, = g(2)
> Traceback (most recent call last):
>    File "<interactive input>", line 1, in ?
> ValueError: too many values to unpack
>  >>> x, = g(0)
> Traceback (most recent call last):
>    File "<interactive input>", line 1, in ?
> ValueError: need more than 0 values to unpack
> 
> Steve

Wow, good advice.  One question, how is the generator class implemented so
that if assigned to a tuple/list, it knows what to do?  Is it possible to
overload the assignment operator kinda like in C++?

Thank you all who replied to the original post, it was very helpful.




More information about the Python-list mailing list