How python deals with module and package having the same name?


Python Problem Overview

Suppose I have a module and a package foo/. If I call

import foo

which one will be loaded? How can I specify I want to load the module, or the package?

Python Solutions

Solution 1 - Python

I believe the package will always get loaded. You can't work around this, as far as I know. So change either the package or the module name. Docs:

Solution 2 - Python

Actually, it is possible, by manually guiding the import machinery to use a .py file instead of directory. (This code is not well tested, but seems to work). UPDATE 2020: Note that this requires using custom import_module() function instead of normal import statement. However, with modern Python3 and its importlib, it might be possible to make the bare import statement to work the same way too. (Note that this answer shows flexibility which Python offers. It's not an encouragement to use this in your applications. Use this only if you know what you're doing.)


print "foo module loaded"

File foo/

print "foo package loaded"


import foo


import os, imp

def import_module(dir, name):
    """ load a module (not a package) with a given name 
        from the specified directory 
	for description in imp.get_suffixes():
		(suffix, mode, type) = description
		if not suffix.startswith('.py'): continue
		abs_path = os.path.join(dir, name + suffix)
		if not os.path.exists(abs_path): continue
		fh = open(abs_path)
		return imp.load_module(name, fh, abs_path, (description))

import_module('.', 'foo')


$ python 
foo package loaded

$ python 
foo module loaded

Solution 3 - Python

Maybe you want to move your classes from module to

This way you'll be able to import them from the package as well as importing optional subpackages:

File foo/

class Bar(object):

File foo/

class SubBar(object):


from foo import Bar
from foo.subfoo import SubBar


All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCharles BrunetView Question on Stackoverflow
Solution 1 - PythonzeekayView Answer on Stackoverflow
Solution 2 - PythonabbView Answer on Stackoverflow
Solution 3 - PythonsteppoView Answer on Stackoverflow