Skip to content

Commit 64cfb93

Browse files
committed
fixes #559
1 parent 256c058 commit 64cfb93

File tree

3 files changed

+98
-1
lines changed

3 files changed

+98
-1
lines changed

fastcore/_modidx.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -612,6 +612,7 @@
612612
'fastcore.xtras.autostart': ('xtras.html#autostart', 'fastcore/xtras.py'),
613613
'fastcore.xtras.bunzip': ('xtras.html#bunzip', 'fastcore/xtras.py'),
614614
'fastcore.xtras.console_help': ('xtras.html#console_help', 'fastcore/xtras.py'),
615+
'fastcore.xtras.dataclass_src': ('xtras.html#dataclass_src', 'fastcore/xtras.py'),
615616
'fastcore.xtras.dict2obj': ('xtras.html#dict2obj', 'fastcore/xtras.py'),
616617
'fastcore.xtras.dumps': ('xtras.html#dumps', 'fastcore/xtras.py'),
617618
'fastcore.xtras.get_source_link': ('xtras.html#get_source_link', 'fastcore/xtras.py'),
@@ -643,6 +644,7 @@
643644
'fastcore.xtras.stringfmt_names': ('xtras.html#stringfmt_names', 'fastcore/xtras.py'),
644645
'fastcore.xtras.trace': ('xtras.html#trace', 'fastcore/xtras.py'),
645646
'fastcore.xtras.truncstr': ('xtras.html#truncstr', 'fastcore/xtras.py'),
647+
'fastcore.xtras.type2str': ('xtras.html#type2str', 'fastcore/xtras.py'),
646648
'fastcore.xtras.untar_dir': ('xtras.html#untar_dir', 'fastcore/xtras.py'),
647649
'fastcore.xtras.utc2local': ('xtras.html#utc2local', 'fastcore/xtras.py'),
648650
'fastcore.xtras.walk': ('xtras.html#walk', 'fastcore/xtras.py')}}}

fastcore/xtras.py

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
'repr_dict', 'is_listy', 'mapped', 'IterLen', 'ReindexCollection', 'get_source_link', 'truncstr',
1010
'sparkline', 'modify_exception', 'round_multiple', 'set_num_threads', 'join_path_file', 'autostart',
1111
'EventTimer', 'stringfmt_names', 'PartialFormatter', 'partial_format', 'utc2local', 'local2utc', 'trace',
12-
'modified_env', 'ContextManagers', 'shufflish', 'console_help', 'hl_md']
12+
'modified_env', 'ContextManagers', 'shufflish', 'console_help', 'hl_md', 'type2str', 'dataclass_src']
1313

1414
# %% ../nbs/03_xtras.ipynb 2
1515
from .imports import *
@@ -576,3 +576,23 @@ def hl_md(s, lang='xml', show=True):
576576
from IPython import display
577577
return display.Markdown(md)
578578
except ImportError: print(s)
579+
580+
# %% ../nbs/03_xtras.ipynb 162
581+
def type2str(typ:type)->str:
582+
"Stringify `typ`"
583+
if typ is None or typ is NoneType: return 'None'
584+
if hasattr(typ, '__origin__'):
585+
args = ", ".join(type2str(arg) for arg in typ.__args__)
586+
if typ.__origin__ is Union: return f"Union[{args}]"
587+
return f"{typ.__origin__.__name__}[{args}]"
588+
elif isinstance(typ, type): return typ.__name__
589+
return str(typ)
590+
591+
# %% ../nbs/03_xtras.ipynb 164
592+
def dataclass_src(cls):
593+
import dataclasses
594+
src = f"@dataclass\nclass {cls.__name__}:\n"
595+
for f in dataclasses.fields(cls):
596+
d = "" if f.default is dataclasses.MISSING else f" = {f.default!r}"
597+
src += f" {f.name}: {type2str(f.type)}{d}\n"
598+
return src

nbs/03_xtras.ipynb

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2407,6 +2407,81 @@
24072407
"hl_md('<test><xml foo=\"bar\">a child</xml></test>')"
24082408
]
24092409
},
2410+
{
2411+
"cell_type": "code",
2412+
"execution_count": null,
2413+
"metadata": {},
2414+
"outputs": [],
2415+
"source": [
2416+
"#| export\n",
2417+
"def type2str(typ:type)->str:\n",
2418+
" \"Stringify `typ`\"\n",
2419+
" if typ is None or typ is NoneType: return 'None'\n",
2420+
" if hasattr(typ, '__origin__'):\n",
2421+
" args = \", \".join(type2str(arg) for arg in typ.__args__)\n",
2422+
" if typ.__origin__ is Union: return f\"Union[{args}]\"\n",
2423+
" return f\"{typ.__origin__.__name__}[{args}]\"\n",
2424+
" elif isinstance(typ, type): return typ.__name__\n",
2425+
" return str(typ)"
2426+
]
2427+
},
2428+
{
2429+
"cell_type": "code",
2430+
"execution_count": null,
2431+
"metadata": {},
2432+
"outputs": [],
2433+
"source": [
2434+
"test_eq(type2str(Optional[float]), 'Union[float, None]')"
2435+
]
2436+
},
2437+
{
2438+
"cell_type": "code",
2439+
"execution_count": null,
2440+
"metadata": {},
2441+
"outputs": [],
2442+
"source": [
2443+
"#| export\n",
2444+
"def dataclass_src(cls):\n",
2445+
" import dataclasses\n",
2446+
" src = f\"@dataclass\\nclass {cls.__name__}:\\n\"\n",
2447+
" for f in dataclasses.fields(cls):\n",
2448+
" d = \"\" if f.default is dataclasses.MISSING else f\" = {f.default!r}\"\n",
2449+
" src += f\" {f.name}: {type2str(f.type)}{d}\\n\"\n",
2450+
" return src"
2451+
]
2452+
},
2453+
{
2454+
"cell_type": "code",
2455+
"execution_count": null,
2456+
"metadata": {},
2457+
"outputs": [],
2458+
"source": [
2459+
"from dataclasses import make_dataclass, dataclass"
2460+
]
2461+
},
2462+
{
2463+
"cell_type": "code",
2464+
"execution_count": null,
2465+
"metadata": {},
2466+
"outputs": [
2467+
{
2468+
"name": "stdout",
2469+
"output_type": "stream",
2470+
"text": [
2471+
"@dataclass\n",
2472+
"class DC:\n",
2473+
" x: int\n",
2474+
" y: Union[float, None] = None\n",
2475+
" z: float = None\n",
2476+
"\n"
2477+
]
2478+
}
2479+
],
2480+
"source": [
2481+
"DC = make_dataclass('DC', [('x', int), ('y', Optional[float], None), ('z', float, None)])\n",
2482+
"print(dataclass_src(DC))"
2483+
]
2484+
},
24102485
{
24112486
"cell_type": "markdown",
24122487
"metadata": {},

0 commit comments

Comments
 (0)