How exactly does Python resolve "from X import Y" if there are multiple Ys in X?
Question: I have a package X which contains two different things named Y

One is a module:

    
    
    # X/Y.py
    print 'hello'
    

The other is a variable:

    
    
    # X/__init__.py
    Y = 'world'
    

If I execute `from X import Y` which Y do I get and _why_? What determines the
order and shadowing rules for import statements?

Lastly, is there anything I might do accidentally that would change the
answer?

Basically I got a bug report that indicates on a user's machine this code
results in the opposite Y importing from what I get on my machine. I don't
have access to the user's machine, so I am trying to figure out what happened.

I am wondering if there are clues in this previous question: [python: from x
import y changes previous import
result](http://stackoverflow.com/questions/37317153/python-from-x-import-y-
changes-previous-import-result)


Answer: Modules in packages, once imported, are also set as an attribute on the parent
module object. The `from module import name` syntax, however, will _first_
look at the attributes of the imported module object (the globals of `X`) to
resolve `name`.

So, the answer is that it depends. If you have not imported the `X.Y` module
yet, then you'll end up with `Y` bound to `'world'`. If you have imported
`X.Y` (with `import X.Y` or `from X.Y import some_name`), then `Y` is bound to
the `X.Y` submodule. The latter is a side-effect of `Y` in `X` having been set
as a global.

Demo:

    
    
    $ mkdir foo
    $ cat << EOF > foo/__init__.py
    > bar = 'from the foo package'
    > EOF
    $ cat << EOF > foo/bar.py
    > baz = 'from the foo.bar module'
    > EOF
    $ bin/python -c 'from foo import bar; print(bar)'
    from the foo package
    $ bin/python -c 'import foo.bar; from foo import bar; print(bar); print(bar.baz)'
    <module 'foo.bar' from 'foo/bar.py'>
    from the foo.bar module
    

