0

I'd like to do the following in python:

  • check if a module has been imported
  • if it hasn't, then import the module using import module_name
  • if it has, then reload the module using importlib.reload(module_name)

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?

1
  • Unless you are writing a debugger or some other specialized code runner, the best thing to do would be to restart your program if the module has been changed. Commented Jan 24, 2022 at 14:44

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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.

3 Comments

importlib.reload doesn't accept string arguments. From the docs "The argument must be a module object, so it must have been successfully imported before"
@user32882 That it is correct, but I have not mentioned anywhere that module_name should be a string argument. there is obviously a difference between 'module_name' and module_name. but in any case I will write an additional note
Thanks for the additional note. It turns out I need something where the module has not been imported before...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.