So, the Style Guide mandates that any non-standard imports (anything beyond Python standard library + numpy, biopython, gridDataFormats, networkx) be imported only at function use level.
This way importing the whole of MDAnalysis or MDAnalysis.analysis won't fail if optional dependencies (e.g., scipy) aren't met.
However, code written like that gets ugly. And it's confusing for contributors that are not so versed in our rules (e.g. #574).
How about creating a module class to specifically handle such cases? So that we'd only have to type:
from MDAnalysis.lib.optional import scipy
######################
# In MDAnalysis.lib.optional
from importlib import import_module
class DummyImport(object):
def __init__(self, modulename):
self.modulename = modulename
def __getattribute__(self, attr):
raise ImportError("Module '{0}' needed for the requested functionality.".format(object.__getattribute__(self, "modulename")))
def optional_import(modulename):
try:
return import_module(modulename)
except ImportError:
return DummyImport(modulename)
scipy = optional_import("scipy")
We'd still have to specifically add each optional module to the MDAnalysis.lib.optional namespace, which prevents problems with typos such as:
from MDAnalysis.lib.optional import spicy
What do you guys think?
So, the Style Guide mandates that any non-standard imports (anything beyond Python standard library +
numpy,biopython,gridDataFormats,networkx) be imported only at function use level.This way importing the whole of MDAnalysis or MDAnalysis.analysis won't fail if optional dependencies (e.g.,
scipy) aren't met.However, code written like that gets ugly. And it's confusing for contributors that are not so versed in our rules (e.g. #574).
How about creating a module class to specifically handle such cases? So that we'd only have to type:
from MDAnalysis.lib.optional import scipyWe'd still have to specifically add each optional module to the
MDAnalysis.lib.optionalnamespace, which prevents problems with typos such as:from MDAnalysis.lib.optional import spicyWhat do you guys think?