Sibbs Gambling
Sibbs Gambling

Reputation: 20355

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?

Upvotes: 1

Views: 97

Answers (1)

Alexander
Alexander

Reputation: 109546

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

Upvotes: 1

Related Questions