explosion / catalogue

Super lightweight function registries for your library

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

suggestion: dry registrations for us lazy registrars

rcox771 opened this issue · comments

Thanks for building this.

Would it be easy to allow the __name__ of the callable being passed in as the default, but allowing a name kwarg to overwrite it? I started going down a decorator rabbit-hole on stack overflow to try and pitch in a solution, but got lost in decorator hell.

Using loaders = catalogue.create("mypackage", "loaders") as our shared example, here's what things look like at the moment:

#passing the name in explicitly
@loaders.register(name='custom_func')
def custom_func(data):
    pass

vs.

#letting the func name itself
@loaders.register
def custom_func(data):
    pass

vs.

#a cool shorthand version
@loaders
def custom_func(data):
    pass

This was my attempt, but it doesn't accept passing in the name kwarg.

class Registry:
    callables = {}
    
    def __call__(self, func, name=None):
        if not name: name = func.__name__
        self.callables[name] = func 
    
    def __contains__(self, func):
        return func in self.callables
        
    def __repr__(self):
        return f"{self.callables}"
    
loaders = Registry()

#this works fine
@loaders
def custom_func(data):
    pass

#this not so much
@loaders(name='blah')
def custom_func(data):
    pass

What do you think?