Skip to main content

cloudzero-costformation

PyPI Python versions CI License

A Python library for defining CostFormation dimensions as classes and generating production-ready YAML output.

📖 Guide: Author CostFormation in Python on docs.cloudzero.com.

Full reference documentation for every class lives in docs/.

Features

Condition Operators

Logical:

  • And / Or — Logical operators with overloading support (&, |)
  • Not — Logical negation

String Comparison:

  • Equals — Equality matching (single value or list)
  • Contains — Substring or list membership
  • BeginsWith — Prefix matching
  • EndsWith — Suffix matching
  • Matches — Regular expression matching

Value Checking:

  • HasValue — Check if dimension has a value

Alphabetical Comparison:

  • Before / BeforeOrEquals — Less than (or equal) alphabetically
  • After / AfterOrEquals — Greater than (or equal) alphabetically

Date:

  • ForDateRange — Check if data exists in a date range

Dimension Types

  • CoreDimension — Cloud provider primitives (Account, Service, Region, etc.)
    • Class names with underscores convert to colons (e.g. K8s_Cluster → K8s:Cluster)
    • Cannot be serialized to YAML (only referenced)
  • GlobalDimension — CloudZero-managed dimensions (CZ:Defined: prefix)
    • Cannot be serialized to YAML (only referenced)
    • Inherits from CoreDimension
  • GroupDimension — User-defined grouping dimensions
  • AllocationDimension — Telemetry and proportional allocations

Dimension Attributes

  • name — Display name (defaults to class name)
  • source — Source dimension(s), single or list
  • rules — List of GroupRule, GroupByRule, or MetadataRule objects
  • transforms — Dimension-level transforms applied before rules
  • default_value — Fallback when no rules match
  • child — Hierarchical dimension relationships
  • override — Override another dimension
  • hide — Hide from UI
  • disable — Disable dimension from processing

Rule Types

  • GroupRule — Static grouping with conditions, optional rule-level source (overrides dimension source)
  • GroupByRule — Dynamic grouping based on source values; supports transforms, conditions, and plural sources with CoalesceSources for fallback logic
  • MetadataRule — Pattern matching with substring search; supports hierarchical value patterns and optional format string for output

Transforms

  • Lower, Upper, Title — Case conversion
  • Split — Split by delimiter and extract index (optional maxsplit)
  • Trim — Remove leading/trailing whitespace
  • Clean — Remove whitespace and convert special chars to dashes
  • Normalize — Combined lowercase + whitespace removal + normalization

Allocations

  • Telemetry — AllocateByStreams with stream names
  • Rule-based — AllocateByRules with an AllocationMethod of Proportional or Even

Usage

Install the library from PyPI with uv:

uv add cloudzero-costformation

Or with pip:

pip install cloudzero-costformation

The package installs as cloudzero-costformation; the import name is costformation.

Core & Global Dimensions

The library includes all core cloud provider, Kubernetes, and CloudZero-managed global dimensions from the official CFDL specification:

from costformation import (
    # Core cloud provider dimensions
    Account, Service, Region, Operation, UsageType,
    CloudProvider, Resource,
    # Kubernetes dimensions
    Tag, K8s_Cluster, K8s_Namespace, K8s_Workload, K8s_Label,
    # Global dimensions (CloudZero-managed)
    ServiceDisplay, ResourceType, Category, InstanceType,
)

Core and global dimensions are never defined in CostFormation YAML, only referenced. Attempting to serialize them will raise a TypeError.

Cloud Provider Dimensions: Account, BillingConnectionID, CloudProvider, CommittedUseSubscription, Description, InvoiceID, LineItemType, Operation, PayerAccount, PricingTerm, PricingUnit, PricingUnits, ProductFamily, Region, Resource, RequestType, Service, TransferType, UsageDay, UsageFamily, UsageType

Kubernetes Dimensions: K8s_Cluster, K8s_Namespace, K8s_Workload

Dynamic Dimensions:

  • Tag(key) — Cloud resource tags with any key, e.g. Tag('Environment'), Tag('aws:cloudformation:stack-name')
  • K8s_Label(name) — Kubernetes labels with any name, e.g. K8s_Label('app'), K8s_Label('node:instance-type')

