According to the official documentation, os.path
is a module. Thus, what is the preferred way of importing it?
# Should I always import it explicitly?
import os.path
Or...
# Is importing os enough?
import os
Please DON'T answer "importing os
works for me". I know, it works for me too right now (as of Python 2.6). What I want to know is any official recommendation about this issue. So, if you answer this question, please post your references.
Interestingly enough, importing os.path will import all of os. try the following in the interactive prompt:
The result will be the same as if you just imported os. This is because os.path will refer to a different module based on which operating system you have, so python will import os to determine which module to load for path.
reference
With some modules, saying
import foo
will not exposefoo.bar
, so I guess it really depends the design of the specific module.In general, just importing the explicit modules you need should be marginally faster. On my machine:
import os.path
:7.54285810068e-06
secondsimport os
:9.21904878972e-06
secondsThese times are close enough to be fairly negligible. Your program may need to use other modules from
os
either now or at a later time, so usually it makes sense just to sacrifice the two microseconds and useimport os
to avoid this error at a later time. I usually side with just importing os as a whole, but can see why some would preferimport os.path
to technically be more efficient and convey to readers of the code that that is the only part of theos
module that will need to be used. It essentially boils down to a style question in my mind.