Is it possible to redefine keywords in Python?
Asked Answered
G

1

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?

Grenier answered 23/8, 2018 at 18:47 Comment(5)
Nope.....unless you fork the python project and rewrite the return keyword, will work but only if you want to return json everywhere....lolGowon
Is it a class? You can decorate all methods in a class with a single decorator.Crystallize
@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.Grenier
Yep, I was just trying to think of other alternatives to the origin of the question because I have hit similar.Crystallize
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.Credit
C
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.

Credit answered 26/8, 2018 at 12:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.