| 1 | # Copyright: 2005 Brian Harring <ferringb@gmail.com> |
|---|
| 2 | # License: GPL2 |
|---|
| 3 | |
|---|
| 4 | """ |
|---|
| 5 | dynamic import functionality |
|---|
| 6 | """ |
|---|
| 7 | |
|---|
| 8 | import sys |
|---|
| 9 | |
|---|
| 10 | class FailedImport(ImportError): |
|---|
| 11 | def __init__(self, trg, e): |
|---|
| 12 | ImportError.__init__( |
|---|
| 13 | self, "Failed importing target '%s': '%s'" % (trg, e)) |
|---|
| 14 | self.trg, self.e = trg, e |
|---|
| 15 | |
|---|
| 16 | |
|---|
| 17 | def load_module(name): |
|---|
| 18 | """load 'name' module, throwing a FailedImport if __import__ fails""" |
|---|
| 19 | if name in sys.modules: |
|---|
| 20 | return sys.modules[name] |
|---|
| 21 | try: |
|---|
| 22 | m = __import__(name) |
|---|
| 23 | # __import__('foo.bar') returns foo, so... |
|---|
| 24 | for bit in name.split('.')[1:]: |
|---|
| 25 | m = getattr(m, bit) |
|---|
| 26 | return m |
|---|
| 27 | except (KeyboardInterrupt, SystemExit): |
|---|
| 28 | raise |
|---|
| 29 | except Exception, e: |
|---|
| 30 | raise FailedImport(name, e) |
|---|
| 31 | |
|---|
| 32 | |
|---|
| 33 | def load_attribute(name): |
|---|
| 34 | """load a specific attribute, rather then a module""" |
|---|
| 35 | chunks = name.rsplit(".", 1) |
|---|
| 36 | if len(chunks) == 1: |
|---|
| 37 | raise FailedImport(name, "it isn't an attribute, it's a module") |
|---|
| 38 | try: |
|---|
| 39 | m = load_module(chunks[0]) |
|---|
| 40 | m = getattr(m, chunks[1]) |
|---|
| 41 | return m |
|---|
| 42 | except (AttributeError, ImportError), e: |
|---|
| 43 | raise FailedImport(name, e) |
|---|
| 44 | |
|---|
| 45 | |
|---|
| 46 | def load_any(name): |
|---|
| 47 | """Load a module or attribute.""" |
|---|
| 48 | try: |
|---|
| 49 | return load_module(name) |
|---|
| 50 | except FailedImport, fi: |
|---|
| 51 | if not isinstance(fi.e, ImportError): |
|---|
| 52 | raise |
|---|
| 53 | return load_attribute(name) |
|---|