6

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?

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
Simon
  • 855
  • 9
  • 24
  • 4
    Nope.....unless you fork the python project and rewrite the return keyword, will work but only if you want to return json everywhere....lol – Rodrigo Alencar Aug 23 '18 at 18:50
  • 1
    Is it a class? You can decorate all methods in a class with a [single decorator.](https://stackoverflow.com/questions/6307761/how-can-i-decorate-all-functions-of-a-class-without-typing-it-over-and-over-for) – bison Aug 23 '18 at 19:00
  • @Grant McCloskey I'm not so much trying to solve a specific problem here as gain a better understanding of the language as a whole. I wrote my thought process out so people can understand what I'm asking. – Simon Aug 23 '18 at 19:09
  • Yep, I was just trying to think of other alternatives to the origin of the question because I have hit similar. – bison Aug 23 '18 at 19:32
  • I was a little surprised that I couldn't find a duplicate for this question, so I've expanded a little on the comment by @RodrigoAlencar to make it a "proper" answer. – Zero Piraeus Aug 26 '18 at 13:02

1 Answers1

6

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.

Community
  • 1
  • 1
Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160