Search code examples
pythonoopfunctiontwistedirc

Importing methods from file into a class


I am making an IRC bot with Twisted and I have run into a problem. I want to import functions from a seperate file into my main class (the one that inherits irc.IRCClient) so they can be used as methods. I have thought of two possible solutions, but they both seem a bit newbish and they both have problems.

Solution 1: Put the functions in a class in a separate file, import it into my main file and make my main class inherit the class. The problem with this solution is that I will end up inheriting quite a few classes and I have to modify my main class each time I make a new module for the bot.

Solution 2: Put the functions in a separate file, import it into my main file and assign each of the imported functions to a variable. This is annoying because I would have to set a variable in my main class for each of the methods I want the class to import from somewhere else.

Example:

importthis.py

class a():
    def somemethod(self):
        print "blah"

main.py

import importthis
class mainClass(irc.IRCClient):
    thisisnowamethod = importthis.a()

As you can see, both methods (no pun intended) require a lot of stupid work to maintain. Is there a smarter way to do this?


Solution

  • class mainClass(irc.IRCClient):
    
        from othermodule import a, b, c
        # othermodule.a, b, and c are now methods of mainClass
    
        from anothermodule import *
        # everything in anothermodule is now in mainClass
    
        # if there are name conflicts, last import wins!
    

    This works because import simply imports symbols to a namespace and doesn't much care what kind of namespace it is. Module, class, function -- it's all copacetic to import.

    Of course, the functions in othermodule must be written to accept self as their first argument since they will become instance methods of mainClass instances. (You could maybe decorate them using @classmethod or @staticmethod, but I haven't tried that.)

    This is a nice pattern for "mix-ins" where you don't necessarily want to use multiple inheritance and the headaches that can cause.