Mp0int
Mp0int

Reputation: 18737

Importing a module which have the same name with a system module

My situation is similar to one in this question... The difference is,

In our python/django project, we have a directory called utils, which keeps basic functions...

Sometimes, we need to test some modules by running thm from console like

python myproject/some_module.py

It is all good, until python tries to import something from our utils directory...

from utils.custom_modules import some_function
ImportError: No module named custom_modules

I check my python path, and our project is on the list, each folder under the project file has __init__.py files, and when i run ipython within project directory... Everything is ok, otherwise, python imports from its own utils directory...

My collegues use the sama method without any problem, but it throws ImportError on my environment... What could be the problem that all of us was missing?

UPDATE: My project directory, and each sub-drectory have __init__.py file, and i can import other modules from my project without any problem... When i am in a diffrent folder than my procekt and i run ipython, a such import have no problem...

from someothermodule.submodule imprort blahblahblah

But, when it comes to importing utils, it fails...

UPATE 2: What caused the problem was the utils directory under django folder, which is also in the python path...

Upvotes: 3

Views: 3232

Answers (2)

agf
agf

Reputation: 176960

See the PEP on absolute and relative imports for the semantics. You probably want

from .utils.custom_modules import some_function

if you're in a file at the top level of your package.

Edit: This can only be done from inside a package. This is for a good reason -- if you're importing something that is part of your project, then you're already treating it like a Python package, and you should actually make it one. You do this by adding an __init__.py file to project directory.

Edit 2: You've completely changed the question. It may be possible to work around the problem, but the correct thing to do is not refer to your packed the same way as a builtin package. You either need to rename utils, or make it a subpackage of another package, so you can refer to it by a non-conflicting name (like from mydjangoapp.utils.custom_modules import some_function).

Upvotes: 6

arpd
arpd

Reputation: 1

I'm not going to bother telling you to try and make sure you don't name your own modules after the stdlib modules;

If you want to leave the name like this, you'll have to use something like this in everything that imports your own utils module:

import sys, imp

utils = sys.modules.get('utils')
if not utils: utils = imp.load_module('utils',*imp.find_module('utils/utils'))

However, unless there's a lot of stuff that you'd have to change after renaming it, I'd suggest you rename it.

Upvotes: -1

Related Questions