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 contain the function test_xxx_func, all modules are in the same folder.

I would like to use something like this:

from tests import *
test_001.test_001_func()

But it does not work

+4
source share
4 answers

Create a file __init__.pyin the test directory and put in it:

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

Then you can:

import tests

tests.test_001_func()

or

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

N.B. , import * , , , : a) b) .

+1

tests, __init__.py __all__.

, __init__.py tests - :

__all__ == ["test_001", "test_002" <<etc...>>]

* .

0

script.

, :

run.py
tests
  -> test_001.py
  -> test_002.py

tests/__init__.py

import os
import sys

# Append to path "test" folder (also can be any other name)
sys.path.append(os.path.basename(os.path.dirname(__file__)))

__all__ = []
for k in xrange(1, 3):
    name = "test_%03d" % k

    # __import__ can load module by string name
    globals()[name] = __import__(name)

    # set that we export only required names like test_001, test_002
    __all__.append(name)

test_001.py:

def test_001_func():
    print "test1"

test_002.py:

def test_002_func():
    print "test2"

run.py:   

print tests.test_001
print tests.test_001.test_001_func

print tests.test_002

run.py script :

test@test:~/Desktop/python$ python run.py 
<module 'test_001' from 'tests/test_001.pyc'>
<function test_001_func at 0xb728b09c>
<module 'test_002' from 'tests/test_002.pyc'>
0

, __all__, , :

# In your tests/__init__.py do something along the following lines:

import os.path, pkgutil, importlib
__path = os.path.dirname(__file__)
__all__ = [name for _, name, _ in pkgutil.iter_modules([__path])]
for __module in __all__:
    importlib.import_module("." + __module, __name__)

Python 2.7+ code is due importlib, but it can be modified for older versions of Python using bare __import__.

Then use it as follows:

import tests
tests.test_002.test_002_func()

or

from tests import *
test_002.test_002_func()

However , if it is for unit testing, I highly recommend unittesttaking a look at or something like Nose , which will handle test detection in a more pythonic way.

0
source

Source: https://habr.com/ru/post/1536997/


All Articles