Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the module instance for a class in Python?

Tags:

python

I am learning Python, and as always, I'm being ambitious with my starter projects. I am working on a plugin system for a community site toolkit for App Engine. My plugin superclass has a method called install_path. I would like to obtain the __path__ for the __module__ for self (which in this case will be the subclass). Problem is, __module__ returns a str rather than the module instance itself. eval() is unreliable and undesirable, so I need a good way of getting my hands on the actual module instance that doesn't involve evalling the str I get back from __module__.

like image 454
Bob Aman Avatar asked Oct 05 '09 22:10

Bob Aman


3 Answers

The sys.modules dict contains all imported modules, so you can use:

mod = sys.modules[__module__]
like image 168
Lukáš Lalinský Avatar answered Oct 16 '22 21:10

Lukáš Lalinský


How about Importing modules

X = __import__(‘X’) works like import X, with the difference that you 1) pass the module name as a string, and 2) explicitly assign it to a variable in your current namespace.

You could pass the module name (instead of 'X') and get the module instance back. Python will ensure that you don't import the same module twice, so you should get back the instance that you imported earlier.

like image 45
Tom Leys Avatar answered Oct 16 '22 21:10

Tom Leys


Alternatively, you can use the module's global __file__ variable if all you want is the module's path.

like image 1
u0b34a0f6ae Avatar answered Oct 16 '22 22:10

u0b34a0f6ae