Protecting Constant Variables

Why protect certain variables?

When reading data from a file (like a CSV), it's common to want to keep an intact copy of the original data, even after processing it.

If we accidentally modify a variable containing important data, we risk losing information and making the program difficult to fix.

Protecting a variable doesn't mean it's "really" constant in Python, but that we adopt conventions to avoid modifying it by mistake.

Convention: write in uppercase

In Python, it's customary to write the names of variables we want to consider as constants entirely in uppercase.

Example:

ORIGINAL_DATA = ["Name", "Firstname", "Age"]

This indicates to code readers (and ourselves!) that this variable should not be modified.

Use a tuple instead of a list

A tuple is an immutable structure in Python: we cannot modify its content after creation.

Thus, to protect a set of fixed values, it's preferable to use a tuple:

EXPECTED_COLUMNS = ("Name", "Firstname", "Age")
Warning: if the tuple contains objects that are themselves modifiable (like lists), their content can be modified. The tuple only makes the "structure" immutable.

Clearly name transformation steps

When processing data (cleaning, sorting, typing...), it's useful to create new variables at each step, with precise names.

For example:

csv_data = load_csv("file.csv")
cleaned_data = clean(csv_data)
typed_data = type(cleaned_data)

This allows:

  • keeping previous versions if needed,
  • better understanding the sequence of transformations,
  • limiting errors by directly modifying the right data.
Each variable should have a name that recalls the processing step it represents.

Summary

TipAdvantage
Uppercase for constantsVisually identifiable in code
Use a tupleProtects against accidental modifications
Name steps clearlyPromotes clarity and security