简体   繁体   中英

Python namespace confusion

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.

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 ac 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM