How to do relative imports in Python?

前端 未结 15 2806
情深已故
情深已故 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??

    0 讨论(0)
  • 2020-11-21 05:44
    main.py
    setup.py
    app/ ->
        __init__.py
        package_a/ ->
           __init__.py
           module_a.py
        package_b/ ->
           __init__.py
           module_b.py
    
    1. You run python main.py.
    2. main.py does: import app.package_a.module_a
    3. module_a.py does import app.package_b.module_b

    Alternatively 2 or 3 could use: from app.package_a import module_a

    That will work as long as you have app in your PYTHONPATH. main.py could be anywhere then.

    So you write a setup.py to copy (install) the whole app package and subpackages to the target system's python folders, and main.py to target system's script folders.

    0 讨论(0)
  • 2020-11-21 05:44

    On top of what John B said, it seems like setting the __package__ variable should help, instead of changing __main__ which could screw up other things. But as far as I could test, it doesn't completely work as it should.

    I have the same problem and neither PEP 328 or 366 solve the problem completely, as both, by the end of the day, need the head of the package to be included in sys.path, as far as I could understand.

    I should also mention that I did not find how to format the string that should go into those variables. Is it "package_head.subfolder.module_name" or what?

    0 讨论(0)
提交回复
热议问题