samman
samman

Reputation: 613

Do imports carry over when importing a script

From my understanding, when you are importing a script to run, from another script, the imports will carry over to the new script. I.E. I import pandas in the script below, and now pandas is imported to the new script, so I no longer need to write "import pandas as pd" in the new script.

I know there is this answer: Do a python module's imports need to be carried over when importing that module? but that appears to be discussing custom imports (e.g. from app-helper). I'm discussing more general imports like os, pandas, numpy, time, sys, etc.

import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import time
import sys

if input('Will you be using the free or bound state peaks? (Type in "Free" or "Bound")\n').lower() != 'free':
    import slow_exchange_bound
    sys.exit()

#rest of the script

Based on the above script though, if I don't have all the import lines in my slow_exchange_bound script, then it doesn't run properly (i.e. in slow_exchange_bound, I have to reinput import os, import pandas, etc.)

Upvotes: 0

Views: 623

Answers (1)

chepner
chepner

Reputation: 531165

You still need import pandas as pd, etc in slow_exchange_bound so that the name pd is available in the global namespace of slow_exchange_bound. The "carryover" comes from the fact that the module is only evaluated once; subsequent imports find the module in sys.modules already and simply add a reference to the module to the relevant namespace.

Upvotes: 3

Related Questions