2

I'm trying to create a module and it's worried that I might be doing something wrong. I'm encountering some problems with my namespace. I've made an example much like what I have, it has three files with file names according to the comments.

# $PYTHON_PATH/a/b.py

class X:
    pass

def make_x():
    return X()

and I have an init file

# $PYTHON_PATH/a/__init__.py

from b import make_x

Then I have a file

# $PYTHON_PATH/a/c.py

from b import X
x = X()

# For testing
if __name__ == "__main__":
    from a import *
    y = make_x()

    print x.__class__
    print y.__class__

    print isinstance(x,X)
    print isinstance(y,X)

Output on running c.py

b.X
a.b.X
True
False

Perhaps this is just a problem with importing the module from within the module and will go away when I am not testing in this kind of hacky way (from a import *). Is this true, or is there something wrong with how I am structuring the whole thing.

2
  • This is not answer.. Try run python -m a.c in the parent directory of directory a. Commented Jun 15, 2013 at 20:03
  • @falsetru That seems to work. This implies it would be fine as a module... right? Commented Jun 15, 2013 at 20:11

1 Answer 1

1

You've hit upon one of Python's import quirks. Each of the submodules is importing X a different way. The way to fix this would be to perform a relative import of X from .b in a.c instead of the flawed import it currently uses. This will restrict a to being a package, but the presence of __init__.py implies this regardless.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.