Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 79 lines (55 sloc) 2.207 kB
1f2fb6e @tito kivy: first import
tito authored
1 '''
2 Factory: used for register and create any classes
3
4 The factory can be also use for automaticly importing any class from a module,
5 by specifing the module to import instead of the class instance.
6
7 The class list + modules available is automaticly generated with setup.py.
8
9 Example of registering a class/module ::
10
11 from kivy.factory import Factory
12
13 Factory.register('Widget', 'kivy.uix.widget')
14 Factory.register('Vector', 'kivy.vector')
15
16 Example of using the Factory ::
17
18 from kivy.factory import Factory
19
20 widget = Factory.Widget(pos=(456,456))
21 vector = Factory.Vector(9, 2)
22
23 '''
24
25 __all__ = ('Factory', 'FactoryException')
26
27 from kivy.logger import Logger
28
29 class FactoryException(Exception):
30 pass
31
32 class FactoryBase(object):
33 def __init__(self):
34 super(FactoryBase, self).__init__()
35 self.classes = {}
36
37 def register(self, classname, cls=None, module=None):
38 '''Register a new classname refering to a real class or class definition
39 in a module.
40 '''
41 if cls is None and module is None:
42 raise ValueError('You need a cls= or module=')
43 self.classes[classname] = {
44 'module': module,
45 'cls': cls
46 }
47
48 def __getattr__(self, name):
49 classes = self.classes
50 if name not in classes:
51 raise FactoryException('Unknown class <%s>' % name)
52
53 item = classes[name]
54 cls = item['cls']
55
56 # No class to return, import the module
57 if cls is None:
58 module = __import__(name=item['module'], fromlist='.')
59 if not hasattr(module, name):
60 raise FactoryException('No class named <%s> in <%s>' % (
61 name, item['module']))
62 cls = item['cls'] = getattr(module, name)
63
64 return cls
65
66
67 #: Factory instance to use for getting new classes
68 Factory = FactoryBase()
69
70 # Now import the file with all registers
71 # automaticly generated from build_factory
72 import kivy.factory_registers
73 Logger.info('Factory: %d symbols loaded' % len(Factory.classes))
74
75 if __name__ == '__main__':
76 Factory.register('Vector', module='kivy.vector')
77 Factory.register('Widget', module='kivy.uix.widget')
78
Something went wrong with that request. Please try again.