Making your own statements

后端 未结 5 489
情深已故
情深已故 2020-12-21 15:03

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 sta

相关标签:
5条回答
  • 2020-12-21 15:29

    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

    0 讨论(0)
  • 2020-12-21 15:38

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

    0 讨论(0)
  • 2020-12-21 15:45

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

    0 讨论(0)
  • 2020-12-21 15:46

    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.

    0 讨论(0)
  • 2020-12-21 15:48

    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.

    0 讨论(0)
提交回复
热议问题