spaceKelan
spaceKelan

Reputation: 187

Using seperate files per function - global import

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))

Upvotes: 1

Views: 55

Answers (1)

Expurple
Expurple

Reputation: 921

It's better when all dependencies are explicit. Let's imagine that subfile implicitly uses time from main, like you want. This causes problems:

  1. You can't unit-test subfile anymore, because it can't work separately from main and dependencies defined there. You would have to import time in the testing module. Now main and tests both have that import, instead of just subfile.
  2. If (for some reason) you decide to remove import time from main, subfile becomes 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.

Upvotes: 2

Related Questions