Elffuss BraidHub

kikocis/llama-stack public

main · 1.2 KiBRawPermalink
1# Copyright (c) Meta Platforms, Inc. and affiliates.
2# All rights reserved.
3#
4# This source code is licensed under the terms described in the LICENSE file in
5# the root directory of this source tree.
6
7"""
8Type-safe data interchange for Python data classes.
9
10:see: https://github.com/hunyadi/strong_typing
11"""
12
13import keyword
14from typing import Optional
15
16from .auxiliary import Alias
17from .inspection import get_annotation
18
19
20def python_field_to_json_property(
21 python_id: str, python_type: Optional[object] = None
22) -> str:
23 """
24 Map a Python field identifier to a JSON property name.
25
26 Authors may use an underscore appended at the end of a Python identifier as per PEP 8 if it clashes with a Python
27 keyword: e.g. `in` would become `in_` and `from` would become `from_`. Remove these suffixes when exporting to JSON.
28
29 Authors may supply an explicit alias with the type annotation `Alias`, e.g. `Annotated[MyType, Alias("alias")]`.
30 """
31
32 if python_type is not None:
33 alias = get_annotation(python_type, Alias)
34 if alias:
35 return alias.name
36
37 if python_id.endswith("_"):
38 id = python_id[:-1]
39 if keyword.iskeyword(id):
40 return id
41
42 return python_id