Brent Newey
Brent Newey

Reputation: 4509

How Do I Get the Module Name of an Object's Class Definition Rather Than the Module Name of the Object's Instantiation?

In python 2.5, I have the following code in a module called modtest.py:

def print_method_module(method):
    def printer(self):
        print self.__module__
        return method(self)
    return printer

class ModTest():

    @print_method_module
    def testmethod(self):
        pass

if __name__ == "__main__":
    ModTest().testmethod()

However, when I run this, it prints out:

__main__

If I create a second file called modtest2.py and run it:

import modtest

if __name__ == "__main__":
    modtest.ModTest().testmethod()

This prints out:

modtest

How can I change the decorator to always print out modtest, the name of the module in which the class is defined?

Upvotes: 25

Views: 38395

Answers (2)

Matt Anderson
Matt Anderson

Reputation: 19809

When you execute a python source file directly, the module name of that file is __main__, even if it is known by another name when you execute some other file and import it.

You probably want to do like you did in modtest2, and import the module containing the class definition instead of executing that file directly. However, you can get the filename of the main module like so, for your diagnostic purposes:

def print_method_module(method):
    def printer(self):
        name = self.__module__
        if name == '__main__':
            filename = sys.modules[self.__module__].__file__
            name = os.path.splitext(os.path.basename(filename))[0]
        print name
        return method(self)
    return printer

Upvotes: 21

djc
djc

Reputation: 11731

I'm guessing you could use sys._getframe() hackery to get at what you want.

Upvotes: -2

Related Questions