Why does “import module” and then “from package import module” load the module again?

前端 未结 2 1945
青春惊慌失措
青春惊慌失措 2021-02-13 14:23

I have a package in my PYTHONPATH that looks something like this:

package/
    __init__.py
    module.py
        print \'Loading module\'

If I\

2条回答
  •  青春惊慌失措
    2021-02-13 14:45

    It is a minor defect of the current module system.

    When importing module, you do it from the current namespace, which has no name. the values inside this namespace are the same as those in package, but the interpreter cannot know it.

    When importing package.module, you import module from the package namespace.

    This the reason, that the main.py should be outside the package forlder. Many modules have this organisation :

    package /
        main.py
        package /
            sub_package1/
            sub_package2/
            sub_package3/
            module1.py
            module2.py
    

    Calling only main.py make sure the namespaces are correctly set, aka the current namespace is main.py's. Its makes impossible to call import module1.py in module2.py. You'ld need to call import package.module1. Makes things simpler and homogeneous.

    And yes, import the current folder as the current nameless folder was a bad idea. It is a PITA if you go beyond a few scripts. But as Python started there, it was not completely senseless.

提交回复
热议问题