mmagician
mmagician

Reputation: 2120

Import a function from a module without module's dependencies

I would like to import a function foo() from module abc.py However, abc.py contains other functions which rely on modules which are not available for Python (i.e. I cannot import them into python interpreter, because I use ImageJ to run abc.py as Jython)

One solution I found is to put the problematic imports inside the name == "main" check, such as:

# abc.py
def foo():
    print("Hello, World!")

def run_main_function():
    foo()
    ...other stuff using IJ...

if __name__ == "__main__":
    from ij import IJ
    run_main_function()

So when I try to import foo from into another script def.py, e.g.:

# def.py
from abc import foo

def other_func():
    foo()

if __name__ == "__main__":
    other_func()

This works. But when I put imports in normal fashion, at the top of the script, I get an error: No module named 'ij'. I would like to know if there is a solution to this problem? Specifically, that I put the imports at the top of the script and then within def.py I say to import just the function, without dependencies of abc.py?

Upvotes: 0

Views: 2031

Answers (1)

I would like to know if there is a solution to this problem? Specifically, that I put the imports at the top of the script and then within def.py I say to import just the function, without dependencies of abc.py?

As far I know, it's the way that python works. You should put that import in the function that uses it if won't be aviable always.

def run_main_function():
    from ij import IJ
    foo()

Also, don't use abc as a module name, it's a standard library module: Abstract Base Class 2.7, Abstract Base Class 3.6

Edit: don't use trailing .py when importing as Kind Stranger stated.

Upvotes: 1

Related Questions