I have classes in a Python project that depend on an external packages. I would like these classes to be created only if their dependencies are available.
For example, how can I have a class YamlParser
which only exists if yaml
can be imported?
I have classes in a Python project that depend on an external packages. I would like these classes to be created only if their dependencies are available.
For example, how can I have a class YamlParser
which only exists if yaml
can be imported?
You can do this within a try
- except
block.
However, this can highly complicate things if you want to access the class in other places, as the error handling will become more and more complex.
try:
import yaml
Class YamlParser():
pass
except ImportError:
pass
#error handling here
You can also see How to check if a python module exists without importing it for ways to do this without the import statement.
Use try and except to handle this cases:
try:
import yaml
## your code goes here
except ImportError:
## here you handle the expcetion
The modular and extensible solution is to put YamlParser
in its own source file, and simply put the import yaml
statement at the beginning. Any code which tries to import
this code will fail if the required module yaml
is missing.