Decorators API (bd103.decorators)

@bd103.decorators.requires_module(module: str, package: Optional[str] = None, silent: bool = False) collections.abc.Callable[source]

Only allows the use of the function if a certain module or package is installed.

This uses importlib to detect what modules are installed. A common example of this decorator would be in the bd103.ext package.

Parameters
  • module – The name of the module that needs to be installed. This also works on subpackages.

  • package – Finds module relative to the given package name. See importlib.util.find_spec().

  • silent – If false, this function will raise a ModuleNotFoundError. If true, it will skip this function and continue.

Examples

try:
    import colorama
except ImportError:
    colorama = None

@requires_module("colorama")
def do_color_stuff():
    colorama.init()
    print("\x1b[34mHELLO\x1b[0m")
    colorama.deinit()
Raises

ModuleNotFoundError – Package is most likely not installed.

@bd103.decorators.requires_os(os_name: Union[str, List[str]], silent: bool = False) collections.abc.Callable[source]

Only allows the use of the function if running on a certain operating system.

OS detection is done through platform.system().

Parameters
  • os_name – A string or list of strings that say either “windows”, “ubuntu”, or “darwin”. (Or anything that platform.system() might return.)

  • silent – If false and on the wrong OS, it will raise an OSError. If true, it will skip the function and continue.

Examples

@requires_os("windows")
def only_windows():
    print("I CAN SEE THROUGH WINDOWS")
@requires_os(["linux", "darwin"])
def access_home() -> str:
    with open("~/myfile.txt", "rt") as fp:
        return fp.read()
Raises

OSError – Wrong OS type!