I want to print in Python 3.6 using colored if that package is available, like so:
print('{}Hello, world!{}'.format(colored.fg(1), colored.attr(0)))
However, I want to make colored
optional if possible, while still printing any text that would optionally be stylized. Simply creating a wrapper function for printing seems inadequate, due to the multiple ways you can use colored
, such as colored.stylize()
and adding colors together:
cheerful = colored.fg('cyan') + colored.attr('bold')
print(colored.stylize("Hello, world!", cheerful, colored.attr("underlined"))
Although mocking is usually used for testing, is it acceptable practice to create a mock library to use if the optional library isn't available? Something like so, in a module called colored_mock
(mocking as described in this question):
from unittest.mock import Mock
import sys
import types
module_name = 'mock_colored'
mock_colored = types.ModuleType(module_name)
sys.modules[module_name] = mock_colored
# following the original definition
def stylize(string, styles, reset=True):
# return the original string so it can be used
return string
mock_colored.stylize = Mock(name=module_name+'.stylize', side_effect=stylize)
# and so on until most of the module attributes and functions are covered
This way I can do:
try:
import colored
except ImportError:
from .mock_colored import mock_colored as colored