I found (after another question here on StackOverflow) this interesting library written in Python which goal is the grammar parsing.
http://code.google.com/p/modgrammar/
And I also found this tutorial regarding it:
http://packages.python.org/modgrammar/tutorial.html
So, after reading all the tutorial, I understood that this is what I'm looking for! I tried to write the first example in the tutorial:
from modgrammar import *
class MyGrammar (Grammar):
grammar = (LITERAL("Hello,"), LITERAL("world!"))
but I ran into this error:
Traceback (most recent call last):
File "test.py", line 1, in <module>
from modgrammar import *
File "/Users/tesi/Desktop/Prova/modgrammar/__init__.py", line 503
class Grammar(metaclass=GrammarClass):
^
SyntaxError: invalid syntax
The problem seems to be in the metaclass declaration. Might be I have to add a "compilation flag" when I call the python interpreter? Some good news?! :) Thx
A metaclass in Python is a class of a class that defines how a class behaves. A class is itself an instance of a metaclass. A class in Python defines how the instance of the class will behave. In order to understand metaclasses well, one needs to have prior experience working with Python classes.
To create your own metaclass in Python you really just want to subclass type . A metaclass is most commonly used as a class-factory. When you create an object by calling the class, Python creates a new class (when it executes the 'class' statement) by calling the metaclass.
In object-oriented programming, a metaclass is a class whose instances are classes. Just as an ordinary class defines the behavior of certain objects, a metaclass defines the behavior of certain classes and their instances.
type is a metaclass, of which classes are instances. Just as an ordinary object is an instance of a class, any new-style class in Python, and thus any class in Python 3, is an instance of the type metaclass.
class Grammar(metaclass=GrammarClass)
is using Python3 syntax. The equivalent Python2 syntax would be
class Grammar(object):
__metaclass__=GrammarClass
but since there may be lots of other Python3-isms, you may have to use Python3 to use modgrammar
.
I've backport modgrammar to Python 2.6+. Backport will also work with Python 3.x. You can find it here: https://github.com/don-ramon/modgrammar-py2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With