frange() question
Stargaming
stargaming at gmail.com
Thu Sep 20 09:25:41 EDT 2007
On Thu, 20 Sep 2007 09:08:17 -0400, George Trojan wrote:
> A while ago I found somewhere the following implementation of frange():
>
> def frange(limit1, limit2 = None, increment = 1.):
> """
> Range function that accepts floats (and integers). Usage:
> frange(-2, 2, 0.1)
> frange(10)
> frange(10, increment = 0.5)
> The returned value is an iterator. Use list(frange) for a list.
> """
> if limit2 is None:
> limit2, limit1 = limit1, 0.
> else:
> limit1 = float(limit1)
> count = int(math.ceil(limit2 - limit1)/increment) return (limit1 +
> n*increment for n in range(count))
>
> I am puzzled by the parentheses in the last line. Somehow they make
> frange to be a generator:
> >> print type(frange(1.0, increment=0.5))
> <type 'generator'>
> But I always thought that generators need a keyword "yield". What is
> going on here?
>
> George
Consider the following:
def foo():
yield 1
def bar():
return foo()
Still, ``type(bar())`` would be a generator.
I don't want to tell you anything wrong because I don't know how
generators are implemented on the C level but it's more like changing
foo's (or frange's, in your example) return value.
HTH,
Stargaming
More information about the Python-list
mailing list