开发者

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?


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