Lets say you’re in a file called logging.py. If you try to import the standard logging module, you’ll end up importing the file you’re in. How can you import the standard logging module from here?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The answer from samy.vilar gives lots of useful options. But if you’re looking for the simplest and most direct answer:
A few things to note here:
The
load_modulecall is more likereload(logging)thanimport loggingin that it won’t bind the nameloggingin the local scope, but will replace any existing module under the namelogging. So, if you’ve done animport loggingbefore this, that name now refers to the new module, not the old one; if you hadn’t, the nameloggingisn’t bound in your scope. (That’s why thelogging =is there above, to put it into scope.)I don’t know if it’s actually guaranteed that the ” that puts the current directory into the module path is actually the first entry in
sys.path. For that matter, it’s always possible to insert ”, or for that matter ‘.’, into sys.path yourself. So, if you want to be paranoid you could do something like this:Or you could get even more paranoid, e.g., compare
abspath(path)tosys.argv[0]andos.getcwd()in various ways to make sure nobody is sneakily forcing you to re-import yourself. It depends on what your goals are.