Bulk Adding Methods Pythonically

Steven D'Aprano steve at pearwood.info
Wed Jun 15 21:38:19 EDT 2016

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.)


More information about the Python-list mailing list