How importing works. Why imported modules not inheriting other imported modules?

The details of importing get very complicated, but conceptually it is very simple.

The details of importing get very complicated, but conceptually it is very simple. When you write: import some_module It is equivalent to this: some_module = import_module("some_module") where import_module is kind of like: def import_module(modname): if modname in sys. Modules: module = sys.

Modulesmodname else: filename = find_file_for_module(modname) python_code = open(filename).read() module = create_module_from_code(python_code) sys. Modulesmodname = module return module Two things to note here: the assignment of some_module is specific: an import statement really does nothing in the current module except assign a module object to the name you specify. That's why you don't automatically get the names from the imported module, and why it isn't like copying the imported code into the current module.

Also, in the import_module pseudo-function, if the name has already been imported somewhere, it will be in the global list of all modules (sys. Modules), and so will simply be reused. The file won't be opened again, it won't be executed again, the globals in that modules won't get new values again, and so on.

Importing the same module into many places is not wasteful or extra work, it is very fast.

1 This peak "under the hood" helps me understand better what is going on. Thanks. – narnie Oct 9 '10 at 16:28.

Import is required to bring the contents of the py file into the namespace of that module - if you don't import, the names in it cannot be referenced. Some more info: effbot.org/zone/import-confusion.htm When Python imports a module, it first checks the module registry (sys. Modules) to see if the module is already imported.

If that’s the case, Python uses the existing module object as is.

Take particular note that no matter how many times you import the module, the outer-scope code in the imported module runs only once (barring unload & reload, of course). OP will not have 2 'gtk's in memory. The effect of subsequent imports is only to bring things into the local namespace.

– Russell Borogove Oct 9 '10 at 1:56 Thanks for this clarification. It seems a lot of "extra" work and a bit of a waste to do this, but if that is the way it is, that is the way it is. Thank for the link.

I just started reading it and I think it is exactly what I need to think better in python. – narnie Oct 9 '10 at 2:14.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions