Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 860
chriscauley Avatar asked Sep 23 '10 18:09

chriscauley


People also ask

Why is Python not importing module?

This is caused by the fact that the version of Python you're running your script with is not configured to search for modules where you've installed them. This happens when you use the wrong installation of pip to install packages.

Can a module import another module?

Python modules can get access to code from another module by importing the file/function using import. The import statement is the most common way of invoking the import machinery, but it is not the only way.

Does Python import module multiple times?

So each module is imported only one time.

Can two Python modules import each other?

Modules can import each other cyclically, but there's a catch. In the simple case, it should work by moving the import statements to the bottom of the file or not using the from syntax. Here's why that works: When you import a module, Python first checks sys.


1 Answers

In Python, modules need to be imported before they're accessible. import logging imports just the logging module. It so happens that logging is a package with submodules, but those submodules are still not automatically loaded. So, you need to explicitly import logging.handlers before you can access it.

If you're wondering why it looks like sometimes you don't need those extra imports: some packages import some or all of their submodules when they are imported -- simply by doing those imports in their __init__.py files. In other cases it might be that something else that you import, also imported logging.handlers. It doesn't matter which piece of code does the import; as long as something in your process imports logging.handlers before you access it, it'll be there. And sometimes a module that looks like a package really isn't one, like os and os.path. os isn't a package, it just imports the correct other module (for your platform) and calls it path, just so you can access it as os.path.

like image 113
Thomas Wouters Avatar answered Sep 22 '22 20:09

Thomas Wouters