Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional import in a module

I have created a module modA which I am importing in my main program. Depending on what happens in my main program (it has an interactive mode and a batch script mode), I want modA itself to import matplotlib with either the TkAgg backend or the ps backend. Is there a way for my main program to communicate information to modA to tell it how it should import matplotlib?

To clarify the situation:

The main program:

#if we are in interactive mode
#import modA which imports matplotlib using TkAgg backend
#else
#import modA which imports matplotlib using the ps backend

Module modA:

#import matplotlib
#matplotlib.use('ps') or matplotlib.use('TkAgg') (how can I do this?)
like image 282
user3208430 Avatar asked Jan 23 '14 02:01

user3208430


People also ask

Can import be conditional in Python?

Python conditional import comes into use while importing modules. In python, modules are pieces of code containing a set of functions that can be imported into other code. Modules help in managing code by supporting readability.

How can I conditionally import an ES6 module?

To conditionally import an ES6 module with JavaScript, we can use the import function. const myModule = await import(moduleName); in an async function to call import with the moduleName string to import the module named moduleName . And then we get the module returned by the promise returned by import with await .

How do I import a module dynamically?

To load dynamically a module call import(path) as a function with an argument indicating the specifier (aka path) to a module. const module = await import(path) returns a promise that resolves to an object containing the components of the imported module.

What does __ import __ do in Python?

The __import__() in python module helps in getting the code present in another module by either importing the function or code or file using the import in python method. The import in python returns the object or module that we specified while using the import module.


1 Answers

Have a function in your module which will determine this.

import matplotlib

def setEnv(env):
    matplotlib.use(env)

Then in your program you can have modA.setEnv('ps') or something else based on if-else statement condition.

You do not need a conditional import here (since you are using only one external module), but it is possible to do it:

if condition:
    import matplotlib as mlib
else:
    import modifiedmatplotlib as mlib

For more information about importing modules within function see these:

Python: how to make global imports from a function

Is it possible to import to the global scope from inside a function (Python)?

like image 138
sashkello Avatar answered Sep 19 '22 04:09

sashkello