Source code for schrodinger.utils.moduleproxy
"""
A module proxy class to be used when a non-essential module can't be
imported. It will raise an ImportError any time something from the module is
accessed.
"""
# Copyright Schrodinger, LLC.
[docs]def try_import(name):
"""
Return the module named or a proxy that will raise an ImportError the
first time any of its attributes are accessed.
This allows for a non-essential module to be imported and mostly ignored
if not present.
"""
try:
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
except ImportError:
return ModuleProxy(name)
[docs]class ModuleProxy:
"""
A class to use as a placeholder for a non-essential module, raising an
exception when something tries to use it.
"""
[docs] def __init__(self, name):
self.name = name
def __getattr__(self, attr):
"""
Simply raise an exception any time something tries to make use of
functionality from the fake module.
"""
raise ImportError("The '%s' module is not available on this platform." %
self.name)
def __bool__(self):
"""
Always return False, indicating that the instance is not usable as a
module.
This allows for conditional behavior to be set up, based on a check
for a proxy module. For example:
matplotlib = try_import("matplotlib")
if matplotlib:
create_pretty_graph()
else:
print_boring_numbers()
"""
return False