Search code examples
python

how to stop the import of a python module


suppose I have a file my_plugin.py

var1 = 1
def my_function():
    print("something")

and in my main program I import this plugin

import my_plugin

Is there a way to silently disable this plugin with something like a return statement?

for example I could "mask" the behavior of my_function like this:

def my_function():
    return
    print("something")

I am wondering if I can do this for the module as a way to turn it on and off depending on what I am trying to do with the overall project. So something like:

return  # this is invalid, but something that says stop running this module
        # but continue on with the rest of the python program
var1 = 1
def my_function():
    print("something")

I suppose I could just comment everything out and that would work... but I was wondering if something a little more concise exists

--- The purpose: The thinking behind this is I have a large-ish code-base that is extensible by plugins. There is a plugins directory so the main program looks in the directory and runs all the modules that are in there. The use case was just to put a little kill switch inside plugins that are causing problems as an alternative to deleting or moving the file temporarily


Solution

  • You can just conditionally import the module:

    if thing == otherthing:
       import module
    

    This is entire valid syntax in python. With this you can set a flag on a variable at the start of your project that will import modules based on what you need in that project.