Package pyamf :: Package adapters

[hide private]
[frames] | no frames]

# Source Code for Package pyamf.adapters

     1  # Copyright (c) 2007-2009 The PyAMF Project.
     2  # See LICENSE for details.
     3
     4  """
     5  The adapter package provides additional functionality for other Python
     6  packages. This includes registering classes, setting up type maps etc.
     7
     8  @since: 0.1.0
     9  """
    10
    11  import os.path, glob
    12
    13  from pyamf.util import imports
    14
    15 -class PackageImporter(object):
    16      """
    17      Package importer used for lazy module loading.
    18      """
    19 -    def __init__(self, name):
    20          self.name = name
    21
    22 -    def __call__(self, mod):
    23          __import__('%s.%s' % ('pyamf.adapters', self.name))
    24
    25  adapters_registered = False
    26
    27 -def register_adapters():
    28      global adapters_registered
    29
    30      if adapters_registered is True:
    31          return
    32
    33      try:
    34          import pkg_resources
    35          packageDir = pkg_resources.resource_filename('pyamf', 'adapters')
    36      except:
    37          packageDir = os.path.dirname(__file__)
    38
    39      for f in glob.glob(os.path.join(packageDir, '*.py')):
    40          mod = os.path.basename(f).split(os.path.extsep, 1)[0]
    41
    42          if mod == '__init__' or not mod.startswith('_'):
    43              continue
    44
    45          try:
    46              register_adapter(mod[1:].replace('_', '.'), PackageImporter(mod))
    47          except ImportError:
    48              pass
    49
    50      adapters_registered = True
    51
    52 -def register_adapter(mod, func):
    53      """
    54      Registers a callable to be executed when a module is imported. If the
    55      module already exists then the callable will be executed immediately.
    56      You can register the same module multiple times, the callables will be
    57      executed in the order they were registered. The root module must exist
    58      (i.e. be importable) otherwise an C{ImportError} will be thrown.
    59
    60      @param mod: The fully qualified module string, as used in the imports
    61          statement. E.g. 'foo.bar.baz'. The string must map to a module
    62          otherwise the callable will not fire.
    63      @type mod: C{str}
    64      @param func: The function to call when C{mod} is imported. This function
    65          must take one arg, the newly imported C{module} object.
    66      @type func: callable
    67      @raise TypeError: C{func} must be callable
    68      """
    69      if not callable(func):
    70          raise TypeError('func must be callable')
    71
    72      imports.whenImported(str(mod), func)
    73