How to import self defined modul

2021-10-17  本文已影响0人  Jiafu

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.
上一篇下一篇

猜你喜欢

热点阅读