Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, import functions from modules

I have many modules (hundreds). In each module I have at least one function. My question is how can I import all functions from all modules with only one line? Because I do not want to do it like this:

from tests.test_001 import test_001_func
from tests.test_002 import test_002_func
from tests.test_003 import test_003_func
...
from tests.test_999 import test_999_func

test_xxx are modules and these modules contains test_xxx_func function, all modules are in one folder.

I would like use something like this:

from tests import *
test_001.test_001_func()

But this is not working

like image 336
Lodhart Avatar asked Nov 11 '22 09:11

Lodhart


1 Answers

Create a __init__.py file in the tests directory and in it put:

__all__ = [
    "test_001_func", "test_002_func", # etc
    ]

Then you can either:

import tests

tests.test_001_func()

or

from tests import *  # Not the best way to do things.

N.B. The reason that the import * is not the prefered solution is that you loose the namespace from the calls so you can a) possibly have collisions with names from other modules and b) your code is less clear.

like image 144
Steve Barnes Avatar answered Nov 14 '22 21:11

Steve Barnes