2 # Copyright (C) 2007-2013 EDF R&D
4 # This library is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU Lesser General Public
6 # License as published by the Free Software Foundation; either
7 # version 2.1 of the License.
9 # This library is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 # Lesser General Public License for more details.
14 # You should have received a copy of the GNU Lesser General Public
15 # License along with this library; if not, write to the Free Software
16 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
22 Ce module contient des fonctions utilitaires
29 from N_Exception import AsException
30 from N_types import is_int, is_float, is_complex, is_str, is_sequence, is_assd
31 from strfunc import get_encoding
36 # Si la version de Python possède la fonction _getframe
38 cur_frame = sys._getframe
41 def cur_frame(offset=0):
42 """ Retourne la frame d execution effective eventuellement en remontant
43 de offset niveaux dans la pile d execution
44 Si il y a moins de offset niveaux retourne None
49 frame = sys.exc_info()[2].tb_frame.f_back
58 def callee_where(niveau=4):
60 recupere la position de l appel
62 frame = cur_frame(niveau)
64 return 0, "inconnu", 0, {}
66 # Python 2.7 compile function does not accept unicode filename, so we encode it
67 # with the current locale encoding in order to have a correct traceback.
68 # Here, we convert it back to unicode.
69 filename = unicode(frame.f_code.co_filename, get_encoding())
70 return frame.f_lineno, filename, frame.f_code.co_firstlineno, frame.f_locals
72 return 0, "inconnu", 0, {}
77 Retourne le type d'un concept (a) à partir
78 des caractéristiques de l'objet Python
92 raise AsException("type inconnu: %r %s" % (a, type(a)))
96 print "*" * (len(s) + 10)
97 print "*" * 5 + s + "*" * 5
98 print "*" * (len(s) + 10)
101 def repr_float(valeur):
103 Cette fonction représente le réel valeur comme une chaine de caractères
104 sous forme mantisse exposant si nécessaire cad si le nombre contient plus de
106 NB : valeur est un réel au format Python ou une chaine de caractères représentant un réel
108 if type(valeur) == str:
109 valeur = eval(valeur)
113 if abs(valeur) < 10000.:
116 if abs(valeur) > 0.01:
119 if t.find('e') != -1 or t.find('E') != -1:
120 # le réel est déjà sous forme mantisse exposant !
121 # --> on remplace e par E
122 t = t.replace('e', 'E')
123 # --> on doit encore vérifier que la mantisse contient bien un '.'
124 if t.find('.') != -1:
127 # -->il faut rajouter le point avant le E
128 t = t.replace('E', '.E')
136 if t[0].atof() == 0.:
137 # réel plus petit que 1
141 while t[0].atof() == 0.:
148 # réel plus grand que 1
150 if t[1:].atof() == 0.:
164 if r + 1 == len(t) or t[r + 1:].atof() == 0.:
166 s = s + 'E' + neg * '-' + repr(cpt)
170 def import_object(uri):
171 """Load and return a python object (class, function...).
172 Its `uri` looks like "mainpkg.subpkg.module.object", this means
173 that "mainpkg.subpkg.module" is imported and "object" is
174 the object to return.
176 path = uri.split('.')
177 modname = '.'.join(path[:-1])
178 if len(modname) == 0:
179 raise ImportError(u"invalid uri: %s" % uri)
184 mod = sys.modules[modname]
185 except ImportError, err:
187 u"can not import module : %s (%s)" % (modname, str(err)))
189 object = getattr(mod, objname)
190 except AttributeError, err:
191 raise AttributeError(u"object (%s) not found in module '%s'. "
192 "Module content is: %s" % (objname, modname, tuple(dir(mod))))
196 class Singleton(object):
198 """Singleton implementation in python."""
199 # add _singleton_id attribute to the class to be independant of import
203 def __new__(cls, *args, **kargs):
204 cls_id = getattr(cls, '_singleton_id', cls)
205 if Singleton.__inst.get(cls_id) is None:
206 Singleton.__inst[cls_id] = object.__new__(cls)
207 return Singleton.__inst[cls_id]
213 This class emulates a C-like enum for python. It is initialized with a list
214 of strings to be used as the enum symbolic keys. The enum values are automatically
215 generated as sequencing integer starting at 0.
218 def __init__(self, *keys):
221 for inum, key in enumerate(keys):
222 setattr(self, key, 2 ** inum)
223 self._dict_keys[2 ** inum] = key
225 def exists(self, value):
226 """Tell if value is in the enumeration"""
227 return self.get_id(value) is not None
229 def get_id(self, value):
230 """Return the key associated to the given value"""
231 return self._dict_keys.get(value, None)