Package orm2 :: Package util
[hide private]
[frames] | no frames]

Source Code for Package orm2.util

  1  #!/usr/bin/env python 
  2  # -*- coding: iso-8859-1 -*- 
  3   
  4  ##  This file is part of orm, The Object Relational Membrane Version 2. 
  5  ## 
  6  ##  Copyright 2002-2006 by Diedrich Vorberg <diedrich@tux4web.de> 
  7  ## 
  8  ##  All Rights Reserved 
  9  ## 
 10  ##  For more Information on orm see the README file. 
 11  ## 
 12  ##  This program is free software; you can redistribute it and/or modify 
 13  ##  it under the terms of the GNU General Public License as published by 
 14  ##  the Free Software Foundation; either version 2 of the License, or 
 15  ##  (at your option) any later version. 
 16  ## 
 17  ##  This program is distributed in the hope that it will be useful, 
 18  ##  but WITHOUT ANY WARRANTY; without even the implied warranty of 
 19  ##  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 20  ##  GNU General Public License for more details. 
 21  ## 
 22  ##  You should have received a copy of the GNU General Public License 
 23  ##  along with this program; if not, write to the Free Software 
 24  ##  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA 
 25  ## 
 26  ##  I have added a copy of the GPL in the file gpl.txt. 
 27   
 28   
 29  # Changelog 
 30  # --------- 
 31  # $Log: __init__.py,v $ 
 32  # Revision 1.6  2006/09/07 13:56:32  diedrich 
 33  # Added module_property class. 
 34  # 
 35  # Revision 1.5  2006/05/08 22:41:54  diedrich 
 36  # Added import_with_new_modules() 
 37  # 
 38  # Revision 1.4  2006/04/28 09:49:26  diedrich 
 39  # Docstring updates for epydoc 
 40  # 
 41  # Revision 1.3  2006/01/01 20:48:40  diedrich 
 42  # Added the stupid_dict class. 
 43  # 
 44  # Revision 1.2  2005/12/31 18:33:06  diedrich 
 45  # Updated year in copyright header ;) 
 46  # 
 47  # Revision 1.1  2005/11/21 19:50:23  diedrich 
 48  # Initial commit 
 49  # 
 50  # 
 51   
 52  """ 
 53  This module defines a number of miscellaneous helper functions and classes. 
 54  """ 
 55   
 56  import sys 
 57  from types import * 
 58  from string import * 
 59  import imp 
 60  import __builtin__ 
 61  python_import = __builtin__.__import__ 
 62   
 63  _replacement_modules = {} 
 64   
