The Perils of PyContract (and Generators)
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Wed Aug 5 03:23:29 EDT 2009
On Wed, 5 Aug 2009 03:06 pm Nick Daly wrote:
> The problem actually lies in the contract. Generally, the PyContract
> shouldn't affect the return values or in any way modify the code, which
> it doesn't, as long as the function returns a list values (the way the
> code had in fact originally been written). However, the contract
> mentioned above is actually quite wrong for a generator.
Yes, because you are conflating the items yielded from the generator with
the generator object returned from the generator function "find_files". You
can't look inside the generator object without using up whichever items you
look at.
[...]
> Correcting the above example involves doing nothing more than
> simplifying the contract:
>
> post:
> name in __return__
That can't be right, not unless PyContract is doing something I don't
expect. I expect that would be equivalent of:
'fish' in <generator object>
which should fail:
>>> __return__ = find_files('fish') # a generator object
>>> 'fish' in __return__
False
>>>
>>> __return__ = find_files('fish')
>>> __return__ = list(__return__)
>>> 'fish' in __return__
False
>>> __return__
['one fish', 'two fish', 'red fish', 'blue fish']
Of course, I may be mistaking what PyContract is doing.
--
Steven
More information about the Python-list
mailing list