Bulk Adding Methods Pythonically

Rob Gaddi rgaddi at highlandtechnology.invalid
Wed Jun 15 13:37:03 EDT 2016

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.  Am I missing some cleaner answer?  I thought about just
checking for all of it in __getattr__, but that's hacky too and doesn't
docstring nicely. Python 3.4

class Channel:
    # Lots of stuff in here.

# Add functions for a zillion different single channel measurements to
# the Channel object.  Relative measurements are more complex, and need to be
# handled separately.
for fnname, measparam in (
    ('frequency', 'FREQ'), ('falltime', 'FTIM'), ('negduty', 'NDUT'),
    ('negwidth', 'NWID'), ('overshoot', 'OVER'), ('duty', 'PDUT'),
    ('period', 'PER'), ('preshoot', 'PRE'), ('width', 'PWID'),
    ('amplitude', 'VAMP'), ('mean', 'VAVG'), ('base', 'VBAS'),
    ('max', 'VMAX'), ('min', 'VMIN'), ('ptp', 'VPP'),
    ('rms', 'VRMS'), ('top', 'VTOP')):
    def measmaker(p):
        def inner(self, cursorarea=False):
            region = 'CREG' if cursorarea else 'SCR'
            return float(self.scope.query(':MEAS:AREA {reg};{meas}? {chan}'.format(
                reg = region, meas = p, chan = self.name
        inner.__name__ = fnname
        inner.__doc__ = "Channel {} measurement".format(fnname)
        return inner
    setattr(Channel, fnname, measmaker(measparam))

Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.

More information about the Python-list mailing list