-
Notifications
You must be signed in to change notification settings - Fork 321
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Import optional packages in a nicer way #346
Comments
I would agree with the first usage example, define |
Found some related PRs in other repos, so let me leave them here:
|
@ananyahjha93 Any thoughts on this? :] |
🚀 Feature
I would like to suggest to implement a context manager class in order to handle optional imports better. With the context manager implemented, importing optional packages and deferring raising
ModuleNotFoundError
will look like:Motivation
The suggested context manager reduces duplicate information in the codebase. Currently, there are redundant lines such as
try: ... except ModuleNotFoundErorr: ...
,_PACKAGE_AVAILABLE
andraise ModuleNotFoundError(...)
.Example
https://github.com/PyTorchLightning/pytorch-lightning-bolts/blob/4d254fde6112b21436003028d553a726bf7ea6ef/pl_bolts/datamodules/cifar10_datamodule.py#L12-L20
https://github.com/PyTorchLightning/pytorch-lightning-bolts/blob/4d254fde6112b21436003028d553a726bf7ea6ef/pl_bolts/datamodules/cifar10_datamodule.py#L86-L89
Pitch
Here is a minimal implementation of context manager and its behaviour.
Example
Alternatives
As suggested in #338 (comment) by @Borda, we could define global variables like
_TORCHVISION_AVAILABLE
inpl_bolts/__init__.py
, but in that way, we will have to add new variables like_NEW_PACKAGE_AVAILABLE
as we add new optional packages to Bolts.See also
Built-in Types - Context Manager Types
Stack Overflow - How to safely handle an exception inside a context manager
Other comments
We can implement the suggested context manager in PL and use it from Bolts. If it should be implemented in PL, could you transfer this issue to PL repo? GitHub Docs - Transferring an issue to another repository
Let me know if it sounds reasonable or too much engineering!
The text was updated successfully, but these errors were encountered: