ikornaselur / dict-typer Goto Github PK
View Code? Open in Web Editor NEWConvert JSON or Python dictionaries to Python TypedDict definitions
License: MIT License
Convert JSON or Python dictionaries to Python TypedDict definitions
License: MIT License
Minimal example:
[{"item": 123}, {"item": "foo"}]
should produce
class RootTypeItem(TypedDict):
item: Union[int, str]
RootType = List[RootTypeItem]
but now creates
class RootItemType(TypedDict):
item: int
class RootItemType1(TypedDict):
item: str
RootType = List[Union[RootItemType, RootItemType1]]
Add relevant imports from typing
and typing_extensions
{
"dictList": [{ "id": 123 }, { "id": 456 }]
}
Switch to alternative definition of a TypedDict when using any keys with reserved keywords. Keywords can be queried from keyword
:
In [2]: import keyword
In [3]: keyword.kwlist
Out[3]:
['False',
'None',
'True',
'and',
'as',
'assert',
'async',
'await',
'break',
'class',
'continue',
'def',
'del',
'elif',
'else',
'except',
'finally',
'for',
'from',
'global',
'if',
'import',
'in',
'is',
'lambda',
'nonlocal',
'not',
'or',
'pass',
'raise',
'return',
'try',
'while',
'with',
'yield']
At the moment, it's required that the root object is a dictionary.
Support root object being a list by either:
If the input is a list in 2., then output a comment that lists the types of the input list]
[
1,
2,
{"id": 123},
{"id": 456},
]
from typing_extensions import TypedDict
class RootType(TypedDict):
id: int
# Input: Union[int, RootType]
While the output of this tool uses TypedDict from typing_extensions heavily, the actual core tool itself doesn't. It's only used in tests.
Review empty lines between definitions and imports
Minimal example:
[{"items": []}, {"items": [1, 2, 3]}]
should produce
from typing import List
class RootTypeItem(TypedDict):
items: List[int]
RootType = List[RootTypeItem]
but now creates
from typing import List, Union
from typing_extensions import TypedDict
class RootItemType(TypedDict):
items: Union[List, List[int]]
RootType = List[RootItemType]
Take the examples from https://json.org/example.html and use them as integration tests
The root type has to come after any nested definitions
Add an interactive option to the CLI, which should:
Check with [1, 2.0, "3"]
and show imports to reproduce, which should import Union
and List
Update the CLI experience with the following things:
Click
for --help
{"foo": {"foo": 10}}
will result in
Traceback (most recent call last):
File "/usr/local/opt/pyenv/versions/3.8.2/bin/dict-typer", line 8, in <module>
sys.exit(cli())
File "/usr/local/opt/pyenv/versions/3.8.2/lib/python3.8/site-packages/click/core.py", line 829, in __call__
return self.main(*args, **kwargs)
File "/usr/local/opt/pyenv/versions/3.8.2/lib/python3.8/site-packages/click/core.py", line 782, in main
rv = self.invoke(ctx)
File "/usr/local/opt/pyenv/versions/3.8.2/lib/python3.8/site-packages/click/core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/usr/local/opt/pyenv/versions/3.8.2/lib/python3.8/site-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/usr/local/opt/pyenv/versions/3.8.2/lib/python3.8/site-packages/dict_typer/__init__.py", line 50, in cli
output = get_type_definitions(parsed, show_imports=imports)
File "/usr/local/opt/pyenv/versions/3.8.2/lib/python3.8/site-packages/dict_typer/type_definitions.py", line 229, in get_type_definitions
return builder.build_output()
File "/usr/local/opt/pyenv/versions/3.8.2/lib/python3.8/site-packages/dict_typer/type_definitions.py", line 180, in build_output
typing_imports |= definition.get_imports()
File "/usr/local/opt/pyenv/versions/3.8.2/lib/python3.8/site-packages/dict_typer/models.py", line 132, in get_imports
imports |= sub_member.get_imports()
File "/usr/local/opt/pyenv/versions/3.8.2/lib/python3.8/site-packages/dict_typer/models.py", line 132, in get_imports
imports |= sub_member.get_imports()
File "/usr/local/opt/pyenv/versions/3.8.2/lib/python3.8/site-packages/dict_typer/models.py", line 132, in get_imports
imports |= sub_member.get_imports()
[Previous line repeated 987 more times]
File "/usr/local/opt/pyenv/versions/3.8.2/lib/python3.8/site-packages/dict_typer/models.py", line 129, in get_imports
imports = set()
RecursionError: maximum recursion depth exceeded while calling a Python object
When an unknown data type is encountered, try to handle it:
instance.__class__.__name__
and list as a comment in the importsSome definitions might be annoyingly long, such as
itemsTuple: Tuple[Union[Set[Union[float, int]], int]],
so support extracting this out in a separate alias, such as
ItemsTupleType = Tuple[Union[Set[Union[float, int]], int]]
...
itemsTuple: ItemsTupleType
Minimal example:
{}
or
{"foo": {}}
Should either default to just Dict
or a TypedDict
with pass
as body
Minimal example to reproduce
In [13]: d
Out[13]:
{'nest': {'a': 'a'},
'deep_nest': {'deeply_nested': {'a': 'a'},
'deep_deep_nest': {'nest': {'a': 'a'}}}}
In [14]: print(convert(d))
class NestType(TypedDict):
a: str
class DeeplyNestedType(TypedDict):
a: str
class NestType(TypedDict):
a: str
class DeepDeepNestType(TypedDict):
nest: NestType
class DeepNestType(TypedDict):
deeply_nested: DeeplyNestedType
deep_deep_nest: DeepDeepNestType
class RootType(TypedDict):
nest: NestType
deep_nest: DeepNestType
Current focus has been support what JSON needs, but there are sequences such as tuples and sets in python that need to be supported.
I'm unsure of if there's some place to find all builtin types that make sense (such as keyword.kwlist
for keywords), but at least keep set and tuples as first class citizens.
Optionally support a naming map, to rename certain types. Mostly useful for pytyper.dev
{
"foo": {"count": 1},
"bar": {"count": 2}
}
class Foo(TypedDict):
count: int
class Root(TypedDict):
foo: Foo
bar: Foo
{
"Foo": "Count"
}
->
class Count(TypedDict):
count: int
class Root(TypedDict):
foo: Count
bar: Count
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.