Bulk Adding Methods Pythonically
Lawrence D’Oliveiro
lawrencedo99 at gmail.com
Wed Jun 15 21:59:04 EDT 2016
On Thursday, June 16, 2016 at 5:37:14 AM UTC+12, Rob Gaddi wrote:
> I've got a whole lot of methods I want to add to my Channel class, all
> of which following nearly the same form. The below code works, but
> having to do the for loop outside of the main class definition feels
> kludgey.
No, that’s fine. Table-driven programming is a good technique, and I’ve done this sort of thing myself.
> for fnname, measparam in (
> ...
> def measmaker(p):
Since this function makes no direct reference to “fnname” or “measparam”, why not move the definition to before the loop so it gets executed just once?
> def inner(self, cursorarea=False):
> ...
> return inner
And there, ladies and gentlemen, you see the benefits of functions as first-class objects. :)
> setattr(Channel, fnname, measmaker(measparam))
I would follow the loop with a “del fnname, measparam, measmaker", just to avoid polluting your module namespace with leftover debris.
More information about the Python-list
mailing list