python import module from a package

后端 未结 3 1110
执念已碎
执念已碎 2021-01-31 12:06

folder structure:


   main.py
   packages 
      __init__.py
      mod.py

main py:

3条回答
  •  囚心锁ツ
    2021-01-31 13:02

    you can load the modules inside the same packages directly. The following code works and it loads all the modules inside mod.py.

    Inside __init__.py

    from mod import *
    print hello()
    

    Efficient import - loads only hello function

    from mod import hello
    print hello()
    

    In your code, from packages import * you are telling the interpreter to look for a modules inside packages(in the same directory as __init__.py). But it does not exist there. It exist one directory above the __init__.py. (I suspect my terminologies are wrong)

    Here is a reference that explains how to load the containing package itself.

    FOUND IT

    It was very interesting to read about python import mechanisms. Ref1 Ref2 Ref3

    Apparently the parent modules is loaded first. For example, Ref3 states that, the code import mod inside __init__.py is automatically interpreted as packages.mod. Now I have to find out what happens if you write import packages.mod. Ref1 is more up-to-date with python3 conventions. Refer it for more info. Hope this helps you.

提交回复
热议问题