Debian Codegraph @

gavo/grammars/customgrammar.py

raw
1 """
2 A grammar that imports a user-defined module and takes the RowIterator
3 from there.
4
5 The module has to define a RowIterator derived from CustomRowIterator. It may
6 define a function makeDataPack receiving the grammar as its argument and
7 returning anything. This anything will then be available as
8 self.grammar.dataPack to the row iterator. Use this for expensive, one-time
9 preparations your row iterator has to perform.
10 """
11
12 #c Copyright 2008-2025, the GAVO project <[email protected]>
13 #c
14 #c This program is free software, covered by the GNU GPL. See the
15 #c COPYING file in the source distribution.
16
17
18 from gavo import base
19 from gavo import rscdef
20 from gavo import utils
21 from gavo.grammars import common
22
23
24 _knownModules = {}
25
26
27 def getModuleName():
28 i = 0
29 while True:
30 name = "usergrammar%d"%i
31 if name not in _knownModules:
32 _knownModules[name] = None
33 return name
34
35
36 class CustomGrammar(common.Grammar, base.RestrictionMixin):
37 """A Grammar with a user-defined row iterator taken from a module.
38
39 See the `Writing Custom Grammars`_ (in the reference manual) for details.
40 """
41 # To save on time when initializing the grammar (which happens at
42 # RD parsing time), we delay initializing the user grammar to when
43 # it's actually used (which happens much less frequently than loading
44 # the RD).
45
46 name_ = "customGrammar"
47
48 _module = rscdef.ResdirRelativeAttribute("module", default=base.Undefined,
49 description="Path to module containing your row iterator.", copyable=True)
50 _isDispatching = base.BooleanAttribute("isDispatching", default=False,
51 description="Is this a dispatching grammar (i.e., does the row iterator"
52 " return pairs of role, row rather than only rows)?", copyable=True)
53
54 def _initUserGrammar(self):
55 self.userModule, _ = utils.loadPythonModule(self.module)
56 self.rowIterator = self.userModule.RowIterator
57 if hasattr(self.userModule, "makeDataPack"):
58 self.dataPack = self.userModule.makeDataPack(self)
59
60 def parse(self, *args, **kwargs):
61 if not hasattr(self, "userModule"):
62 self._initUserGrammar()
63 return common.Grammar.parse(self, *args, **kwargs)
64
65
66 class CustomRowIterator(common.RowIterator):
67 """is a base class for custom row iterators.
68
69 Implement at least _iterRows. And pass on any keyword args to __init__
70 to the next constructor.
71 """