I'd like to figure out the cleanest and preferably self contained way to use my packages in scripts that are in a different directory to the package itself.
The example problem is as follows:
The modules in lib
need to both be imported, and run as a script.
My project directory is as below and I'm having two issues:
- in
lib/api.py
, I want to read indata_files/key.txt
correctly whenapi.py
is called or imported - in
testing_script.py
I want to import and uselib/get_data.py
I can't seem to find a clean way to do this, does this mean my project is structured in a non-pythonic way?
Thanks for the help.
my-project-git
├── LICENSE
├── README.md
├─── my_project
│ ├── data_files
│ │ ├── key.txt
│ │ ├── mappings.csv
│ ├── lib
│ │ ├── __init__.py
│ │ ├── api.py
│ │ └── get_data.py
│ └── test
│ ├── __init__.py
│ └── testing_script.py
├── requirements.txt
└── setup.py
As far as I know, there's isn't a pythonic way to structure your project.
This is what Kenneth Reitz recommended in 2013 and it's how I use it: https://www.kennethreitz.org/essays/repository-structure-and-python.
Inside
sample
(my_project
in your case) you can separate into categories as you like. E.g. Utils (common functions), Database (read, write), View (user commands), etc. It depends on your project.As for calling the modules at the same level, you should define them in the
__init__
file of the top hierarchy module which issample
in this case.For example:
__init__
in _my_project
then from
/test/test_basic.py
you do:Take a look at the sample module repository: https://github.com/navdeep-G/samplemod