I need to know if there is a way to access parent modules from submodules. If I import submodule:
from subprocess import types
I have types
- is there some Python magic to get access to subprocess
module from types
? Something similar to this for classes ().__class__.__bases__[0].__subclasses__()
.
I assume you are not inside the subprocess module already, you could do
Then you could inspect the children of subprocess with the inspect module: http://docs.python.org/library/inspect.html
Maybe the getmodule method would be useful for you? http://docs.python.org/library/inspect.html#inspect.getmodule
On my machine __package__ returns empty for 'types', but can be more useful for my own modules as it does return the parent module as a string
If you've accessed a module you can typically get to it from the
sys.modules
dictionary. Python doesn't keep "parent pointers" with names, particularly because the relationship is not one-to-one. For example, using your example:If you'll note the presence of
types
in thesubprocess
module is just an artifact of theimport types
statement in it. You justimport types
if you need that module.In fact, a future version of
subprocess
may not importtypes
any more, and your code will break. You should only import the names that appear in the__all__
list of a module; consider other names as implementation details.So, for example:
You can see that most of the names visible in
subprocess
are just other top-level modules that it imports.For posterity, I ran into this also and came up with the one liner:
The
or '__main__'
part is just in case you load the file directly it will return itself.