jratliff
jratliff

Reputation: 9

Name clashes in Python modules

I have this problem for homework:

For module1, module2, and the client module shown below, indicate which of the imported identifiers would result in a name clash if the imported identifiers were not fully qualified.

enter image description here

I answered:
func_2 clashes between module2 and module3
func_3 clashes between module2 and main

However, the answer listed in the text is just
func_3.
Am I wrong?

Thank you.

Upvotes: -1

Views: 334

Answers (1)

zondo
zondo

Reputation: 20366

In module1, there is no name clash, because module1 does not know that module2 and client module exist. module2 does not know that module1 and client module exist. client module, however, imports module1 and module2. Therefore, it has defined func_1 once (in module1), func_2 twice (in module1 and module2), and func_3 twice (in module2 and client module). For illustration, I'll write two files: main_module and imported_module.

imported_module looks like this:

x = True
print 'x in imported_module: %s' % ('x' in locals())
print 'y in imported_module: %s' % ('y' in locals())

main_module looks like this:

y = True
from imported_module import *
print "" # put a blank line between what imported_module prints and what
         # main_module prints
print 'y in main_module: %s' % ('y' in locals())
print 'x in main_module: %s' % ('x' in locals())

The result of running main_module:

y in imported_module: False
x in imported_module: True

y in main_module: True
x in main_module: True

main_module has both variables, because it defined y and imported x. imported_module has x, because it defined it, but it does not have y.

Upvotes: 0

Related Questions