sykloid
sykloid

Reputation: 101336

Python: Problem with local modules shadowing global modules

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)?

Upvotes: 17

Views: 3659

Answers (2)

Ryan Ginstrom
Ryan Ginstrom

Reputation: 14121

I try to avoid shadowing the standard library. How about renaming your module to "_numbers.py" ?

And of course, you could still do:

import _numbers as numbers

Upvotes: 7

SilentGhost
SilentGhost

Reputation: 319881

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

Upvotes: 9

Related Questions