Storing environment variables in a separate file and loading them into your notebooks is a good approach. Here are a few suggestions to improve your strategy:
1. Use a configuration file
Instead of hardcoding the variables in a Python file, consider using a configuration file in a format like JSON or YAML. This makes it easy to manage and switch between different configurations.
Create a file config.json:
{
"CANVAS_SIZE": [800, 600],
"PINK": "#FFC0CB",
"RED": "#FF0000"
}
2. Use a Python module for configuration
Create a Python module, e.g., config.py, that loads the configuration from the JSON file:
import json
def load_config(config_file='config.json'):
with open(config_file, 'r') as f:
config = json.load(f)
return config
config = load_config()
3. Use a context or a class for variable management
Instead of making the variables global, consider using a context or a class to manage the variables. This approach helps avoid polluting the global namespace.
Create a class Config:
class Config:
def __init__(self, config_file='config.json'):
self.config_file = config_file
self.load_config()
def load_config(self):
with open(self.config_file, 'r') as f:
self.config = json.load(f)
def __getitem__(self, key):
return self.config[key]
config = Config()
4. Use in your notebook
In your notebook, you can import the config module or class and access the variables:
from config import config
print(config['CANVAS_SIZE']) # [800, 600]
print(config['PINK']) # #FFC0CB
Alternatively, you can use the Config class:
from config import Config
config = Config()
print(config['CANVAS_SIZE']) # [800, 600]
print(config['PINK']) # #FFC0CB
5. Consider using environment variables
If you have sensitive information, like API keys, consider using environment variables instead of a configuration file. You can use libraries like python-dotenv to load environment variables from a .env file.
Example use case
Suppose you have multiple notebooks that use the same configuration. You can create a config.py file with the Config class and import it in each notebook:
# config.py
import json
class Config:
def __init__(self, config_file='config.json'):
self.config_file = config_file
self.load_config()
def load_config(self):
with open(self.config_file, 'r') as f:
self.config = json.load(f)
def __getitem__(self, key):
return self.config[key]
config = Config()
# notebook1.ipynb
from config import config
print(config['CANVAS_SIZE']) # [800, 600]
print(config['PINK']) # #FFC0CB
# notebook2.ipynb
from config import config
print(config['CANVAS_SIZE']) # [800, 600]
print(config['RED']) # #FF0000
This approach keeps your configuration in a single place and makes it easy to manage and switch between different configurations.