I have two specific situations where I don’t understand how importing works in Python:
1st specific situation:
When I import the same module in two different Python scripts, the module isn’t imported twice, right? The first time Python encounters it, it is imported, and second time, does it check if the module has been imported, or does it make a copy?
2nd specific situation:
Consider the following module, called bla.py:
a = 10
And then, we have foo.py, a module which imports bla.py:
from bla import *
def Stuff ():
return a
And after that, we have a script called bar.py, which gets executed by the user:
from foo import *
Stuff() #This should return 10
a = 5
Stuff()
Here I don’t know: Does Stuff() return 10 or 5?
Part 1
The module is only loaded once, so there is no performance loss by importing it again. If you actually wanted it to be loaded/parsed again, you’d have to
reload()the module.Part 2
from foo import *importsato the local scope. When assigning a value toa, it is replaced with the new value – but the originalfoo.avariable is not touched.So unless you
import fooand modifyfoo.a, both calls will return the same value.For a mutable type such as a list or dict it would be different, modifying it would indeed affect the original variable – but assigning a new value to it would still not modify
foo.whatever.If you want some more detailed information, have a look at http://docs.python.org/reference/executionmodel.html:
The two bold sections are the relevant ones for you: First the name
ais bound to the value offoo.aduring the import. Then, when doinga = 5, the nameais bound to5. Since modifying a list/dict does not cause any binding, those operations would modify the original one (bandfoo.bare bound to the same object on which you operate). Assigning a new object tobwould be a binding operation again and thus separatebfromfoo.b.It is also worth noting what exactly the
importstatement does:import foobinds the module name to the module object in the current scope, so if you modifyfoo.whatever, you will work with the name in that module – any modifications/assignments will affect the variable in the module.from foo import barbinds the given name(s) only (i.e.foowill remain unbound) to the element with the same name infoo– so operations onbarbehave like explained earlier.from foo import *behaves like the previous one, but it imports all global names which are not prefixed with an underscore. If the module defines__all__only names inside this sequence are imported.Part 3 (which doesn’t even exist in your question :p)
The python documentation is extremely good and usually verbose – you find answer on almost every possible language-related question in there. Here are some useful links:
import,yield)for,try,with)