Is there are good DRY fix for this painful design pattern?

Ian Kelly ian.g.kelly at gmail.com
Mon Feb 26 13:31:18 EST 2018


On Mon, Feb 26, 2018 at 8:06 AM, Chris Angelico <rosuav at gmail.com> wrote:
> On Tue, Feb 27, 2018 at 1:41 AM, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
>> I have a class with a large number of parameters (about ten) assigned in
>> `__init__`. The class then has a number of methods which accept
>> *optional* arguments with the same names as the constructor/initialiser
>> parameters. If those arguments are None, the defaults are taken from the
>> instance attributes.
>
> I have a very similar problem in a project of mine, and it's currently
> an unsolved problem. My current best theory is to basically just
> accept **kwargs for everything (so there's no None defaults), and then
> use chain_map for all lookups. Seems inefficient, but at least it'd be
> functional. Haven't implemented it though.
>
> If you get any better ideas, I'll be reading them too.

I would be tempted to take this and then formalize it into a Context
class that would be passed to the various methods and initializers
rather than passing all the sundry arguments directly. Similar to what
the decimal class uses although perhaps without the idea of a global
context (which just leads to trouble down the road).



More information about the Python-list mailing list