4 ms·
How about a decorator? from functools import wraps def defaults(**default_kwargs): # Decorator factory def decorator(func): # Decorator func
by IgorPartola 5y ago
How about a decorator?
from functools import wraps
def defaults(**default_kwargs): # Decorator factory
def decorator(func): # Decorator function
@wraps(func)
def wrapper(*args, **kwargs): # Actual wrapper
# Iterate over all default keyword arguments
for name in default_kwargs.keys():
# And if not specified in the passed in kwargs use the default
kwargs[name] = kwargs.get(name, default_kwargs[name]())
# Call the actual function
return func(*args, **kwargs)
return wrapper
return decorator
# Note that the default argument value should be a callable to avoid the pitfall with mutable arguments
@defaults(bar=lambda: [1, 2, 3])
def foo(bar):
print(bar)
foo()
- softwaredoug 5y agoYeah, exactly. I just hacked together a similar thing here :) https://gist.github.com/softwaredoug/bbfa2541d48c685908ebd6a6a78e6829 https://gist.github.com/softwaredoug/bbfa2541d48c685908ebd6a...
- zzzeek 5y agotyping tools won't know what the above decorator does, without some fancy PEP-612 annotations and I'm not sure pep612 can cover that level of automation. I think intent and all is clear for everyone just having the construction done in the method body for the (IMO, should be) seldom case this is needed
- IgorPartola 5y agoEh. I don't use typing tools for most things because (and I know this isn't a popular opinion even though I believe it's the correct one) they rarely save you from real world problems. They are mostly useful for auto-complete in your IDE, so you have to weigh the time you spend annotating your code to help your IDE auto-complete function signatures vs the time the auto-complete saves you. I think that if you use this as: def foo(bar: list): print(bar) that type checking will be happy.
- daanluttik 5y agoIf you use it in conjunction with mypy it definitely saves you from alot of real word issues. In addition, it is also an amazing way of documenting an important element of your code. And annotations van be used by modules (like pydantic) to get even more use. Improvement to anotations have been the biggest improvement in python since 3.6 imho.
- IgorPartola 5y agoWhat kind of bugs have you encountered in practice that were caught by mypy but not at runtime, manual, or automated testing? I am genuinely curious because in my experience the only time I have seen this is when you either transpose the order or arguments to a function (detected the first time you run it) or if you pass None when an actual value was necessary (detected the first time you run it).