Imported Upstream version 3.13.1
[platform/upstream/pygobject2.git] / gi / importer.py
1 # -*- Mode: Python; py-indent-offset: 4 -*-
2 # vim: tabstop=4 shiftwidth=4 expandtab
3 #
4 # Copyright (C) 2005-2009 Johan Dahlin <johan@gnome.org>
5 #
6 #   importer.py: dynamic importer for introspected libraries.
7 #
8 # This library is free software; you can redistribute it and/or
9 # modify it under the terms of the GNU Lesser General Public
10 # License as published by the Free Software Foundation; either
11 # version 2.1 of the License, or (at your option) any later version.
12 #
13 # This library 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 GNU
16 # Lesser General Public License for more details.
17 #
18 # You should have received a copy of the GNU Lesser General Public
19 # License along with this library; if not, write to the Free Software
20 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301
21 # USA
22
23 from __future__ import absolute_import
24 import sys
25
26 from ._gi import Repository
27 from .module import DynamicModule
28
29
30 repository = Repository.get_default()
31 modules = {}
32
33
34 class DynamicImporter(object):
35
36     # Note: see PEP302 for the Importer Protocol implemented below.
37
38     def __init__(self, path):
39         self.path = path
40
41     def find_module(self, fullname, path=None):
42         if not fullname.startswith(self.path):
43             return
44
45         path, namespace = fullname.rsplit('.', 1)
46         if path != self.path:
47             return
48
49         if repository.enumerate_versions(namespace):
50             return self
51         else:
52             raise ImportError('cannot import name %s, '
53                               'introspection typelib not found' % namespace)
54
55     def load_module(self, fullname):
56         if fullname in sys.modules:
57             return sys.modules[fullname]
58
59         path, namespace = fullname.rsplit('.', 1)
60         dynamic_module = DynamicModule(namespace)
61         modules[namespace] = dynamic_module
62
63         dynamic_module.__file__ = '<%s>' % fullname
64         dynamic_module.__loader__ = self
65
66         sys.modules[fullname] = dynamic_module
67         dynamic_module._load()
68
69         return dynamic_module