美文网首页
How to import self defined modul

How to import self defined modul

作者: Jiafu | 来源:发表于2021-10-17 17:31 被阅读0次

    The directory structure is shown below:

    
    - lib
      - __init__.py
      - a.py
      - b.py
      - sublib
        - c.py
    - script
      - mylib.py
      - test.py
    - main.py
    

    File Content:

    a.py:

    def a():
        print('this is a function, %s, %s' % (__package__, __name__))
    

    b.py:

    from . import a # Here we import a.py which is in the same directory as b.py.
    
    
    def b():
        a.a()
        return 'hello world'
    

    c.py:

    from .. import b # Here we import b.py which is in the upper directory of sublib.
    
    
    def c():
        b.b()
        print("c is call:%s %s" % (__package__, __name__) )
    

    You cant see from the example, if we are making self defined modules, we can use relative import, which is simple and straightforward. And since we use the relative import, we can change some directory name without changing all the relative py files.

    For example, if c.py use absolute import to import b.py, it looks like below:

    from lib import b
    

    If we change the name of lib to lib2, then we have to change b.py.
    But if we use relative import, we don't have to change.

    Import self defined modules using sys.path

    Sometimes we need to import self defined modules which can not be found in the working direcory when using absolute import.

    Look at the example in script/test.py:

    print("test.py package:%s"%__package__)
    
    print("test.py name :%s"%__name__)
    
    import mylib # This will add lib's parent directory to sys.path, see mylib.py.
    from lib import a
    from lib import b
    from lib.sublib import c
    a.a()
    b.b()
    c.c()
    

    script/mylib.py:

    import os
    import sys
    
    cur_dir = os.path.dirname(os.path.realpath(__file__)) # cur_dir will be script.
    sys.path.append("%s/.." % cur_dir) ## Add script's parent directory to sys.path.
    

    相关文章

      网友评论

          本文标题:How to import self defined modul

          本文链接:https://www.haomeiwen.com/subject/ljewoltx.html