Global Dimensions (CloudZero-managed): BillingLineItem, Category, Elasticity, InstanceType, NetworkingCategory, NetworkingSubCategory, PaymentOption, ResourceDisplay, ResourceNameOnly, ResourceSummaryDisplay, ResourceSummaryID, ResourceType, ServiceDisplay, ServiceDetail, TaggableVsUntaggable

Basic Example

from costformation import (
    Service,
    GroupDimension,
    GroupRule,
    Equals,
)

class MyServices(GroupDimension):
    name = 'My Services'
    source = Service()
    default_value = 'Other'
    rules = [
        GroupRule(
            name='Compute',
            condition=Equals(['EC2', 'Lambda', 'ECS'])
        ),
        GroupRule(
            name='Storage',
            condition=Equals(['S3', 'EBS'])
        ),
    ]

dimension = MyServices()
yaml_dict = dimension.to_dict()

Output:

{
  "Name": "My Services",
  "Type": "Group",
  "Source": "Service",
  "Rules": [
    {
      "Type": "Group",
      "Name": "Compute",
      "Conditions": [{"Equals": ["EC2", "Lambda", "ECS"]}]
    },
    {
      "Type": "Group",
      "Name": "Storage",
      "Conditions": [{"Equals": ["S3", "EBS"]}]
    }
  ],
  "DefaultValue": "Other"
}

Operator Overloading

from costformation import (
    Category,
    Contains,
    GroupDimension,
    GroupRule,
    Lower,
    Operation,
)

class AI_Operations(GroupDimension):
    name = 'AI Operations'
    source = Operation()
    transforms = [Lower()]
    default_value = 'Non-AI'
    rules = [
        GroupRule(
            name='Input',
            condition=(
                Category().equals('AI') &
                Contains(['input', 'prompt'])
            )
        ),
    ]

No Top-Level Source

class ResourceName(GroupDimension):
    name = 'Resource Name'
    source = None
    override = ResourceNameOnly()
    rules = [
        GroupByRule(
            source=ResourceDisplay(),
            conditions=[Not(BeginsWith('billingitem-'))]
        ),
    ]

Rule-Level Source

# CustomerNames_Allocation and Customer are user-defined dimensions
# (definitions omitted for brevity)
class Customer_Names(GroupDimension):
    name = 'Customer Names'
    source = None
    rules = [
        GroupByRule(source=CustomerNames_Allocation()),
        GroupRule(
            name='CloudZero',
            source=Customer(),
            condition=Equals('00000000-0000-0000-0000-000000000000')
        ),
    ]

Allocation Dimensions

class AI_Telemetry(AllocationDimension):
    name = 'AI Telemetry'
    hide = True
    streams = ['cost-per-ai-call', 'ai-token-metrics']

class RuleBasedAlloc(AllocationDimension):
    name = 'Rule-based Allocation'
    allocation_method = AllocationMethod.PROPORTIONAL
    spend_to_allocate = [Service().equals('AmazonEC2')]
    across_elements = [
        GroupRule(name='by-account', condition=Account().begins_with('prod-')),
    ]

Evaluation

Dimensions can be evaluated against test data:

test_data = {
    'Service': 'Lambda',
    'Category': 'AI',
    'Operation': 'RunInput'
}

result = MyServices.evaluate(test_data)
# Returns: 'Compute' (matches the Lambda rule)

Publishing to CloudZero

to_yaml() produces CostFormation (CFDL) YAML — the same format you'd write by hand — which you then apply to your CloudZero account. First serialize your dimensions to a file:

from costformation import CostFormation

with open('my-costformation.yaml', 'w') as f:
    f.write(CostFormation([MyServices()]).to_yaml())

Then publish it with any of:

  • CloudZero API (ideal for CI/CD) — POST the YAML with your CloudZero API key. Add ?validate_only=true to check it without publishing:

    curl -X POST "https://api.cloudzero.com/v2/costformation/definition/versions" \
      -H "Authorization: <YOUR_API_KEY>" \
      -H "Content-Type: text/plain" \
      --data-binary @my-costformation.yaml
    
  • CloudZero app — paste the YAML into the CostFormation editor and publish.

  • CostFormation Toolkit for VS Code — download the target namespace (this links the file to CloudZero), replace its contents with your generated YAML, then publish.

