is this a good way to do imports ?

Discussion in 'Python' started by Stef Mientki, Nov 5, 2008.

  1. Stef Mientki

    Stef Mientki Guest

    hello,

    I can't find any good documentation or examples of packages,
    so I'm not sure if this is good / correct way, although it seems to work.

    root
    / dir1
    / file1.py
    / general.py

    / dir2
    / file2.py

    / general_root.py

    Now I want to be able to use functions of file2 in file1,
    and vice-versa.
    In practice the directory structure is more complex and nested more deeply,
    and basically I want all modules to be reachable by all other modules.

    ==== file1.py ====
    import general
    import file2
    print file2.var

    ==== file2.py ====
    var = 33

    ==== general.py ====
    dir = '../dir'
    import sys
    if not ( dir in sys.path ) :
    sys.path.append ( dir )

    For a more complex directory structure this is not doable.
    So another approach could be

    ==== file1.py ====
    import general
    import file2
    print file2.var

    ==== file2.py ====
    var = 33

    ==== general.py ==== is doesn't need to know about other branches, only
    of the root
    dir = '../'
    import sys
    if not ( dir in sys.path ) :
    sys.path.append ( dir )
    import general_root

    ==== general_root.py ==== this can be fully automated
    dir = '../dir2/'
    import sys
    if not ( dir in sys.path ) :
    sys.path.append ( dir )

    And for the last thought I had:
    why not use __init__.py instead of the general.py procedure ??

    Maybe I should also set the current working directory to the root or to
    the python file I launch ??

    please enlighten me.

    thanks,
    Stef Mientki
     
    Stef Mientki, Nov 5, 2008
    #1
    1. Advertisements

  2. Terrence Brannon, Nov 5, 2008
    #2
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.