Home > other >  Python version 3.9 does not support match statements
Python version 3.9 does not support match statements

Time:11-11

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"?

CodePudding user response:

Match statements are a feature of Python 3.10. You'd do best by upgrading to 3.10 or 3.11.

https://monovm.com/blog/how-to-update-python-version/

CodePudding user response:

The simple answer: upgrade to Python 3.10.

If you cannot upgrade, then you can use a Python dictionary as alternative:

MATCH = {
    '.pkl': df.to_pickle
    '.csv': df.to_csv
}

_, ext = os.path.splitext(filename)

try:
    MATCH[ext](filepath)
except KeyError:
    raise NotImplementedError(f"Saving as {ext}-files not implemented.")

CodePudding user response:

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.")
  • Related