Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #48692
| From | Wolfgang Maier <wolfgang.maier@biologie.uni-freiburg.de> |
|---|---|
| Subject | Re: decorator to fetch arguments from global objects |
| Date | 2013-06-19 07:39 +0000 |
| References | <CAF_E5JYg39VdwmLFnyXNOMPRx1UD8ZNGiBRpqgU=A_9rU_ukpw@mail.gmail.com> <kppv2q$shk$1@ger.gmane.org> <CAF_E5JZ3afve8WxOS_vmL_i9vC863uVYc723fV4NPAS=xod7vQ@mail.gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.3571.1371627599.3114.python-list@python.org> (permalink) |
andrea crotti <andrea.crotti.0 <at> gmail.com> writes:
>
> 2013/6/18 Terry Reedy <tjreedy <at> udel.edu>
> On 6/18/2013 5:47 AM, andrea crotti wrote:
> Using a CouchDB server we have a different database object potentially
> for every request.
> We already set that db in the request object to make it easy to pass it
> around form our django app, however it would be nice if I could set it
> once in the API and automatically fetch it from there.
> Basically I have something like
> class Entity:
> def save_doc(db)
>
> If save_doc does not use an instance of Entity (self) or Entity itself
(cls), it need not be put in the class.
>
> I missed a self it's a method actually..
> ...
> I would like basically to decorate this function in such a way that:
> - if I pass a db object use it
> - if I don't pass it in try to fetch it from a global object
> - if both don't exist raise an exception
>
> Decorators are only worthwhile if used repeatedly. What you specified can
easily be written, for instance, as
> def save_doc(db=None):
> if db is None:
> db = fetch_from_global()
> if isinstance(db, dbclass):
> save_it()
> else:
> raise ValueError('need dbobject')
>
>
> Yes that's exactly why I want a decorator, to avoid all this boilerplate
for every function method that uses a db object..
>
The standard way of avoiding boilerplate like this is not to use a
decorator, but a regular function/method that you call from within your
code. Just encapsulate Terry's code into a module-level function (or a
static class method):
def guarantee_dbobject(db):
if db is None:
db = fetch_from_global()
elif not isinstance(db, dbclass):
raise TypeError('need dbobject')
return db
Then use it as a simple one-liner like this:
def save_doc(self, db=None):
db = guarantee_dbobject(db)
...
It's as much effort to use this as decorating the method, but I think it's
clearer and it avoids the potential problems that a decorator causes with
introspection (which might not be a problem now, but could turn into one at
some point).
Wolfgang
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: decorator to fetch arguments from global objects Wolfgang Maier <wolfgang.maier@biologie.uni-freiburg.de> - 2013-06-19 07:39 +0000
csiph-web