Suppose i have package named src
src - __init__.py - app.py
___version__ = '0.1.0' import os ENTRY_DIR = os.path.dirname(__file__) BASE_DIR = os path.dirname(ENTRY_DIR) DATA_DIR = os.path.join(BASE_DIR, 'data')
how can i access the variable DATA_DIR in app.py
I tried like this,
from src import DATA_DIR print(DATA_DIR)
It didn’t worked, i got an error.
ModuleNotFoundError: No module named ‘src’
How can i acces the variable inside the app module
it seems like you are referencing wrong path for that variable.
import the file in app.py
then you will be able to use variables from that file in same package.
use underscore with file name
__init__.py file is used to define how your package looks for an other one so you cannot do what you are trying to do since you are inside.
You can create a
cfg.py like this :
# cfg.py import os ENTRY_DIR = os.path.dirname(__file__) BASE_DIR = os path.dirname(ENTRY_DIR) DATA_DIR = os.path.join(BASE_DIR, 'data')
So you can import
DATA_DIR easily from
# app.py from cfg import DATA_DIR print(DATA_DIR)
If you need to use the variables defined in
cfg.py outside of your package you can modified the
# __init__.py ___version__ = "0.1.0" from .cfg import *