Bringing Everything into the Current Scope

Note a special feature of modules: Sometimes you may want to have the entire contents of a module available without having to specify each name that is available from it explicitly. To do this, Python provides a special character, the asterisk, which can be used with the from . . . import . . . statement. It's important to understand that you can only import using the * when you are importing into the global scope:

from Foods import *

This would bring Omelet into your current scope, as well as everything else at the top of the recipe module. In other words, now you no longer have type Foods.Omelet(), just Omelet(), and you need to do this only once, instead of one time for each name you want to make local.

Packages can be made to work in a similar fashion, but underneath, they actually work differently. For packages, you need to specify the names you want to be provided when from . . . import *, and these need to be stated explicity. You can make the three modules in the Kitchen package available by using the__all__list in__init__.py. Any names that appear in the__all__list will be exported by the *

but only those names.

The elements that are present in the__all__list are the names of functions, classes, or data that will be automatically imported into the global scope of the program that is asked to import *.

You can expect users of modules and packages you write to automatically use the from . . . import * syntax within their programs. To work with packages, you must specify a list of names that will be exported! However, if you have a large module, you can also create an__all__list at the top of your module file, and it will also have the effect of restricting the names in the module in the same way as it would in a package.

Was this article helpful?

0 0

Post a comment