pyang: YANG Validator and Converter

2.7.1 · active · verified Tue Apr 14

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

Install

Imports

Quickstart

This quickstart demonstrates how to programmatically load and validate a YANG module using `pyang`'s Python API. It creates a dummy YANG file, initializes the plugin system, sets up a file repository, and then adds and validates the module within a context.

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)

view raw JSON →