| 1 |
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. |
| 2 |
# |
| 3 |
# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
# you may not use this file except in compliance with the License. |
| 5 |
# You may obtain a copy of the License at |
| 6 |
# |
| 7 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
# |
| 9 |
# Unless required by applicable law or agreed to in writing, software |
| 10 |
# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
# See the License for the specific language governing permissions and |
| 13 |
# limitations under the License. |
| 14 |
# ============================================================================== |
| 15 |
|
| 16 |
"""A LazyLoader class.""" |
| 17 |
|
| 18 |
from __future__ import absolute_import |
| 19 |
from __future__ import division |
| 20 |
|
| 21 |
import importlib |
| 22 |
import types |
| 23 |
|
| 24 |
|
| 25 |
class LazyLoader(types.ModuleType): |
| 26 |
"""Lazily import a module, mainly to avoid pulling in large dependencies. |
| 27 |
|
| 28 |
`contrib`, and `ffmpeg` are examples of modules that are large and not always |
| 29 |
needed, and this allows them to only be loaded when they are used. |
| 30 |
""" |
| 31 |
|
| 32 |
# The lint error here is incorrect. |
| 33 |
def __init__(self, local_name, parent_module_globals, name, warning=None): # pylint: disable=super-on-old-class |
| 34 |
self._local_name = local_name |
| 35 |
self._parent_module_globals = parent_module_globals |
| 36 |
self._warning = warning |
| 37 |
|
| 38 |
super(LazyLoader, self).__init__(name) |
| 39 |
|
| 40 |
def _load(self): |
| 41 |
"""Load the module and insert it into the parent's globals.""" |
| 42 |
# Import the target module and insert it into the parent's namespace |
| 43 |
module = importlib.import_module(self.__name__) |
| 44 |
self._parent_module_globals[self._local_name] = module |
| 45 |
|
| 46 |
# Update this object's dict so that if someone keeps a reference to the |
| 47 |
# LazyLoader, lookups are efficient (__getattr__ is only called on lookups |
| 48 |
# that fail). |
| 49 |
self.__dict__.update(module.__dict__) |
| 50 |
|
| 51 |
return module |
| 52 |
|
| 53 |
def __getattr__(self, item): |
| 54 |
module = self._load() |
| 55 |
return getattr(module, item) |
| 56 |
|
| 57 |
def __dir__(self): |
| 58 |
module = self._load() |
| 59 |
return dir(module) |