• Posts
  • RSS
  • ◂◂RSS
  • Contact

  • Importing Python By Path

    February 17th, 2011
    python, tech  [html]

    Update 2012-01-06: Warning: this post is what you get if you don't know about the function __import__ and try to reinvent it.

    Imagine I have two different python files that are drop-in replacements for each other, perhaps for some kind of plugin system:

      $ cat a/c.py
      def d():
         print "hello world a"
      $ cat b/c.py
      def d():
         print "hello world b"
      
    And futher imagine I want to use both of them in the same program. I might write:
      import c
      c.d()
      import c
      c.d()
      
    But that has no chance of working. Python doesn't know where to find 'c'. So I need to tell python where to look for my code by changing sys.path:
      sys.path.append("a")
      import c
      c.d()
      sys.path.append("b")
      import c
      c.d()
      
    This will work, ish. It will print "hello world a" twice. Part of this is that the path "a" is sys.path before "b". I really only want this sys.path change to last long enough for my import to work. So maybe I should do:
      class sys_path_containing(object):
         def __init__(self, fname):
             self.fname = fname
    
         def __enter__(self):
             self.old_path = sys.path
             sys.path = sys.path[:]
             sys.path.append(self.fname)
    
         def __exit__(self, type, value, traceback):
             sys.path = self.old_path
    
      with sys_path_containing("a"):
         import c
    
      c.d()
    
      with sys_path_containing("b"):
          import c
    
      c.d()
      
    This is closer to working. I define a context manager so that code run with sys_path_containing will see a different sys.path. So my first "import c" will see a sys.path like ["foo", "bar", "a"] and my second import will see ["foo", "bar", "b"]. Each is isolated from the other and from other system changes. Unfortunately, it still won't work, because python remembers what it has imported before and doesn't do it again, this will still only print "hello world a" twice. Switching the second "import c" to a "reload(c)" does fix this problem, but at the expense of you already having to know whether something is loaded. Switching to "del sys.modules['c']" and using __import__ would work, though. Let's make that change and put it all into a context manager that does most of the work for us:
      class imported(object):
         def __init__(self, fname):
             self.fname = os.path.abspath(fname)
    
         def __enter__(self):
             if not os.path.exists(self.fname):
                 raise ImportError("Missing file %s" % self.fname)
    
             self.old_path = sys.path
             sys.path = sys.path[:]
    
             file_dir, file_name = os.path.split(self.fname)
             sys.path.append(file_dir)
    
             file_base, file_ext = os.path.splitext(file_name)
             module = __import__(file_base)
             del sys.modules[file_base]
    
             return module
    
         def __exit__(self, type, value, traceback):
             sys.path = self.old_path
    
      with imported("a/c.py") as c:
         c.d()
    
      with imported("b/c.py") as c:
         c.d()
      
    This will print "hello world a" and then "hello world b". Yay!

    Recent posts on blogs I like:

    Pulses (Hoisted from Comments)

    Robert Jackel asked me an excellent question in comments: what is a pulse? I’ve talked about timed transfers a lot in the last almost 10 years of this blog, but I never wrote a precise definition. This is a critical tool for every public transportation op…

    via Pedestrian Observations February 23, 2021

    Collections: The Universal Warrior, Part III: The Cult of the Badass

    This is the third and final part of a discussion (I, IIa, IIb) discussion of the notion that there is a ‘universal warrior’ – a transcendent sameness about either the experience of war or ‘warrior values’ which might provide some sort of useful blueprint …

    via A Collection of Unmitigated Pedantry February 19, 2021

    The Troubling Ethics of Writing (A Speech from Ancient Sumer)

    (Translated from a transcript of an ancient Sumerian speech by Uruk's most well-respected Scriptological Ethicist) Writing is a profoundly dangerous technology: Access to writing was initially, and still remains, uneven. What's worse, the rich are m…

    via BLOG - Cullen O'Keefe February 15, 2021

    more     (via openring)


  • Posts
  • RSS
  • ◂◂RSS
  • Contact