How to include conditional installs -- namely for backports #10
Replies: 3 comments
-
Posted the question to this stackoverflow question. |
Beta Was this translation helpful? Give feedback.
-
In the first if sys.version_info >= (3, 8):
import importlib.metadata as importlib_metadata
else:
import importlib_metadata It has its merits: We'd be more explicit there. In the |
Beta Was this translation helpful? Give feedback.
-
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 x Example usage:
|
Beta Was this translation helpful? Give feedback.
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.cfg
install_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.cfg
took care of doing two things:pip install importlib-resources
if python version < 3.9importlib_resources
is an alias forimportlib.resources
if 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.
Beta Was this translation helpful? Give feedback.
All reactions