Why use “from <module> import <something>” after “import <module>”?

假如想象 提交于 2021-01-29 12:53:06

问题


I'm trying to understand why in some code it is common practice to import a module first and afterwards importing specific member from the module.

import module_a
from module_a import member_a

Is it just out of pure laziness to not have to write module_a.member_a and instead access member_a directly?

Here's the code snippet my question originates from:

import spinup
from spinup.utils.run_utils import ExperimentGrid
from spinup.utils.serialization_utils import convert_json

回答1:


Is it just out of pure laziness to not have to write module_a.member_a and instead access member_a directly?

Yes essentially, It allows one to use any functions or classes in spinup, with spinup.foo and spinup.Bar. It's subjectively preferable to use the spinup.foo way for most of the time, since this way it's really clear from where the function you're using is defined.

This technique also enables the use of ExperimentGrid without specifying spinup.utils.run_utils.ExperimentGrid every time it's used. This is especially useful with classes/types when using type annotations:

def foo(param: ExperimentGrid) -> ExperimentGrid:

is a lot cleaner than

def foo(param: spinup.utils.run_utils.ExperimentGrid) -> spinup.utils.run_utils.ExperimentGrid:


来源:https://stackoverflow.com/questions/57159948/why-use-from-module-import-something-after-import-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!