{"id":7123,"library":"dafnyruntimepython","title":"Dafny runtime for Python","description":"The `dafnyruntimepython` library provides the necessary runtime support for Python code generated by the Dafny verifier-aware programming language. Dafny compiles its formally verified code into various target languages, including Python. This runtime library is automatically included as source when Dafny builds a Python target. The current version is 4.11.0, and the Dafny project maintains a regular release cadence, with minor versions often released monthly or bi-monthly.","status":"active","version":"4.11.0","language":"en","source_language":"en","source_url":"https://github.com/dafny-lang/dafny","tags":["formal-verification","code-generation","runtime","dafny"],"install":[{"cmd":"pip install dafnyruntimepython","lang":"bash","label":"Install `dafnyruntimepython`"}],"dependencies":[],"imports":[{"note":"The `dafnyruntimepython` library is primarily an internal dependency for code generated by the Dafny compiler. User-written Python code typically imports specific modules (e.g., `MyModule`) from the directory generated by Dafny (e.g., `MyProgram_py`), which then internally relies on `dafnyruntimepython` for its operations. Direct import of `dafnyruntimepython` by user code is uncommon.","wrong":"import dafnyruntimepython","symbol":"Dafny generated modules","correct":"from MyProgram_py import MyModule"},{"note":"The core runtime components are often found within an `_dafny` submodule nested inside the Dafny-generated output directory (e.g., `MyProgram_py/_dafny`). These are usually imported internally by other generated Dafny code and are not intended for direct interaction by users, though they are part of the runtime.","wrong":"import _dafny","symbol":"_dafny","correct":"from MyProgram_py._dafny import ..."}],"quickstart":{"code":"import os\nimport subprocess\n\n# 1. Create a dummy Dafny file\ndafny_code = \"\"\"\n// MyDafnyProgram.dfy\nmodule {:extern \"MyDafnyModule\"} MyModule {\n  class C {\n    static method SayHello() {\n      print \"Hello from Dafny!\\n\";\n    }\n  }\n}\nmethod Main() {\n  MyModule.C.SayHello();\n}\n\"\"\"\n\nwith open(\"MyDafnyProgram.dfy\", \"w\") as f:\n    f.write(dafny_code)\n\nprint(\"Dafny source file created: MyDafnyProgram.dfy\")\n\n# 2. Compile Dafny to Python\n# Requires the 'dafny' CLI tool to be installed and in PATH.\n# This step generates a directory like MyDafnyProgram-py/\ncompile_cmd = [\"dafny\", \"build\", \"--target:py\", \"MyDafnyProgram.dfy\"]\nprint(f\"Executing: {' '.join(compile_cmd)}\")\ntry:\n    subprocess.run(compile_cmd, check=True, capture_output=True, text=True)\n    print(\"Dafny compiled successfully to Python.\")\nexcept subprocess.CalledProcessError as e:\n    print(f\"Dafny compilation failed:\\n{e.stdout}\\n{e.stderr}\")\n    exit(1)\n\n# 3. Execute the generated Python code\n# Add the generated directory to PYTHONPATH to allow imports\nos.environ[\"PYTHONPATH\"] = os.getcwd() + \":\" + os.path.join(os.getcwd(), \"MyDafnyProgram-py\")\n\n# The entry point for the generated Python code is typically in the top-level generated .py file.\n# The name will be derived from the .dfy file (e.g., MyDafnyProgram.py in MyDafnyProgram-py/)\n# For Dafny 4.x, the Main method is typically directly runnable or imported.\n# Let's find the main generated file.\n\noutput_dir = \"MyDafnyProgram-py\"\nif os.path.exists(output_dir):\n    python_main_file = os.path.join(output_dir, \"MyDafnyProgram.py\")\n    if os.path.exists(python_main_file):\n        print(f\"Executing generated Python: python3 {python_main_file}\")\n        try:\n            run_cmd = [\"python3\", python_main_file]\n            result = subprocess.run(run_cmd, check=True, capture_output=True, text=True)\n            print(\"\\n--- Generated Python Output ---\")\n            print(result.stdout)\n            if result.stderr:\n                print(\"--- Generated Python Errors ---\")\n                print(result.stderr)\n            print(\"-------------------------------\")\n        except subprocess.CalledProcessError as e:\n            print(f\"Execution of generated Python failed:\\n{e.stdout}\\n{e.stderr}\")\n            exit(1)\n    else:\n        print(f\"Error: Main Python file not found in {output_dir}\")\n        exit(1)\nelse:\n    print(f\"Error: Dafny output directory {output_dir} not found.\")\n    exit(1)\n\n# Clean up generated files (optional)\n# import shutil\n# if os.path.exists(\"MyDafnyProgram.dfy\"):\n#     os.remove(\"MyDafnyProgram.dfy\")\n# if os.path.exists(output_dir):\n#     shutil.rmtree(output_dir)\n","lang":"python","description":"This quickstart demonstrates the typical workflow for using `dafnyruntimepython`: writing a Dafny program, compiling it to Python using the `dafny` CLI, and then executing the generated Python code. The `dafnyruntimepython` library is implicitly used by the generated Python files. Ensure the `dafny` CLI is installed and in your system's PATH to run this example."},"warnings":[{"fix":"Always interact with Dafny-generated functionality through the modules produced by the Dafny compiler, rather than trying to import `dafnyruntimepython` directly. The generated Python code will handle its internal dependencies.","message":"The `dafnyruntimepython` library is not intended for direct interaction or import by user-written Python code. It is an internal dependency for Python code generated by the Dafny compiler. Attempts to `import dafnyruntimepython` directly will not yield useful functionality as its components are typically exposed through the generated Dafny modules.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Keep your `dafny` CLI tool and `dafnyruntimepython` library updated to their latest compatible versions. The `dafny` CLI is typically installed via `dotnet tool install --global dafny` or by downloading a binary distribution.","message":"When compiling Dafny to Python, ensure the `dafny` CLI tool is installed and its version is compatible with the `dafnyruntimepython` library version. Mismatched versions can lead to unexpected runtime behavior or compilation errors, though the runtime library itself aims for backward compatibility.","severity":"gotcha","affected_versions":"All versions"},{"fix":"When integrating Dafny-generated code with native Python, be mindful of type boundaries. It may be necessary to explicitly convert or map between Dafny-specific types and standard Python types at the interface points to ensure correct behavior and avoid runtime errors.","message":"Generated Python classes from Dafny currently cannot be directly compared or mixed with native Python types in a semantically equivalent way. This can lead to unexpected behavior when passing Dafny-generated objects to native Python functions or vice-versa, especially for complex data structures.","severity":"gotcha","affected_versions":"All versions (as of Dafny 4.x)"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"Ensure that the directory created by the Dafny compiler (e.g., `MyProgram-py/`) is added to your `PYTHONPATH` environment variable before running the generated Python script. For example: `PYTHONPATH=./MyProgram-py python3 MyProgram-py/MyProgram.py`.","cause":"The Python interpreter cannot find the `_dafny` runtime module, which is part of the Dafny-generated output. This usually happens when the `PYTHONPATH` environment variable is not correctly set to include the directory containing the generated code.","error":"ModuleNotFoundError: No module named '_dafny'"},{"fix":"Install the Dafny CLI tool. Instructions are available on the official Dafny website or GitHub repository. Typically, it's installed as a .NET tool (`dotnet tool install --global dafny`) or by downloading a pre-built binary and adding it to your PATH.","cause":"The `dafny` command-line interface tool is not installed or not available in the system's PATH. The `dafnyruntimepython` library is a runtime dependency, but the initial compilation from Dafny source requires the `dafny` CLI.","error":"dafny build --target:py MyProgram.dfy\nError: The command 'dafny' could not be found."},{"fix":"Explicitly convert Dafny-generated collection types to native Python collections (e.g., lists, dicts) before passing them to Python functions that expect specific behaviors. Similarly, if passing native Python collections to Dafny code, ensure they conform to the expected Dafny types and contracts.","cause":"This error can occur when a Dafny-generated type (e.g., a class instance) is passed to a native Python function that expects a standard Python iterable (like a list or tuple), but the Dafny type does not implement the necessary Python iteration protocols.","error":"TypeError: argument of type 'MyDafnyModule_C' is not iterable"}]}