On Tue, Jun 18, 2013 at 10:47 AM, andrea crotti <andrea.crott...@gmail.com> wrote: > def with_optional_db(func): > """Decorator that sets the database to the global current one if > not passed in or if passed in and None > """ > @wraps(func) > def _with_optional_db(*args, **kwargs): > func_args = func.func_code.co_varnames > db = None > # if it's defined in the first elements it needs to be > # assigned to *args, otherwise to kwargs > if 'db' in func_args: > assert 'db' == func_args[0], "Needs to be the first defined" > else: > db = kwargs.get('db', None) > > if db is None: > kwargs['db'] = get_current_db() > > assert kwargs['db'] is not None, "Can't have a not defined database" > ret = func(*args, **kwargs) > return ret > > return _with_optional_db >
If db is always the first argument, you could also use type (or hasattr) checking of the first argument, and push a db if it's not one. Or be specific about it and take a db or some kind of placeholder (such as an object, DEFAULT_DB, or the "default" string) Cheers -- Fábio Santos
-- http://mail.python.org/mailman/listinfo/python-list