[MERGE] forward port of branch 7.0 up to 65d92da
[odoo/odoo.git] / openerp / tools / func.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
6 #    Copyright (C) 2010 OpenERP s.a. (<http://openerp.com>).
7 #
8 #    This program is free software: you can redistribute it and/or modify
9 #    it under the terms of the GNU Affero General Public License as
10 #    published by the Free Software Foundation, either version 3 of the
11 #    License, or (at your option) any later version.
12 #
13 #    This program is distributed in the hope that it will be useful,
14 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
15 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 #    GNU Affero General Public License for more details.
17 #
18 #    You should have received a copy of the GNU Affero General Public License
19 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 #
21 ##############################################################################
22
23 __all__ = ['synchronized']
24
25 from functools import wraps
26 from inspect import getsourcefile
27
28 def synchronized(lock_attr='_lock'):
29     def decorator(func):
30         @wraps(func)
31         def wrapper(self, *args, **kwargs):
32             lock = getattr(self, lock_attr)
33             try:
34                 lock.acquire()
35                 return func(self, *args, **kwargs)
36             finally:
37                 lock.release()
38         return wrapper
39     return decorator
40
41 def frame_codeinfo(fframe, back=0):
42     """ Return a (filename, line) pair for a previous frame .
43         @return (filename, lineno) where lineno is either int or string==''
44     """
45     
46     try:
47         if not fframe:
48             return "<unknown>", ''
49         for i in range(back):
50             fframe = fframe.f_back
51         try:
52             fname = getsourcefile(fframe)
53         except TypeError:
54             fname = '<builtin>'
55         lineno = fframe.f_lineno or ''
56         return fname, lineno
57     except Exception:
58         return "<unknown>", ''
59
60 def compose(a, b):
61     """ Composes the callables ``a`` and ``b``. ``compose(a, b)(*args)`` is
62     equivalent to ``a(b(*args))``.
63
64     Can be used as a decorator by partially applying ``a``::
65
66          @partial(compose, a)
67          def b():
68             ...
69     """
70     @wraps(b)
71     def wrapper(*args, **kwargs):
72         return a(b(*args, **kwargs))
73     return wrapper
74
75 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: