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