On May 2, 12:18 am, Kiuhnm <kiuhnm03.4t.yahoo.it> wrote: > "Most Pythonic" doesn't mean better, unfortunately.
Neither does "Kiuhnm prefers it". > For instance, assume that you want to write a function that accepts a > dictionary of callbacks: > func(some_args, callbacks) > > Pythonic way > ------------ > > def when_odd(n): > pass > > def when_prime(n): > pass > > def before_check(): > pass > > def after_check(): > pass > > func(some_args, {'when_odd' : when_odd, > 'when_prime' : when_prime, > 'before_check' : before_check, > 'after_check' : after_check}) I'm sorry, when would you _ever_ do this? Why are you naming the functions twice? If you're passing in a dynamic set of functions, you'd _never know the names_, so my guess is you'd be iterating across it. If you _do_ know the names, why aren't you accessing them directly from the surrounding scope? Why aren't you including them in the function signature? Presenting bad examples as the Pythonic approach is a bit of a straw man. > My way > ------ > > with func(some_args) << ':dict': > with when_odd as 'n': > pass > with when_prime as 'n': > pass > with before_check as '': > pass > with after_check as '': > pass I'm not sure what value your code blocks really provide. 1. You're effectively making "with when_odd as 'n'" mean "def when_odd(n)" 2. The 'with code_block_name as arguments' syntax is unintuitive, to say the least. Personally, I don't see what value it provides over something more explicit and standard: def func(x, before_check=None, after_check=None, when_odd=None, when_prime=None): pass with FOO(func, arg): def before_check(x): pass def after_check(x): pass def when_odd(x): pass def when_prime(x): pass I couldn't think of a name for the context manager...but I can't really think of a use for it either, so that seems fair. Actually, here's an even simpler example. In this case, the context manager doesn't have to interrogate the surrounding stack, but the function call itself is then explicit. class FOO(object): def __init__(self, fn): self.fn = fn def __enter__(self): return self.fn def __exit__(self, exc_type, exc_value, traceback): pass def func(x, before_check=None, after_check=None, when_odd=None, when_prime=None): pass with FOO(func) as f: def before_check(x): pass def after_check(x): pass def when_odd(x): pass def when_prime(x): pass f(1) But again _what do you gain from this_ other than an extra layer of unnecessary complexity. -- http://mail.python.org/mailman/listinfo/python-list