Skip to main content

MyPy to TS generator

Project description

myts

PyPI - Version PyPI - Python Version GitHub License GitHub Actions Workflow Status

In beta - this is not production ready

Road to ready:

  • Better test coverage, 80% baseline
  • Support for generics, enums with auto, most MyPy typing.

Converts MyPy types to TS types. Uses MyPy's internal api to gather type info.

Call as a cli, optionally directory watchable. Or import and invoke directly from your Python code.

Installation

pip

pip install myts

uv

uv add --dev myts

poetry

poetry add myts --group dev

Usage

In your code

Myts looks for any classes that inherit from MytsType to start building its dependency graph. These by default will be included in the output TS.

Alternatively you can use the myts_export decorator on Enums and TypedDicts and classes that you would like to have exported without needing to be referenced by a MytsType class.

Note: Right now you cannot alias either of these, in a future version that will be okay.

from enum import IntEnum
from myts import MytsType, myts_export

@myts_export
class Fruit(IntEnum): # Will be in the TS output
	apple = 0
	orange = 1
	banana = 2

class Vegetable(IntEnum): # Will not be, because it is not referenced ever and is not decorated with myts_export
	carrot = 0
	celery = 1
	lettuce = 2

class Drink(IntEnum): # Will be in the output, reference by a MytsType below
	water = 0
	milk = 1
	soda = 2

class BeveragePreference(MytsType): # Will export and will also export the Drink enum
	drink: Drink
	person: Person

CLI

To see all cli options run

myts -h

Optionally a config file can be used. By default myts will attempt to find a myts.toml in the specified root. Alternatively a config file can be supplied through the -c or --config argument to the cli.

You can also specify these options under a [tool.myts] section in your pyproject.toml found at the --root path.

Note: that arguments to the cli will override config settings found in the config.

The resolution of options is: (lowest → highest priority)

  1. pyproject [tool.myts]
  2. myts.toml
  3. command line arguments

Meaning an option defined in [tool.myts] can and will be overwritten by the same option if provided to myts.toml or the command line.

myts.toml or [tool.myts] is a flat toml that can optionally supply any or none of the following:

root = "/some/path" # If specifying root in the config make sure it is an absolute path
output = "./out/" # When output is relative, it is relative to root
group = "module" # "module" or "single"
preserve_structure = true # When group is "module" this will create folders matching the py structure
dry_run = false
#output_file_name = "out.ts" # When using group = "single" this will be the name of the output file
#trim_root = "myapp.has.a.long.root.path" # Optionally provide a python formatted module path to trim from all output

Simplest example

To generate the .ts files.

cd <myprojectroot>
myts --output your/output/dir/

A more complex example

Uses trim-root to remove a common py module path from the output.

Uses watch to automatically update generated ts when the py changes.

cd <myprojectroot>
myts --output your/output/dir/ -w

Py

import pathlib
import myts

config = myts.MytsConfiguration(
	root=pathlib.Path('someprojdir'), # defaults to os.cwd()
	output=pathlib.Path('someoutputdir'),
	group='module', # 'single' or 'module' - single will output a single .ts file, 'module' will output files matching the `py` files they come from
	preserve_structure=True, # No effect if group == 'single', otherwise determines output structure. If true folders will be created to match py paths
	dry_run=False, # If true, just prints the paths of output files that would be written
	output_file_name='types.ts', # Only used if group == 'single', determines the name of the single file generated
	trim_root="myapp.some.path" # When preserving structure, use this to trim a common root 
)

myts.extract_ts(config)

Roadmap

  • Export to multiple files, flat folder or matching py module structure
  • Support generics
  • Watch for py changes and auto generate ts
  • Config options for
    • [Py api] override output names of vars and files
    • Variable and type naming options (camelCase, PascalCase, snake_case)
    • Interface vs type output
  • myts_export params to override naming and module grouping
  • Name overwriting using meta class on MytsType or params to myts_export

Example of functionality

Python (Mypy)

from myts import MytsType, myts_export
from pytdantic import BaseModel


class APIModel(BaseModel, MytsType):
	"""
		All pydantic models that extend from this will be picked up by Myts
	"""
	...


class MyPydanticModel(APIModel): # Myts will grab this
	name: str


@myts_export # Flags for export even though it is never referenced
class MyNotReferencedEnum(StrEnum):
	A = "🍁"
	B = "🐝"
	C = "👀"

class SomeEnum(IntEnum): # Automatically exported due to being reference by OtherThing
	A = 5
	B = 6
	C = 12

class MyTypedDict[T: "Example"](TypedDict): # Generics supported
	a: NotRequired[T]
	b: Literal["one", "two", "three"]

class Example(MytsType): # Inherits MytsType -- will be exported
	something: str
	other_thing: "OtherThing"

@dataclass
class OtherThing(MytsType):
	thing: SomeEnum
	info: MyTypedDict

Output (Typescript) (Out of date)

export enum MyNotReferencedEnum {
	A = "🍁",
	B = "🐝",
	C = "👀",
}

export enum SomeEnum {
	A = 5,
	B = 6,
	C = 12,
}

export type MyTypedDict<T extends Example> = {
	a?: T;
	b: "one" | "two" | "three";
};

export type Example = {
	something: string;
	otherThing: OtherThing;
};

export type OtherThing = {
	thing: SomeEnum;
	info: MyTypedDict;
};

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

myts-0.3.1.tar.gz (17.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

myts-0.3.1-py3-none-any.whl (23.5 kB view details)

Uploaded Python 3

File details

Details for the file myts-0.3.1.tar.gz.

File metadata

  • Download URL: myts-0.3.1.tar.gz
  • Upload date:
  • Size: 17.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.10.9 {"installer":{"name":"uv","version":"0.10.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for myts-0.3.1.tar.gz
Algorithm Hash digest
SHA256 3c2caa2476878ae1cd38ec34e0ad97e55c4137119bab070855e5daab32826873
MD5 6ac7fe3af71a38830707130e3b243edf
BLAKE2b-256 744c713fede037571c16997cab80bd43f0a38805985f3a3b1b66493e3fbdefd4

See more details on using hashes here.

File details

Details for the file myts-0.3.1-py3-none-any.whl.

File metadata

  • Download URL: myts-0.3.1-py3-none-any.whl
  • Upload date:
  • Size: 23.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.10.9 {"installer":{"name":"uv","version":"0.10.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for myts-0.3.1-py3-none-any.whl
Algorithm Hash digest
SHA256 3245999fe47dd1ebafe60f5f1411d20129608ee564a4c7c1cd73dfd2694ab36d
MD5 af1b6abee6ab042b33e301d601deb88d
BLAKE2b-256 490b8c1262d403176259f322fa8ba80741cee0d7ca6343d4220e3ce70a02b344

See more details on using hashes here.

Supported by

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