Tidbits @ Kassemi

A collection of opinions, thoughts, tricks and misc. information.

Saturday, September 30, 2006

 

Use __import__ on an actual path...

Now, this is definitely not the wisest thing to do, but sometimes you'll want to simply import a module when you know its path. The built in __import__ function won't let you go about doing this. If you're looking for something that works, but might be a little dirty, I've got the trick for you.


# 2006 James Kassemi, (james@tweekedideas.com)
# ================================================
# Import all from all modules in this directory...

import os, imp

def import_path(path, return_name=False):
''' Use like __import__, but with the path to a module. '''
if os.path.isdir(path):
mn = path.split('/')[-1]
path = os.path.join(path, '__init__.py')
if not os.path.exists(path):
path += 'c'
else:
mn = path.split('/')[-1]
mn = mn[:mn.rfind('.')]

suffixes = imp.get_suffixes()
for suffix, mode, type in suffixes:
if path.endswith(suffix):
fp = open(path, mode)
m = imp.load_module(mn, fp, path, (suffix, mode, type))
fp.close()
if return_name: m = (m, mn)
return m
raise ImportError("Not a module: %s" % path)

focal_dir = os.path.dirname(__file__)
for f in os.listdir(focal_dir):
if f.startswith('.') or f.startswith('_'): continue
temp_mod = import_path(os.path.join(focal_dir, f))
for k, v in temp_mod.__dict__.iteritems():
globals()[k] = v



Place the above contents in an __init__.py file and it will automatically load all of the contents from all of the sibling files in the directory. No more specifying an __all__, either, as you can quickly hack this to just import the module itself as well:


focal_dir = os.path.dirname(__file__)
for f in os.listdir(focal_dir):
if f.startswith('.') or f.startswith('_'): continue
module, name = import_path(os.path.join(focal_dir, f), True)
globals()[name] = module


Now there are some concerns with approaching the problem this way... Mainly compatibility with other import statements in the same namespace, sys.modules mapping, etc, but it will work when you're in a pinch.

James

Comments: Post a Comment



<< Home

Archives

August 2005   September 2005   October 2005   November 2005   December 2005   January 2006   February 2006   March 2006   April 2006   June 2006   July 2006   August 2006   September 2006   October 2006   November 2006  

This page is powered by Blogger. Isn't yours?