问题
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 accessmember_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