Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing modules dynamically in Python 3.X

I would like to import a module from inside a functions. For example from this:

from directory.folder.module import module

def import():   
    app.register_blueprint(module)

To this:

def import():   
    from directory.folder.module import module

But, without hardcoding it. For example:

def import():
    m = "module"
    from directory.folder.m import m

Is it possible? Thanks in advance

like image 238
BigMeister Avatar asked Oct 17 '25 06:10

BigMeister


2 Answers

You want the importlib module.

Here's the most simplistic way to use this module. There are lots of different ways of weaving the results of calls to the module into the environment:

import importlib

math = importlib.import_module("math")

print(math.cos(math.pi))

Result:

-1.0

I've used this library a lot. I built a whole plug-in deployment system with it. Scripts for all the various deploys were dropped in directories and only imported when they were mentioned in a config file rather than everything having to be imported right away.

Something I find very cool about this module is what's stated at the very top of its documentation:

The purpose of the importlib package is two-fold. One is to provide the implementation of the import statement (and thus, by extension, the import() function) in Python source code.

The intro in the 2.7 docs is interesting as well:

New in version 2.7.

This module is a minor subset of what is available in the more full-featured package of the same name from Python 3.1 that provides a complete implementation of import. What is here has been provided to help ease in transitioning from 2.7 to 3.1.

like image 191
CryptoFool Avatar answered Oct 18 '25 18:10

CryptoFool


You can use the importlib module to programmatically import modules.

import importlib

full_name = "package." + "module"

m = importlib.import_module(full_name)
like image 39
sphennings Avatar answered Oct 18 '25 18:10

sphennings



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!