Making your own statements

2020-02-14 18:27发布

Is there a way to define new statements like def, with, for of my own in Python? Of course, I don't mean to override the existing statements, only create some of my own.

If so, how do I do it? Can you point me to good docs on the subject?

5条回答
戒情不戒烟
2楼-- · 2020-02-14 18:41

While you can't modify the syntax of Python itself (without recompiling as Alex has mentioned), you can use metaprogramming techniques. Below is a link to a presentation on creating a DSL in Python.

http://blog.brianbeck.com/post/53538107/python-dsl-i

If you're not married to Python, Ruby is a great language for defining DSL's, as it has broader metaprogramming capabilities.

http://www.themomorohoax.com/2009/02/25/how-to-write-a-clean-ruby-dsl-rails

查看更多
别忘想泡老子
3楼-- · 2020-02-14 18:50

Ren'Py is an example of an extension for Python that allows custom statements by implementing its own parser and compiler.

查看更多
劫难
4楼-- · 2020-02-14 18:52

There are programming languages that let you do this (Tcl, for example), but Python isn't one of those languages.

查看更多
我只想做你的唯一
5楼-- · 2020-02-14 18:53

You can't (re)define language keywords without rewriting a compiler/interpreter/etc. What you could do perhaps is write a something like a DSL (domain-specific language) and something that translates your keyword statements into proper python statements, which might be an easier route.

查看更多
姐就是有狂的资本
6楼-- · 2020-02-14 18:56

No, you cannot add new syntax within a Python program. The only way to alter the language is to edit and recompile the grammar file and supporting C code, to obtain a new altered interpreter, compiler and runtime.

查看更多
登录 后发表回答