Kim Vallée
Kim Vallée

Reputation: 455

Best and fastest way to use constants

Here are the files I have for the moment:

main.py
functions.py
constants.py

I am working on a project in python which requires some constants and I decided to stock them in a python file called constants.py which looks like:

A = 5
B = 6
C = 7
# etc.

This file is both imported as a module in functions.py and main.py However I would like to add some scripting and change these constants in main.py with parameters for examples, but if I change these constant in main.py they don't change anyway in functions.py which uses it a lot And I didn't find any solution to that problem yet, so I am using a dictionary but dictionary takes 3 times longer to access a variable i.e:

timeit.timeit(stmt='b = a[5]; b = 0', setup="a = {5:5}", number=5000)
# 0.000302988540795468
timeit.timeit(stmt='b = a; b = 0', setup="a = 5", number=5000)
# 0.00013507954133143288

Upvotes: 0

Views: 320

Answers (1)

Alex Hall
Alex Hall

Reputation: 36013

Putting aside the fact that these are not constants, you are probably changing the wrong thing when you're trying to change the values accross files. Use import constants and always refer to constants.A and changes to constants.A will be reflected everywhere. Do not do from constants import A and do not do A = constants.A; A = 10 and expect that to change A to 10 everywhere. Rather do constants.A = 10.

Upvotes: 2

Related Questions