Sibbs Gambling Sibbs Gambling - 1 year ago 68
Python Question

Import function from another file that itself imports unavailable modules?

I wrote some functions in

a.py
. I run
a.py
with my generic python binary. Inside
a.py
, I have

import some_module

def simple_function():
...

def complex_function():
some_module.some_func()


Now, I want to import
simple_function()
into
b.py
, which has to be run with another python (a software-bundled installation), and this python doesn't have
some_module
installed.

When I run
b.py
(which contains line
from a import simple_function
) with the software-bundled python, I received this error, as expected.

ImportError: No module named 'some_module'


Is there a way around it? As you see,
simple_function()
does not need
some_module
.




One solution I can think of is to put the import statement inside
complex_function
.

def simple_function():
...

def complex_function():
import some_module
some_module.some_func()


But I'm sure linters and format checkers will complain about it. Better solutions?

Answer Source

Solution is to split the complex function into a separate module on its own.

When you import a function within a module, you are importing the entire module.

Other solution is to install some_module in the other python installation...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download