import question

Discussion in 'Python' started by Raaijmakers, Vincent \(GE Infrastructure\), Apr 5, 2004.

  1. Question:
    my src path looks like this:
    src\root\sub1
    src\root\sub2

    My main code is in root, lets say main.py and there is also a lib.py.
    In sub1 there if foo1.py and sub2 foo2.py

    Sorry for the long introduction...please don't stop reading... :-(

    In both sub1 and sub2 there is an empty __init__.py for making them a package.
    Ok the problem:

    this works fine:

    main.py
    from sub1 import foo1
    from sub1 import foo2

    However, in foo1 and foo2 I have this line "import lib".

    So lib.py is not in the same path as foo1.py and foo2.py, it seems to find lib.py in a higher path.
    (Reason for this is the import from main , which has lib.py in the same path?)

    However, if I'm in the subfolders sub1 or sub2, and I run foo1.py or foo2.py standalone, they can't find lib.py. Yeah of course.

    So, how to avoid this? How can I refer back to a module higher in the "hierarchical" path.
    Up is so easy.. just say import foo.foo2.foo3. But up, what is the correct way of doing that?
    Something to put in __init__.py, like sys.path.apppend('..')? Looks ugly to me....

    Or, the way how I share lib for both files is wrong, please let me know.
    Anyway, I need this behavior because of my unittest structure.

    Thanks,
    Vincent
     
    Raaijmakers, Vincent \(GE Infrastructure\), Apr 5, 2004
    #1
    1. Advertising

  2. > So, how to avoid this? How can I refer back to a module higher in the "hierarchical" path.
    > Up is so easy.. just say import foo.foo2.foo3. But up, what is the correct way of doing that?
    > Something to put in __init__.py, like sys.path.apppend('..')? Looks ugly to me....


    PEP 328, Relative imports should take care of your issue.

    In the meantime...

    #in main.py
    import lib

    #in foo1.py and foo2.py
    import sys
    lib = sys.modules['lib']


    Now both of them will refer to the same 'lib' that main.py imported.

    - Josiah
     
    Josiah Carlson, Apr 5, 2004
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Paul Opal
    Replies:
    12
    Views:
    962
    Paul Opal
    Oct 11, 2004
  2. JPractitioner
    Replies:
    13
    Views:
    20,166
    Roedy Green
    Feb 24, 2006
  3. Vitali Gontsharuk
    Replies:
    2
    Views:
    571
    Vitali Gontsharuk
    Aug 25, 2005
  4. Artur M. Piwko

    import/from import question

    Artur M. Piwko, Jun 29, 2003, in forum: Python
    Replies:
    1
    Views:
    843
    Peter Hansen
    Jul 2, 2003
  5. Dennis
    Replies:
    2
    Views:
    507
    Dennis
    Aug 18, 2003
Loading...

Share This Page