Package smartcard :: Module ClassLoader
[hide private]
[frames] | no frames]

Source Code for Module smartcard.ClassLoader

 1  """ClassLoader allows you to load modules from packages without
 
 2  hard-coding their class names in code; instead, they might be
 
 3  specified in a configuration file, as command-line parameters,
 
 4  or within an interface.
 
 5  
 
 6  Source: Robert Brewer at the Python Cookbook:
 
 7  http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/223972
 
 8  """ 
 9  
 
10  import sys 
11  import types 
12  
 
13  
 
14 -def get_mod(modulePath):
15 """Import a module.""" 16 return __import__(modulePath, globals(), locals(), [''])
17 18
19 -def get_func(fullFuncName):
20 """Retrieve a function object from a full dotted-package name.""" 21 22 # Parse out the path, module, and function 23 lastDot = fullFuncName.rfind(u".") 24 funcName = fullFuncName[lastDot + 1:] 25 modPath = fullFuncName[:lastDot] 26 27 aMod = get_mod(modPath) 28 aFunc = getattr(aMod, funcName) 29 30 # Assert that the function is a *callable* attribute. 31 assert callable(aFunc), u"%s is not callable." % fullFuncName 32 33 # Return a reference to the function itself, 34 # not the results of the function. 35 return aFunc
36 37
38 -def get_class(fullClassName, parentClass=None):
39 """Load a module and retrieve a class (NOT an instance). 40 41 If the parentClass is supplied, className must be of parentClass 42 or a subclass of parentClass (or None is returned). 43 """ 44 aClass = get_func(fullClassName) 45 46 # Assert that the class is a subclass of parentClass. 47 if parentClass is not None: 48 if not issubclass(aClass, parentClass): 49 raise TypeError(u"%s is not a subclass of %s" % 50 (fullClassName, parentClass)) 51 52 # Return a reference to the class itself, not an instantiated object. 53 return aClass
54