user32882
user32882

Reputation: 5877

Reload module if it hasn't been loaded yet in python

I'd like to do the following in python:

I've tried the following, but it doesn't seem to work:

try:
    importlib.reload(module_name)
except NameError:
    import (module_name)

Is there perhaps a better way?

Upvotes: 0

Views: 1062

Answers (2)

user32882
user32882

Reputation: 5877

This is the solution, if the module name is only available as a string and not loaded beforehand:

import importlib
import sys

mod_str = "module_name"

if mod_str in sys.modules:
  mod_obj = importlib.import_module(mod_str)
  importlib.reload(mod_obj)
else:
  mod_obj = importlib.import_module(mod_str)

Upvotes: 1

ncica
ncica

Reputation: 7206

A simple way to get modules imported in your Python script is using ModuleFinder (standard Python module).

ModuleFinder class in this module provides run_script() and report() methods to determine the set of modules imported by a script.

Example:

from modulefinder import ModuleFinder
import importlib

finder = ModuleFinder()
finder.run_script('C:/path/your_script.py')

if 'module_name' in finder.modules.keys():
    importlib.reload(module_name)
else:
    importlib.import_module(module_name)

NOTE:

Reload and imoprt are previously imported modules. The argument must be a module object, so it must have been successfully imported before.

Upvotes: 0

Related Questions