How modules work in Python

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Nov 16 19:24:18 EST 2014


Abdul Abdul wrote:

> Hello,
> 
> I'm new to Python, and just have a small question, and thought you might
> have an idea on it.
> 
> I came across the following example that uses the Python Imaging Library
> (PIL):
> 
> from PIL import Image
> img = Image.open('xyz.jpg')
> 
> I know that PIL is a module. And, I think that Image is also a module,
> especially we are importing it.
> 
> I also understood the Image,open() part, as it appears we are using the
> method open() from the Image module.
> 
> My question is, where did PIL go here? Can a module have another module
> inside it?

Yes it can. 

If I have a module "spam.py", which imports "eggs.py", then I can do this:

from spam import eggs
eggs.some_function()


In your case, PIL hasn't gone anywhere, it still exists. Importing does
three things:

* it runs the code inside the file, creating a module object;
* it caches that module object in sys.modules;
* it optionally creates a name in your current namespace for that module.

So when you run `from PIL import Image`, something more or less like the
following events happen:

- Python locates the PIL file
- Python runs the PIL file and builds a module object
- which contains a line like "import Image"
  +- Python locates the Image file 
  +- Python runs the Image file and builds a module object
  +- caches Image in sys.module
  +- creates a name Image = <the Image module object> inside PIL
- Python finishes running the PIL module
- and caches PIL in sys.module
- it looks up PIL.Image in that module
- and creates a name Image = <the Image module object> inside your module


Think of `from PIL import Image` as being effectively something quite close
to this:

    import PIL as _temporary_name_123456
    Image = _temporary_name_123456.Image
    del _temporary_name_123456

except that no temporary name is actually created. So you can see, the PIL
module has been imported (that's the only way Python can look up Image
inside PIL), but you don't have access to it in your name space. But you
can then do:

    import PIL

which will be really quick because it is already cached and ready to go.




-- 
Steven




More information about the Python-list mailing list