Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Problem with local modules shadowing global modules

Tags:

python

I've got a package set up like so:

packagename/
    __init__.py
    numbers.py
    tools.py
    ...other stuff

Now inside tools.py, I'm trying to import the standard library module fractions. However, the fractions module itself imports the numbers module, which is supposed to be the one in the standard library.

The problem is that it tries to import the numbers modules from my package instead (ie my numbers.py is shadowing the stdlib numbers module), and then complains about it, instead of importing the stdlib module.

My question is, is there a workaround so that I can keep the current structure of my package, or is the only solution to rename my own offending module (numbers.py)?

like image 953
sykora Avatar asked Jan 29 '09 14:01

sykora


People also ask

Why can't I import modules in Python?

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.

Does Python cache imports?

Python caches all imported modules This all happened because Python caches modules. In Python, every module that is imported is stored in a dictionary called sys.

What is module aliasing in Python?

In python programming, the second name given to a piece of data is known as an alias. Aliasing happens when the value of one variable is assigned to another variable because variables are just names that store references to actual value.


1 Answers

absolute and relative imports can be used since python2.5 (with __future__ import) and seem to be what you're looking for.

like image 147
SilentGhost Avatar answered Sep 17 '22 22:09

SilentGhost