I'm working on a program that needs to work with partial functionality if a package is not installed on a machine. Specifically it outputs a stream of data either as a TCP message or over ROS. On a machine that doesn't have ROS installed I would like to disable that option. My current solution is to wrap the optional functionality in a class that will initialize fully if an import succeeds and will return nothing if it is not
try:
import rospy
ros_available = True
except ModuleNotFoundError as e:
print(e)
ros_available = False
class ROSOutput:
def __init__(self):
self.ros_available = ros_available
if not ros_available:
return
# if available- initialize
def do_things():
if not self.ros_available:
return False # Nope
# if available- do things
Can anyone suggest a smarter way to do this? Can I avoid defining a variable during imports?