Vlad Vladimir Hercules
Vlad Vladimir Hercules

Reputation: 1869

How to import files from other folders

Introduction

I am using Python 3.9. I have seen quite a few answers online but I am struggling to make it work for me.

I saw that you can set default PYTHONPATH (PYTHONPATH=. python app/models/TestModel.py) but it sounds very hacky and I don't see how that would work should other devs try to use the code...

As someone who comes from a world of composer and node, I was expecting files to be pulled from a route dir but there seem to be some magic in the background that I am missing.

Issue

I have the following dir structure:

Within BaseModel.py I print hello world:

print("Hello World")

Within TestModel.py I am trying to import my BaseModel

import modules.commons.models.BaseModel

The output if I am to call TestModel.py via CLI is below:

import modules.commons.models.BaseModel
ModuleNotFoundError: No module named 'modules'

Upvotes: 0

Views: 86

Answers (1)

Glenn Gribble
Glenn Gribble

Reputation: 390

Try python -m app.models.TestModel from the top of your package. In this case, python adds the current directory to the sys.path.

When you run python app/models/TestModel.py, python assumes app/models is the top of your package and adds ./app/models to sys.path.

Alternatively, you can put all your main entry points at the top level.

Upvotes: 1

Related Questions