Skip to content

Move the mongo, redis, sqlite3 imports to __init__ of the savers #81

Description

@M1h4n1k

Problem

Currently if I do raw uv add spotapi and then try to import spotapi it will fail with:

Traceback (most recent call last):
  File "<frozen runpy>", line 198, in _run_module_as_main
  File "<frozen runpy>", line 88, in _run_code
  File "...", line 7, in <module>
    import spotapi
  File "...\spotapi\__init__.py", line 1, in <module>
    from spotapi.artist import *
  File "...\spotapi\artist.py", line 7, in <module>
    from spotapi.client import BaseClient
  File "...\spotapi\client.py", line 10, in <module>
    from spotapi.utils.logger import Logger
  File "...\spotapi\utils\__init__.py", line 2, in <module>
    from spotapi.utils.saver import *
  File "...\spotapi\utils\saver.py", line 9, in <module>
    import pymongo
ModuleNotFoundError: No module named 'pymongo'

Reason

It's happening because of imports here

import pymongo
import redis
import sqlite3

Workaround

I do not plan to use any of those savers, so I don't want to install additional dependencies, as a workaround this works:

import sys
from unittest.mock import MagicMock


sys.modules["pymongo"] = MagicMock()
sys.modules["sqlite3"] = MagicMock()

# import only after mocking not needed libraries
import spotapi # noqa: E402

How to solve?

Claude suggests to move the imports to the __init__ of the corresponding savers, need to check. Like this:

class SqliteSaver(SaverProtocol):
    # ...

    def __init__(self, path: str = "sessions.db") -> None:
        import sqlite3  # maybe wrap in a try-catch block to inform about missing dependencies

        self.conn = sqlite3.connect(self.path, check_same_thread=False)
        # ...

Also, I believe, it's usually done via pyproject with optional dependencies, like pip install spotapi[pymongo], or pip install spotapi[redis], etc. I can take a look in a ~month

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions