I've been wondering, if using multiple subfiles in a project to make the code look clean, why I have to import each module e.g. logging or time in each subfile explicitly. is there no way to make the subfile.py aware of the imports of main.py. See an example below where I want to use import time globally
main.py
import logging
import time
from subfile import myfunc
myfunc("Test")
subfile.py
import logging
def myfunc(var):
logging.info("entered myfunc")
time.sleep(2)
logging.info("Variable: {}".format(var))
CodePudding user response:
It's better when all dependencies are explicit. Let's imagine that subfile implicitly uses time from main, like you want. This causes problems:
- You can't unit-test
subfileanymore, because it can't work separately frommainand dependencies defined there. You would have toimport timein the testing module. Nowmainandtestsboth have that import, instead of justsubfile. - If (for some reason) you decide to remove
import timefrommain,subfilebecomes broken, but there's no way you can know that, unless you run some code analyser on the whole project. The current model allows you to find missing dependencies just by scanning one file and the directory structure.
If you really have a lot of common dependencies (e.g. you need time, logging, and 10 other packages in every file), this thread: How to share imports between modules? can help with managing that.
