Python元类和ModGrammar

13 投票
3 回答
4771 浏览
提问于 2025-04-16 23:37

我在StackOverflow上看到一个有趣的Python库,它的目的是用来解析语法。

http://code.google.com/p/modgrammar/

我还找到了一份关于这个库的教程:

http://packages.python.org/modgrammar/tutorial.html

看完这个教程后,我明白这正是我需要的!我尝试写了教程里的第一个例子:

from modgrammar import *
class MyGrammar (Grammar):
  grammar = (LITERAL("Hello,"), LITERAL("world!"))

但是我遇到了这个错误:

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

问题似乎出在元类的声明上。也许我在调用Python解释器时需要加一个“编译标志”?有什么好消息吗?! :) 谢谢

3 个回答

1

是的,这个是Python3的一个库,链接在这里:http://code.google.com/p/modgrammar/source/browse/setup.py#32

Python2.x不支持 class Grammar(metaclass=GrammarClass) 这个写法。

4

我把modgrammar这个工具移植到了Python 2.6及以上版本。这个移植的版本也可以在Python 3.x上使用。你可以在这里找到它:https://github.com/don-ramon/modgrammar-py2

19
class Grammar(metaclass=GrammarClass)

这里使用的是Python3的语法。相应的Python2语法是

class Grammar(object):
    __metaclass__=GrammarClass

不过因为可能还有很多其他Python3特有的写法,你可能需要用Python3来使用 modgrammar

撰写回答