defining classes within loops?

Tim Peters tim.one at home.com
Fri Jul 27 18:18:32 EDT 2001


[Roy Smith]
> Just out of curiosity, how many people have ever written a function or
> class definition nested inside a loop?  Seems like sort of a
> strange thing  to do, although I suppose it might be useful in some
> situations.

Never a class, but sometimes a function.  This can be (marginally!) handy
when abusing the default-argument mechanism to build a family of functions
that differ in some regular way.

For a non-trivial example (it's simply fresh on my mind), the 2.2
test_generators.py contains a generator-based N-Queens solver, which uses a
different column-number generator for each row of the board.  The column
generators are created in a loop, using the default-argument trick to give
each row's column-number generator its own pre-initialized local list
containing info about the diagonals reachable from each square in that row.

So that's the problem:  examples are either too complex to explain both
clearly and briefly, or so trivial that if I included one here I'd be
subject to another rash of "but that's so useless only an academic
propeller-head could think it was valuable!" rants <0.9 wink>.

not-a-*common*-practice-regardless-ly y'rs  - tim





More information about the Python-list mailing list