Dynamic Importing in Python

Filed under: Articles — ewall at 12:57 PM on Dec 29, 2008
Adding the simplest little bit to a Python/PyGTK app today, I ran into a strange problem where my module couldn't import os.path. Mind you, I could do this from the Python Shell or from other modules, but this one gave some interesting errors:
  • If I told it to import os, I'd get an error saying "AttributeError: 'module' object has no attribute 'path'".

  • If I told it to import os.path, I'd get an error saying "ImportError: No module named path".
Grr...

However, I found the solution on DiveIntoPython's page on Dynamic Importing: After dynamically importing with the line os = __import__('os'), I could call os.path methods just fine. Mind you, I'm not entirely sure why this works, but I figure it has something to do with the way that os.path has to dynamically load the operating system-appropriate module ('posixpath' or Unices or 'ntpath' for Windoze).

Maybe that will help someone out there who is having this same problem, since Google searches show a lot of questions about it, but few solutions.
Only logged in users are allowed to comment. register/log in