Skip to main content

Environment specific method calls

Recently I stumbled upon a problem that pandas.read_csv() changed its date parsing behaviour in version 2.0.0. Long story short there was a need to have an environment specific csv reading method calls. As it turns out there is a neat way to reach that behaviour via a core utility packaging. In production we have pandas version specified in a compatible release clause while in other places strict and newer version is present. We need these steps to set up a universal flow:

  1. Create specifier set that will match ~= versions
  2. Parse given environment package version
  3. Compare above 2 and do the mehtod call accordingly.

Long story short we need to have these lines to have environment specific method call:

from packaging.specifiers import SpecifierSet
from packaging.version import Version

ver = Version(pd.__version__)
if ver in SpecifierSet("~=1.3.5"):
    print("We are in the first environment with the older version of pandas.")
else:
    print("We are in the second environment with newer version of pandas.")

Elegant, no?

P.S. We know that we can’t have older than 1.3.5 version of pandas anywhere.