seeking deeper (language theory) reason behind Python design choice
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Fri May 11 02:03:19 EDT 2018
On Thu, 10 May 2018 20:38:39 -0600, Ian Kelly wrote:
> Would you also contend that generator functions are wrong because they
> pretend to be normal functions?
You're going to need to be more specific. In what way are they not normal
functions? You call them like normal functions, providing arguments like
normal functions, and receiving a result just like normal functions.
If you call a function like iter(), you also get back an iterator, just
as you do when you call a generator. Is iter() not a normal function?
We also call classes, and callable instances, as if they were normal
functions. Is that also a problem?
I guess the answer depends on what we mean by "function":
- an instance of FunctionType
- a thing we call to get back a result
or possibly both, as context requires.
> def totally_not_a_generator(n):
> while True:
> if n % 2 == 0:
> n //= 2
> else:
> n = n * 3 + 1
> stealthily = n
> yield stealthily
> if n == 1:
> return n
I must admit, I'm a little perplexed. In what way is this totally not a
generator? (To be precise, a generator function.) The inspect module
thinks it is (and so do I):
py> inspect.isgeneratorfunction(totally_not_a_generator)
True
as well as a function:
py> inspect.isfunction(totally_not_a_generator)
True
It's not a *generator object*, but it returns one:
py> inspect.isgenerator(totally_not_a_generator)
False
py> inspect.isgenerator(totally_not_a_generator(99))
True
--
Steve
More information about the Python-list
mailing list