For the full guide, see Author CostFormation in Python in the CloudZero docs.

Development

Dependency Management

Set up a development environment

With uv installed, create the virtual environment at ./.venv and install all dependencies with:

make init

There's no need to activate the environment — uv run and the make targets below use it automatically. To pin a specific Python version, run uv venv -p 3.12 ./.venv first.

Updating Dependencies

We uv lock requested dependencies from the pyproject.toml file into a deterministic uv.lock file. For more information about managing dependencies with uv, see the official docs.

Library Dependencies

These are dependencies your library needs when a client installs it. If you want to edit library dependencies, simply edit the project.dependencies value in pyproject.toml, or use the uv add command to do it for you, eg. uv add "pydantic~=2.0".

Development Dependencies

Development dependencies are dependencies needed for development only, eg tests or linting. If you want to edit development dependencies, then add the dependency to the appropriate dependency-group in pyproject.toml. Alternatively, you can use uv add to edit the file for you eg, run uv add --group lint ruff.

Locking Dependencies

Whenever you update dependencies, you should be sure to run make lock-requirements in order to ensure reproducible development environments. Whenever dependencies are updated, make sure to run make init to sync your virtual environment.

Checks

Linting

You can run all the python linting (mypy, ruff) with:

make lint

Then auto-fix linting errors with:

make lint-fix

Unit Tests

You can run all the python tests with pytest:

make test

Full Validation

You can run both linting and testing with:

make check

Publishing new versions of the package

Publishing to PyPI is done by the publish-to-pypi.yml workflow (using Trusted Publishing) whenever a GitHub Release is published:

  1. Open a PR that bumps __version__ in costformation/__init__.py and adds a matching section to CHANGELOG.md (CI enforces both).
  2. Merge it, then create a GitHub Release from main with a tag matching the new version.
  3. The workflow builds the package with uv and publishes it to PyPI.

License

This project is licensed under the Apache License, Version 2.0 — see the LICENSE file for details.

Trademarks

"CloudZero" and the CloudZero logo are trademarks of CloudZero, Inc. Use of these trademarks is limited to identification and attribution as required by the Apache License. You may not use CloudZero trademarks in a way that suggests endorsement or affiliation without written permission.

Metadata

Release files for cloudzero-costformation 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for cloudzero-costformation 0.3.0
File Size Uploaded Provenance Actions
cloudzero_costformation-0.3.0.tar.gz 53.7 kB With provenance Details for cloudzero_costformation-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for cloudzero-costformation 0.3.0
File Interpreter ABI Platform Actions
cloudzero_costformation-0.3.0-py3-none-any.whl Python 3 none any Details for cloudzero_costformation-0.3.0-py3-none-any.whl

Total release size: 91.8 kB

Release files / cloudzero_costformation-0.3.0.tar.gz

Download URL cloudzero_costformation-0.3.0.tar.gz
Size 53.7 kB
Tags Source
SHA-256 checksum
How to use checksums
c63613e6cbcbfa3049f296ec9eeec5067a908f4c49f5b6570e5c6df2f3662908
BLAKE2b-256 checksum
How to use checksums
929cd129012991725b6b6c20fa364a44d7c591f01793c4d5c12efec73f484ed6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 26, 2026.

Transparency log

Release files / cloudzero_costformation-0.3.0-py3-none-any.whl

Download URL cloudzero_costformation-0.3.0-py3-none-any.whl
Size 38.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
4c967d29018f82da489137c6e37ef2365ca720c3ebb05000c30bc757d8242a35
BLAKE2b-256 checksum
How to use checksums
ebf9b52569aa79e0400c727c1a451a82487665c4304d6ac1988234c20ab22c92
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 26, 2026.

Transparency log

Security for cloudzero-costformation 0.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for cloudzero_costformation-0.3.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 26, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page