Override __import__ in python

633 views Asked by At

I need to override __import__ function in python when I dynamically import a derived class. (I only have access to the base class code). For example:

Servers=[]

class ServerBase(object):
    name='' #name of the specific server class, for each server class

    def __init__(self):
        self.connected = False
        self.name = self.__class__.__module__.capitalize()
        Servers.append(self)

When a derived class is imported I need to call __init__ of the base class to add it to Servers[] list, so when in the main module I call:

__import__('DerivedClassName')

Base __init__ will be called

1

There are 1 answers

0
Alex Gill On BEST ANSWER

I ended up metaclassing the Servers class:

Servers=[]

''' Servers Metaclass that handles addition of servers to the list '''
class MetaServer(type):
    def __init__(self, name, bases, attrs):
        self.name = name.capitalize()
        Servers.append(self)
        super(MetaServer, self).__init__(name, bases, attrs)

class ServerBase:
    __metaclass__ = MetaServer
    name='' #name of the specific server class, for each server class

    def __init__(self):
        self.connected = False

That way every time a derived class was imported meta-init got called. Exactly what I wanted. Thanks @MartijnPieters