7 ms·
What about: def foo(Bar=Bar): bar = Bar() ... Pass in the class or any callable and then call it in the body to make an instance.
by peachy_no_pie 5y ago
What about:
def foo(Bar=Bar):
bar = Bar()
...
Pass in the class or any callable and then call it in the body to make an instance.
- dragonwriter 5y agoThe problem with that compared to late-bound parameters is that you have to pass it a callable for non-default uses as well. It's nice sometimes to have a deferred (callable-supplied) default but pass immediate values for non-default.
- ShamelessC 5y agoYeah, this is the correct answer and it works with functions or objects. This is commonly used to implement logging callbacks e.g. from collections.abc import Callable def log_fn(message: str = ''): print(f'This is your log: {message}') def run_read_file(file_to_read:str, log_handler: Callable=log_fn): contents = open(file_to_read).readlines() for line in contents: log_handler(message=line)