Relative import of submodules

In Python, how to do the equivalent of the following

import http.client 

but using relative imports:

 from . import http.client import .http.client 

For the http packet in the current packet? Then I want to access the client module through its parent name http.client , since I would be able to if I made top-level import.

+4
source share
3 answers

I think you are looking for the following:

 from ..http import client 
+2
source

I would look for inspiration in the corresponding PEP 0328 . If you are in http.__init__.py and want to access the client:

 from . import client 
+3
source

You need to import it using from. import http

However, at this point, you will not load the http.client module, and you will not be able to access it:

 >>> http.client AttributeError: 'module' object has no attribute 'client' 

There are various ways around this. The simplest thing is to do it in http/__init__.py

 from . import client 

Other things you can do is

 import types http = types.ModuleType('http') from .http import client http.client = client 

What can you do if it is not practical to modify http/__init__.py

However, since I assume that for some reason this will result in a replacement http.client with a replacement, I would recommend that you do this:

 try: from .http import client except ImportError: from http import client 

And then use the client name instead. This is by far the easiest and most beautiful solution.

Or, if you do not want to use the client as a name:

 try: from .http import client as http_client except ImportError: from http import client as http_client 
+1
source

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


All Articles