AnswerDotAI / AnswerDotAI/fastcore

Add default arguments to delegation

Open
#175 7 comments 0 reactions 0 assignees View on GitHub
waiting for response
Dominant language
Jupyter Notebook
Stars
1.1k
Forks
295
Avg merge
1d 6h
Merged PRs (30d)
7

Description

Scenario:
You have function a, e.g:
`def cnn(c_in, c_mid, c_out, act, bn=.., ..., blocks=CNNBlock): ...`
and you want to add a specification for it:
`def resnet(c_in, c_mid, c_out, act=relu, bn=..., ..., blocks=ResBlock): ... return cnn(...)`

Right now as far as I understand this is the implementation:
```
use_kwargs(blocks=ResBlock)
delegates(cnn)
def resnet(c_in, c_mid, c_out, act=relu, **kwargs):
if 'blocks' not in kwargs: kwargs['blocks'] = ResBlock
...
cnn(c_in, c_mid, c_out, act, **kwargs
```

So I'm thinking of doing this instead:
```
add_kwargs(act=relu, blocks=ResBlock)
delegates(cnn)
def resnet(c_in, c_mid, c_out, **kwargs):
...
return cnn(c_in, c_mid, c_out, **kwargs)
```

example of implementation:
```
def add_kwargs(**kwargs):
"Decorator: add argument with default value to `**kwargs` in both signature and function"
def _f(f):
@wraps(f)
def _inner(*args, **kw): return f(*args, **{**kwargs, **kw})
sig = inspect.signature(_inner)
sigd = dict(sig.parameters)
for k,v in kwargs.items():
if k in sigd.keys():
assert sigd[k].kind.name not in ['POSITIONAL_ONLY', 'VAR_KEYWORD', 'VAR_POSITIONAL'], \
f'cannot assign an existing variable ({k!r}) of type {sigd[k].kind.name}'
sigd[k] = sigd[k].replace(default=v, kind=inspect._ParameterKind.KEYWORD_ONLY)
else: sigd[k] = inspect.Parameter(k, inspect._ParameterKind.KEYWORD_ONLY, default=v)
params = [[p for p in sigd.values() if p.kind == t] for t in range(5)]
_inner.__signature__ = sig.replace(parameters=concat(*params))
return _inner
return _f
```

What do you think?

Contributor guide

Open the contributing guide

Research direction

Start by reading the existing `delegates` and `use_kwargs` implementations and the proposed `add_kwargs` decorator using `inspect.signature`. Check how delegated signatures and default values are currently represented, then determine whether the requested behavior can preserve explicit caller overrides and valid parameter ordering. Done means the delegation API supports these defaults with coverage for the described `cnn` and `resnet` scenario.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.