Generator - Provide parameters to url - requests
Peter Otten
__peter__ at web.de
Wed Jul 5 06:13:53 EDT 2017
Sayth Renshaw wrote:
> Thanks.
>
> I left "base" out as i was trying to remove as much uneeded code from
> example as possible. I had defined it as
>
> base = datetime.datetime(2017,1,1)
You actually did provide that line in your post.
> Reading your code this sounds to simple :-).
>
> def dates(first, numdays):
> # generate datetime objects for extra clarity
> # note there are no implicit arguments like `base` in your code
> for _ in range(numdays):
> yield first
> first += ONE_DAY
>
> Thanks
You could write the above generator
ONE_DAY = datetime.timedelta(days=1)
base = datetime.datetime(2017, 1, 1)
def dates(numdays):
date = base
for _ in range(numdays):
yield date
date += ONE_DAY
but this is bad design.
You get the most predictable output when you write functions in such a way
that the result only depends on the function's arguments. Such functions are
called "pure", and are much easier to reason about and to cover with unit
tests.
As Python does not provide constants this is sometimes a judgment call:
While ONE_DAY will never be changed base is likely to be changed to
base = datetime.datetime(2018, 1, 1)
next year. Therefore it should be an argument. If you were to change the
generator to support varying intervals the signature should be changed, too,
to
def dates(first, numdays, daystep=1):
# ...
or similar.
More information about the Python-list
mailing list