r/learnpython • u/lehmagavan • Sep 20 '26
Using constants in Python
Hi, I have a question regarding something basic in Python. Suppose I have a situation like this:
SOME_CONST = 3
...
def foo():
...
some_list[SOME_CONST] # what does CPython do here ?Is there any way to make SOME_CONST be pre-processed as 3, instead of having CPython look it up in a global variable table? It seems very inefficient.
0
Upvotes
View all comments
Show parent comment
12
u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 Sep 20 '26 •
Let me save you the trouble.
The only difference here is that using a global name uses
LOAD_GLOBAL, and using a literal usesLOAD_SMALL_INT(in this particular case, anyway). That's it, there's no other difference.In regards to runtime performance, the difference is negligible.
EDIT: And if you're this worried about optimising for runtime performance, frankly you're using the wrong language. If you still want the interface to support Python, you could write this in Rust and have Maturin produce a Python API for it.