Import gotchas

  • Import problems can be tricky, since they reference many parts of the codebase and may cross into other modules or libraries. If you’re having difficulty with import, then something is wrong with your organization or how you’re importing the code. You may need to separate out different pieces of code (but sometimes they’re interdependent) and in general you need to organize code to reuse key pieces in other code with minimum reduplication of your effort. And you may need to have a single area to maintain and update key pieces of code – but there’s initialization and setup code also needed
  • import gotchas – from tips from Westra Chapter 7
    • name masking
      • If you name your package with the same name as a another package, then depending on the search order the interpreter will find one or the other package but you may introduce confusing difficult bugs.
      • If you name a python script with the same name as a different module, you can also mask the name and run into confusing difficulties. If you try to import the module you can end up erroneously importing your file.
      • The fix: you need to identify and give unique names, and you can use the package hierarchy to help
    • double import problems
      • sys.path issues
        • if we add a package directory to sys.path instead of the directory containing the package then the interpreter can import modules both directly and as part of the package, but the interpreter will initialize the module twice which can create subtle errors.
        • The fix: sys.path should include the directory containing the package and not any of its subdirectories
      • if you have executable top level run-once code in a script A and then write some additional functions in a script B that imports A, then the interpreter will run A twice.
        • The fix: it is best to move code that you want the interpreter run in an if __name__ == “__main__” block, which allows both
          • 1) the functions in the module to be imported without triggering the code and
          • 2) the module to be run at the command line
  • You can check out Westra’s Modular Programming book Chapter 7 for more on this, and sign up for more ideas on fixing complex bugs