I've been programming in Python and ran into a problem that I think makes my code a lot more messy, and I'm trying to find a workaround. It's a large program, so instead of just dropping it here and making you sort through it I'll give a summary of my problem.
Basically, my program consists of 3 files.
The first, main.py, looks like this:
import util
import content
util.myfunc('unique parameters')
content.otherfunc()
The second, content.py, looks like this:
import util
def otherfunction()
util.myfunc('unique parameters')
What's happening is that I want to use the util module's functions in content and main.
The problem here is that, I have this messy problem where I can call all the stuff from util from content from main.
main.py:
import content
import util
content.util.myfunc()
but I don't want to have to do this because content is not related to util in the sense that it only imports it to use the functions. They do not have a shared purpose.
Also, this results in importing util twice.
I'm trying to get neater code and would like to find a solution WITHOUT importing util twice. Any ideas?
Do nothing. Your first code sample works fine, even if both modules happen to import the same utility module. It does so happen that content.util.myfunc() is valid, but you're unlikely to use it on your own, and that doesn't make it impossible to also call util.myfunc().
I also would not worry about having multiple import util lines. The import line appears once in each file where you call a util function. That's a clear rule, and it makes it easy to tell what your dependencies are even if you're directly importing a file for a unit test, or an alternate entry point, or something else.
If it really bothers you that it's possible to call content.util, you can use the __all__ special variable to limit the included module to only the specific things you want to export:
import util
def otherfunction() -> None:
util.myfunc('unique parameters')
__all__ = ["otherfunction"]
With this, if you import content, you will still be able to call content.otherfunction(), but content.util will no longer be defined and you can't invoke the module that way. (If you are extremely strict about API stability, then removing the import util statement from the intermediate module won't change the module API if it was not exported.)