Binson Eldhose
Binson Eldhose

Reputation: 1013

How to organize package/modules in python

My life with python is just started. I am clueless about how to organize folders in python(flask)

My intention is to organize my application in following directory/file structure

srcenter image description here

server.py is the main file

database.py holding DB related sharable resources

customer.py is a simple python class which need DB instance from database.py

from ....shared.database import DB # How to solve this

class Customer():
    def __init__(self):
        self._first_name="John"

but I am getting an error Attempted relative import beyond top-level package

How do I make this works?!.

folder strucure representation

src
  app
    /modules
         /customers
              /models
                 customer.py
    /shared
       /database.py
  /server.py

Upvotes: 0

Views: 1047

Answers (2)

RITESH DUBEY
RITESH DUBEY

Reputation: 75

To declare your folder as the package you should add blank init.py files in each folder which contains any code that you want to call from other subfolders.

And if you are still not able to do it then, please see this other alternative.

You can try doing this as a quick way to access other source codes from other subfolders within the same module: Add this before doing your import if name == 'main': import os import sys sys.path.append(os.getcwd()) from app.shared.database import DB

Upvotes: 0

jobrachem
jobrachem

Reputation: 153

Your directories need to contain an __init__.py file in order to be recognized as packages and thus work with imports. The file can be empty.

More info on __init__.py here: What is __init__.py for?

Upvotes: 1

Related Questions