Object Structure Utilities

The object structure utilities provide convenient functions to extract and analyze the complete object hierarchy from an Xplain session.

Quick Start

from xplain import create_session, get_full_object_structure

session = create_session()
session.startup('MyConfig')

structure = get_full_object_structure(session)
print(f"Found {len(structure['objects'])} objects")

Functions

get_full_object_structure

Get the complete object structure from an active Xplain session.

from xplain import get_full_object_structure

structure = get_full_object_structure(session)

Returns:

A dictionary with the following structure:

{
    "session_id": "...",
    "root_object": "Root",
    "objects": {
        "ObjectName": {
            "type": "root" | "object",
            "parent": "ParentName" or None,
            "children": ["ChildName1", "ChildName2"],
            "dimensions": [
                {
                    "name": "DimensionName",
                    "type": "categorical" | "numerical" | ...,
                    "attributes": [
                        {
                            "name": "AttributeName",
                            "type": "string" | "int" | ...,
                            "hierarchy_levels": ["Level1", "Level2"]  # optional
                        }
                    ]
                }
            ]
        }
    }
}

save_object_structure

Save the object structure to a JSON file.

from xplain import save_object_structure

filename = save_object_structure(structure, 'my_structure.json')
print(f"Saved to {filename}")

Parameters:

  • structure (dict): Structure from get_full_object_structure()

  • filename (str): Output filename (default: ‘object_structure.json’)

Returns: Path to saved file (str)

get_object_summary

Get a summary with statistics about the object structure.

from xplain import get_object_summary

summary = get_object_summary(structure)

print(f"Objects: {summary['object_count']}")
print(f"Dimensions: {summary['dimension_count']}")
print(f"Attributes: {summary['attribute_count']}")

Returns:

{
    "session_id": "...",
    "root_object": "Root",
    "object_count": 4,
    "dimension_count": 8,
    "attribute_count": 15,
    "objects": {
        "ObjectName": {
            "type": "root",
            "parent": None,
            "dimensions": 2,
            "attributes": 3,
            "children": 1
        }
    }
}

Usage Examples

Basic Usage

from xplain import create_session, get_full_object_structure

# Connect and load data
session = create_session(profile='production')
session.startup('SalesData')

# Get structure
structure = get_full_object_structure(session)

# Access objects
for obj_name, obj_data in structure['objects'].items():
    print(f"{obj_name}: {len(obj_data['dimensions'])} dimensions")

Access Specific Object

structure = get_full_object_structure(session)

# Get specific object
customers = structure['objects']['Customers']

print(f"Type: {customers['type']}")
print(f"Parent: {customers['parent']}")
print(f"Children: {customers['children']}")

# Iterate dimensions
for dim in customers['dimensions']:
    print(f"Dimension: {dim['name']} ({dim['type']})")

    # Iterate attributes
    for attr in dim['attributes']:
        print(f"  Attribute: {attr['name']} ({attr['type']})")

Save and Load

from xplain import save_object_structure
import json

# Save
save_object_structure(structure, 'structure.json')

# Load later
with open('structure.json') as f:
    loaded_structure = json.load(f)

# Use loaded structure
print(f"Root: {loaded_structure['root_object']}")

Traverse Hierarchy

def traverse_objects(structure, obj_name, indent=0):
    """Recursively traverse object hierarchy."""
    obj = structure['objects'][obj_name]

    print("  " * indent + obj_name)

    # Process children
    for child_name in obj['children']:
        traverse_objects(structure, child_name, indent + 1)

# Start from root
structure = get_full_object_structure(session)
traverse_objects(structure, structure['root_object'])

Error Handling

from xplain import create_session, get_full_object_structure

session = create_session()

try:
    structure = get_full_object_structure(session)
except ValueError as e:
    if "Session not initialized" in str(e):
        print("Call session.startup() first")
    elif "No object data" in str(e):
        print("No data loaded in session")
    else:
        raise

Integration with Tests

Use in test scripts:

def test_object_structure():
    """Test that all expected objects are present."""
    from xplain import create_session, get_full_object_structure

    session = create_session(profile='test')
    session.startup('TestConfig')

    structure = get_full_object_structure(session)

    # Assert expected objects exist
    assert 'Customers' in structure['objects']
    assert 'Orders' in structure['objects']

    # Assert hierarchy
    customers = structure['objects']['Customers']
    assert 'Orders' in customers['children']

    # Assert dimensions
    assert len(customers['dimensions']) >= 2

See Also