Bulk Adding Methods Pythonically

Rob Gaddi rgaddi at highlandtechnology.invalid
Tue Jun 21 13:04:42 EDT 2016

Steven D'Aprano wrote:

> On Thu, 16 Jun 2016 04:39 am, Rob Gaddi wrote:
>>> class Channel:
>>> frequency = mkmeasure('frequency', 'FREQ')
>>> falltime = mkmeasure('falltime', 'FTIM')
>> Thought about it, but whenever I'm dropping 20-someodd of those there's
>> inevitably some place where I screw up the replication of the quoted
>> name and the bound name.
> So? You have unit tests, right? Add one more test that checks the names. You
> can even add that to your class definition code:
> NAMES = ('frequency', 'falltime')
> class Channel:
>     for name, thingy in zip(NAMES, THINGIES):
>         locals()[name] = mkmeasure(name, thingy)
> assert all(getattr(Channel, name).__name__ == name for name in NAMES)
> But at the point that you have 20+ almost identical methods, you should take
> that as a cold-smell. Why do you have so many almost identical methods?
> (That doesn't mean it is *necessarily* wrong, only that you have to think
> carefully about whether it is or not.)

The context is that I've got an oscilloscope here on my desk with a USB
cable around to my PC.  There are a slew of different measurements that
I can request it make of the waveform on a given channel (i.e. the cable
connected to the front-panel connector marked "2").  I send it ASCII
commands like ':MEAS:VAMP? CHAN1' and it sends me ASCII replies like
'1.033e-01'.  I'm trying to wrap an API around all this that allows me
to treat channels as Channels and ask questions like:
  0.1 < chan.amplitude() < 0.2

I could just implement all that as a lookup in __getattr__, I suppose. 
The efficiency hit would be invisible next to the time spent doing all
that I/O.  But it feels hacky compared to having inspectable methods
with docstrings, like the sort of thing that future me will want to take
past me behind the woodshed for.

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