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?
No, you can't redefine reserved words in Python. Their meaning is … drumroll … reserved, 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With