简体   繁体   English

导入 Python 模块而不将其添加到本地命名空间

[英]Import a Python module without adding it to the local namespace

What I'd like to do我想做的事

I'd like to import a Python module without adding it to the local namespace.我想导入 Python 模块而不将其添加到本地命名空间。

In other words, I'd like to do this:换句话说,我想这样做:

import foo
del foo

Is there a cleaner way to do this?有没有更清洁的方法来做到这一点?

Why I want to do it为什么我想做

The short version is that importing foo has a side effect that I want, but I don't really want it in my namespace afterwards.简短的版本是导入foo具有我想要的副作用,但之后我真的不希望它在我的命名空间中。

The long version is that I have a base class that uses __init_subclass__() to register its subclasses.长版本是我有一个基础 class 使用__init_subclass__()注册其子类。 So base.py looks like this:所以base.py看起来像这样:

class Base:
    _subclasses = {}

    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        cls._subclasses[cls.__name__] = cls

    @classmethod
    def get_subclass(cls, class_name):
        return cls._subclasses[class_name]

And its subclasses are defined in separate files, eg foo_a.py :它的子类定义在单独的文件中,例如foo_a.py

from base import Base

class FooA(Base):
    pass

and so on.等等。

The net effect here is that if I do这里的净效果是,如果我这样做

from base import Base

print(f"Before import: {Base._subclasses}")

import foo_a
import foo_b

print(f"After import: {Base._subclasses}")

then I would see然后我会看到

Before import: {}
After import: {'FooA': <class 'foo_a.FooA'>, 'FooB': <class 'foo_b.FooB'>}

So I needed to import these modules for the side effect of adding a reference to Base._subclasses , but now that that's done, I don't need them in my namespace anymore because I'm just going to be using Base.get_subclass() .所以我需要导入这些模块以获得添加对Base._subclasses的引用的副作用,但现在已经完成,我不再需要它们在我的命名空间中,因为我将使用Base.get_subclass() .

I know I could just leave them there, but this is going into an __init__.py so I'd like to tidy up that namespace.我知道我可以把它们留在那里,但这将进入一个__init__.py所以我想整理那个命名空间。

del works perfectly fine, I'm just wondering if there's a cleaner or more idiomatic way to do this. del工作得很好,我只是想知道是否有更清洁或更惯用的方法来做到这一点。

If you want to import a module without assigning the module object to a variable, you can use importlib.import_module and ignore the return value:如果要导入模块而不将模块 object 分配给变量,可以使用importlib.import_module并忽略返回值:

import importlib

importlib.import_module("foo")

Note that using importlib.import_module is preferable over using the __import__ builtin directly for simple usages.请注意,使用importlib.import_module比直接使用__import__内置的简单用法更可取。 See the builtin documenation for details.有关详细信息,请参阅内置文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM