|
2407 | 2407 | "hl_md('<test><xml foo=\"bar\">a child</xml></test>')" |
2408 | 2408 | ] |
2409 | 2409 | }, |
| 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 | + }, |
2410 | 2485 | { |
2411 | 2486 | "cell_type": "markdown", |
2412 | 2487 | "metadata": {}, |
|
0 commit comments