I just wanna know about os.path module..

Peter Otten __peter__ at web.de
Thu Jul 21 04:03:34 EDT 2005

kimes wrote:

> You said 'At first os - module, or package, it doesn't matter here - is
> imported.'

With a file mop.py in your path

import mop

creates a module instance and executes mop.py to fill it with content --
classes, functions, whatever python objects you can think of -- and puts
that module instance into the sys.modules cache. With a file
mop/__init__.py, the process is the same except that the code to fill the
module is taken from the __init__.py file. Differences only appear when you
try to import submodules.

> I'm still confused about that..
> When I just call import os.path without calling import os..
> In that case, you mean 'import os' is called implicitly?

Yes. Try it yourself with a package/submodule where __init__.py and
submodule.py just contain a print statement. I find such an experimental
approach often more convenient than haunting the docs.

> Why? and How?

Because it's a sensible assumption that a submodule depends on its parent
package? Because it makes access of submodules as easy as attribute access
for any other object? Because it makes conditional imports easy (see
Terry's post)? Because it's the simplest approach that just works?

> how python knows it should call import when we call import os?
> Please make me clear.. :)

Conceptually, when you have a module alpha.beta.gamma you need just a bit of
string processing. "alpha.beta.gamma".split() -- aah, I have to import
alpha, then alpha.beta, then alpha.beta.gamma... read the source for the
strategy that is actually taken if you really care.


More information about the Python-list mailing list