A quick reference for some interesting python concepts. This is not intended to be complete documentation for python by any means.

Using __import__


There are some times where it is useful to use the __import__ mechanism to import code when you only have string names for the modules. The problem with using __import__ directly is that it can by tricky to get the same result that the "import" statments provide.

To help with that I’ve written this method that handles the details for you. Just give it a package name and a list of modules to import. The method will handle the imports for any submodules listed in the modules list.

def _import(self, pkg_name, modules, obj=None, pkg_attr=None):
    subpackages = {}
    for module in modules[:]:
        if module.find('.') > 0:
            parts = module.split('.')
            subpkg_name = '.'.join([pkg_name, parts[0]])
            subpkg_attr = parts[0]
            if subpkg_name in subpackages:
                subpackages[subpkg_name] = (['.'.join(parts[1:])], subpkg_attr)

    if pkg_attr:
        setattr(obj, pkg_attr,
                __import__(pkg_name, globals(), locals(), modules))
        obj = __import__(pkg_name, globals(), locals(), modules)

    for subpkg_name, (submodules, subpkg_attr) in subpackages.iteritems():
        obj = self._import(subpkg_name, submodules, obj, subpkg_attr)

    return obj

Abstract Classes


Many languages have ways to define Abstract classes and enforce a particular behaviour with those objects. Typically an Abstract class is a class that should not be instantiated directly, but instead either subclassed or instantiated by some generator class.

Python, however, does not explicitly provide a way to do this.

That said, Python does have the tools necessary to achieve the same goal.

class Dog(Object):
    """An abstract class representing a dog.  Should not be directly
    instantiated, instead you should use a subclassed breed.
    def __init__(self, name):
        if self.__class__ is Dog:
            raise NotImplementedError('"Dog" is not a valid breed.')
        self.name = name

    def bark(self):
        print 'WOOF, I'm a %s, WOOF' % self.__class__

class Poodle(Dog):
    def __init__(self, name):
        super(Poodle, self).__init__(name)

class Dalmation(Dog):
    def __init__(self, name):
        super(Dalmation, self).__init__(name)

As you can see, if somebody tries to instantiate the Dog class directly they’ll get an exception with the message "Not Implemented: "Dog" is not a valid breed.". However, everything should work fine if they instantiate a Poodle or a Dalmation.

>>> pup = Dog('fido')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NotImplementedError: "Dog" is not a valid breed.
>>> pup = Poodle('fido')
>>> pup.bark()
WOOF, I'm a Poodle, WOOF
>>> pup = Dalmation('fido')
>>> pup.bark()
WOOF, I'm a Dalmation, WOOF
" "