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.
As mentioned above, yes. And you can write simple test to be sure:
I recommend writing such tests every time you're in doubt how some importing or subclassing or thomething else works.
Yes,
from MODULE import OBJECT
executes everything in the module and then effectively doesOBJECT = MODULE.OBJECT
. You can tell that the module has already been loaded, in a sense, because now it resides in thesys.modules
dictionary.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.
and on the use of
from-import
:Note I've elided some matter. It's worth reading the entire document, it's actually quite short.
Looks like like the answer is yes: