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  License: PSF license (http://docs.python.org/license.html).
 
10  """ 
11  
 
12 -def get_mod(modulePath):
13 """Import a module.""" 14 return __import__(modulePath, globals(), locals(), [''])
15 16
17 -def get_func(fullFuncName):
18 """Retrieve a function object from a full dotted-package name.""" 19 20 # Parse out the path, module, and function 21 lastDot = fullFuncName.rfind(u".") 22 funcName = fullFuncName[lastDot + 1:] 23 modPath = fullFuncName[:lastDot] 24 25 aMod = get_mod(modPath) 26 aFunc = getattr(aMod, funcName) 27 28 # Assert that the function is a *callable* attribute. 29 assert callable(aFunc), u"%s is not callable." % fullFuncName 30 31 # Return a reference to the function itself, 32 # not the results of the function. 33 return aFunc
34 35
36 -def get_class(fullClassName, parentClass=None):
37 """Load a module and retrieve a class (NOT an instance). 38 39 If the parentClass is supplied, className must be of parentClass 40 or a subclass of parentClass (or None is returned). 41 """ 42 aClass = get_func(fullClassName) 43 44 # Assert that the class is a subclass of parentClass. 45 if parentClass is not None: 46 if not issubclass(aClass, parentClass): 47 raise TypeError(u"%s is not a subclass of %s" % 48 (fullClassName, parentClass)) 49 50 # Return a reference to the class itself, not an instantiated object. 51 return aClass
52