65 -def _my_import(name, g, l, from_list):
66 global _replacement_modules 67 68 if _replacement_modules.has_key(name): 69 return _replacement_modules[name] 70 else: 71 return python_import(name, g, l, from_list)
72
73 -def import_with_new_modules(module_name, replacement_modules={}):
74 """ 75 This is a nifty function that allows your modules to inherit from each 76 other maintaining upward compatibility with regard as (for instance) 77 orm2 based data models. 78 79 Example: 80 81 >>> import model2 82 >>> controllers1 = import_with_new_modules('mytest.sub.controllers1', 83 {'model1': model2}) 84 85 >>> email = controllers1.make_email() 86 >>> print email.__module__ 87 model2 88 89 The controllers1.py module was written for a datamodel stored in the 90 model1.py module in the same package. So it imports it. Now, the function 91 calls above will import controllers1 with model2 as its datamodel. Of 92 course the new module must be a super set of the old for this to work. 93 (In this example the email class has been extended by an attribute.) 94 95 @param module_name: The name of the module to import (including 96 package name(s)) 97 @param replacement_modules: A dictionary mapping module names (<b>as 98 they are imported by the module references by module_name</b>) and the 99 module object it is supposed to be replaces with. 100 101 """ 102 global _replacement_modules 103 104 imp.acquire_lock() 105 parts = split(module_name, ".") 106 107 path = None 108 for package in parts[:-1]: 109 file, filename, description = imp.find_module(package, path) 110 module = imp.load_module(package, file, filename, description) 111 path = module.__path__ 112 113 file, filename, description = imp.find_module(parts[-1], module.__path__) 114 module = imp.load_module(module_name, file, filename, description) 115 116 globs = module.__dict__.copy() 117 _replacement_modules = replacement_modules 118 119 filename = module.__file__ 120 if filename.endswith("pyc"): filename = filename[:-1] 121 122 __builtin__.__import__ = _my_import 123 execfile(filename, globs) 124 __builtin__.__import__ = python_import 125 imp.release_lock() 126 127 module = imp.new_module("imported with new modules: %s %s" % \ 128 (module.__name__, repr(replacement_modules),)) 129 module.__dict__.update(globs) 130 return module
131 132 133 134 135 136 137 138 139
140 -class stupid_dict:
141 """ 142 This class implements the mapping (dict) interface. It uses a 143 simple list to store its data and sequential search to access 144 it. It does not depend on __hash__() to manage contained 145 objects. (See Python Reference Manual Chapter 3.3) 146 147 The actual data is stored in self.data as a list of tuples like 148 (key, value). 149 150 See the docstring of orm2.sql._part for details on why this is here. 151 """
152 - def __init__(self, initdata=[]):
153 if type(initdata) in (ListType, TupleType,): 154 self.data = [] 155 for tpl in initdata: 156 if type(tpl) not in (ListType, TupleType) or len(tpl) != 2: 157 raise ValueError("Cannot inittiate stupid_dict from "+\ 158 "that data") 159 else: 160 self.data.append(tpl) 161 elif type(initdata) == DictType: 162 self.data = initdata.items() 163 else: 164 raise ValueError("A stupid_dict must be initialized either by "+\ 165 "a list of pairs or a regular dictionary.")
166
167 - def __len__(self):
168 return len(self.data)
169
170 - def __getitem__(self, which):
171 for key, value in self.data: 172 if key == which: 173 return value 174 175 if hasattr(self, "default"): 176 return self.default 177 else: 178 raise KeyError(what)
179
180 - def __setitem__(self, which, what):
181 if self.has_key(which): 182 self.__delitem__(which) 183 184 self.data.append( (which, what,) )
185
186 - def __delitem__(self, which):
187 if self.has_key(which): 188 idx = self.keys().index(which) 189 del self.data[idx] 190 else: 191 raise KeyError(which)
192 193
194 - def __iter__(self):
195 for key, value in self.data: yield key
196 197
198 - def __contains__(self, which):
199 return which in self.keys()
200
201 - def __cmp__(self, other):
202 raise NotImplementedError("I have no idea on how to do this...")
203
204 - def __eq__(self, other):
205 self.data.sort() 206 other.data.sort() 207 208 if self.data == other.data: 209 return True 210 else: 211 return False
212
213 - def __repr__(self):
214 return "stupid_dict(%s)" % repr(self.data)
215
216 - def clear(self):
217 self.data = []
218
219 - def copy(self):
220 return stupid_dict(self.data[:])
221
222 - def get(self, which, default=None):
223 if self.has_key(which): 224 return self[which] 225 else: 226 return default
227
228 - def has_key(self, which):
229 if which in self.keys(): 230 return True 231 else: 232 return False
233
234 - def items(self):
235 return self.data[:]
236
237 - def iteritems(self):
238 for tpl in self.data: yield tpl
239 240 iterkeys = __iter__ 241
242 - def itervalues(self):
243 for key, value in self.data: yield value
244
245 - def keys(self):
246 return list(self.iterkeys())
247
248 - def values(self):
249 return list(self.itervalues())
250
251 - def pop(self):
252 raise NotImplementedError("This doesn't make sense in a stupid_dict,"+\ 253 " or does it? No, seriously...")
254 255 popitem = pop 256
257 - def setdefault(self, default):
258 self.default = default
259
260 - def update(self, other):
261 """ 262 Other must implement the mapping (i.e. dict) interface. 263 """ 264 for key, value in other.items(): 265 self[key] = value
266 267
268 -class module_property(property):
269 """ 270 Property class the will return the module object of the module the 271 owning class was loaded from. 272 """
273 - def __get__(self, dbobj, owner=None):
274 return sys.modules[dbobj.__class__.__module__]
275 276 # Local variables: 277 # mode: python 278 # ispell-local-dictionary: "english" 279 # End: 280