martian 2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- martian/README.rst +428 -0
- martian/__init__.py +52 -0
- martian/components.py +108 -0
- martian/context.py +50 -0
- martian/context.rst +182 -0
- martian/core.py +265 -0
- martian/core.rst +1253 -0
- martian/directive.py +369 -0
- martian/directive.rst +1213 -0
- martian/edgecase.rst +303 -0
- martian/error.py +24 -0
- martian/interfaces.py +113 -0
- martian/martiandirective.py +59 -0
- martian/scan.py +226 -0
- martian/scan.rst +287 -0
- martian/testing.py +90 -0
- martian/tests/__init__.py +1 -0
- martian/tests/public_methods_from_class.rst +32 -0
- martian/tests/scan_for_classes.rst +32 -0
- martian/tests/scanforclasses/__init__.py +11 -0
- martian/tests/scanforclasses/test1.py +20 -0
- martian/tests/scanforclasses/test2.py +24 -0
- martian/tests/scanforclasses/test3.py +27 -0
- martian/tests/scanforclasses/test4.py +40 -0
- martian/tests/stoneage/__init__.py +1 -0
- martian/tests/stoneage/cave.py +9 -0
- martian/tests/stoneage/hunt/__init__.py +1 -0
- martian/tests/stoneage/hunt/mammoth.py +6 -0
- martian/tests/stoneage/hunt/mammoth_templates/index.pt +5 -0
- martian/tests/stoneage/notpackage/dummy.py +1 -0
- martian/tests/stoneage/painting/__init__.py +1 -0
- martian/tests/test_all.py +59 -0
- martian/tests/testpackage/__init__.py +1 -0
- martian/tests/testpackage/alpha/__init__.py +5 -0
- martian/tests/testpackage/animal.py +2 -0
- martian/tests/testpackage/beta/__init__.py +1 -0
- martian/tests/testpackage/beta/three.py +5 -0
- martian/tests/testpackage/one.py +13 -0
- martian/tests/testpackage/two.py +5 -0
- martian/tests/with__main__/__init__.py +1 -0
- martian/tests/with__main__/__main__.py +5 -0
- martian/tests/with__main__/package.py +2 -0
- martian/tests/withbogusmodules/.bogus.py +1 -0
- martian/tests/withbogusmodules/.bogussubpackage/__init__.py +0 -0
- martian/tests/withbogusmodules/1alsobogus.py +1 -0
- martian/tests/withbogusmodules/__init__.py +0 -0
- martian/tests/withbogusmodules/nonbogus.py +1 -0
- martian/tests/withbogusmodules/subpackage/__init__.py +0 -0
- martian/tests/withpyconly/__init__.py +0 -0
- martian/tests/withpyconly/foo.py +1 -0
- martian/tests/withpyconly/subpackage/__init__.py +0 -0
- martian/tests/withtestsmodules/__init__.py +0 -0
- martian/tests/withtestsmodules/ftests.py +5 -0
- martian/tests/withtestsmodules/subpackage/__init__.py +0 -0
- martian/tests/withtestsmodules/tests.py +5 -0
- martian/tests/withtestspackages/__init__.py +0 -0
- martian/tests/withtestspackages/ftests/__init__.py +0 -0
- martian/tests/withtestspackages/subpackage/__init__.py +0 -0
- martian/tests/withtestspackages/tests/__init__.py +0 -0
- martian/tests/withtestspackages/tests/subpackage/__init__.py +0 -0
- martian/util.py +136 -0
- martian-2.0.dist-info/LICENSE.txt +44 -0
- martian-2.0.dist-info/METADATA +877 -0
- martian-2.0.dist-info/RECORD +66 -0
- martian-2.0.dist-info/WHEEL +5 -0
- martian-2.0.dist-info/top_level.txt +1 -0
martian/README.rst
ADDED
|
@@ -0,0 +1,428 @@
|
|
|
1
|
+
Martian tutorial
|
|
2
|
+
****************
|
|
3
|
+
|
|
4
|
+
Introduction
|
|
5
|
+
============
|
|
6
|
+
|
|
7
|
+
"There was so much to grok, so little to grok from." -- Stranger in a
|
|
8
|
+
Strange Land, by Robert A. Heinlein
|
|
9
|
+
|
|
10
|
+
Martian provides infrastructure for declarative configuration of
|
|
11
|
+
Python code. Martian is especially useful for the construction of
|
|
12
|
+
frameworks that need to provide a flexible plugin
|
|
13
|
+
infrastructure. Martian doesn't actually provide infrastructure for
|
|
14
|
+
plugin registries (except for itself). Many frameworks have their own
|
|
15
|
+
systems for this, and if you need a generic one, you might want to
|
|
16
|
+
consider ``zope.component``. Martian just allows you to make the
|
|
17
|
+
registration of plugins less verbose.
|
|
18
|
+
|
|
19
|
+
You can see Martian as doing something that you can also solve with
|
|
20
|
+
metaclasses, with the following advantages:
|
|
21
|
+
|
|
22
|
+
* the developer of the framework doesn't have to write a lot of ad-hoc
|
|
23
|
+
metaclasses anymore; instead we offer an infrastructure to make life
|
|
24
|
+
easier.
|
|
25
|
+
|
|
26
|
+
* configuration doesn't need to happen at import time, but can happen at
|
|
27
|
+
program startup time. This also makes configuration more tractable for
|
|
28
|
+
a developer.
|
|
29
|
+
|
|
30
|
+
* we don't bother the developer that *uses* the framework with the
|
|
31
|
+
surprising behavior that metaclasses sometimes bring. The classes
|
|
32
|
+
the user has to deal with are normal classes.
|
|
33
|
+
|
|
34
|
+
Why is this package named ``martian``? In the novel "Stranger in a
|
|
35
|
+
Strange Land", the verb *grok* is introduced:
|
|
36
|
+
|
|
37
|
+
Grok means to understand so thoroughly that the observer becomes a
|
|
38
|
+
part of the observed -- to merge, blend, intermarry, lose identity
|
|
39
|
+
in group experience.
|
|
40
|
+
|
|
41
|
+
In the context of this package, "grokking" stands for the process of
|
|
42
|
+
deducing declarative configuration actions from Python code. In the
|
|
43
|
+
novel, grokking is originally a concept that comes from the planet
|
|
44
|
+
Mars. Martians *grok*. Since this package helps you grok code, it's
|
|
45
|
+
called Martian.
|
|
46
|
+
|
|
47
|
+
Martian provides a framework that allows configuration to be expressed
|
|
48
|
+
in declarative Python code. These declarations can often be deduced
|
|
49
|
+
from the structure of the code itself. The idea is to make these
|
|
50
|
+
declarations so minimal and easy to read that even extensive
|
|
51
|
+
configuration does not overly burden the programmers working with the
|
|
52
|
+
code.
|
|
53
|
+
|
|
54
|
+
The ``martian`` package is a spin-off from the `Grok project`_, in the
|
|
55
|
+
context of which this codebase was first developed. While Grok uses
|
|
56
|
+
it, the code is completely independent of Grok.
|
|
57
|
+
|
|
58
|
+
.. _`Grok project`: http://grok.zope.org
|
|
59
|
+
|
|
60
|
+
Motivation
|
|
61
|
+
==========
|
|
62
|
+
|
|
63
|
+
"Deducing declarative configuration actions from Python code" - that
|
|
64
|
+
sounds very abstract. What does it actually mean? What is
|
|
65
|
+
configuration? What is declarative configuration? In order to explain
|
|
66
|
+
this, we'll first take a look at configuration.
|
|
67
|
+
|
|
68
|
+
Larger frameworks often offer a lot of points where you can modify
|
|
69
|
+
their behavior: ways to combine its own components with components you
|
|
70
|
+
provide yourself to build a larger application. A framework offers
|
|
71
|
+
points where it can be *configured* with plugin code. When you plug
|
|
72
|
+
some code into a plugin point, it results in the updating of some
|
|
73
|
+
registry somewhere with the new plugin. When the framework uses a
|
|
74
|
+
plugin, it will first look it up in the registry. The action of
|
|
75
|
+
registering some component into a registry can be called
|
|
76
|
+
*configuration*.
|
|
77
|
+
|
|
78
|
+
Let's look at an example framework that offers a plugin point. We
|
|
79
|
+
introduce a very simple framework for plugging in different template
|
|
80
|
+
languages, where each template language uses its own extension. You
|
|
81
|
+
can then supply the framework with the template body and the template
|
|
82
|
+
extension and some data, and render the template.
|
|
83
|
+
|
|
84
|
+
Let's look at the framework::
|
|
85
|
+
|
|
86
|
+
>>> import string
|
|
87
|
+
>>> class templating(FakeModule):
|
|
88
|
+
...
|
|
89
|
+
... class InterpolationTemplate(object):
|
|
90
|
+
... "Use %(foo)s for dictionary interpolation."
|
|
91
|
+
... def __init__(self, text):
|
|
92
|
+
... self.text = text
|
|
93
|
+
... def render(self, **kw):
|
|
94
|
+
... return self.text % kw
|
|
95
|
+
...
|
|
96
|
+
... class TemplateStringTemplate(object):
|
|
97
|
+
... "PEP 292 string substitutions."
|
|
98
|
+
... def __init__(self, text):
|
|
99
|
+
... self.template = string.Template(text)
|
|
100
|
+
... def render(self, **kw):
|
|
101
|
+
... return self.template.substitute(**kw)
|
|
102
|
+
...
|
|
103
|
+
... # the registry, we plug in the two templating systems right away
|
|
104
|
+
... extension_handlers = { '.txt': InterpolationTemplate,
|
|
105
|
+
... '.tmpl': TemplateStringTemplate }
|
|
106
|
+
...
|
|
107
|
+
... def render(data, extension, **kw):
|
|
108
|
+
... """Render the template at filepath with arguments.
|
|
109
|
+
...
|
|
110
|
+
... data - the data in the file
|
|
111
|
+
... extension - the extension of the file
|
|
112
|
+
... keyword arguments - variables to interpolate
|
|
113
|
+
...
|
|
114
|
+
... In a real framework you could pass in the file path instead of
|
|
115
|
+
... data and extension, but we don't want to open files in our
|
|
116
|
+
... example.
|
|
117
|
+
...
|
|
118
|
+
... Returns the rendered template
|
|
119
|
+
... """
|
|
120
|
+
... template = extension_handlers[extension](data)
|
|
121
|
+
... return template.render(**kw)
|
|
122
|
+
|
|
123
|
+
Since normally we cannot create modules in a doctest, we have emulated
|
|
124
|
+
the ``templating`` Python module using the ``FakeModule``
|
|
125
|
+
class. Whenever you see ``FakeModule`` subclasses, imagine you're
|
|
126
|
+
looking at a module definition in a ``.py`` file. Now that we have
|
|
127
|
+
defined a module ``templating``, we also need to be able to import
|
|
128
|
+
it. Fake modules are always placed automatically into the
|
|
129
|
+
``martiantest.fake`` namespace so you can import them from there::
|
|
130
|
+
|
|
131
|
+
>>> from martiantest.fake import templating
|
|
132
|
+
|
|
133
|
+
Now let's try the ``render`` function for the registered template
|
|
134
|
+
types, to demonstrate that our framework works::
|
|
135
|
+
|
|
136
|
+
>>> templating.render('Hello %(name)s!', '.txt', name="world")
|
|
137
|
+
'Hello world!'
|
|
138
|
+
>>> templating.render('Hello ${name}!', '.tmpl', name="universe")
|
|
139
|
+
'Hello universe!'
|
|
140
|
+
|
|
141
|
+
File extensions that we do not recognize cause a ``KeyError`` to be
|
|
142
|
+
raised::
|
|
143
|
+
|
|
144
|
+
>>> templating.render('Hello', '.silly', name="test")
|
|
145
|
+
Traceback (most recent call last):
|
|
146
|
+
...
|
|
147
|
+
KeyError: '.silly'
|
|
148
|
+
|
|
149
|
+
We now want to plug into this filehandler framework and provide a
|
|
150
|
+
handler for ``.silly`` files. Since we are writing a plugin, we cannot
|
|
151
|
+
change the ``templating`` module directly. Let's write an extension
|
|
152
|
+
module instead::
|
|
153
|
+
|
|
154
|
+
>>> class sillytemplating(FakeModule):
|
|
155
|
+
... class SillyTemplate(object):
|
|
156
|
+
... "Replace {key} with dictionary values."
|
|
157
|
+
... def __init__(self, text):
|
|
158
|
+
... self.text = text
|
|
159
|
+
... def render(self, **kw):
|
|
160
|
+
... text = self.text
|
|
161
|
+
... for key, value in kw.items():
|
|
162
|
+
... text = text.replace('{%s}' % key, value)
|
|
163
|
+
... return text
|
|
164
|
+
...
|
|
165
|
+
... templating.extension_handlers['.silly'] = SillyTemplate
|
|
166
|
+
>>> from martiantest.fake import sillytemplating
|
|
167
|
+
|
|
168
|
+
In the extension module, we manipulate the ``extension_handlers``
|
|
169
|
+
dictionary of the ``templating`` module (in normal code we'd need to
|
|
170
|
+
import it first), and plug in our own function. ``.silly`` handling
|
|
171
|
+
works now::
|
|
172
|
+
|
|
173
|
+
>>> templating.render('Hello {name}!', '.silly', name="galaxy")
|
|
174
|
+
'Hello galaxy!'
|
|
175
|
+
|
|
176
|
+
Above we plug into our ``extension_handler`` registry using Python
|
|
177
|
+
code. Using separate code to manually hook components into registries
|
|
178
|
+
can get rather cumbersome - each time you write a plugin, you also
|
|
179
|
+
need to remember you need to register it.
|
|
180
|
+
|
|
181
|
+
Doing template registration in Python code also poses a maintenance
|
|
182
|
+
risk. It is tempting to start doing fancy things in Python code such
|
|
183
|
+
as conditional configuration, making the configuration state of a
|
|
184
|
+
program hard to understand. Another problem is that doing
|
|
185
|
+
configuration at import time can also lead to unwanted side effects
|
|
186
|
+
during import, as well as ordering problems, where you want to import
|
|
187
|
+
something that really needs configuration state in another module that
|
|
188
|
+
is imported later. Finally, it can also make code harder to test, as
|
|
189
|
+
configuration is loaded always when you import the module, even if in
|
|
190
|
+
your test perhaps you don't want it to be.
|
|
191
|
+
|
|
192
|
+
Martian provides a framework that allows configuration to be expressed
|
|
193
|
+
in declarative Python code. Martian is based on the realization that
|
|
194
|
+
what to configure where can often be deduced from the structure of
|
|
195
|
+
Python code itself, especially when it can be annotated with
|
|
196
|
+
additional declarations. The idea is to make it so easy to write and
|
|
197
|
+
register a plugin so that even extensive configuration does not overly
|
|
198
|
+
burden the developer.
|
|
199
|
+
|
|
200
|
+
Configuration actions are executed during a separate phase ("grok
|
|
201
|
+
time"), not at import time, which makes it easier to reason about and
|
|
202
|
+
easier to test.
|
|
203
|
+
|
|
204
|
+
Configuration the Martian Way
|
|
205
|
+
=============================
|
|
206
|
+
|
|
207
|
+
Let's now transform the above ``templating`` module and the
|
|
208
|
+
``sillytemplating`` module to use Martian. First we must recognize
|
|
209
|
+
that every template language is configured to work for a particular
|
|
210
|
+
extension. With Martian, we annotate the classes themselves with this
|
|
211
|
+
configuration information. Annotations happen using *directives*,
|
|
212
|
+
which look like function calls in the class body.
|
|
213
|
+
|
|
214
|
+
Let's create an ``extension`` directive that can take a single string
|
|
215
|
+
as an argument, the file extension to register the template class
|
|
216
|
+
for::
|
|
217
|
+
|
|
218
|
+
>>> import martian
|
|
219
|
+
>>> class extension(martian.Directive):
|
|
220
|
+
... scope = martian.CLASS
|
|
221
|
+
... store = martian.ONCE
|
|
222
|
+
... default = None
|
|
223
|
+
|
|
224
|
+
We also need a way to easily recognize all template classes. The normal
|
|
225
|
+
pattern for this in Martian is to use a base class, so let's define a
|
|
226
|
+
``Template`` base class::
|
|
227
|
+
|
|
228
|
+
>>> class Template(object):
|
|
229
|
+
... pass
|
|
230
|
+
|
|
231
|
+
We now have enough infrastructure to allow us to change the code to use
|
|
232
|
+
Martian style base class and annotations::
|
|
233
|
+
|
|
234
|
+
>>> class templating(FakeModule):
|
|
235
|
+
...
|
|
236
|
+
... class InterpolationTemplate(Template):
|
|
237
|
+
... "Use %(foo)s for dictionary interpolation."
|
|
238
|
+
... extension('.txt')
|
|
239
|
+
... def __init__(self, text):
|
|
240
|
+
... self.text = text
|
|
241
|
+
... def render(self, **kw):
|
|
242
|
+
... return self.text % kw
|
|
243
|
+
...
|
|
244
|
+
... class TemplateStringTemplate(Template):
|
|
245
|
+
... "PEP 292 string substitutions."
|
|
246
|
+
... extension('.tmpl')
|
|
247
|
+
... def __init__(self, text):
|
|
248
|
+
... self.template = string.Template(text)
|
|
249
|
+
... def render(self, **kw):
|
|
250
|
+
... return self.template.substitute(**kw)
|
|
251
|
+
...
|
|
252
|
+
... # the registry, empty to start with
|
|
253
|
+
... extension_handlers = {}
|
|
254
|
+
...
|
|
255
|
+
... def render(data, extension, **kw):
|
|
256
|
+
... # this hasn't changed
|
|
257
|
+
... template = extension_handlers[extension](data)
|
|
258
|
+
... return template.render(**kw)
|
|
259
|
+
>>> from martiantest.fake import templating
|
|
260
|
+
|
|
261
|
+
As you can see, there have been very few changes:
|
|
262
|
+
|
|
263
|
+
* we made the template classes inherit from ``Template``.
|
|
264
|
+
|
|
265
|
+
* we use the ``extension`` directive in the template classes.
|
|
266
|
+
|
|
267
|
+
* we stopped pre-filling the ``extension_handlers`` dictionary.
|
|
268
|
+
|
|
269
|
+
So how do we fill the ``extension_handlers`` dictionary with the right
|
|
270
|
+
template languages? Now we can use Martian. We define a *grokker* for
|
|
271
|
+
``Template`` that registers the template classes in the
|
|
272
|
+
``extension_handlers`` registry::
|
|
273
|
+
|
|
274
|
+
>>> class meta(FakeModule):
|
|
275
|
+
... class TemplateGrokker(martian.ClassGrokker):
|
|
276
|
+
... martian.component(Template)
|
|
277
|
+
... martian.directive(extension)
|
|
278
|
+
... def execute(self, class_, extension, **kw):
|
|
279
|
+
... templating.extension_handlers[extension] = class_
|
|
280
|
+
... return True
|
|
281
|
+
>>> from martiantest.fake import meta
|
|
282
|
+
|
|
283
|
+
What does this do? A ``ClassGrokker`` has its ``execute`` method
|
|
284
|
+
called for subclasses of what's indicated by the ``martian.component``
|
|
285
|
+
directive. You can also declare what directives a ``ClassGrokker``
|
|
286
|
+
expects on this component by using ``martian.directive()`` (the
|
|
287
|
+
``directive`` directive!) one or more times.
|
|
288
|
+
|
|
289
|
+
The ``execute`` method takes the class to be grokked as the first
|
|
290
|
+
argument, and the values of the directives used will be passed in as
|
|
291
|
+
additional parameters into the ``execute`` method. The framework can
|
|
292
|
+
also pass along an arbitrary number of extra keyword arguments during
|
|
293
|
+
the grokking process, so we need to declare ``**kw`` to make sure we
|
|
294
|
+
can handle these.
|
|
295
|
+
|
|
296
|
+
All our grokkers will be collected in a special Martian-specific
|
|
297
|
+
registry::
|
|
298
|
+
|
|
299
|
+
>>> reg = martian.GrokkerRegistry()
|
|
300
|
+
|
|
301
|
+
We will need to make sure the system is aware of the
|
|
302
|
+
``TemplateGrokker`` defined in the ``meta`` module first, so let's
|
|
303
|
+
register it first. We can do this by simply grokking the ``meta``
|
|
304
|
+
module::
|
|
305
|
+
|
|
306
|
+
>>> reg.grok('meta', meta)
|
|
307
|
+
True
|
|
308
|
+
|
|
309
|
+
Because ``TemplateGrokker`` is now registered, our registry now knows
|
|
310
|
+
how to grok ``Template`` subclasses. Let's grok the ``templating``
|
|
311
|
+
module::
|
|
312
|
+
|
|
313
|
+
>>> reg.grok('templating', templating)
|
|
314
|
+
True
|
|
315
|
+
|
|
316
|
+
Let's try the ``render`` function of templating again, to demonstrate
|
|
317
|
+
we have successfully grokked the template classes::
|
|
318
|
+
|
|
319
|
+
>>> templating.render('Hello %(name)s!', '.txt', name="world")
|
|
320
|
+
'Hello world!'
|
|
321
|
+
>>> templating.render('Hello ${name}!', '.tmpl', name="universe")
|
|
322
|
+
'Hello universe!'
|
|
323
|
+
|
|
324
|
+
``.silly`` hasn't been registered yet::
|
|
325
|
+
|
|
326
|
+
>>> templating.render('Hello', '.silly', name="test")
|
|
327
|
+
Traceback (most recent call last):
|
|
328
|
+
...
|
|
329
|
+
KeyError: '.silly'
|
|
330
|
+
|
|
331
|
+
Let's now register ``.silly`` from an extension module::
|
|
332
|
+
|
|
333
|
+
>>> class sillytemplating(FakeModule):
|
|
334
|
+
... class SillyTemplate(Template):
|
|
335
|
+
... "Replace {key} with dictionary values."
|
|
336
|
+
... extension('.silly')
|
|
337
|
+
... def __init__(self, text):
|
|
338
|
+
... self.text = text
|
|
339
|
+
... def render(self, **kw):
|
|
340
|
+
... text = self.text
|
|
341
|
+
... for key, value in kw.items():
|
|
342
|
+
... text = text.replace('{%s}' % key, value)
|
|
343
|
+
... return text
|
|
344
|
+
>>> from martiantest.fake import sillytemplating
|
|
345
|
+
|
|
346
|
+
As you can see, the developer that uses the framework has no need
|
|
347
|
+
anymore to know about ``templating.extension_handlers``. Instead we can
|
|
348
|
+
simply grok the module to have ``SillyTemplate`` be register appropriately::
|
|
349
|
+
|
|
350
|
+
>>> reg.grok('sillytemplating', sillytemplating)
|
|
351
|
+
True
|
|
352
|
+
|
|
353
|
+
We can now use the ``.silly`` templating engine too::
|
|
354
|
+
|
|
355
|
+
>>> templating.render('Hello {name}!', '.silly', name="galaxy")
|
|
356
|
+
'Hello galaxy!'
|
|
357
|
+
|
|
358
|
+
Admittedly it is hard to demonstrate Martian well with a small example
|
|
359
|
+
like this. In the end we have actually written more code than in the
|
|
360
|
+
basic framework, after all. But even in this small example, the
|
|
361
|
+
``templating`` and ``sillytemplating`` module have become more
|
|
362
|
+
declarative in nature. The developer that uses the framework will not
|
|
363
|
+
need to know anymore about things like
|
|
364
|
+
``templating.extension_handlers`` or an API to register things
|
|
365
|
+
there. Instead the developer can registering a new template system
|
|
366
|
+
anywhere, as long as he subclasses from ``Template``, and as long as
|
|
367
|
+
his code is grokked by the system.
|
|
368
|
+
|
|
369
|
+
Finally note how Martian was used to define the ``TemplateGrokker`` as
|
|
370
|
+
well. In this way Martian can use itself to extend itself.
|
|
371
|
+
|
|
372
|
+
Grokking instances
|
|
373
|
+
==================
|
|
374
|
+
|
|
375
|
+
Above we've seen how you can grok classes. Martian also supplies a way
|
|
376
|
+
to grok instances. This is less common in typical frameworks, and has
|
|
377
|
+
the drawback that no class-level directives can be used, but can still
|
|
378
|
+
be useful.
|
|
379
|
+
|
|
380
|
+
Let's imagine a case where we have a zoo framework with an ``Animal``
|
|
381
|
+
class, and we want to track instances of it::
|
|
382
|
+
|
|
383
|
+
>>> class Animal(object):
|
|
384
|
+
... def __init__(self, name):
|
|
385
|
+
... self.name = name
|
|
386
|
+
>>> class zoo(FakeModule):
|
|
387
|
+
... horse = Animal('horse')
|
|
388
|
+
... chicken = Animal('chicken')
|
|
389
|
+
... elephant = Animal('elephant')
|
|
390
|
+
... lion = Animal('lion')
|
|
391
|
+
... animals = {}
|
|
392
|
+
>>> from martiantest.fake import zoo
|
|
393
|
+
|
|
394
|
+
We define an ``InstanceGrokker`` subclass to grok ``Animal`` instances::
|
|
395
|
+
|
|
396
|
+
>>> class meta(FakeModule):
|
|
397
|
+
... class AnimalGrokker(martian.InstanceGrokker):
|
|
398
|
+
... martian.component(Animal)
|
|
399
|
+
... def execute(self, instance, **kw):
|
|
400
|
+
... zoo.animals[instance.name] = instance
|
|
401
|
+
... return True
|
|
402
|
+
>>> from martiantest.fake import meta
|
|
403
|
+
|
|
404
|
+
Let's create a new registry with the ``AnimalGrokker`` in it::
|
|
405
|
+
|
|
406
|
+
>>> reg = martian.GrokkerRegistry()
|
|
407
|
+
>>> reg.grok('meta', meta)
|
|
408
|
+
True
|
|
409
|
+
|
|
410
|
+
We can now grok the ``zoo`` module::
|
|
411
|
+
|
|
412
|
+
>>> reg.grok('zoo', zoo)
|
|
413
|
+
True
|
|
414
|
+
|
|
415
|
+
The animals will now be in the ``animals`` dictionary::
|
|
416
|
+
|
|
417
|
+
>>> sorted(zoo.animals.items())
|
|
418
|
+
[('chicken', <Animal object at ...>),
|
|
419
|
+
('elephant', <Animal object at ...>),
|
|
420
|
+
('horse', <Animal object at ...>),
|
|
421
|
+
('lion', <Animal object at ...>)]
|
|
422
|
+
|
|
423
|
+
More information
|
|
424
|
+
================
|
|
425
|
+
|
|
426
|
+
For many more details and examples of more kinds of grokkers, please
|
|
427
|
+
see ``src/martian/core.txt``. For more information on directives see
|
|
428
|
+
``src/martian/directive.txt``.
|
martian/__init__.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
from martian.components import ClassGrokker
|
|
2
|
+
from martian.components import GlobalGrokker
|
|
3
|
+
from martian.components import InstanceGrokker
|
|
4
|
+
from martian.components import MethodGrokker
|
|
5
|
+
from martian.context import GetDefaultComponentFactory
|
|
6
|
+
from martian.core import GrokkerRegistry
|
|
7
|
+
from martian.core import MetaMultiGrokker
|
|
8
|
+
from martian.core import ModuleGrokker
|
|
9
|
+
from martian.core import MultiGrokker
|
|
10
|
+
from martian.core import grok_dotted_name
|
|
11
|
+
from martian.core import grok_module
|
|
12
|
+
from martian.core import grok_package
|
|
13
|
+
from martian.directive import CLASS
|
|
14
|
+
from martian.directive import CLASS_OR_MODULE
|
|
15
|
+
from martian.directive import DICT
|
|
16
|
+
from martian.directive import MODULE
|
|
17
|
+
from martian.directive import MULTIPLE
|
|
18
|
+
from martian.directive import MULTIPLE_NOBASE
|
|
19
|
+
from martian.directive import ONCE
|
|
20
|
+
from martian.directive import ONCE_IFACE
|
|
21
|
+
from martian.directive import ONCE_NOBASE
|
|
22
|
+
from martian.directive import UNKNOWN
|
|
23
|
+
from martian.directive import Directive
|
|
24
|
+
from martian.directive import MarkerDirective
|
|
25
|
+
from martian.directive import MultipleTimesDirective
|
|
26
|
+
from martian.directive import UnknownError
|
|
27
|
+
from martian.directive import validateClass
|
|
28
|
+
from martian.directive import validateInterface
|
|
29
|
+
from martian.directive import validateInterfaceOrClass
|
|
30
|
+
from martian.directive import validateText
|
|
31
|
+
from martian.martiandirective import baseclass
|
|
32
|
+
from martian.martiandirective import component
|
|
33
|
+
from martian.martiandirective import directive
|
|
34
|
+
from martian.martiandirective import ignore
|
|
35
|
+
from martian.martiandirective import priority
|
|
36
|
+
from martian.util import scan_for_classes
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
__all__ = [
|
|
40
|
+
'ModuleGrokker', 'MultiGrokker', 'MetaMultiGrokker', 'grok_dotted_name',
|
|
41
|
+
'grok_package', 'grok_module', 'GrokkerRegistry',
|
|
42
|
+
'GlobalGrokker', 'ClassGrokker', 'InstanceGrokker',
|
|
43
|
+
'MethodGrokker', 'scan_for_classes',
|
|
44
|
+
'Directive', 'MarkerDirective', 'MultipleTimesDirective',
|
|
45
|
+
'ONCE', 'ONCE_NOBASE', 'ONCE_IFACE', 'MULTIPLE', 'MULTIPLE_NOBASE', 'DICT',
|
|
46
|
+
'CLASS', 'CLASS_OR_MODULE', 'MODULE', 'UNKNOWN', 'UnknownError',
|
|
47
|
+
'validateText', 'validateInterface', 'validateClass',
|
|
48
|
+
'validateInterfaceOrClass',
|
|
49
|
+
'component', 'directive', 'priority', 'baseclass', 'ignore',
|
|
50
|
+
'GetDefaultComponentFactory'
|
|
51
|
+
|
|
52
|
+
]
|
martian/components.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
##############################################################################
|
|
2
|
+
#
|
|
3
|
+
# Copyright (c) 2006-2007 Zope Foundation and Contributors.
|
|
4
|
+
# All Rights Reserved.
|
|
5
|
+
#
|
|
6
|
+
# This software is subject to the provisions of the Zope Public License,
|
|
7
|
+
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
|
|
8
|
+
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
|
|
9
|
+
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
|
10
|
+
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
|
|
11
|
+
# FOR A PARTICULAR PURPOSE.
|
|
12
|
+
#
|
|
13
|
+
##############################################################################
|
|
14
|
+
|
|
15
|
+
from zope.interface import implementer
|
|
16
|
+
|
|
17
|
+
from martian import util
|
|
18
|
+
from martian.error import GrokError
|
|
19
|
+
from martian.interfaces import IComponentGrokker
|
|
20
|
+
from martian.interfaces import IGrokker
|
|
21
|
+
from martian.martiandirective import component
|
|
22
|
+
from martian.martiandirective import directive
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@implementer(IGrokker)
|
|
26
|
+
class GrokkerBase:
|
|
27
|
+
|
|
28
|
+
def grok(self, name, obj, **kw):
|
|
29
|
+
raise NotImplementedError
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class GlobalGrokker(GrokkerBase):
|
|
33
|
+
"""Grokker that groks once per module.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
def grok(self, name, obj, **kw):
|
|
37
|
+
raise NotImplementedError
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@implementer(IComponentGrokker)
|
|
41
|
+
class ClassGrokker(GrokkerBase):
|
|
42
|
+
"""Grokker that groks classes in a module.
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
def grok(self, name, class_, module_info=None, **kw):
|
|
46
|
+
module = None
|
|
47
|
+
if module_info is not None:
|
|
48
|
+
module = module_info.getModule()
|
|
49
|
+
|
|
50
|
+
# Populate the data dict with information from the directives:
|
|
51
|
+
for d in directive.bind().get(self.__class__):
|
|
52
|
+
kw[d.name] = d.get(class_, module, **kw)
|
|
53
|
+
return self.execute(class_, **kw)
|
|
54
|
+
|
|
55
|
+
def execute(self, class_, **data):
|
|
56
|
+
raise NotImplementedError
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class MethodGrokker(ClassGrokker):
|
|
60
|
+
|
|
61
|
+
def grok(self, name, class_, module_info=None, **kw):
|
|
62
|
+
module = None
|
|
63
|
+
if module_info is not None:
|
|
64
|
+
module = module_info.getModule()
|
|
65
|
+
|
|
66
|
+
# Populate the data dict with information from class or module
|
|
67
|
+
directives = directive.bind().get(self.__class__)
|
|
68
|
+
for d in directives:
|
|
69
|
+
kw[d.name] = d.get(class_, module, **kw)
|
|
70
|
+
|
|
71
|
+
# Ignore methods that are present on the component baseclass.
|
|
72
|
+
basemethods = set(util.public_methods_from_class(
|
|
73
|
+
component.bind().get(self.__class__)))
|
|
74
|
+
methods = set(util.public_methods_from_class(class_)) - basemethods
|
|
75
|
+
if not methods:
|
|
76
|
+
raise GrokError("%r does not define any public methods. "
|
|
77
|
+
"Please add methods to this class to enable "
|
|
78
|
+
"its registration." % class_, class_)
|
|
79
|
+
|
|
80
|
+
results = []
|
|
81
|
+
for method in methods:
|
|
82
|
+
# Directives may also be applied to methods, so let's
|
|
83
|
+
# check each directive and potentially override the
|
|
84
|
+
# class-level value with a value from the method *locally*.
|
|
85
|
+
data = kw.copy()
|
|
86
|
+
for bound_dir in directives:
|
|
87
|
+
d = bound_dir.directive
|
|
88
|
+
class_value = data[bound_dir.name]
|
|
89
|
+
data[bound_dir.name] = d.store.get(d, method,
|
|
90
|
+
default=class_value)
|
|
91
|
+
results.append(self.execute(class_, method, **data))
|
|
92
|
+
|
|
93
|
+
return max(results)
|
|
94
|
+
|
|
95
|
+
def execute(self, class_, method, **data):
|
|
96
|
+
raise NotImplementedError
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
@implementer(IComponentGrokker)
|
|
100
|
+
class InstanceGrokker(GrokkerBase):
|
|
101
|
+
"""Grokker that groks instances in a module.
|
|
102
|
+
"""
|
|
103
|
+
|
|
104
|
+
def grok(self, name, class_, **kw):
|
|
105
|
+
return self.execute(class_, **kw)
|
|
106
|
+
|
|
107
|
+
def execute(self, class_, **kw):
|
|
108
|
+
raise NotImplementedError
|
martian/context.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
from martian.directive import UnknownError
|
|
2
|
+
from martian.util import scan_for_classes
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class GetDefaultComponentFactory:
|
|
6
|
+
|
|
7
|
+
def __init__(self, iface, component_name, directive_name):
|
|
8
|
+
"""Create a get_default_component function.
|
|
9
|
+
|
|
10
|
+
iface - the iface that the component to be associated implements.
|
|
11
|
+
for example: IContext
|
|
12
|
+
component_name - the name of the type of thing we are looking for.
|
|
13
|
+
for example: context
|
|
14
|
+
directive_name - the name of the directive in use.
|
|
15
|
+
for example: grok.context.
|
|
16
|
+
"""
|
|
17
|
+
self.iface = iface
|
|
18
|
+
self.component_name = component_name
|
|
19
|
+
self.directive_name = directive_name
|
|
20
|
+
|
|
21
|
+
def __call__(self, component, module, **data):
|
|
22
|
+
"""Determine module-level component.
|
|
23
|
+
|
|
24
|
+
Look for components in module.
|
|
25
|
+
|
|
26
|
+
iface determines the kind of module-level component to look for
|
|
27
|
+
(it will implement iface).
|
|
28
|
+
|
|
29
|
+
If there is no module-level component, raise an error.
|
|
30
|
+
|
|
31
|
+
If there is one module-level component, it is returned.
|
|
32
|
+
|
|
33
|
+
If there are more than one module-level component, raise
|
|
34
|
+
an error.
|
|
35
|
+
"""
|
|
36
|
+
components = list(scan_for_classes(module, self.iface))
|
|
37
|
+
if len(components) == 0:
|
|
38
|
+
raise UnknownError(
|
|
39
|
+
"No module-level %s for %r, please use the '%s' "
|
|
40
|
+
"directive."
|
|
41
|
+
% (self.component_name, component, self.directive_name),
|
|
42
|
+
component)
|
|
43
|
+
elif len(components) == 1:
|
|
44
|
+
return components[0]
|
|
45
|
+
else:
|
|
46
|
+
raise UnknownError(
|
|
47
|
+
"Multiple possible %ss for %r, please use the '%s' "
|
|
48
|
+
"directive."
|
|
49
|
+
% (self.component_name, component, self.directive_name),
|
|
50
|
+
component)
|