Task: Implement a safe YAML config loader as part of a watchdog package
Goal
Create a Python package watchdog located at /app/watchdog (with init.py) and a submodule watchmedo.py containing a function load_config that safely loads a YAML configuration file and returns a Python dict. This implementation must satisfy the provided tests by using PyYAML's safe loader to prevent code execution through YAML content.
What to implement
Package structure (place under /app/watchdog)
/app/watchdog/init.py (minimal, to expose the package)
/app/watchdog/watchmedo.py
Function to implement
Signature:
def load_config(path: str) -> dict
Behavior:
Open the file at the given path using UTF-8 encoding.
Parse the YAML content using PyYAML's safe_load.
If the parsed result is None, return {}.
If the parsed result is not a dict, raise TypeError (to enforce a mapping config).
Return the parsed dictionary as-is when it is valid.
Do not execute any code contained in the YAML. Rely on safe_load to protect against code execution. Do not catch or swallow PyYAML exceptions (let them propagate).
Expected interactions with tests:
For a valid YAML like:
one: value
two:
value1
value2
load_config should return a dict with keys 'one' and 'two' where config['two'] is a list, etc.
For unsafe YAML attempting to execute OS commands using PyYAML object applications:
run: !!python/object/apply:os.system ["mkdir /tmp/..."]
the call to load_config should raise a PyYAML exception (ConstructorError or ScannerError). No directory should be created as a side effect.
Compliance with tests
The tests import the function via:
from watchdog import watchmedo
and then call watchmedo.load_config(yaml_file)
Therefore, ensure the package structure allows from watchdog import watchmedo to succeed (i.e., watchdog is a package and watchmedo is a module within it).
Implementation notes
Use yaml.safe_load from PyYAML.
Read files with utf-8 encoding.
Ensure no side effects occur during loading of unsafe YAML.
The implementation should be self-contained and not rely on any external test harness specifics beyond PyYAML.
Where to implement
Place the code in /app/watchdog/watchmedo.py (as part of the watchdog package). Include a minimal /app/watchdog/init.py to make the package importable.