In python, can I import to parent stack frame for automating shared imports and variable setting?

33 views Asked by At

I have a bunch of shared imports used in multiple different Jupyter notebooks. It would be nice for me and for users to collect these in one place so that users of the notebooks (exercises) could just do something like

from ne1 import setup_exercise
setup_exercise()

instead of having a cell in each notebook like this one:

import time # for time.sleep(seconds)
import numpy as np # numpy for arrays etc
from scipy import stats # for stats.linregress
import matplotlib
import matplotlib.pyplot as plt # for plotting
import matplotlib
plt.rcParams.update({'font.size': 12}) # make the detault font size larger for your readers
matplotlib.rcParams['pdf.fonttype'] = 42 # save fonts as type that are not outlined in illustrator or other drawing programs
from engineering_notation import EngNumber as ef # format numbers in engineering format quickly, e.g. ef(2e-9)='2n'
from pathlib import Path # used for saving data

datapath = Path('data/lab3') # make a data folder to save your data called data/lab1
datapath.mkdir(parents=True, exist_ok=True)
from jupyter_save_load_vars import savevars, loadvars

from ne1 import Coach # import Coach() class
import logging
p=Coach(logging_level=logging.INFO) # create a Coach object called p; you will use it to talk to class chip, change to logging.DEBUG for troubleshooting

The setup_lab() should import the packages to its parent frame and set the variable datapath and p in it.

Note: I don't want to import from a parent folder, I want to import to and set variables in a parent stack frame.

Is there any way to do this? It might involve using inspect, e.g. with the f_back field

    import inspect
    frame = inspect.currentframe().f_back

but I don't know what do do from here.

0

There are 0 answers