pythonpython-3.9

Python version 3.9 does not support match statements


I installed Python on a new computer and unfortunately I get an error message from a code that I had been using for quite some time. It is about the match statement. Here is the code:

import os

def save(df, filepath):
    dir, filename = os.path.split(filepath)
    os.makedirs(dir, exist_ok=True)
    _, ext = os.path.splitext(filename)
    match ext:
        case ".pkl":
            df.to_pickle(filepath)
        case ".csv":
            df.to_csv(filepath)
        case _:
            raise NotImplementedError(f"Saving as {ext}-files not implemented.")

Now my question is, how can I tackle the problem of "Python version 3.9 does not support match statements"?


Solution

  • Or just if and elif.

    import os
    
    def save(df, filepath):
        dir, filename = os.path.split(filepath)
        os.makedirs(dir, exist_ok=True)
        _, ext = os.path.splitext(filename)
        if ext == ".pkl":
            df.to_pickle(filepath)
        elif ext == ".csv":
            df.to_csv(filepath)
        else:
            raise NotImplementedError(f"Saving as {ext}-files not implemented.")