Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?

One of my Python problems was to name modules in my projects. Whenever I had used same module name with built-in one or higher level modules, I was getting in trouble. Because, when I try to import built-in or higher level libraries in my code, only my module was seen and I had import error.

Here is clear explanation; Assume that I have a Project structer like;

* root
	* my_app
    	* logging
        	* __init__.py
            * my_logging_code.py
        * my_code.py

Whenever I try to import built-in logging libraray to getLogger in my_code.py, my logging modules was overriding it and I can't import it. Here is the situation

import logging

logger = logging.getLogger(__name__)

The result was;

Traceback (most recent call last):
  File "<input>", line 3, in <module>
AttributeError: 'module' object has no attribute 'getLogger'

I realised that it was seeing my logging module totaly. Only way I saw was to change my module name and it was really bothering me about Python.

Today I found a way by not changing my module name. Solution was to use absolute_import. Here is the true version of my_code.py

from __future__ import absolute_import
import logging

logger = logging.getLogger(__name__)

So, after now, feel free to use built-in module names and higher level library names like; django,celery etc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment