Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to redefine keywords in Python?

I ran into an issue wherein I had to jsonify everything that my API was set to return. As I was writing a decorator and applying it to every single method, a thought occurred to me:

"Can't I just overwrite the return keyword so that it performs this operation for me every time?"

I did some searching, but I can't find anything on the topic. However, since "everything is an object", maybe it's possible?

Obviously overwriting return is a bad idea but in a more general sense, my question is:

Can you alter the behavior of reserved words and keywords in Python?

like image 336
Simon Avatar asked Aug 23 '18 18:08

Simon


1 Answers

No, you can't redefine reserved words in Python. Their meaning is … drumrollreserved, so by definition it cannot be altered.

The closest I can find to an explicit declaration of this fact in the official documentation is in the Lexical Analysis chapter of the Language Reference (emphasis mine):

2.3.1. Keywords

The following identifiers are used as reserved words, or keywords of the language, and cannot be used as ordinary identifiers. They must be spelled exactly as written here:

False      await      else       import     pass
None       break      except     in         raise
True       class      finally    is         return
and        continue   for        lambda     try
as         def        from       nonlocal   while
assert     del        global     not        with
async      elif       if         or         yield

Since keywords cannot be used as ordinary identifiers, they cannot be assigned to, be used as function names in def statements, etc.

It's important to understand that it's the fundamental nature of keywords which actually prohibits changes to their meaning, though – that assignment and so on won't work is a consequence of that nature, not the cause of it.

like image 193
Zero Piraeus Avatar answered Oct 21 '22 05:10

Zero Piraeus