{"id":6042,"library":"pyang","title":"pyang: YANG Validator and Converter","description":"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.","status":"active","version":"2.7.1","language":"en","source_language":"en","source_url":"https://github.com/mbj4668/pyang","tags":["YANG","validator","converter","networking","schema","parser"],"install":[{"cmd":"pip install pyang","lang":"bash","label":"Install pyang"}],"dependencies":[],"imports":[{"note":"Required for initializing pyang's plugin system which provides various functionalities like output formats.","symbol":"plugin","correct":"from pyang import plugin"},{"note":"Provides classes like FileRepository to manage YANG module lookup paths.","symbol":"repository","correct":"from pyang import repository"},{"note":"The central object (Context) for a pyang parsing and validation session.","symbol":"context","correct":"from pyang import context"},{"note":"Provides utilities for handling and formatting pyang's validation errors and warnings.","symbol":"error","correct":"from pyang import error"}],"quickstart":{"code":"import os\nimport tempfile\nfrom pyang import plugin, repository, context, error\n\n# Create a dummy YANG file content\nyang_content = \"\"\"\nmodule example-module {\n  namespace \"urn:example:module\";\n  prefix \"ex\";\n\n  container my-container {\n    leaf my-leaf {\n      type string;\n      description \"A simple leaf.\";\n    }\n  }\n}\n\"\"\"\n\n# Create a temporary directory and file for the YANG module\ntemp_dir = tempfile.mkdtemp()\nyang_file_path = os.path.join(temp_dir, 'example-module.yang')\n\nwith open(yang_file_path, 'w') as f:\n    f.write(yang_content)\n\ntry:\n    # 1. Initialize pyang plugins\n    # This is crucial as many functionalities (like output formats) are plugins\n    plugin.init()\n\n    # 2. Create a repository pointing to the directory containing our YANG module\n    repo = repository.FileRepository(temp_dir)\n\n    # 3. Create a pyang context (a parsing and validation session)\n    ctx = context.Context(repo)\n    ctx.opts.add_opts = [] # Ensure no unexpected options interfere\n\n    # 4. Load the module\n    module = ctx.add_module(yang_file_path)\n    if module:\n        print(f\"Successfully loaded module: {module.arg}\")\n        \n        # 5. Validate the context for errors and warnings\n        ctx.validate()\n\n        if ctx.errors:\n            print(\"Validation issues found:\")\n            for e in ctx.errors:\n                print(f\"  {error.err_to_str(e)}\")\n        else:\n            print(\"Module validated successfully with no errors or warnings.\")\n    else:\n        print(f\"Failed to load module from {yang_file_path}\")\nexcept Exception as e:\n    print(f\"An unexpected error occurred: {e}\")\nfinally:\n    # Clean up the temporary file and directory\n    os.remove(yang_file_path)\n    os.rmdir(temp_dir)\n","lang":"python","description":"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."},"warnings":[{"fix":"Initialize plugins with `plugin.init()` and ensure relevant output plugins are loaded or explicitly used with the `Context` to leverage their functionality. For CLI-like output, you might need to replicate the `pyang` script's logic for invoking plugins.","message":"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.","severity":"gotcha","affected_versions":"All versions when using the Python API for output."},{"fix":"Pass the correct directory paths to `FileRepository`'s constructor, or use `ctx.repository.add_path()` for additional lookup directories. Ensure all imported YANG modules are accessible via these configured paths.","message":"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`.","severity":"gotcha","affected_versions":"All versions."},{"fix":"Thoroughly re-validate YANG modules, especially those with complex `pattern` restrictions, when upgrading to or from `pyang` 2.3.2 and later. Adjust patterns if necessary to comply with the XML Schema regex engine's semantics.","message":"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.","severity":"breaking","affected_versions":"Upgrading to or from `pyang` 2.3.2 and later, particularly from versions where a non-XML Schema regex engine was in use."},{"fix":"Upgrade `pyang` to version 2.4.0 or newer. If an upgrade is not possible, use `pip < 10.0.0` or run `pyang` within a virtual environment.","message":"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'`.","severity":"gotcha","affected_versions":"Versions of `pyang` prior to ~2.4.0 when used with `pip` 10.0.0 or later."}],"env_vars":null,"last_verified":"2026-04-14T00:00:00.000Z","next_check":"2026-07-13T00:00:00.000Z"}