How to include conditional installs -- namely for backports #10
Replies: 3 comments
|
Posted the question to this stackoverflow question. |
|
In the first if sys.version_info >= (3, 8):
import importlib.metadata as importlib_metadata
else:
import importlib_metadataIt has its merits: We'd be more explicit there. In the |
|
Unless we put it in a often used package, like Here's the code without the docs: def find_obj(*module_and_obj_names):
module_and_obj_names = list(map(_ensure_pair, module_and_obj_names))
for module_name, obj_name in module_and_obj_names:
try:
return import_obj(module_name, obj_name)
except (ImportError, ModuleNotFoundError, AttributeError):
continue
from_import_statements = "\n\t" + "\n\t".join(
map("from {} import {}".format, *zip(*module_and_obj_names))
)
raise ImportError(f"All of these import attempts failed:{from_import_statements}")
def import_obj(module_name: str, obj_name: str):
module = __import__(module_name, fromlist=[obj_name])
obj = getattr(module, obj_name)
return obj
def _ensure_pair(x):
if isinstance(x, str):
x = x.split()
assert len(x) == 2, f"should be a pair of strings: {x}"
return xExample usage: |
Uh oh!
There was an error while loading. Please reload this page.
Let's start with a concrete example.
It often happens that I want to use
from importlib.resources import files, but that only exists in 3.9+.In my code, I end up doing:
But I feel shame when copy/pasting this code everywhere. Additionally, it still doesn't solve my problem "completely".
The question is: Do I include
importlib_resources, a third-party backport ofimportlib.resources, in mysetup.cfginstall_requires? If I don't, my code will fail on python < 3.9. If I do include it, I'm overkilling my dependencies.Ideally, I'd like a solution where I can just do
in my code, and trust that the
setup.cfgtook care of doing two things:pip install importlib-resourcesif python version < 3.9importlib_resourcesis an alias forimportlib.resourcesif in 3.9+, and ofimportlib_resources(the pip install backport) if not.Trying to solve the first problem only, I did this.
But it doesn't condition the install at all (it's installed on both 3.8 and 3.10!).
Not sure how to even start with the second "aliasing" desire.
All reactions