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?
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?
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.
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.
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
Ren'Py is an example of an extension for Python that allows custom statements by implementing its own parser and compiler.
There are programming languages that let you do this (Tcl, for example), but Python isn't one of those languages.