-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
lazymodules.py
69 lines (51 loc) · 2.06 KB
/
lazymodules.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) 2009- Spyder Kernels Contributors
#
# Licensed under the terms of the MIT License
# (see spyder_kernels/__init__.py for details)
# -----------------------------------------------------------------------------
"""
Lazy modules.
They are useful to not import big modules until it's really necessary.
"""
from spyder_kernels.utils.misc import is_module_installed
# =============================================================================
# Auxiliary classes
# =============================================================================
class FakeObject(object):
"""Fake class used in replacement of missing objects"""
pass
class LazyModule(object):
"""Lazy module loader class."""
def __init__(self, modname, second_level_attrs=None):
"""
Lazy module loader class.
Parameters
----------
modname: str
Module name to lazy load.
second_level_attrs: list (optional)
List of second level attributes to add to the FakeObject
that stands for the module in case it's not found.
"""
self.__spy_modname__ = modname
self.__spy_mod__ = FakeObject
# Set required second level attributes
if second_level_attrs is not None:
for attr in second_level_attrs:
setattr(self.__spy_mod__, attr, FakeObject)
def __getattr__(self, name):
if is_module_installed(self.__spy_modname__):
self.__spy_mod__ = __import__(self.__spy_modname__)
else:
return self.__spy_mod__
return getattr(self.__spy_mod__, name)
# =============================================================================
# Lazy modules
# =============================================================================
numpy = LazyModule('numpy', ['MaskedArray'])
pandas = LazyModule('pandas')
PIL = LazyModule('PIL.Image', ['Image'])
bs4 = LazyModule('bs4', ['NavigableString'])
scipy = LazyModule('scipy.io')