ysfzack
ysfzack

Reputation: 31

Importing modules in python (3 modules)

Let's say i have 3 modules within the same directory. (module1,module2,module3)

Suppose the 2nd module imports the 3rd module then if i import module2 in module 1. Does that automatically import module 3 to module 1 ?

Thanks

Upvotes: 1

Views: 129

Answers (3)

Konstantin Grigorov
Konstantin Grigorov

Reputation: 1602

What importing does conceptually is outlined below.

import some_module

The statement above is equivalent to:

module_variable = import_module("some_module")

All we have done so far is bind some object to a variable name. When it comes to the implementation of import_module it is also not that hard to grasp.

def import_module(module_name):
  if module_name in sys.modules:
      module = sys.modules[module_name]
  else:
      filename = find_file_for_module(module_name)
      python_code = open(filename).read()
      module = create_module_from_code(python_code)
      sys.modules[module_name] = module
  return module

First, we check if the module has been imported before. If it was, then it will be available in the global list of all modules (sys.modules), and so will simply be reused. In the case that the module is not available, we create it from the code. Once the function returns, the module will be assigned to the variable name that you have chosen. As you can see the process is not inefficient or wasteful. All you are doing is creating an alias for your module. In most cases, transparency is prefered, hence having a quick look at the top of the file can tell you what resources are available to you. Otherwise, you might end up in a situation where you are wondering where is a given resource coming from. So, that is why you do not get modules inherently "imported".

Resource: Python doc on importing

Upvotes: 0

Alfie
Alfie

Reputation: 2013

No, it will not be imported unless you explicitly specify python to, like so:

from module2 import *

Upvotes: 0

knh190
knh190

Reputation: 2882

No. The imports only work inside a module. You can verify that by creating a test.

Saying,

# module1
import module2

# module2
import module3

# in module1
module3.foo() # oops

This is reasonable because you can think in reverse: if imports cause a chain of importing, it'll be hard to decide which function is from which module, thus causing complex naming conflicts.

Upvotes: 1

Related Questions