pyang: YANG Validator and Converter
A YANG (RFC 6020/7950) validator and converter, `pyang` provides tools for parsing, validating, and transforming YANG modules. It is primarily used as a command-line tool but also offers a Python API for programmatic access to perform validation, convert modules to formats like YIN (XML) or tree structures, and generate code. The project maintains an `active` development pace with frequent minor releases, currently at version 2.7.1.
Warnings
- gotcha Users often expect `pyang` to output various formats (tree, JSON, YIN, etc.) directly after loading a module via the API. However, these functionalities are provided by plugins that must be initialized and potentially explicitly called or activated within the `Context` to produce the desired output, mimicking command-line flags. Without proper plugin setup, `ctx.emit()` might not produce expected results.
- gotcha When using `repository.FileRepository`, ensuring that the repository paths correctly include directories containing both the primary YANG module and any modules it `import`s is crucial. `pyang` will fail to resolve dependencies if they are not found within the configured repository paths, leading to "module not found" errors during `add_module` or `validate`.
- breaking In version 2.3.2, `pyang` reverted a fix for issue #587, causing it to switch back to using the XML Schema regular expression engine for pattern validation. This means that YANG modules relying on specific behaviors or features of the previously used Python `re` engine for pattern matching might exhibit different validation results (e.g., a module that was previously valid might become invalid, or vice-versa) when moving to or from versions where this change was active.
- gotcha Older versions of `pyang` (prior to approximately 2.4.0) could crash when installed with `pip` versions 10.0.0 or higher due to changes in `pip`'s internal structure (specifically, the removal of `pip.locations`). Users attempting to install older `pyang` or run `pyang` in environments with `pip` 10+ might encounter `AttributeError: module 'pip' has no attribute 'locations'`.
Install
-
pip install pyang
Imports
- plugin
from pyang import plugin
- repository
from pyang import repository
- context
from pyang import context
- error
from pyang import error
Quickstart
import os
import tempfile
from pyang import plugin, repository, context, error
# Create a dummy YANG file content
yang_content = """
module example-module {
namespace "urn:example:module";
prefix "ex";
container my-container {
leaf my-leaf {
type string;
description "A simple leaf.";
}
}
}
"""
# Create a temporary directory and file for the YANG module
temp_dir = tempfile.mkdtemp()
yang_file_path = os.path.join(temp_dir, 'example-module.yang')
with open(yang_file_path, 'w') as f:
f.write(yang_content)
try:
# 1. Initialize pyang plugins
# This is crucial as many functionalities (like output formats) are plugins
plugin.init()
# 2. Create a repository pointing to the directory containing our YANG module
repo = repository.FileRepository(temp_dir)
# 3. Create a pyang context (a parsing and validation session)
ctx = context.Context(repo)
ctx.opts.add_opts = [] # Ensure no unexpected options interfere
# 4. Load the module
module = ctx.add_module(yang_file_path)
if module:
print(f"Successfully loaded module: {module.arg}")
# 5. Validate the context for errors and warnings
ctx.validate()
if ctx.errors:
print("Validation issues found:")
for e in ctx.errors:
print(f" {error.err_to_str(e)}")
else:
print("Module validated successfully with no errors or warnings.")
else:
print(f"Failed to load module from {yang_file_path}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
finally:
# Clean up the temporary file and directory
os.remove(yang_file_path)
os.rmdir(temp_dir)