I want to update a library so that a requirement is optional (using extras_require).
Unfortunately, imported classes from the optional requirement are used everywhere in the lib as type hints. Here is an example:
from typing import List
try:
from extra.sub import ExtraFoo, ExtraBar
except ImportError:
pass
def optional(foo: ExtraFoo) -> List[ExtraBar]:
pass
def greeting(name: str) -> str:
return 'Hello ' + name
if __name__ == '__main__':
greeting('John Smith')
In this example, we won't use optional() if extra was not installed. Indeed, such code will raise a NameError since ExtraFoo and ExtraBar are used as a type hint.
A possible fix is to declare class ExtraFoo: pass and class ExtraBar: pass in the except block. However, there are situations like that everywhere in the code with multiple types from the same module.
I'd like to avoid polluting the code with declaration of dummy imports. Is there a common way to deal with this situation (e.g. a proxy module)?