2

How can I import a python class but avoid running the import statement in that module?

Module foo
    from bar import A

Module bar
    import alpha

    class A(object):
        ...

    class B(objects):
        ...

I want to import class A but don't need class B. The import statement in the module bar is required for class B but I'd like to avoid needing to install that dependency if possible, as (I assume) it will be loaded into memory but not used.

Any help would be appreciated.

4

2 回答 2

3

你不能停止bar导入alpha而不破解它的源代码。alpha但是您可以通过将其写入以下内容来“伪造” sys.modules

>>> import alpha
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named alpha
>>> import sys; sys.modules['alpha'] = object()
>>> import alpha
>>>

这是因为 Python 将导入的模块缓存在sys.modules. 添加alpha它意味着 Python 认为您已经导入了alpha,因此当bar尝试这样做时,它只会取回缓存的副本。

显然,您应该仔细考虑您是否愿意这样做——bar如果它实际上在任何地方使用,将会以意想不到的方式崩溃alpha

于 2012-04-26T09:33:27.333 回答
1

将导入放在 B 类初始化中

class B:
    def __init__:
        import alpha

如果我没记错的话,这可能会奏效

于 2012-04-26T09:35:14.180 回答