Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dynamic import methods from file

Tags:

python

I have multiple files with a structure like a file example.py:

    def initialize(context):
        pass


    def daj_omacku_teplu(context, data):
        pass


    def hmataj_pomaly(context, data):
        pass


    def chvatni_paku(context, data):
        pass


    def mikaj_laktom(context, data):
        pass

and I need to be able to dynamically import methods from "example.py" in a different python file like:

    for fn in os.listdir('.'):
       if os.path.isfile(fn):
           from fn import mikaj_laktom
           mikaj_laktom(example_context, sample_data)

For multiple reasons, I can not change the structure of example.py so I need to make a mechanism to load methods and evaluate them. I tried to use importlib but it can only import a class, not file with only methods defined. Thanks for the help.

like image 505
ememem Avatar asked Nov 29 '17 17:11

ememem


People also ask

How do you call a function from another file in Python?

To use the functions written in one file inside another file include the import line, from filename import function_name . Note that although the file name must contain a . py extension, . py is not used as part of the filename during import.

What does Importlib Import_module do?

The import_module() function acts as a simplifying wrapper around importlib. __import__() . This means all semantics of the function are derived from importlib.

How do you use relative import in Python?

Relative imports use dot(.) notation to specify a location. A single dot specifies that the module is in the current directory, two dots indicate that the module is in its parent directory of the current location and three dots indicate that it is in the grandparent directory and so on.


1 Answers

Python import does not support importing using paths, so you will need to have the files accessible as modules, see (sys.path). Assuming for now that your sources are located in the same folder as the main script, I would use the following (or similar):

import sys

def load_module(module):

    # module_path = "mypackage.%s" % module
    module_path = module

    if module_path in sys.modules:
        return sys.modules[module_path]

    return __import__(module_path, fromlist=[module])

# Main script here... Could be your for loop or anything else
# `m` is a reference to the imported module that contains the functions
m = load_module("example")
m.mikaj_laktom(None, [])

The source files can also be part of another package, in which case you will need an __init__.py in the same folder with the .py files (see packages) and you import with "mypackage.module" notation. (Note that the top level folder should be in your path, in the above example this is the folder containing "mypackage")


UDPATE:

  • As pointed out by @skyking there are lib that can help you do the same thing. See this post
  • My comment on __init__.py is outdate since things have changed in py3. See this post for some more detailed explanation
like image 70
urban Avatar answered Nov 02 '22 23:11

urban