[Python-ideas] Classes returned from functions

Juancarlo Añez apalala at gmail.com
Tue Oct 7 01:38:04 CEST 2014


Grako is a PEG parser builder in Python:

https://bitbucket.org/apalala/grako

In grako, there's code to synthesize AST node types according to
annotations in the grammar whenever a type is not previously provided. This
is the code:

    def _get_nodetype(self, typename):
        typename = str(typename)
        if typename in self.nodetypes:
            return self.nodetypes[typename]

        # synthethize a new type
        nodetype = type(typename, (self.baseType,), {})
        self._register_nodetype(nodetype)
        return nodetype

It works, but the classes thus created are "weird". I don't remember the
details right now, but I think they don't have a proper module or qualname.

This particular feature (exploiting this Python capability) is very useful
in the early stages of developing a parser, while most of the work goes
into debugging the grammar. Having a nice AST produced cheaply is of great
value.

Cheers,

-- 
Juancarlo *Añez*
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20141006/7d52b5fe/attachment.html>


More information about the Python-ideas mailing list