Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #48624 > unrolled thread

Re: decorator to fetch arguments from global objects

Started byFábio Santos <fabiosantosart@gmail.com>
First post2013-06-18 13:59 +0100
Last post2013-06-18 13:59 +0100
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: decorator to fetch arguments from global objects Fábio Santos <fabiosantosart@gmail.com> - 2013-06-18 13:59 +0100

#48624 — Re: decorator to fetch arguments from global objects

FromFábio Santos <fabiosantosart@gmail.com>
Date2013-06-18 13:59 +0100
SubjectRe: decorator to fetch arguments from global objects
Message-ID<mailman.3529.1371560839.3114.python-list@python.org>

[Multipart message — attachments visible in raw view] — view raw

On Tue, Jun 18, 2013 at 10:47 AM, andrea crotti <andrea.crotti.0@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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web