After import, some submodules are accessible and some aren't

Chris Angelico rosuav at gmail.com
Fri Oct 28 17:46:07 EDT 2016


On Sat, Oct 29, 2016 at 8:24 AM, John Gordon <gordon at panix.com> wrote:
> After importing a module, I can access some of its submodules directly
> but others require an explicit import of the submodule.
>
> As an example, see ldap.dn and ldap.modlist:
>
> % python
> Python 2.7.8 (default, Aug  4 2016, 09:29:33)
> [GCC 4.4.7 20120313 (Red Hat 4.4.7-9)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> import ldap
>>>> ldap.__version__
> '2.4.19'
>>>> ldap.modlist
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> AttributeError: 'module' object has no attribute 'modlist'
>>>> ldap.dn
> <module 'ldap.dn' from '/opt/rh/python27/root/usr/lib64/python2.7/site-packages/ldap/dn.pyc'>
>>>> import ldap.modlist
>>>> ldap.modlist
> <module 'ldap.modlist' from '/opt/rh/python27/root/usr/lib64/python2.7/site-packages/ldap/modlist.pyc'>
>
> Why the difference?

A package can leave some of its modules for lazy loading. By default,
only the package itself gets loaded (making available any names in
__init__.py itself, but no modules); if the package wishes to eagerly
load some of the modules, it can import them itself ("from . import
dn"). It's probably something along the lines of ldap.dn being
critical but ldap.modlist being optional - you'd have to check the
docs or ask the author to find out exactly why.

ChrisA



More information about the Python-list mailing list