1# -*- Mode: Python; py-indent-offset: 4 -*- 2# pygtk - Python bindings for the GTK toolkit. 3# Copyright (C) 2006 Johan Dahlin 4# 5# This library is free software; you can redistribute it and/or 6# modify it under the terms of the GNU Lesser General Public 7# License as published by the Free Software Foundation; either 8# version 2.1 of the License, or (at your option) any later version. 9# 10# This library is distributed in the hope that it will be useful, 11# but WITHOUT ANY WARRANTY; without even the implied warranty of 12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13# Lesser General Public License for more details. 14# 15# You should have received a copy of the GNU Lesser General Public 16# License along with this library; if not, write to the Free Software 17# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 18# USA 19 20# Private to PyGTK, do not use in applications 21 22import sys 23from types import ModuleType 24 25class LazyModule(object): 26 def __init__(self, name, locals): 27 self._name = name 28 self._locals = locals 29 self._modname = '%s.%s' % (self._locals.get('__name__'), self._name) 30 31 def __getattr__(self, attr): 32 module = __import__(self._name, self._locals, {}, ' ') 33 sys.modules[self._modname] = module 34 if attr == '__members__': 35 return dir(module) 36 return getattr(module, attr) 37 38class _NotLoadedMarker: 39 pass 40_marker = _NotLoadedMarker() 41 42class LazyDict(dict): 43 def __init__(self, module): 44 self._module = module 45 dict.__init__(self) 46 47 def __getitem__(self, name): 48 print name 49 return getattr(self._module, name) 50 51class LazyNamespace(ModuleType): 52 def __init__(self, module, locals): 53 ModuleType.__init__(self, locals['__name__']) 54 self._imports = {} 55 56 ns = self.__dict__ 57 ns.update(locals) 58 ns['__module__'] = self 59 lazy_symbols = {} 60 for symbol in module._get_symbol_names(): 61 lazy_symbols[symbol] = ns[symbol] = _marker 62 63 ns.update(__dict__=LazyDict(self), 64 __bases__=(ModuleType,), 65 add_submodule=self.add_submodule) 66 67 def __getattribute__(_, name): 68 v = ns.get(name, _marker) 69 if v is not _marker: 70 return v 71 if name in lazy_symbols: 72 s = module._get_symbol(ns, name) 73 return s 74 elif name in self._imports: 75 m = __import__(self._imports[name], {}, {}, ' ') 76 ns[name] = m 77 return m 78 79 raise AttributeError(name) 80 LazyNamespace.__getattribute__ = __getattribute__ 81 82 def add_submodule(self, name, importname): 83 self._imports[name] = importname 84 85