Why name spacing using filenames is broken?

Two other titles I debated between are "Why library code should always use absolute imports" and the click bait "How I broke python using two simple (innocent) lines of code"

Here is the code:

import logging

logger = logging.getLogger(__name__)

Nothing seems wrong. Does it? Type it in your favorite editor or the python REPL. Everything works. So where is the problem?

Type it out in a file and save it as string.py. Now it gets interesting. You get a circular import. Because logging depends on string (which ships with python). But python interpreter links it depends on the string you just wrote. So now logging depends on (your) string.py and (your) string.py depends on logging causing the circular import.

At this point, you are thinking who the fuck names their file string.py? Apparently, I do. It contained string utility functions conveniently kept in util.string.

In fact here is where it becomes even more interesting. Create another file in the same directory and import logging. Let me save you time and tell you what happens. The python interpreter given you an Import Error. ImportError: cannot import name 'Template' from 'string' to be precise.

And that's exactly what happened with me. I was working in some other file. And I found it weird cause my code worked. All tests passed and everything was good. Until I added:

if __name__ == '__main__'
    print(foo())

to test foo manually.

I don't know how to fix this in python short of renaming the file. All help is appreciated.

In C++, namespace do not depend on files and the standard string is inside the std namespace so you specifically have to use std::string. It is annoying but hey! No collisions.

Let me know how your favorite language handles name spacing in the comments.