【发布时间】:2020-04-27 10:37:16
【问题描述】:
您好,提前感谢他们对我的帮助,
请看下面的代码:
import types
_MSG = ("Failed importing {name}. Please install {name}."
" Using pip install {name}")
class Empty(): # pylint: disable=too-few-public-methods
"""Empty class for beam API."""
def __call__(self, *args, **kwargs):
return None
class DummyBeam(types.ModuleType): # pylint: disable=too-few-public-methods
DoFn = Empty
Pipeline = Empty
def __init__(self, name="apache_beam"):
super(DummyBeam, self).__init__(name)
def __getattribute__(self, _):
if getattr(DummyBeam, _, None) is Empty:
err_msg = _MSG.format(name=self.__name__)
raise ImportError(err_msg)
我想检查apache_beam是否未安装,它将成功加载所有光束类,如DoFn和管道,但调用某些函数会引发错误,请参阅下面的代码以查看上面正在使用的代码。
try:
import apache_beam as beam
except ImportError:
beam = DummyBeam()
class SomeFn(beam.DoFn):
pass
class SomeOtherFn(beam.Pipeline):
pass
SomeFn()
在上面的代码中,现在访问beam.DoFn 会引发错误,但我希望它在访问beam.DoFn 时不会引发错误,尽管它会在调用SomeFn() 时引发错误。还尝试将getattribute 替换为getattr,但它没有给我预期的结果,尽管它对所有代码都运行良好,但它在调用 SomeFn() 时不会引发错误。
感谢您对此进行调查。
【问题讨论】:
标签: python python-3.x oop pep