Why do Python modules sometimes not import their sub-modules?

Viewed 28110

I noticed something weird today I would like explained. I wasn't 100% sure how to even phrase this as a question, so google is out of the question. The logging module does not have access to the module logging.handlers for some odd reason. Try it yourself if you don't believe me:

>>> import logging
>>> logging.handlers
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'handlers'
>>> import logging.handlers
>>> logging.handlers
<module 'logging.handlers' from '/usr/lib/python2.6/logging/handlers.pyc'>

Can anyone explain why this happens?

4 Answers

Thomas Wouters answered this question very well, but alas, I only found this question after finding the answer in the original documentation. To that end I thought I would add to this in the hopes it pops up closer to the top of the search engine in the future.

QUESTION

Why does the error: 'AttributeError: module 'module_name' has no attribute 'sub_module_name' appear even though my editor (e.g. Visual Code) auto-completes the sub-module name:

 import module_name
 module_name.sub_module_name(parameter)

ANSWER

Your editor is basing its autocomplete off of the file structure of your project and not off of Python behavior. Sub-modules are not 'automatically' imported when you import a module. Reference Python Documentation for details on how to 'automatically' import sub-modules when using

 import module_name

The key contribution with this answer being the addition of AttributeError when trying to import a 'module' or 'package'

Hope this helps someone!

I've faced recently the same odd situation. So, I bet you've removed some third-party lib import. That removed lib contained from logging import handlers or from logging import * and provided you handlers. And in other script you've had something like import logging and just used logging.handlers and you've thought that is a way things work as I did.

Related