在Python中,如何在一行中导入库中的所有模块?

2024-09-30 08:27:24 发布

您现在位置:Python中文网/ 问答频道 /正文

以下代码起作用:

import torch
import pytorch_lightning   as torchl
import pytorch_forecasting as torchf 
from pytorch_forecasting.data.examples import get_stallion_data
x = torchf.data.examples.get_stallion_data()
print(x)

但是,如果删除第4行,则会出现错误:

AttributeError: module 'pytorch_forecasting.data' has no attribute 'examples'

仅仅为了从一个库中加载多个模块而花费许多行,这既单调又丑陋,例如:

from pytorch_lightning.callbacks import EarlyStopping, LearningRateMonitor
from pytorch_lightning.loggers import TensorBoardLogger
from pytorch_forecasting import Baseline, TemporalFusionTransformer, TimeSeriesDataSet
from pytorch_forecasting.data import GroupNormalizer
from pytorch_forecasting.metrics import SMAPE, PoissonLoss, QuantileLoss
from pytorch_forecasting.models.temporal_fusion_transformer.tuning import optimize_hyperparameters
from pytorch_forecasting.data.examples import get_stallion_data

是否有一种方法可以仅使用一行导入所有这些模块,然后将其用作:

x=torchf.bla.bla.bla.bla(parameters)

我更喜欢这种方式,因为名称冲突的危险更小:调用x=library1.module(); y=library2.module();避免名称冲突,这与from library1 import *; from library2 import *; x=module(); y=module();不同


Tags: 模块fromimport名称datagetaspytorch
1条回答
网友
1楼 · 发布于 2024-09-30 08:27:24

要从包中导入所有内容,只需执行import pytorch_lightning,它将导入包中的所有模块和文件。然后您可以将其用作x = pytorch_lightning.callbacks.EarlyStopping()

缺点是您正在加载不一定需要的文件和模块(以及它们连续导入的包),这会增加导入时间

相关问题 更多 >

    热门问题