Connecting and getting mysql connection object I have written this code that connects to a mysql database. The function should be able to be used as a context manager - via with. It is working, but I am not sure if this is a great way of doing it.

conect.py

import os
import mysql.connector
from mysql.connector import errorcode
import contextlib

_CFG = {
  'user': os.getenv("MYSQL_USER"),
  'password': os.getenv("MYSQL_PASSWORD"),
  'host': os.getenv("MYSQL_SERVER"),
  'database': os.getenv("SENSOR_DB"),
  'raise_on_warnings': True
}

@contextlib.contextmanager
def _connect(db=None):
    if db:
        _CFG["database"] = db

    try:
        print("{usr} connecting to {db} on {host}.".format(
            usr=_CFG["user"],
            db=_CFG["database"],
            host=_CFG["host"]
            )
        )
        connection = mysql.connector.connect(**_CFG)
        yield connection
    except mysql.connector.Error as err:
        if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
            print("Something is wrong with your user name or password")
        elif err.errno == errorcode.ER_BAD_DB_ERROR:
            print("Database does not exist")
        else:
            print(err)
        yield None
    else:
        connection.commit()
    finally:
        connection.close()
Obvious (dumb) point - I'd suggest using logging instead of print
I would have some kind of builder for _CFG so I could choose if I use environment variables for configuration or something else
Instead of str.format, you may want to use fstring: f"{_CFG["user"]} connecting to {_CFG["database"]} on {_CFG["host"]}."
Instead of yield None you may want to reraise exception (from the docs, "If an exception is trapped merely in order to log it or to perform some action (rather than to suppress it entirely), the generator must reraise that exception"). Otherwise, your code will fail with a funny exception.