Security News
Bun 1.2 Released with 90% Node.js Compatibility and Built-in S3 Object Support
Bun 1.2 enhances its JavaScript runtime with 90% Node.js compatibility, built-in S3 and Postgres support, HTML Imports, and faster, cloud-first performance.
python3 -m pip install kcl-lib
import kcl_lib.api as api
args = api.ExecProgram_Args(k_filename_list=["/path/to/kcl_file.k"])
api = api.API()
result = api.exec_program(args)
print(result.yaml_result)
Setup virtualenv:
python3 -m venv venv
Activate venv:
source venv/bin/activate
Install maturin:
cargo install maturin
Build bindings:
maturin develop
Test
python3 -m pytest
Execute KCL file with arguments and return the JSON/YAML result.
The content of schema.k
is
schema AppConfig:
replicas: int
app: AppConfig {
replicas: 2
}
Python Code
import kcl_lib.api as api
args = api.ExecProgram_Args(k_filename_list=["schema.k"])
api = api.API()
result = api.exec_program(args)
assert result.yaml_result == "app:\n replicas: 2"
A case with the file not found error
import kcl_lib.api as api
try:
args = api.ExecProgram_Args(k_filename_list=["file_not_found"])
api = api.API()
result = api.exec_program(args)
assert False
except Exception as err:
assert "Cannot find the kcl file" in str(err)
Parse KCL single file to Module AST JSON string with import dependencies and parse errors.
The content of schema.k
is
schema AppConfig:
replicas: int
app: AppConfig {
replicas: 2
}
Python Code
import kcl_lib.api as api
args = api.ParseParseFile_Args(path=TEST_FILE)
api = api.API()
result = api.parse_file(args)
Parse KCL program with entry files and return the AST JSON string.
The content of schema.k
is
schema AppConfig:
replicas: int
app: AppConfig {
replicas: 2
}
Python Code
import kcl_lib.api as api
args = api.ParseProgram_Args(paths=["schema.k"])
api = api.API()
result = api.parse_program(args)
assert len(result.paths) == 1
assert len(result.errors) == 0
load_package provides users with the ability to parse KCL program and semantic model information including symbols, types, definitions, etc.
The content of schema.k
is
schema AppConfig:
replicas: int
app: AppConfig {
replicas: 2
}
Python Code
import kcl_lib.api as api
args = api.LoadPackage_Args(
parse_args=api.ParseProgram_Args(paths=["schema.k"]), resolve_ast=True
)
api = api.API()
result = api.load_package(args)
assert list(result.symbols.values())[0].ty.schema_name == "AppConfig"
list_variables provides users with the ability to parse KCL program and get all variables by specs.
The content of schema.k
is
schema AppConfig:
replicas: int
app: AppConfig {
replicas: 2
}
Python Code
import kcl_lib.api as api
args = api.ListVariables_Args(files=[TEST_FILE])
api = api.API()
result = api.list_variables(args)
list_options provides users with the ability to parse KCL program and get all option information.
The content of options.k
is
a = option("key1")
b = option("key2", required=True)
c = {
metadata.key = option("metadata-key")
}
Python Code
import kcl_lib.api as api
args = api.ParseProgram_Args(paths=["options.k"])
api = api.API()
result = api.list_options(args)
assert len(result.options) == 3
assert result.options[0].name == "key1"
assert result.options[1].name == "key2"
assert result.options[2].name == "metadata-key"
Get schema type mapping defined in the program.
The content of schema.k
is
schema AppConfig:
replicas: int
app: AppConfig {
replicas: 2
}
Python Code
import kcl_lib.api as api
exec_args = api.ExecProgram_Args(k_filename_list=["schema.k"])
args = api.GetSchemaTypeMapping_Args(exec_args=exec_args)
api = api.API()
result = api.get_schema_type_mapping(args)
assert result.schema_type_mapping["app"].properties["replicas"].type == "int"
Override KCL file with arguments. See https://www.kcl-lang.io/docs/user_docs/guides/automation for more override spec guide.
The content of main.k
is
a = 1
b = {
"a": 1
"b": 2
}
Python Code
import kcl_lib.api as api
import pathlib
test_file = "main.k"
args = api.OverrideFile_Args(
file=test_file,
specs=["b.a=2"],
)
api = api.API()
result = api.override_file(args)
assert len(result.parse_errors) == 0
assert result.result == True
assert pathlib.Path(test_file).read_text() == """\
a = 1
b = {
"a": 2
"b": 2
}
"""
Format the code source.
Python Code
import kcl_lib.api as api
source_code = """\
schema Person:
name: str
age: int
check:
0 < age < 120
"""
args = api.FormatCode_Args(source=source_code)
api_instance = api.API()
result = api_instance.format_code(args)
assert (
result.formatted.decode()
== """\
schema Person:
name: str
age: int
check:
0 < age < 120
"""
)
Format KCL file or directory path contains KCL files and returns the changed file paths.
The content of format_path.k
is
schema Person:
name: str
age: int
check:
0 < age < 120
Python Code
import kcl_lib.api as api
args = api.FormatPath_Args(path="format_path.k")
api_instance = api.API()
result = api_instance.format_path(args)
print(result)
Lint files and return error messages including errors and warnings.
The content of lint_path.k
is
import math
a = 1
Python Code
import kcl_lib.api as api
args = api.LintPath_Args(paths=["lint_path.k"])
api_instance = api.API()
result = api_instance.lint_path(args)
Validate code using schema and JSON/YAML data strings.
Python Code
import kcl_lib.api as api
code = """\
schema Person:
name: str
age: int
check:
0 < age < 120
"""
data = '{"name": "Alice", "age": 10}'
args = api.ValidateCode_Args(code=code, data=data, format="json")
api_instance = api.API()
result = api_instance.validate_code(args)
assert result.success == True
assert result.err_message == ""
Rename all the occurrences of the target symbol in the files. This API will rewrite files if they contain symbols to be renamed. Return the file paths that got changed.
The content of main.k
is
a = 1
b = a
Python Code
import kcl_lib.api as api
args = api.Rename_Args(
package_root=".",
symbol_path="a",
file_paths=["main.k"],
new_name="a2",
)
api_instance = api.API()
result = api_instance.rename(args)
Rename all the occurrences of the target symbol and return the modified code if any code has been changed. This API won't rewrite files but return the changed code.
Python Code
import kcl_lib.api as api
args = api.RenameCode_Args(
package_root="/mock/path",
symbol_path="a",
source_codes={"/mock/path/main.k": "a = 1\nb = a"},
new_name="a2",
)
api_instance = api.API()
result = api_instance.rename_code(args)
assert result.changed_codes["/mock/path/main.k"] == "a2 = 1\nb = a2"
Test KCL packages with test arguments.
Python Code
import kcl_lib.api as api
args = api.Test_Args(
pkg_list=["path/to/testing/pkg/..."],
)
api_instance = api.API()
result = api_instance.test(args)
Load the setting file config defined in kcl.yaml
The content of kcl.yaml
is
kcl_cli_configs:
strict_range_check: true
kcl_options:
- key: key
value: value
Python Code
import kcl_lib.api as api
args = api.LoadSettingsFiles_Args(
work_dir=".", files=["kcl.yaml"]
)
api_instance = api.API()
result = api_instance.load_settings_files(args)
assert result.kcl_cli_configs.files == []
assert result.kcl_cli_configs.strict_range_check == True
assert (
result.kcl_options[0].key == "key" and result.kcl_options[0].value == '"value"'
)
Download and update dependencies defined in the kcl.mod
file and return the external package name and location list.
The content of module/kcl.mod
is
[package]
name = "mod_update"
edition = "0.0.1"
version = "0.0.1"
[dependencies]
helloworld = { oci = "oci://ghcr.io/kcl-lang/helloworld", tag = "0.1.0" }
flask = { git = "https://github.com/kcl-lang/flask-demo-kcl-manifests", commit = "ade147b" }
Python Code
import kcl_lib.api as api
args = api.UpdateDependencies_Args(
manifest_path="module"
)
api_instance = api.API()
result = api_instance.update_dependencies(args)
pkg_names = [pkg.pkg_name for pkg in result.external_pkgs]
assert len(pkg_names) == 2
assert "helloworld" in pkg_names
assert "flask" in pkg_names
Call exec_program
with external dependencies
The content of module/kcl.mod
is
[package]
name = "mod_update"
edition = "0.0.1"
version = "0.0.1"
[dependencies]
helloworld = { oci = "oci://ghcr.io/kcl-lang/helloworld", tag = "0.1.0" }
flask = { git = "https://github.com/kcl-lang/flask-demo-kcl-manifests", commit = "ade147b" }
The content of module/main.k
is
import helloworld
import flask
a = helloworld.The_first_kcl_program
Python Code
import kcl_lib.api as api
args = api.UpdateDependencies_Args(
manifest_path="module"
)
api_instance = api.API()
result = api_instance.update_dependencies(args)
exec_args = api.ExecProgram_Args(
k_filename_list=["module/main.k"],
external_pkgs=result.external_pkgs,
)
result = api_instance.exec_program(exec_args)
assert result.yaml_result == "a: Hello World!"
Return the KCL service version information.
Python Code
import kcl_lib.api as api
api_instance = api.API()
result = api_instance.get_version()
print(result.version_info)
FAQs
KCL Programming Language Python Lib
We found that kcl-lib demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Bun 1.2 enhances its JavaScript runtime with 90% Node.js compatibility, built-in S3 and Postgres support, HTML Imports, and faster, cloud-first performance.
Security News
Biden's executive order pushes for AI-driven cybersecurity, software supply chain transparency, and stronger protections for federal and open source systems.
Security News
Fluent Assertions is facing backlash after dropping the Apache license for a commercial model, leaving users blindsided and questioning contributor rights.