How do I import and run a Python function and have all the dependencies it uses use the imports from the main Python file?
Main Python file:
from im import er
import time
er()
Python file with function to be imported:
def er():
time.sleep(1)
print('hi')
This doesn't work because the time module is not imported in the im.py. How can I make this work without importing the modules it needs each time I run the function?
You have to import the function in the main, and required module for the function in the function file.
Main Python file:
from im import er
er()
Imported module :
from time import sleep
def er():
sleep(1)
print('hi')
This behave this way because Python run the imported module when you import it. Then, depending of your import statement, it will do:
import <module>: create a module object named <module> with attributes allowing you to access global scope of this module. If a function is in the global scope of the module, you access it with <module>.<function_name>.from <module> import *: add to the global scope of the current module the global scope of the imported module (not exactly, but if you need more informations about it, look for wildcard import behaviour). As a good rule of thumb with this import: don't use this.from <module> import <symbol>: add the symbol of the imported module to the global scope of the current module.More info about imports:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With