lkml Python LookML Parser
lkml is a speedy LookML parser and serializer implemented in pure Python. It parses LookML strings into Python dictionaries and serializes Python dictionaries back into LookML strings. The library is actively maintained with frequent minor releases to support new LookML syntax and improve parsing/serialization accuracy.
Warnings
- gotcha `lkml.load()` discards comments and most original whitespace by default. When a dictionary is serialized back to LookML using `lkml.dump()`, the output will follow lkml's opinionated formatting, losing any original comments or custom whitespace. For lossless round-trip parsing that preserves comments and whitespace, direct manipulation of the parse tree (`lkml.tree`) is required.
- gotcha `lkml.dump()` does not perform semantic validation of the generated LookML. It only guarantees that the output can be successfully parsed by `lkml.load()`. It is the developer's responsibility to ensure the input Python dictionary represents valid LookML constructs to avoid generating malformed or non-functional LookML.
- breaking In versions prior to `1.3.1` and `1.3.2`, `lkml.dump()` could unexpectedly mutate the input Python dictionary. This behavior was fixed, preventing unintended side effects on the original data structure.
- gotcha LookML keys that can be repeated (e.g., `dimension`, `view`, `join`) are automatically converted into pluralized lists (e.g., `dimensions`, `views`, `joins`) when parsed into a Python dictionary. Special handling exists for keys like `allowed_value` and contents of the `query` block, which might also be lists but are not pluralized.
Install
-
pip install lkml
Imports
- load
from lkml import load
- dump
from lkml import dump
Quickstart
import lkml
lookml_content = '''
view: users {
sql_table_name: `analytics.users`;;
dimension: id {
primary_key: yes
type: number
sql: ${TABLE}.id ;;
}
}
'''
# Parse LookML to a Python dictionary
parsed_lookml = lkml.load(lookml_content)
print("Parsed LookML:", parsed_lookml)
# Modify the dictionary (e.g., change dimension type)
for view in parsed_lookml.get('views', []):
if view.get('name') == 'users':
for dimension in view.get('dimensions', []):
if dimension.get('name') == 'id':
dimension['type'] = 'string'
# Serialize the Python dictionary back to LookML
modified_lookml = lkml.dump(parsed_lookml)
print("\nModified LookML:\n", modified_lookml)