Controlling a generator the pythonic way

Thomas Lotze thomas at thomas-lotze.de
Sat Jun 11 19:48:41 EDT 2005


Mike Meyer wrote:

> Yes, such a switch gets the desired behavior as a side effect. Then again,
> a generator that returns tokens has a desired behavior (advancing to the
> next token) as a side effect(*).

That's certainly true.

> If you think about these things as the
> state of the object, rather than "side effects", it won't seem nearly as
> ugly. In fact, part of the point of using a class is to encapsulate the
> state required for some activity in one place.
> 
> Wanting to do everything via parameters to methods is a very top-down way
> of looking at the problem. It's not necessarily correct in an OO
> environment.

What worries me about the approach of changing state before making a
next() call instead of doing it at the same time by passing a parameter is
that the state change is meant to affect only a single call. The picture
might fit better (IMO) if it didn't look so much like working around the
fact that the next() call can't take parameters for some technical reason.

I agree that decoupling state changes and next() calls would be perfectly
beautiful if they were decoupled in the problem one wants to model. They
aren't.

> *) It's noticable that some OO languages/libraries avoid this side
> effect: the read method updates an attribute, so you do the read then
> get the object read from the attribute. That's very OO, but not very
> pythonic.

Just out of curiosity: What makes you state that that behaviour isn't
pythonic? Is it because Python happens to do it differently, because of a
gut feeling, or because of some design principle behind Python I fail to
see right now?

-- 
Thomas



More information about the Python-list mailing list