11# Copyright 2023 Canonical Ltd.
22# Licensed under the Apache V2, see LICENCE file for details.
3+ from __future__ import annotations
34
45import argparse
56import builtins
1314from collections import defaultdict
1415from glob import glob
1516from pathlib import Path
16- from typing import Any , Dict , List , Mapping , Sequence
17+ from typing import Any , Mapping , Sequence
1718
1819import packaging .version
1920import typing_inspect
21+ from typing_extensions import TypeAlias
2022
2123from . import codegen
2224
25+ # Plain JSON, what is received from Juju
26+ _JSON_LEAF : TypeAlias = None | bool | int | float | str
27+ _JSON : TypeAlias = "_JSON_LEAF|list[_JSON]|dict[str, _JSON]"
28+
29+ # Type-enriched JSON, what can be sent to Juju
30+ _RICH_LEAF : TypeAlias = "_JSON_LEAF|Type"
31+ _RICH_JSON : TypeAlias = "_RICH_LEAF|list[_RICH_JSON]|dict[str, _RICH_JSON]"
32+
2333_marker = object ()
2434
2535JUJU_VERSION = re .compile (r"[0-9]+\.[0-9-]+[\.\-][0-9a-z]+(\.[0-9]+)?" )
@@ -634,7 +644,7 @@ class {name}Facade(Type):
634644
635645
636646class TypeEncoder (json .JSONEncoder ):
637- def default (self , obj ) :
647+ def default (self , obj : _RICH_JSON ) -> _JSON :
638648 if isinstance (obj , Type ):
639649 return obj .serialize ()
640650 return json .JSONEncoder .default (self , obj )
@@ -653,7 +663,7 @@ def __eq__(self, other):
653663
654664 return self .__dict__ == other .__dict__
655665
656- async def rpc (self , msg ) :
666+ async def rpc (self , msg : dict [ str , _RICH_JSON ]) -> _JSON :
657667 result = await self .connection .rpc (msg , encoder = TypeEncoder )
658668 return result
659669
@@ -704,13 +714,13 @@ def _parse_nested_list_entry(expr, result_dict):
704714 return cls (** d )
705715 return None
706716
707- def serialize (self ):
717+ def serialize (self ) -> dict [ str , _JSON ] :
708718 d = {}
709719 for attr , tgt in self ._toSchema .items ():
710720 d [tgt ] = getattr (self , attr )
711721 return d
712722
713- def to_json (self ):
723+ def to_json (self ) -> str :
714724 return json .dumps (self .serialize (), cls = TypeEncoder , sort_keys = True )
715725
716726 def __contains__ (self , key ):
@@ -917,8 +927,8 @@ def generate_definitions(schemas):
917927
918928
919929def generate_facades (
920- schemas : Dict [str , List [Schema ]],
921- ) -> Dict [str , Dict [int , codegen .Capture ]]:
930+ schemas : dict [str , list [Schema ]],
931+ ) -> dict [str , dict [int , codegen .Capture ]]:
922932 captures = defaultdict (codegen .Capture )
923933
924934 # Build the Facade classes
0 commit comments