Python 具有简化 class 创建规则的预处理器(领域特定语言)
Python preprocessor with rules to simplify class creation (domain specific language)
我正在为非常具体的应用程序构建介于 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):
super().__init__()
self.rect = ...
之类的东西。我需要那些特定的人能够用更简单的方言写作,我的工具将其翻译成常规 Python.
你正在尝试写方言。
您可以在一定程度上做到这一点,请参阅 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)
我正在为非常具体的应用程序构建介于 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):
super().__init__()
self.rect = ...
之类的东西。我需要那些特定的人能够用更简单的方言写作,我的工具将其翻译成常规 Python.
你正在尝试写方言。
您可以在一定程度上做到这一点,请参阅 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)