Is there a way to access parent modules in Python

I need to know if there is a way to access parent modules from submodules. If I import a submodule:

from subprocess import types 

I have types - is there any Python magic to access the subprocess module from types ? Something similar to this for classes ().__class__.__bases__[0].__subclasses__() .

+4
source share
3 answers

If you got access to the module, you can get it in the sys.modules dictionary. Python does not store parent pointers with names, especially because relationships are not one-to-one. For example, using your example:

 >>> from subprocess import types >>> types <module 'types' from '/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/types.pyc'> >>> import sys >>> sys.modules['subprocess'] <module 'subprocess' from '/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.pyc'> 

If you notice that the presence of types in a subprocess module is just an artifact of the import types operator in it. You are just import types if you need this module.

In fact, a future version of subprocess can no longer import types , and your code will break. You should import the names that appear in the __all__ list of the module; consider other names as implementation details.

So for example:

 >>> import subprocess >>> dir(subprocess) ['CalledProcessError', 'MAXFD', 'PIPE', 'Popen', 'STDOUT', '_PIPE_BUF', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_active', '_cleanup', '_demo_posix', '_demo_windows', '_eintr_retry_call', '_has_poll', 'call', 'check_call', 'check_output', 'errno', 'fcntl', 'gc', 'list2cmdline', 'mswindows', 'os', 'pickle', 'select', 'signal', 'sys', 'traceback', 'types'] >>> subprocess.__all__ ['Popen', 'PIPE', 'STDOUT', 'call', 'check_call', 'check_output', 'CalledProcessError'] 

You can see that most of the names visible in subprocess are just the other top-level modules that it imports.

+6
source

For posterity, I came across this and came up with one liner:

 import sys parent_module = sys.modules['.'.join(__name__.split('.')[:-1]) or '__main__'] 

The or '__main__' , just in case you upload the file directly, it will return itself.

0
source

I assume that you are no longer in the subprocess module, you can do

 import somemodule children = dir(somemodule) 

Then you can test the child objects of the subprocess with the validation 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

 import inspect parent_module = inspect.getmodule(somefunction) children = dir(parent_module) package = parent_module.__package__ 

On my machine, __package__ returns an empty value for "types", but may be more useful for my own modules, since it returns the parent module as a string

-1
source

Source: https://habr.com/ru/post/1343488/


All Articles