Skip to main content

Python type code generator

Project description

CircleCI codecov

py2ts

Covert Python dataclass and Enum to TypeScript interface.

Mapping of Scalar Types

assert python_type_to_typescript(str) == "string"
assert python_type_to_typescript(int) == "number"
assert python_type_to_typescript(bool) == "boolean"
assert python_type_to_typescript(float) == "number"
assert python_type_to_typescript(datetime) == "string"
assert python_type_to_typescript(date) == "string"
assert python_type_to_typescript(Decimal) == "string"
assert python_type_to_typescript(dict) == "{}"
assert python_type_to_typescript(list) == "Array<any>"

Usage

Create a schema with Python dataclass:

class EnumFruit(Enum):
    APPLE = "APPLE"
    ORANGE = "ORANGE"


@dataclass
class NestedSchema:
    string_field: str
    nullable_datetime_field: Optional[datetime]
    recursively_nested_field: Optional["NestedSchema"]


@dataclass
class ComplexSchema:
    nullable_int_field: Optional[int]
    nullable_decimal_field: Optional[int]
    nullable_enum_field: Optional[EnumFruit]
    nullable_nested_field: Optional[NestedSchema]
    nested_list_field: List[NestedSchema]

blocks = []
for path, node in schemas2typescript([ComplexSchema]).items():
    blocks.append(node.to_typescript())

print("\n".join(blocks))

The output is:

export enum EnumFruit {
  APPLE = 'APPLE',
  ORANGE = 'ORANGE'
}
export interface NestedSchema {
  string_field: string;
  nullable_datetime_field: string | null;
  recursively_nested_field: NestedSchema | null;
}
export interface ComplexSchema {
  nullable_int_field: number | null;
  nullable_decimal_field: number | null;
  nullable_enum_field: EnumFruit | null;
  nullable_nested_field: NestedSchema | null;
  nested_list_field: Array<NestedSchema>;
}

Generate service registry

Dependency: ripgrep

Generate boilerplate service registry code.

Usage

python -m py2ts.generate_service_registry > service_registery.py

How it works

The command assumes that any classes named XXXService should be included in the service registry. For example:

class TestService:
    pass

will generate the following code:

# Generated code. DO NOT EDIT!

from dataclasses import dataclass

from tests.test_generate_service_registr import TestService


@dataclass
class ServiceRegistry:
    test_service: TestService = TestService()

service_registry = ServiceRegistry()

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

py2ts-0.0.6.tar.gz (7.8 kB view hashes)

Uploaded Source

Built Distribution

py2ts-0.0.6-py3-none-any.whl (7.6 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page