| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
from .. import param |
| 26 |
|
| 27 |
|
| 28 |
class Contexte(dict): |
| 29 |
"""Gestionnaire de contexte. |
| 30 |
|
| 31 |
Exemple d'usage: |
| 32 |
>>> from wxgeometrie.geolib.contexte import Contexte |
| 33 |
>>> # Contexte global |
| 34 |
>>> contexte = Contexte(exact = False, decimales = 7) |
| 35 |
>>> # Contexte local |
| 36 |
>>> with contexte(exact = True): |
| 37 |
... print contexte['exact'] |
| 38 |
True |
| 39 |
>>> print contexte['exact'] |
| 40 |
False |
| 41 |
""" |
| 42 |
|
| 43 |
__slots__ = '__local_dicts', '__no_direct_call', '__parent' |
| 44 |
|
| 45 |
def __init__(self, parent=None, **kw): |
| 46 |
dict.__init__(self, **kw) |
| 47 |
self.__local_dicts = [] |
| 48 |
self.__parent = parent |
| 49 |
nt |
| 50 |
self.__no_direct_call = True |
| 51 |
|
| 52 |
def __getitem__(self, key): |
| 53 |
) |
| 54 |
for dico in reversed(self.__local_dicts): |
| 55 |
if key in dico: |
| 56 |
return dico[key] |
| 57 |
if key in self: |
| 58 |
return dict.__getitem__(self, key) |
| 59 |
elif self.__parent is not None: |
| 60 |
return self.__parent[key] |
| 61 |
raise KeyError(key) |
| 62 |
|
| 63 |
def get(self, key, default=None): |
| 64 |
try: |
| 65 |
return self[key] |
| 66 |
except KeyError: |
| 67 |
return default |
| 68 |
|
| 69 |
def new(self): |
| 70 |
"""Crée un nouveau contexte-fils, qui hérite de celui-ci. |
| 71 |
|
| 72 |
Toutes les clés non trouvées du contexte-fils sont ensuite |
| 73 |
cherchées dans le contexte père.""" |
| 74 |
return self.__class__(parent=self) |
| 75 |
|
| 76 |
def __call__(self, **kw): |
| 77 |
"""Cette méthode ne doit *JAMAIS* être appelée en dehors d'un contexte 'with'. |
| 78 |
|
| 79 |
Exemple d'usage: |
| 80 |
>>> from wxgeometrie.geolib.contexte import Contexte |
| 81 |
>>> contexte = Contexte(exact = False, decimales = 7) |
| 82 |
>>> with contexte(exact = True): |
| 83 |
... print contexte['exact'] |
| 84 |
True |
| 85 |
""" |
| 86 |
|
| 87 |
self.__local_dicts.append(kw) |
| 88 |
nt |
| 89 |
s) |
| 90 |
assert self.__no_direct_call, "Utilisation precedente en dehors d'un contexte 'with'." |
| 91 |
self.__no_direct_call = False |
| 92 |
return self |
| 93 |
|
| 94 |
def __enter__(self): |
| 95 |
__() |
| 96 |
self.__no_direct_call = True |
| 97 |
|
| 98 |
def __exit__(self, type, value, traceback): |
| 99 |
|
| 100 |
self.__local_dicts.pop() |
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
|
| 105 |
contexte = Contexte(exact = True, |
| 106 |
decimales = param.decimales, |
| 107 |
unite_angle = param.unite_angle, |
| 108 |
tolerance = param.tolerance, |
| 109 |
afficher_messages = param.afficher_messages, |
| 110 |
graduation = param.graduation, |
| 111 |
separateur_decimal = param.separateur_decimal, |
| 112 |
) |