0

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
  • It have no sense, just for lazy access – Wonka Jul 23 '19 at 08:36
  • "Is it just out of pure laziness to not have to write module_a.member_a and instead access member_a directly?" > yes. – blues Jul 23 '19 at 08:36
  • Possible duplicate of [\`from ... import\` vs \`import .\`](https://stackoverflow.com/questions/9439480/from-import-vs-import) – Ora Aff Jul 23 '19 at 08:37

1 Answers1

2

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:
ruohola
  • 21,987
  • 6
  • 62
  • 97