Override __import__ in python

I need to override the __import__ function in python when I dynamically import the derived class. (I only have access to the base class). 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 the derived class is imported, I need to call the base class __init__ to add it to the Servers [] list, so when in the main module I call:

__import__('DerivedClassName')

      

The __init__ base will be called

+3


source to share


1 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

      



Thus, every time the derived class was imported, the meta-init got called. Exactly what I wanted. Thanks @MartijnPieters

+2


source







All Articles