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__.
views:
94answers:
3
+1
A:
How about Importing modules
X = __import__(‘X’)works likeimport 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.
Tom Leys
2009-10-05 22:09:45
Well, this does seem to work. I'm kinda hoping for a cleaner solution, but if nothing else comes along, I'll accept it.
Bob Aman
2009-10-05 22:18:43
Note that if you do `__import__('foo.bar')`, it will return the `foo` module, not `foo.bar`. See the `__import__` docs for details.
Lukáš Lalinský
2009-10-05 22:27:34
Well, there are a couple of good reasons why Lukas's solution is much better.
Tom Leys
2009-10-05 22:31:46
+4
A:
The sys.modules dict contains all imported modules, so you can use:
mod = sys.modules[__module__]
Lukáš Lalinský
2009-10-05 22:13:24
+1
A:
Alternatively, you can use the module's global __file__ variable if all you want is the module's path.
kaizer.se
2009-10-05 22:31:26