The Situation
I want to have a module that roughly works like the following:
# my_module.py
my_number = 17
from other_module import foo
my_object = foo(23)
However, there is a problem: Installing other_module
causes problems for some users and is only required for those who want to use my_object
– which in turn is only a small fraction of users. I want to spare those users who do not need my_object
from installing other_module
.
I therefore want the import of other_module
to happen only if my_object
is imported from my_module
. With other words, the user should be able to run the following without having installed other_module
:
from my_module import my_number
My best solution so far
I could provide my_object
via a function that contains the import:
# in my_module.py
def get_my_object():
from other_module import foo
my_object = foo(23)
return my_object
The user would then have to do something like:
from my_module import get_my_object
my_object = get_my_object()
Question
Is there a better way to conditionally trigger the import of other_module
? I am mostly interested in keeping things as simple as possible for the users.