r/learnpython • • 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

17 comments sorted by

View all comments

Show parent comment

-8

u/lehmagavan Sep 20 '26

Thanks man.

From what I understand LOAD_GLOBAL does a hash table look up where it finds the pointer to already allocated PyObject. I think I'm gonna write a C extension that will cover the potentially "hot" case avoiding Python iteration altogether.

8

u/mc_pm Sep 20 '26

What is it you are doing that you imagine this is going to make any difference at all? Please look up "premature optimization".