Home Content Data science tip: store constants in their own file

Data science tip: store constants in their own file

by Jack Simpson

Sometimes when you work on large projects, you can end up with code that looks like this:

if num_values < 15:
    do_thing()

Now, what does the 15 mean? Well, I’m sure you would have known when you first wrote the code, but what happens in 3 months when you try to modify it or pass it on to someone else in your team? Also, what happens if you determine that the number should actually be 16? Now you have to go through all your files and swap numbers in all the right places (and if you miss any you can introduce subtle bugs).

So what’s the solution? Well, what you really need is a single source of truth for your clearly defined constants, which you can:

  • Easily look up
  • Modify/update
  • Import into other code

Python makes this really easy – all you have to do is create a “constants.py” file in your project directory (I suppose you could call it whatever you like, but that’s beside the point). From here, you can import your variables as if you were importing a library:

from constants import NOM_FREQ_HZ, VALUES_IN_MIN

A screenshot of this file from a recent project looks a little like this:

constants code file

This approach helped me write much more readable code, when working with an extremely complicated dataset where numbers were used to represent different value categories.

Obviously for smaller scripts it might not be worth setting up a dedicated file, but for this project, my constants file ended up being a couple of hundred lines long, and is far easier to maintain than if they were defined multiple times across all the files in the project.

Sign up to my newsletter

Sign up to receive the latest articles straight to your inbox

You may also like

Leave a Comment