Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #48624
| References | <CAF_E5JYg39VdwmLFnyXNOMPRx1UD8ZNGiBRpqgU=A_9rU_ukpw@mail.gmail.com> |
|---|---|
| Date | 2013-06-18 13:59 +0100 |
| Subject | Re: decorator to fetch arguments from global objects |
| From | Fábio Santos <fabiosantosart@gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.3529.1371560839.3114.python-list@python.org> (permalink) |
[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
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: decorator to fetch arguments from global objects Fábio Santos <fabiosantosart@gmail.com> - 2013-06-18 13:59 +0100
csiph-web