'Clean python import statements
I've created a python wrapper for a REST API. The API has a lot of endpoints, so I created a single file for every endpoint.
The general idea is that the user can do something like this
from my_package import Client
from my_package.endpoints import Users
prod = Client("myhostname.com", "Username", "Password")
all_users = Users(prod).list()
The files of my package are currently structured like this
my_project/
└-- my_package/
| └-- __init__.py
| └-- client.py
| └-- const.py
| └-- endpoints/
| └-- __init__.py
| └-- contracts.py
| └-- credits.py
| └-- payments.py
| └-- users.py
└-- setup.cfg
└-- readme.md
└-- pyproject.toml
# my_package/__init__.py
from my_package.client import Client
# my_package/endpoints/__init__.py
from my_package.endpoints.contracts import Contracts
from my_package.endpoints.creditsimport Credits
from my_package.endpoints.paymentsimport Payments
from my_package.endpoints.usersimport Users
The problem now, is that when you import, you are provided with a lot of duplicates, through intellisense.
from my_package.endpoints import contracts
Contracts
credits
Credits
payments
Payments
users
Users
How can I clean this up?
Solution 1:[1]
I think that this is the correct behavior. To reduce the intellisense suggestions to the class names only, you would need to move the modules to another package.
E.g.
my_project/
?-- my_package/
?-- __init__.py
?-- client.py
?-- api
| ?-- endpoints.py
?-- endpoints/
?-- __init__.py
?-- contracts.py
?-- credits.py
?-- payments.py
?-- users.py
# my_package/endpoints/__init__.py
# my_package/api/endpoints.py
from my_package.endpoints.contracts import Contracts
from my_package.endpoints.creditsimport Credits
from my_package.endpoints.paymentsimport Payments
from my_package.endpoints.usersimport Users
from my_package.api.endpoints import Contracts
Credits
Payments
Users
You can, of course, name the packages differently or choose another structure that fits your needs. For example, you can move contracts.py
and friends to an impl
subpackage and keep the endpoints/__init__.py
file just with slightly modified imports in it. Or you can move contracts.py
and friends to another package. The number of options is unlimited.
The point is that intellisense always suggests you all the names in the given module. Whether they are submodule names, class names, or any other. And that's what users usually want and what they are used to. We usually use documentation as the way to navigate users through our libraries, not intellisense. But if the suggestions really matter to you, you have to move the names outside of the module. (Or do some ugly tricks with import system and dunder attributes.)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | radekholy24 |