How to access package level variable
Question:
Suppose i have package named src
src
- __init__.py
- app.py
__init__.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,
app.py
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
Answers:
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
import init
print(DATA_DIR)
The __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
:
# 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
:
# __init__.py
___version__ = "0.1.0"
from .cfg import *
Suppose i have package named src
src
- __init__.py
- app.py
__init__.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,
app.py
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
import init
print(DATA_DIR)
The __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
:
# 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
:
# __init__.py
___version__ = "0.1.0"
from .cfg import *