Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: Defer Default with attr.DEFERRED object? #366

Open
peteroconnor-bc opened this issue Mar 19, 2020 · 0 comments
Open

Feature: Defer Default with attr.DEFERRED object? #366

peteroconnor-bc opened this issue Mar 19, 2020 · 0 comments

Comments

@peteroconnor-bc
Copy link

peteroconnor-bc commented Mar 19, 2020

I often, when writing demos, find myself doing something like this:

@attrs
class MyController:
    controller_param_1 = attrib(default=0.4)
    controller_param_2 = attrib(default=7)
    def update(self, x):
        ...
        return motor

def run_demo(dataset_name, n_samples = 100, controller_param_1=0.4, controller_param_2=7):
    controller = MyController(controller_param_1=controller_param_1, controller_param_2=controller_param_2)
    for x in get_data(dataset_name, n_samples): 
        print(controller.update(x))

Yes, I know I could just pass in MyController to run_demo(...) instead of the params - and that (dependency injection) is the right way to do things when designing scalable library code, but it's often easier to just pass in the args directly - run_demo(...) is easier to understand when you don't have to think about how to construct the arguments.

The trouble is that now we've defined defaults controller_param_1=0.4, controller_param_2=7 in multiple places, which violates "Don't Repeat Yourself" and can very easily lead to bugs.

Yes, I know I could just replace controller_param_1=0.4, controller_param_2=7 with **params, but that just obfuscates the interface of run_demo(...) which is exactly what we were trying to avoid in the first place.

My proposal is to just have an attr.DEFERRED object which, when passed as a constructor argument of an attr object, just looks up the default. i.e. change run_demo to:

def run_demo(dataset_name, n_samples = 100, controller_param_1=attr.DEFERRED, controller_param_2=attr.DEFERRED):
    controller = MyController(controller_param_1=controller_param_1, controller_param_2=controller_param_2)
    for x in get_data(dataset_name, n_samples): 
        print(controller.update(x))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant