Importing a function from another folder

Viewed 1279

Let's say I have a structure like this:

tests----------------
                     ___init__.py
                     test_functions_a

functions-----------
                    ___init__.py
                    functions_a
                    functions_b

I want to test a function from functions_a, but inside functions_a I am importing a function from functions_b.

When I am trying:

from functions.functions_a import function_aa

I am getting an error, because inside functions_a I have a line:

from functions_b import function_bb

and not:

from functions.functions_b import function_bb

How can I solve this?

Any good practises are welcome, as I have no experience in structuring projects.

2 Answers

According to Google Python Style Guide, you should:

Use import statements for packages and modules only, not for individual classes or functions. Note that there is an explicit exemption for imports from the typing module.

You should also:

Import each module using the full pathname location of the module.

If you follow those two conventions, you will probably avoid, in the future, situations like the one you just described.


Now, here's how your code will probably look like if you follow those tips:

Module functions.functions_a:

from functions import functions_b as funcs_b

def function_aa():
    print("AA")

def function_aa_bb():
    function_aa()
    funcs_b.function_bb()

Module functions.functions_b:

def function_bb():
    print("BB")

And, finally, test_functions_a.py:

from functions import functions_a as funcs_a

if __name__ == "__main__":
    funcs_a.function_aa()
    funcs_a.function_aa_bb()

Output:

AA
AA
BB

You cannot directly import the function instead you could import File 1 to some other File and then call the function from that particular file you imported .

Related