Trouble Splitting Up Code
> But the problem with this is that db is undefined.

Because you're not returning anything...

This is not peewee-specific but a general question about Python module organization. When you have dependencies like this, the typical solution is to introduce a third module that composes the two (db and main).
The issue I'm running into is pretty specific to my use case and I'm not sure how many it would affect. I'm creating AWS Lambda functions that insert/query from the database. I have my code separated into multiple files so that different lambda functions can re-use code. Here's a very simplified example.

db.py
```python
import os
from peewee import PeeweeException, Model, MySQLDatabase

hostname = os.environ["DB_HOST"]
username = os.environ["DB_USER"]
password = os.environ["DB_PASSWORD"]
database = os.environ["DB_DATABASE"]

try:
    db = MySQLDatabase(
        database=database,
        user=username,
        password=password,
        host=hostname,
        charset="utf8",
        use_unicode=True,
    )
except PeeweeException as e:
    raise


class BaseModel(Model):
    class Meta:
        database = db
```

main.py
```python
import json
import os

import service
from db import db


def handler(event, context):
    try:
        db.connect()
        response = service.run(db, event)
        db.close()
    except Exception as e:
        return {
            "statusCode": 500,
            "body": json.dumps(
                {
                    "code": "InternalFailure",
                    "message": "Internal server error",
                }
            ),
        }

    return response
```

I'm excluding a few files(`model.py`, `service.py`) but `service.run(db, event)` imports model and inserts/queries the database using the models it imports.

The problem occurs when I try to write unit tests for main.py. Since main.py imports db, it immediately tries to read environment variables. So when my unit tests import main to test it, immediately my unit tests fail because those environment variables don't exist. I could easily mock out `os` but I don't think main.py should be calling db.py immediately anyways. So I've tried wrapping some code in db.py in a get_connection() function:

```python
def get_connection():
    hostname = os.environ["DB_HOST"]
    username = os.environ["DB_USER"]
    password = os.environ["DB_PASSWORD"]
    database = os.environ["DB_DATABASE"]

    try:
        db = MySQLDatabase(
            database=database,
            user=username,
            password=password,
            host=hostname,
            charset="utf8",
            use_unicode=True,
        )
    except PeeweeException as e:
        raise

class BaseModel(Model):
    class Meta:
        database = db
```

But the problem with this is that db is undefined. Anyways, the long story short: I've tried a lot of things and I'm unable to figure it out and was wondering if you had any tips for me?