What Is The Concept Of Namespace When Importing A Function From Another Module?
Solution 1:
Each module has its own global name space.
from module1 import some_function
x=10some_function()
some_function
uses module1.x
in its definition, but you are setting x
in the current module. This would work:
from module1 import some_function
import module1
module1.x = 10some_function()
Note that you can't use from module1 import x
, then set x = 10
, because that import
simply initializes a new name x
to have the same initial value as module1.x
; x = 10
then gives a new value to the new variable.
Solution 2:
At the risk of sounding flippant, the rule is pretty simple: if the name hasn't been defined within the module, it simply doesn't exist.
Look at this module:
defsome_function():
printstr(x)
It doesn't define x
, so that name doesn't exist within this module. If you define x
in another module, it still won't exist within this module. Even if you import this module into the other module that defines x
, x
still won't exist within this module.
There's no "global global
" namespace. Each module has its own global
namespace. Names are never implicitly shared between modules, they must always be explicitly imported.
The only exception to this are the builtins
, which—for convenience—don't need to be explicitly imported.
Post a Comment for "What Is The Concept Of Namespace When Importing A Function From Another Module?"