Tampa
Tampa

Reputation: 78342

python and dynamic imports of sub directories

I have a data structure that looks like this in python 2.7

myfile.py
--parsers
  --folder1
    file1.py
         def filemethod(data=None)
            pass

Under the folder parsers, I can add many subfolders

I will always know then name of the function I want to call however

How do I do an import the parser directory so I can find the methods in each of the sub directory and accessible from myfile.py. I use getattr to convert a name to a function object. This is necessary because I get the name of the function to call from a remote call to a redis queue.

import ??????
methodToCall = getattr('filemethod', 'file1')
methodToCall(data)

Upvotes: 3

Views: 2227

Answers (2)

Saullo G. P. Castro
Saullo G. P. Castro

Reputation: 58985

A good way to do dynamic imports is using imp.load_source():

import imp
module = imp.load_source( 'mymodule', module_full_path )

in your case it will be something like:

module = imp.load_source( 'file1', '.\parsers\file1.py')
methodToCall = getattr( module, 'filemethod' )
methodToCall( data )

Make sure you replace 'file1' and '.\parsers\file1.py' with your desired module name and the correct path to its source file.

Upvotes: 4

shx2
shx2

Reputation: 64348

Another way is to first import the subdirectories from parsers/__init__.py.

parsers/__init__.py:

import folder1
import folder2
...

then:

import parsers
foldername = 'folder1'  # for example
mod = getattr(parsers, foldername)
methodToCall = getattr(mod, 'filemethod')
methodToCall(data)

Upvotes: 0

Related Questions