Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python metaclass and ModGrammar

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

like image 786
Dario Avatar asked Aug 15 '11 12:08

Dario


People also ask

What is __ metaclass __ in Python?

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.

How do you use metaclass in Python?

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.

What is metaclass in oops?

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.

Is type a metaclass in Python?

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.


2 Answers

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.

like image 119
unutbu Avatar answered Sep 20 '22 20:09

unutbu


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.

like image 25
Aleksey Rembish Avatar answered Sep 19 '22 20:09

Aleksey Rembish