decorator to fetch arguments from global objects

Fábio Santos fabiosantosart at gmail.com
Tue Jun 18 08:59:58 EDT 2013


On Tue, Jun 18, 2013 at 10:47 AM, andrea crotti <andrea.crotti.0 at 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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20130618/e677fae0/attachment.html>


More information about the Python-list mailing list