lxg95
lxg95

Reputation: 573

How do i structure my Python submodule with a lot of files, so that i have to import only one module

I have a Python Project named osinttool which contains a folder named osinttool which contains the .py-files. In this folder, I have a folder named database that contains a file named db.py and there are several functions for creating entries in my database, deleting them and so on. In my other files, I just import like that 'from database import db' and that works fine.

The problem is, there is such a lot of code in db.py and I want to split up the code so that every different resource has its own file, but I still want to only import one module to use all of these databases function. It would be super nice if I don't even have to change anything in the files that use the DB-module.

How could I do that?

Upvotes: 0

Views: 768

Answers (1)

dspencer
dspencer

Reputation: 4471

I recommend converting db into a package in itself, with a directory structure like below, including an __init__.py file which provides the package's public API.

- db
    - __init__.py
    - dbtools.py

Suppose you have a module dbtools.py inside your db package, which defines a function initialize_db_connection. You could then create an __init__.py file at the same level with contents like:

from .dbtools import initialize_db_connection

You could then import this as from db import initialize_db_connection, even though the function is within a module in the package.

In the modules which already import as from database import db, your function would be accessible as db.initialize_db_connection.

Upvotes: 1

Related Questions