How to do relative imports in Python?

前端 未结 15 2813
情深已故
情深已故 2020-11-21 04:47

Imagine this directory structure:

app/
   __init__.py
   sub1/
      __init__.py
      mod1.py
   sub2/
      __init__.py
      mod2.py

I\'

15条回答
  •  迷失自我
    2020-11-21 05:43

    explanation of nosklo's answer with examples

    note: all __init__.py files are empty.

    main.py
    app/ ->
        __init__.py
        package_a/ ->
           __init__.py
           fun_a.py
        package_b/ ->
           __init__.py
           fun_b.py
    

    app/package_a/fun_a.py

    def print_a():
        print 'This is a function in dir package_a'
    

    app/package_b/fun_b.py

    from app.package_a.fun_a import print_a
    def print_b():
        print 'This is a function in dir package_b'
        print 'going to call a function in dir package_a'
        print '-'*30
        print_a()
    

    main.py

    from app.package_b import fun_b
    fun_b.print_b()
    

    if you run $ python main.py it returns:

    This is a function in dir package_b
    going to call a function in dir package_a
    ------------------------------
    This is a function in dir package_a
    
    • main.py does: from app.package_b import fun_b
    • fun_b.py does from app.package_a.fun_a import print_a

    so file in folder package_b used file in folder package_a, which is what you want. Right??

提交回复
热议问题