OK, so I know that from-import
is "exactly" the same as import
, except that it's obviously not because namespaces are populated differently.
My question is primarily motivated because I have a utils
module which has one or two functions that are used by every other module in my app, and I'm working on incorporating the standard library logging
module, which as far as I can tell I need to do sorta like this:
import logging
logging.basicConfig(filename="/var/log") # I want file logging
baselogger = logging.getLogger("mine")
#do some customizations to baselogger
and then to use it in a different module I would import logging again:
import logging
logger = logging.getlogger("mine")
# log stuff
But what I want to know is if I do a from utils import awesome_func
will my logger definitely be set up, and will the logging module be set up the way I want?
This would apply to other generic set-ups as well.
Looks like like the answer is yes:
$ echo 'print "test"
def f1():
print "f1"
def f2():
print "f2"
' > util.py
$ echo 'from util import f1
f1()
from util import f2
f2()
' > test.py
$ python test.py
test
f1
f2
$
The answer to your question is yes.
For a good explanation of the import process, please see Frederik Lundh's "Importing Python Modules".
In particular, I'll quote the sections that answer your query.
What Does Python Do to Import a Module?
[...]
- Create a new, empty module object (this is essentially a dictionary)
- Insert that module object in the sys.modules dictionary
- Load the module code object (if necessary, compile the module first)
- Execute the module code object in the new module’s namespace. All variables assigned by the code will be available via the module object.
and on the use of from-import
:
There are Many Ways to Import a Module
[...]
from X import a, b, c imports the module X, and creates references in the current namespace to the given objects. Or in other words, you can now use a and b and c in your program.
Note I've elided some matter. It's worth reading the entire document, it's actually quite short.
Yes, from MODULE import OBJECT
executes everything in the module and then effectively does OBJECT = MODULE.OBJECT
. You can tell that the module has already been loaded, in a sense, because now it resides in the sys.modules
dictionary.
As mentioned above, yes.
And you can write simple test to be sure:
# file m.py
import sys
# define function
def f():
pass
#execute this when module is loaded (i.e. imported or run as script)
print 'imported', __name__
# print all "exposed" variables to make sure that the f is visible
print dir(sys.modules[__name__])
# file main.py
from m import f
print 'done'
I recommend writing such tests every time you're in doubt how some importing or subclassing or thomething else works.