Import per String

Normalerweise würde man einen Import über einen String mit __import__() erledigen. Die Semantik ist allerdings etwas gewöhnungsbedürftig. Hier ist eine einfachere Variante, die sehr ähnlich wie ein echter Import benutzt werden kann, siehe Docstring:

   1 def import2(from_name, fromlist=None, globals={}, locals={}):
   2     """
   3     An easy wrapper around ``__import__``.
   4     TODO: Python 2.5 level argument not supported yet.
   5     Link: http://www.python-forum.de/topic-14591.html (de)
   6 
   7     >>> import sys
   8     >>> sys2 = import2("sys")
   9     >>> sys is sys2
  10     True
  11 
  12     >>> import os.path
  13     >>> ospath2 = import2("os.path")
  14     >>> os.path is ospath2
  15     True
  16 
  17     >>> from time import time
  18     >>> time2 = import2("time", "time")
  19     >>> time is time2
  20     True
  21 
  22     >>> from os.path import sep
  23     >>> sep2 = import2("os.path", "sep")
  24     >>> sep is sep2
  25     True
  26 
  27     >>> from os import sep, pathsep
  28     >>> sep2, pathsep2 = import2("os", ["sep", "pathsep"])
  29     >>> sep is sep2; pathsep is pathsep2
  30     True
  31     True
  32 
  33     >>> import2("existiertnicht")
  34     Traceback (most recent call last):
  35         ...
  36     ImportError: No module named existiertnicht
  37 
  38     >>> import2("os", "gibtsnicht")
  39     Traceback (most recent call last):
  40         ...
  41     ImportError: cannot import name gibtsnicht
  42     """
  43 
  44     oneonly = False
  45     if isinstance(fromlist, basestring):
  46         oneonly = True
  47         fromlist = [fromlist]
  48 
  49     obj = __import__(from_name, globals, locals, ['foo'])
  50     if fromlist is None:
  51         return obj
  52 
  53     result = []
  54     for object_name in fromlist:
  55         try:
  56             result.append(getattr(obj, object_name))
  57         except AttributeError:
  58             raise ImportError('cannot import name ' + object_name)
  59 
  60     if oneonly:
  61         return result[0]
  62     return result
  63 
  64 
  65 if __name__ == "__main__":
  66     import doctest
  67     doctest.testmod(verbose=True)

Alternative

Eine Alternative bietet Werkzeug mit der import_string Funktion:

   1 path = import_string('os.path')

Import per String (last edited 2009-06-17 16:14:18 by localhost)