argbind icon indicating copy to clipboard operation
argbind copied to clipboard

Improve subclass binding when __init__ is not defined.

Open DBraun opened this issue 1 year ago • 1 comments

I have a lot of subclasses of an abstract base class. The subclasses all use the the base's __init__, and so I don't explicitly write out the __init__ for each. However, this is causing an issue in argbind when I want to configure the kwargs in the init of each subclass differently. It ends up not configuring the kwargs at all and leaves them at their defaults.

Example of the current argbind:

import abc
from typing import Any, Dict

import argbind


class Base(abc.ABC):
  
    def __init__(self, config: Dict[str, Any] = None):
        self.config = config

    @abc.abstractmethod
    def action(self):
        """Do something"""


@argbind.bind()
class Sub1(Base):

    def action(self):
        print('hello', self.config)


@argbind.bind()
class Sub2(Base):

    def action(self):
        print('goodbye', self.config)


if __name__ == "__main__":

    argbind.parse_args() # add for help text, though it isn't used here.

    args = {
      'Sub1.config': {"a": "apple", "b": "banana"},
      'Sub2.config': {"c": "cherry", "d": "durian"},
    }

    with argbind.scope(args):
        Sub1().action() # prints "hello None"
        Sub2().action() # prints "goodbye None"

Notice that it didn't pass the requested config and instead left it as None.

With this PR, the last section is instead:

    with argbind.scope(args):
        Sub1().action() # prints "hello {'a': 'apple', 'b': 'banana'}"
        Sub2().action() # prints "goodbye {'c': 'cherry', 'd': 'durian'}"

I also updated examples/bind_existing/with_argbind.py to make more sense to me. It produces the same output as before, but I changed some code. I think it's confusing to put the superclass MyClass in the args/yaml. To me, it makes more sense to be able to put the subclass BoundClass.

DBraun avatar Jul 30 '24 01:07 DBraun

@pseeth @seethlord can you take a look?

DBraun avatar Dec 05 '24 17:12 DBraun