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


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

Re: decorator to fetch arguments from global objects

Started byandrea crotti <andrea.crotti.0@gmail.com>
First post2013-06-18 18:21 +0100
Last post2013-06-18 18:21 +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 andrea crotti <andrea.crotti.0@gmail.com> - 2013-06-18 18:21 +0100

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

Fromandrea crotti <andrea.crotti.0@gmail.com>
Date2013-06-18 18:21 +0100
SubjectRe: decorator to fetch arguments from global objects
Message-ID<mailman.3546.1371576102.3114.python-list@python.org>

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

2013/6/18 Terry Reedy <tjreedy@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..

[toc] | [standalone]


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


csiph-web