简体   繁体   中英

python “import package as” strange behaviour

I have this file strtucture:

mainfolder
    package/
        __init__.py
        packagefile.py

__init__.py :

import packagefile as othername

If I import package from mainfolder, package will have packagefile and othername too. What is happening ? Is it imported twice ? I have python 2.7.3. Is this the expected behaviour ? When I do import sys as something_else , sys will not be present on the current namespace.

Yes, this is expected behavior. Basically the package always has the modules inside it defined. What you're doing is also importing one of those modules as another name. This doesn't prevent it from already being defined as it's original name.

I don't believe this has any untoward negative consequences. For example, were you to enter the interactive terminal you should see this:

>>> package.packagefile is package.othername
True

This indicates they are references to the same object - similar to comparing two pointers in C++, for example.

However, if you're just trying to rename a module member, I suggest simply renaming the file instead.

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