如何只在必要时导入模块并且只导入一次
how to only import module if necessary and only once
我有一个 class 可以使用 matplotlib 绘制,但它也可以(并且将会)在不绘制的情况下使用。
我只想在必要时导入 matplotlib,即。如果在 class 的实例上调用 plot 方法,但同时我想只导入一次 matplotlib。
目前我做的是:
class Cheese:
def plot(self):
from matplotlib import pyplot as plt
# *plot some cheese*
..但我想这可能会导致多次导入。
我能想到很多方法来完成只导入一次,但它们并不漂亮。
执行此操作的漂亮且“pythonic”方式是什么?
我并不是说这是“基于意见”的,所以让我澄清一下我所说的“漂亮”是什么意思:
- 使用最少的代码行。
- 最具可读性
- 效率最高
- 最不容易出错
等等
如果模块已经加载,则不会再次加载。你只会得到一个参考。如果你不打算在本地使用这个 class 并且只想满足 typehinter 那么你可以执行以下操作
#imports
#import whatever you need localy
from typing import TYPE_CHECKING
if TYPE_CHECKING: # False at runtime
from matplotlib import pyplot as plt
Python 中的可选导入:
try:
import something
import_something = True
except ImportError:
import something_else
import_something_else = True
Python 中的条件导入:
if condition:
import something
# something library related code
elif condition:
# code without library
与一项功能相关的导入:
def foo():
import some_library_to_use_only_inside_foo
TLDR; Python 已经免费为您做到了。
Python import machinery 只导入一次模块,即使导入了多次。即使来自不同的文件 (docs).
最pythonic 的导入方式是在文件的开头导入。除非您有特殊需要,例如根据某些条件导入 different 模块,例如。平台 (windows, linux).
我有一个 class 可以使用 matplotlib 绘制,但它也可以(并且将会)在不绘制的情况下使用。
我只想在必要时导入 matplotlib,即。如果在 class 的实例上调用 plot 方法,但同时我想只导入一次 matplotlib。
目前我做的是:
class Cheese:
def plot(self):
from matplotlib import pyplot as plt
# *plot some cheese*
..但我想这可能会导致多次导入。
我能想到很多方法来完成只导入一次,但它们并不漂亮。
执行此操作的漂亮且“pythonic”方式是什么?
我并不是说这是“基于意见”的,所以让我澄清一下我所说的“漂亮”是什么意思:
- 使用最少的代码行。
- 最具可读性
- 效率最高
- 最不容易出错 等等
如果模块已经加载,则不会再次加载。你只会得到一个参考。如果你不打算在本地使用这个 class 并且只想满足 typehinter 那么你可以执行以下操作
#imports
#import whatever you need localy
from typing import TYPE_CHECKING
if TYPE_CHECKING: # False at runtime
from matplotlib import pyplot as plt
Python 中的可选导入:
try:
import something
import_something = True
except ImportError:
import something_else
import_something_else = True
Python 中的条件导入:
if condition:
import something
# something library related code
elif condition:
# code without library
与一项功能相关的导入:
def foo():
import some_library_to_use_only_inside_foo
TLDR; Python 已经免费为您做到了。
Python import machinery 只导入一次模块,即使导入了多次。即使来自不同的文件 (docs).
最pythonic 的导入方式是在文件的开头导入。除非您有特殊需要,例如根据某些条件导入 different 模块,例如。平台 (windows, linux).