Question about packages

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • djw

    Question about packages

    I'm sturcturing my (relatively) large application into packages and am
    having trouble understanding one aspect of module/package paths.

    If I have a structure like:

    in /:
    appA.py
    __init__.py

    in X/:
    modX1.py
    modX2.py
    __init__.py

    in Y:/
    modY1.py
    __init__.py

    Now, if I do the following imports and run appA.py, all is well:

    in appA.py:
    from X import modX1
    import Y.modY1

    in modX1:
    import modX2

    in modY1: (as long as run from appA.py)
    import X.modX1

    But, if I try to create a test harness inside modY1 (in an if statement
    checking __name__ with "__main__") and run modY1.py with the last import
    (import X.modX1), I get an ImportError.

    So, the question is, how do you import into a sub-package to allow both
    a script at the root level to import the module ("library mode") and for
    the module itself to run in "test harness" mode with the same import?

    Any hints appreciated.

    -Don










  • Mark McEahern

    #2
    Re: Question about packages

    On Mon, 2003-12-29 at 21:44, djw wrote:[color=blue]
    > So, the question is, how do you import into a sub-package to allow both
    > a script at the root level to import the module ("library mode") and for
    > the module itself to run in "test harness" mode with the same import?[/color]

    You could do something like:

    try:
    import X.modX1
    except ImportError:
    if __name__ == '__main__':
    # Hmm, must be running the test harness, adjust
    # sys.path appropriately, then retry import
    import sys
    sys.path.insert (0, whatever)
    import X.modX1

    but that smells.

    Maybe it's best to separate tests from code?

    Cheers,

    // m


    Comment

    Working...