Python预处理器,具有简化类创建的规则(特定于域的语言)

2024-09-29 21:49:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为非常特定的应用程序在Python库和DSL(领域特定语言)之间构建一些东西,这样我们就可以避免:

class Car(RoomObject):
    def __init__(self):
        super().__init__()
        self.rect = rect(-20, -20, 40, 40)
        self.zindex = -10
        self.pos = self.rect.midbottom  
        _tempvar = 123
    def do(self, x)
        self.foo = x

取而代之的是:

class Car(RoomObject):  # 1) avoid the def and self, all nested paragraphs in class are def 
    init():             # 2) __init__ -> init        3) automatically do the super init
        rect = rect(-20, -20, 40, 40)  # 4) assignations are self. by default...
        zindex = -10
        pos = rect.midbottom  
        _tempvar = 123                 # 5) ...except if variable name begins with _
    do(x):                             # ==> def do(self, x):
        foo = x                        # ==> self.foo = x

是否可以使用内置Python库,例如inspect(代码内省)或预处理器(如果有)来完成此操作?


背景:这是一个利基市场,我不能要求非技术人员一直写像def __init__(self):{}{}这样的东西。我需要那些特定的人能够用更简单的方言编写,我的工具将其翻译成常规的Python


Tags: theposrectselffooinitdefcar
1条回答
网友
1楼 · 发布于 2024-09-29 21:49:33

你在试着写一种方言

在某种程度上可以这样做,请参见https://pypi.org/project/pypreprocessor/的实现

你可以这样写:

import mypreprocessor
mypreprocessor.parse()

class Car(RoomObject):  # 1) avoid the def and self, all nested paragraphs in class are def 
    init():             # 2) __init__ -> init        3) automatically do the super init
        rect = rect(-20, -20, 40, 40)  # 4) assignations are self. by default...
        zindex = -10
        pos = rect.midbottom  
        _tempvar = 123                 # 5) ...except if variable name begins with _
    do(x):                             # ==> def do(self, x):
        foo = x                        # ==> self.foo = x

然后在mypreprocessor.parse()中:

def parse():
    ... load current file
    ... preprocess
    ... call exec()
    ... sys.exit(0)

相关问题 更多 >

    热门问题