Python Best Practices – Defining Constants Based on Function Calls

python

In Python when writing file management scripts I will often have a base path that is a constant,

BASE = "C:/"

Of course I'll be using that base path to create other paths later on, including other paths that will change in no other place. So I define constants like this:

SUB_FOLDER = os.path.join(PROJECT_BASE, "folder")

However it feels like it may be contrary to define what is a constant based on the result of a function call, even if that call will return a fixed result and never be modified.

Is this considered poor style that would confuse people?

Best Answer

This would be considered a run-time constant: the value cannot be known before the program starts, but it is unchanging throughout the entire application once set.

The major advantage to a run-time constant is that it makes it obvious to a developer that the value is unchanging and that it enforces this in some way (to prevent erroneous assignments when the value has already been set), but you acknowledge that it cannot be known until run-time. Compare the value of Pi (which can be known and set before runtime) to the installation path of an application (which can only be figured out once the application starts, but not change when the application is running).

Your example perfectly fits the bill for this: it is a value that is set once and will never change throughout your application and therefore can look like a constant. Just note that this is not a true constant as Python does not have them and you will therefore need some kind of workaround to actually enforce their constant-ness.

Related Topic