Reputation: 187
I would like to call a function in Python like a keyword. For motivation I have following problem:
Multiple variables can be deleted at once by using the keyword del
.
x1,x2=1,1
del x1,x2
However,
x1,x2=1,1
del x1,x2,x3
leads to a name error if x3
is not defined. The convenience function Del
deletes multiple variables independently of their existence (see this SE post):
def Del(*d:list[str])->None:
for i in d:globals().pop(i,None)
I can now call
x1,x2=1,1
Del('x1','x2','x3')
without getting an error message about non-existence of x3
. However, for my new command Del
I have to use brackets and quotes whereas for del
I don't need them. The reason is that Del
is a function, whereas del
is a keyword.
How could I define Del
as a keyword to call it like Del x1,x2,x3
? Of course, any other method that saves quotes or brackets is welcome.
Upvotes: 2
Views: 75
Reputation: 2235
You cannot extend the grammar of Python via Python code.
Python is a mix between an interpreted and compiled language. This means that a process or program must convert the source code into another form before it can be executed. It is this process that ultimately understands the grammar that makes up Python (including all of the keywords, statements, and other syntax).
In order to extend or change the grammar, you need to change/modify the source code of that process. This is possible, but is not something that would be easy to do (you would have to modify the C code from which the Python binary is built). Additionally, even if you were successful, you could only use the new grammar for programs run using your custom binary. Anyone else running your code would receive syntax errors.
Upvotes: 2