views:

146

answers:

5

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  A: 

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.

Alex Martelli
And give it a new name, that's nothing like the word "python". Please don't confuse us with a language that's "mostly python" but otherwise incompatible because of some new syntax.
S.Lott
try pythong, potang, pifun, haha
Matt Joiner
Yes, pythong is good. As is phyton, for the elementary particle of vegetation :)
ΤΖΩΤΖΙΟΥ
+3  A: 

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.

Davy8
+1  A: 

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

Alison R.
... and if you're really serious about DSLs, consider Tcl as well. It lets you create your own core commands, such as your own if statements, your own while and repeat loops, etc. There are no reserved words in Tcl so you can reinvent absolutely anything.
Bryan Oakley
A: 

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

Ignacio Vazquez-Abrams
A: 

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

Bryan Oakley