Typed API Reference¶
Enhanced base configuration class with Pydantic-like functionality.
Typed
¶
Bases: BaseSettings, ABC
Enhanced Pydantic BaseSettings with advanced validation and utility features.
Typed provides a powerful foundation for creating structured data models with automatic validation,
type conversion, serialization, and enhanced error handling. Built on top of Pydantic's
:class:pydantic_settings.BaseSettings (which itself inherits from
:class:pydantic.BaseModel), Typed adds additional convenience methods, improved error
reporting, and lifecycle hooks while maintaining full compatibility with Pydantic's ecosystem
and pydantic-settings' CLI / environment-variable / dotenv source loading.
Why BaseSettings?
Inheriting from :class:BaseSettings gives every Typed subclass first-class CLI
and environment-variable support out of the box. When a Typed instance is constructed
without _cli_parse_args / _env_file / etc., the BaseSettings machinery is a
zero-cost no-op (the init kwargs are passed straight through to BaseModel validation).
When those flags ARE passed, deep nested CLI overrides like
--infra.ray-init.address ray://1.2.3.4:10001 work natively, with the inner Typed
being validated exactly once and identity preserved when a pre-built instance is passed
as a field value (governed by revalidate_instances="never" — see below).
Features
- Enhanced Error Handling: Detailed validation error messages with context
- Type Validation: Automatic type conversion and validation using Pydantic
- Immutable Models: Frozen models by default for thread safety
- JSON Schema: Automatic schema generation for API documentation
- Serialization: JSON and dict serialization with customizable options
- Class Properties: Convenient access to model metadata and field information
- Registry Integration: Compatible with morphic.Registry for factory patterns
- CLI / Env support: Inherited from :class:
pydantic_settings.BaseSettings - Lifecycle Hooks: Four customizable hooks for initialization and validation
pre_initialize: Set up derived fields before validationpre_validate: Validate and normalize input datapost_initialize: Perform side effects after validation (idempotent — runs exactly once per instance even if Pydantic re-fires the underlyingmodel_validator(mode="after")due to nested-Typed re-validation, see https://github.com/pydantic/pydantic/issues/12876).post_validate: Validate the completed instance (also idempotent)
Configuration
The class uses a pre-configured :class:SettingsConfigDict with the following settings:
extra="forbid": Prevents extra fields not defined in the modelfrozen=True: Makes instances immutable after creationvalidate_default=True: Validates default values during model creationarbitrary_types_allowed=True: Allows custom types that don't have Pydantic validatorsrevalidate_instances="never": Preserves instance identity when a pre-built Typed is passed as a field of an outer Typed/Settings (avoids redundant re-validation and clones — see :ref:identity-preservation).cli_kebab_case=True: CLI flags use kebab-case (--ray-initnot--ray_init).cli_implicit_flags=True: Boolean fields auto-generate--flag/--no-flagpairs.nested_model_default_partial_update=True: When a nested model field has a default model instance, deep CLI overrides like--inner.x.y VALUEmerge on top of the default rather than replacing it wholesale.
Basic Usage
from morphic.typed import Typed
from typing import Optional, List
class User(Typed):
name: str
age: int
email: Optional[str] = None
tags: List[str] = []
# Create and pre_validate instances
user = User(name="John", age=30, email="john@example.com")
print(user.name) # "John"
# Automatic type conversion
user2 = User(name="Jane", age="25") # age converted from string to int
print(user2.age) # 25 (int)
# Validation errors with detailed messages
try:
invalid_user = User(name="Bob", age="invalid")
except ValueError as e:
print(e) # Detailed error with field location and input
CLI / Environment Usage:
from morphic.typed import Typed
class RayInit(Typed):
address: str = "auto"
num_cpus: int = 4
class Infra(Typed):
mode: str = "thread"
ray_init: RayInit = RayInit()
class App(Typed):
infra: Infra = Infra()
seed: int = 42
# Programmatic construction (BaseSettings is a no-op when no _* args are passed):
app = App()
# CLI: deep nested override works natively because every Typed is a BaseSettings.
app = App(_cli_parse_args=["--infra.ray-init.address", "ray://1.2.3.4:10001"])
assert app.infra.ray_init.address == "ray://1.2.3.4:10001"
# CLI: inline JSON also works.
app = App(_cli_parse_args=["--infra", '{"mode":"ray"}'])
assert app.infra.mode == "ray"
# CLI: inline JSON + deep override on the SAME field stack correctly.
app = App(_cli_parse_args=[
"--infra", '{"mode":"ray","ray_init":{"address":"ray://orig:10001"}}',
"--infra.ray-init.address", "ray://override:10001",
])
assert app.infra.ray_init.address == "ray://override:10001"
Advanced Usage
from pydantic import Field, field_validator
from morphic.typed import Typed
class Product(Typed):
name: str = Field(..., description="Product name")
price: float = Field(..., gt=0, description="Price must be positive")
category: str = Field(default="general", description="Product category")
@field_validator('name')
@classmethod
def validate_name(cls, v):
if not v.strip():
raise ValueError("Name cannot be empty")
return v.title()
# Factory method
product = Product.of(name="laptop", price=999.99, category="electronics")
# Serialization
data = product.model_dump() # Convert to dict
json_str = product.model_dump_json() # Convert to JSON string
# Schema generation
schema = Product.model_json_schema()
Integration with AutoEnum:
from morphic.autoenum import AutoEnum, auto
from morphic.typed import Typed
class Status(AutoEnum):
ACTIVE = auto()
INACTIVE = auto()
PENDING = auto()
class Task(Typed):
title: str
status: Status = Status.PENDING
# AutoEnum fields work seamlessly
task = Task(title="Review PR", status="ACTIVE") # String converted to enum
assert task.status == Status.ACTIVE
Lifecycle Hooks Example:
from morphic.typed import Typed
from typing import Optional
from datetime import datetime
class User(Typed):
first_name: str
last_name: str
email: str
# Derived fields
full_name: Optional[str] = None
email_domain: Optional[str] = None
created_at: Optional[str] = None
@classmethod
def pre_initialize(cls, data: dict) -> None:
# Set up derived fields before validation
if 'first_name' in data and 'last_name' in data:
data['full_name'] = f"{data['first_name']} {data['last_name']}"
if 'email' in data:
data['email_domain'] = data['email'].split("@")[1]
if data.get('created_at') is None:
data['created_at'] = datetime.now().isoformat()
@classmethod
def pre_validate(cls, data: dict) -> None:
# Normalize and validate input data
if 'email' in data:
data['email'] = data['email'].lower().strip()
if 'first_name' in data:
data['first_name'] = data['first_name'].strip().title()
if 'last_name' in data:
data['last_name'] = data['last_name'].strip().title()
def post_initialize(self) -> None:
# Perform side effects after validation
print(f"User {self.full_name} created at {self.created_at}")
def post_validate(self) -> None:
# Validate the completed instance
if not self.email_domain:
raise ValueError("Email domain is required")
# Usage
user = User(
first_name="john",
last_name="doe",
email=" JOHN@EXAMPLE.COM "
)
assert user.first_name == "John"
assert user.last_name == "Doe"
assert user.email == "john@example.com"
assert user.full_name == "John Doe"
assert user.email_domain == "example.com"
assert user.created_at is not None
See Also:
- morphic.registry.Registry: For factory pattern and class registration
- morphic.autoenum.AutoEnum: For fuzzy-matching enumerations
- pydantic.BaseModel: The underlying Pydantic base class
Source code in src/morphic/typed.py
739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 | |
settings_customise_sources(settings_cls: type, init_settings: Any, env_settings: Any, dotenv_settings: Any, file_secret_settings: Any) -> Tuple[Any, ...]
classmethod
¶
Restrict the default settings sources to init_settings only.
:class:pydantic_settings.BaseSettings defaults to reading from environment
variables, .env files, and secret-file directories. For an
all-Typed-is-BaseSettings codebase this default is catastrophic: every
Typed model with a field named user, home, path, shell,
etc. would silently try to interpret the matching shell environment
variable (USER, HOME, PATH, SHELL) as a value for that
field, almost always failing with a confusing SettingsError about
JSON-decoding a non-JSON string.
We disable env / dotenv / secret-file sources at the Typed level and require users to opt in by overriding this classmethod on a specific subclass:
.. code-block:: python
class MyApp(Typed):
model_config = SettingsConfigDict(env_prefix="MYAPP_")
@classmethod
def settings_customise_sources(cls, settings_cls,
init_settings, env_settings, dotenv_settings,
file_secret_settings):
# Re-enable env vars (with the MYAPP_ prefix above):
return init_settings, env_settings, dotenv_settings, file_secret_settings
CLI parsing is independent of this method. It is enabled when the user
passes _cli_parse_args=... (or sets cli_parse_args=True /
cli_parse_args=[...] in model_config); the CLI source is added
on top of whatever sources this method returns.
Source code in src/morphic/typed.py
parse_cli_args(argv: Optional[List[str]] = None, **kwargs: Any) -> T
classmethod
¶
Parse command-line arguments into a fully validated instance of cls.
This is the recommended entrypoint for CLI scripts that use Typed
as their root config model. It does the work that
cls(_cli_parse_args=...) does, plus it handles __type__
discriminator dispatch for Typed + Registry fields at any depth.
Two-pass dispatch¶
parse_cli_args first scans argv for --<path>.__type__ <key>
flags, recording which Registry-typed field at which depth should be
resolved to which concrete subclass. It then dynamically rebuilds
cls with each abstract Registry field replaced by its resolved
concrete subclass, and hands the rebuilt class to pydantic-settings'
normal CLI source. The result is that subclass-specific fields like
--backend.url (for HttpBackend) become valid CLI flags.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
argv
|
Optional[List[str]]
|
Argument list. Defaults to |
None
|
**kwargs
|
Any
|
Forwarded to |
{}
|
Returns:
| Type | Description |
|---|---|
T
|
A fully validated instance of |
T
|
an abstract Registry base and |
T
|
argv, an instance of the resolved concrete subclass). |
Examples:
Pure Typed root (no Registry fields):
.. code-block:: python
class App(Typed):
seed: int = 42
name: str = "default"
# In script.py:
app = App.parse_cli_args()
Typed + Registry field with discriminator dispatch:
.. code-block:: python
class Backend(Typed, Registry, ABC):
name: str
class HttpBackend(Backend):
aliases = ("http",)
url: str = "http://localhost"
class Config(Typed):
backend: Backend
seed: int = 42
# CLI: python script.py --backend.__type__ http \
# --backend.name api \
# --backend.url http://prod
config = Config.parse_cli_args()
assert isinstance(config.backend, HttpBackend)
assert config.backend.url == "http://prod"
Multiple Registry hierarchies at different depths:
.. code-block:: python
class Auth(Typed, Registry, ABC):
pass
class BasicAuth(Auth):
aliases = ("basic",)
username: str = ""
password: str = ""
class HttpBackend(Backend):
aliases = ("http",)
url: str = "http://localhost"
auth: Auth = BasicAuth() # default subclass
# CLI: --backend.__type__ http
# --backend.auth.__type__ basic
# --backend.auth.username alice
config = Config.parse_cli_args()
assert isinstance(config.backend.auth, BasicAuth)
See Also
- :meth:
Typed.__new__: Direct__type__dispatch when constructing aTyped + Registryabstract base via kwargs. - :data:
TYPED_REGISTRY_DISCRIMINATOR_KEY: The sentinel name.
Source code in src/morphic/typed.py
1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 | |
of(registry_key: Optional[Any] = None, /, **data: Dict[str, Any]) -> T
classmethod
¶
Factory method for creating instances with automatic Registry delegation.
This factory method intelligently delegates to Registry's hierarchical factory when the class inherits from both Typed and Registry, while maintaining the simple Typed factory behavior for pure Typed classes. This ensures that Registry's sophisticated factory patterns work seamlessly with Typed's validation and modeling capabilities.
Delegation Logic
- Registry + Typed Classes: Automatically delegates to Registry.of() for hierarchical factory patterns, registry key lookup, and subclass instantiation
- Pure Typed Classes: Uses simple constructor-based factory for direct instantiation
- Detection: Checks if the class inherits from Registry using method resolution order
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
registry_key
|
Optional[Any]
|
Registry key for subclass lookup. When provided, this triggers Registry-style factory behavior. When None and class inherits from Registry, uses Registry's direct instantiation logic. Defaults to None. |
None
|
**data
|
Dict[str, Any]
|
Field values passed to the class constructor. These undergo Pydantic validation and type conversion. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
T |
T
|
A new instance of the appropriate subclass (for Registry) or the class itself (for Typed). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If validation fails during Typed model creation |
KeyError
|
If registry_key not found in Registry hierarchy |
TypeError
|
If Registry constraints are violated (e.g., abstract class without key) |
Registry Integration Examples
from morphic.registry import Registry
from morphic.typed import Typed
from abc import ABC, abstractmethod
# Proper inheritance order: Typed first, then Registry
class Animal(Typed, Registry, ABC):
name: str
species: str
@abstractmethod
def speak(self) -> str:
pass
class Dog(Animal):
aliases = ["canine", "puppy"]
def __init__(self, name: str = "Buddy", breed: str = "Mixed", **kwargs):
# Extract Typed fields for validation
super().__init__(name=name, species="Canis lupus", **kwargs)
self.breed = breed
def speak(self) -> str:
return f"{self.name} says Woof!"
class Cat(Animal):
aliases = ["feline", "kitty"]
def __init__(self, name: str = "Whiskers", color: str = "Orange", **kwargs):
super().__init__(name=name, species="Felis catus", **kwargs)
self.color = color
def speak(self) -> str:
return f"{self.name} says Meow!"
# Registry factory patterns work seamlessly
dog = Animal.of("Dog", name="Rex", breed="German Shepherd")
assert isinstance(dog, Dog)
assert dog.name == "Rex" # Pydantic validated
assert dog.species == "Canis lupus" # Pydantic validated
assert dog.breed == "German Shepherd" # Custom attribute
# Alias support
cat = Animal.of("feline", name="Shadow", color="Black")
assert isinstance(cat, Cat)
assert cat.speak() == "Shadow says Meow!"
# Direct concrete instantiation
dog2 = Dog.of(name="Buddy", breed="Labrador")
assert isinstance(dog2, Dog)
assert dog2.name == "Buddy"
# Hierarchical scoping still enforced
# Dog.of("Cat") would raise KeyError - not in Dog's hierarchy
Pure Typed Usage
Advanced Registry Patterns
# Complex hierarchies with validation
class DatabaseConnection(Typed, Registry, ABC):
host: str = "localhost"
port: int = 5432
ssl: bool = False
@abstractmethod
def connect(self) -> str:
pass
class PostgreSQL(DatabaseConnection):
aliases = ["postgres", "pg"]
def __init__(self, database: str = "mydb", **kwargs):
super().__init__(**kwargs)
self.database = database
def connect(self) -> str:
return f"postgresql://{self.host}:{self.port}/{self.database}"
# Type conversion and validation happen automatically
db = DatabaseConnection.of(
"postgres",
host="remote.db",
port="5433", # String converted to int
ssl="true", # String converted to bool
database="production"
)
assert db.port == 5433 # Converted and validated
assert db.ssl is True # Converted and validated
assert db.database == "production"
Method Resolution
When a class inherits from both Typed and Registry, the method resolution follows:
- Check if class has Registry in its MRO (method resolution order)
- If Registry found: Delegate to Registry.of() with all arguments
- If no Registry: Use simple Typed factory (ignore registry_key if provided)
Error Handling
# Registry errors are preserved
try:
Animal.of("InvalidAnimal") # KeyError from Registry
except KeyError as e:
print(f"Registry error: {e}")
# Pydantic validation errors are preserved
try:
Animal.of("Dog", name="Rex", age="invalid") # ValueError from Typed
except ValueError as e:
print(f"Validation error: {e}")
Performance Notes
- Registry delegation adds minimal overhead (single MRO check)
- Pydantic validation occurs in all cases for data integrity
- Registry hierarchy lookups use O(1) hash table operations
See Also
morphic.registry.Registry.of(): The underlying Registry factory methodmorphic.typed.Typed.__init__(): Pydantic validation and error handlingmorphic.autoenum.AutoEnum: For creating fuzzy-matching registry keys
Source code in src/morphic/typed.py
1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 | |
class_name() -> str
¶
Get the name of the class as a string.
Returns the simple class name (without module path) of the current class. This is useful for error messages, logging, and debugging.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The name of the class (e.g., "User" for a User class). |
Examples:
class User(Typed):
name: str
print(User.class_name) # "User"
user = User(name="John")
print(user.class_name) # "User" (same for instances)
Source code in src/morphic/typed.py
param_names() -> Set[str]
¶
Get the names of all model fields as a set.
Extracts field names from the model's JSON schema, providing a convenient way to inspect what fields are available on a model without creating an instance.
Returns:
| Type | Description |
|---|---|
Set[str]
|
Set[str]: Set containing all field names defined in the model. |
Examples:
class User(Typed):
name: str
age: int
email: Optional[str] = None
field_names = User.param_names
print(field_names) # {"name", "age", "email"}
# Check if a field exists
if "email" in User.param_names:
print("User model has email field")
Note
This property uses the model's JSON schema, so it reflects the actual fields that Pydantic recognizes for validation and serialization.
Source code in src/morphic/typed.py
param_default_values() -> Dict
¶
Get default values for model fields that have defaults defined.
Extracts default values from the model's JSON schema, providing an easy way to inspect which fields have defaults and what those default values are.
Returns:
| Name | Type | Description |
|---|---|---|
Dict |
Dict
|
Dictionary mapping field names to their default values. Only includes fields that have explicit defaults defined. |
Examples:
class User(Typed):
name: str # No default
age: int # No default
active: bool = True # Has default
role: str = "user" # Has default
email: Optional[str] = None # Has default
defaults = User.param_default_values
print(defaults) # {"active": True, "role": "user", "email": None}
# Check if a field has a default
if "active" in User.param_default_values:
print(f"Default active value: {User.param_default_values['active']}")
Note
- Only fields with explicit defaults are included
- Fields without defaults will not appear in the returned dictionary
- Values are extracted from JSON schema, so they may be serialized representations
Source code in src/morphic/typed.py
pre_set_validate_inputs(data: Dict) -> Dict
classmethod
¶
Default implementation of pre_set_validate_inputs, overridable by subclasses.
Source code in src/morphic/typed.py
pre_initialize(data: Any) -> NoReturn
classmethod
¶
Pre-initialization hook for setting up derived fields before validation.
This classmethod is called after default values are set but before pre_validate. It's designed for initializing fields that depend on multiple input fields (e.g., computed or derived fields).
Execution Order:
1. _set_default_values() - Apply default values for missing fields
2. pre_initialize() - Initialize derived fields (this method)
3. pre_validate() - Validate and normalize input data
4. Pydantic field validation - Type conversion and constraint validation
5. post_initialize() - Post-validation initialization
6. post_validate() - Post-validation validation
Key Features: - Pre-validation Hook: Called before validation logic - Mutable Data: Can modify the input dictionary directly - Derived Fields: Ideal for computing fields based on other fields - Automatic Inheritance: Parent class hooks are called automatically
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Dict
|
The input data dictionary passed to the model constructor. This dictionary is mutable and can be modified in-place. Keys represent field names and values represent the raw input values (with defaults applied). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
NoReturn |
NoReturn
|
This method should not return anything. All modifications should
be made to the |
Note
Parent class pre_initialize methods are called automatically in MRO order
(base to derived), so subclasses don't need to call super().pre_initialize(data).
Override pre_set_validate_inputs if you need custom ordering.
Examples:
Basic Derived Field Initialization:
class User(Typed):
first_name: str
last_name: str
full_name: Optional[str] = None # Will be computed
@classmethod
def pre_initialize(cls, data: Dict) -> NoReturn:
# Compute full_name from first_name and last_name
if 'first_name' in data and 'last_name' in data:
data['full_name'] = f"{data['first_name']} {data['last_name']}"
user = User(first_name="John", last_name="Doe")
assert user.full_name == "John Doe"
Multiple Derived Fields:
from datetime import datetime
class Order(Typed):
subtotal: float
tax_rate: float = 0.1
total: Optional[float] = None
order_date: Optional[str] = None
@classmethod
def pre_initialize(cls, data: Dict) -> NoReturn:
# Compute total from subtotal and tax_rate
if 'subtotal' in data:
subtotal = float(data['subtotal'])
tax_rate = float(data.get('tax_rate', 0.1))
data['total'] = subtotal * (1 + tax_rate)
# Set order date if not provided
if data.get('order_date') is None:
data['order_date'] = datetime.now().isoformat()
order = Order(subtotal=100.0)
assert order.total == 110.0
assert order.order_date is not None
Inheritance Example
class Parent(Typed):
name: str
parent_computed: Optional[str] = None
@classmethod
def pre_initialize(cls, data: Dict) -> NoReturn:
if 'name' in data:
data['parent_computed'] = f"Parent: {data['name']}"
class Child(Parent):
age: int
child_computed: Optional[str] = None
@classmethod
def pre_initialize(cls, data: Dict) -> NoReturn:
# Parent's hook is called automatically before this
if 'name' in data and 'age' in data:
data['child_computed'] = f"Child: {data['name']}, {data['age']}"
# Both hooks run automatically in order
model = Child(name="john", age=30)
assert model.parent_computed == "Parent: john" # From parent
assert model.child_computed == "Child: john, 30" # From child
Three-Level Inheritance Example
class Level1(Typed):
field1: str
level1_data: Optional[str] = None
@classmethod
def pre_initialize(cls, data: Dict) -> NoReturn:
if 'field1' in data:
data['level1_data'] = f"L1: {data['field1']}"
class Level2(Level1):
field2: str
level2_data: Optional[str] = None
@classmethod
def pre_initialize(cls, data: Dict) -> NoReturn:
if 'field2' in data:
data['level2_data'] = f"L2: {data['field2']}"
class Level3(Level2):
field3: str
level3_data: Optional[str] = None
@classmethod
def pre_initialize(cls, data: Dict) -> NoReturn:
if 'field3' in data:
data['level3_data'] = f"L3: {data['field3']}"
# All three hooks run in order: Level1 -> Level2 -> Level3
model = Level3(field1="a", field2="b", field3="c")
assert model.level1_data == "L1: a"
assert model.level2_data == "L2: b"
assert model.level3_data == "L3: c"
Working with Nested Typed Objects
Nested Typed fields are automatically converted from dicts to objects before
pre_initialize is called. This means you can directly access nested objects and
their computed fields without manual conversion.
class Address(Typed):
street: str
city: str
full_address: Optional[str] = None
@classmethod
def pre_initialize(cls, data: Dict) -> NoReturn:
if 'street' in data and 'city' in data:
data['full_address'] = f"{data['street']}, {data['city']}"
class Person(Typed):
name: str
address: Address
summary: Optional[str] = None
@classmethod
def pre_initialize(cls, data: Dict) -> NoReturn:
# address is already an Address object (not a dict!)
if 'address' in data:
addr = data['address']
# Can access computed fields directly
data['summary'] = f"{data['name']} from {addr.full_address}"
# Pass nested data as dict - automatic conversion happens
person = Person(
name="John",
address={"street": "123 Main St", "city": "NYC"}
)
assert person.summary == "John from 123 Main St, NYC"
This works for:
- Direct fields: address: Address
- Optional fields: address: Optional[Address]
- Lists: addresses: List[Address]
- Dicts: locations: Dict[str, Address]
See Also
pre_validate(): For validation and normalization after initializationpost_initialize(): For post-validation initializationpre_set_validate_inputs(): To customize the execution order
Source code in src/morphic/typed.py
2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 | |
pre_validate(data: Any) -> NoReturn
classmethod
¶
Pre-validation hook for validating and normalizing input data.
This classmethod is called after pre_initialize and before Pydantic validation. It's designed for validating input data and normalizing field values.
Execution Order:
1. _set_default_values() - Apply default values for missing fields
2. pre_initialize() - Initialize derived fields
3. pre_validate() - Validate and normalize input data (this method)
4. Pydantic field validation - Type conversion and constraint validation
5. post_initialize() - Post-validation initialization
6. post_validate() - Post-validation validation
Key Features: - Pre-validation Hook: Called before Pydantic's field validation - Mutable Data: Can modify the input dictionary directly - Early Validation: Allows custom validation logic before type conversion - Data Normalization: Can normalize and transform field values - Error Handling: Can raise custom validation errors with detailed messages - Automatic Inheritance: Parent class hooks are called automatically
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Dict
|
The input data dictionary passed to the model constructor or
|
required |
Returns:
| Name | Type | Description |
|---|---|---|
NoReturn |
NoReturn
|
This method should not return anything. All modifications should be
made to the |
Raises:
| Type | Description |
|---|---|
ValueError
|
Should raise ValueError (or subclasses) for validation failures. The error message will be wrapped by Typed's enhanced error handling. |
Any other exception
|
Will be caught and wrapped by Typed's error handling system. |
Note
Parent class pre_validate methods are called automatically in MRO order
(base to derived), so subclasses don't need to call super().pre_validate(data).
Override pre_set_validate_inputs if you need custom ordering.
Examples:
Basic Input Validation:
class User(Typed):
name: str
email: str
age: int
@classmethod
def pre_validate(cls, data: Dict) -> NoReturn:
# Normalize email to lowercase
if 'email' in data:
data['email'] = data['email'].lower()
# Validate age range
if 'age' in data and isinstance(data['age'], (int, str)):
age = int(data['age']) if isinstance(data['age'], str) else data['age']
if age < 0 or age > 150:
raise ValueError(f"Age must be between 0 and 150, got {age}")
# Usage - email gets normalized, age gets validated
user = User(name="John", email="JOHN@EXAMPLE.COM", age=30)
assert user.email == "john@example.com"
# Invalid age raises error before model creation
try:
User(name="John", email="john@example.com", age=200)
except ValueError as e:
print(e) # "Age must be between 0 and 150, got 200"
Data Enrichment and Computed Fields:
class Product(Typed):
name: str
price: float
tax_rate: float = 0.1
total_price: Optional[float] = None # Will be computed
@classmethod
def pre_validate(cls, data: Dict) -> NoReturn:
# Compute total price if not provided
if 'total_price' not in data and 'price' in data:
price = float(data['price'])
tax_rate = float(data.get('tax_rate', 0.1))
data['total_price'] = price * (1 + tax_rate)
# Normalize product name
if 'name' in data:
data['name'] = data['name'].strip().title()
# Usage - total_price gets computed automatically
product = Product(name=" laptop ", price=1000)
assert product.name == "Laptop"
assert product.total_price == 1100.0 # 1000 * 1.1
Complex Validation with Multiple Fields:
class DateRange(Typed):
start_date: str
end_date: str
duration_days: Optional[int] = None
@classmethod
def pre_validate(cls, data: Dict) -> NoReturn:
from datetime import datetime
# Parse and pre_validate dates
if 'start_date' in data and 'end_date' in data:
try:
start = datetime.fromisoformat(data['start_date'])
end = datetime.fromisoformat(data['end_date'])
except ValueError as e:
raise ValueError(f"Invalid date format: {e}")
# Validate date order
if start >= end:
raise ValueError("start_date must be before end_date")
# Compute duration if not provided
if 'duration_days' not in data:
data['duration_days'] = (end - start).days
# Usage - dates get validated and duration computed
date_range = DateRange(
start_date="2024-01-01",
end_date="2024-01-10"
)
assert date_range.duration_days == 9
Conditional Field Processing:
class APIRequest(Typed):
method: str
url: str
headers: Optional[Dict[str, str]] = None
body: Optional[str] = None
@classmethod
def pre_validate(cls, data: Dict) -> NoReturn:
# Normalize HTTP method
if 'method' in data:
data['method'] = data['method'].upper()
# Add default headers if not provided
if 'headers' not in data:
data['headers'] = {}
# For POST/PUT requests, ensure Content-Type is set
method = data.get('method', '').upper()
if method in ['POST', 'PUT', 'PATCH'] and 'body' in data:
headers = data['headers']
if 'Content-Type' not in headers:
headers['Content-Type'] = 'application/json'
# Validate URL format
url = data.get('url', '')
if url and not (url.startswith('http://') or url.startswith('https://')):
raise ValueError(f"URL must start with http:// or https://, got: {url}")
# Usage - method normalized, headers added, URL validated
request = APIRequest(
method="post",
url="https://api.example.com/users",
body='{"name": "John"}'
)
assert request.method == "POST"
assert request.headers["Content-Type"] == "application/json"
Advanced Patterns
Validation with External Dependencies:
class UserAccount(Typed):
username: str
email: str
role: str = "user"
@classmethod
def pre_validate(cls, data: Dict) -> NoReturn:
# Validate username format
username = data.get('username', '')
if username and not username.isalnum():
raise ValueError("Username must be alphanumeric")
# Validate email format (basic check)
email = data.get('email', '')
if email and '@' not in email:
raise ValueError("Invalid email format")
# Validate role against allowed values
role = data.get('role', 'user')
allowed_roles = ['user', 'admin', 'moderator']
if role not in allowed_roles:
raise ValueError(f"Role must be one of {allowed_roles}, got: {role}")
Integration with Registry and AutoEnum
from morphic.autoenum import AutoEnum, auto
from morphic.registry import Registry
class Status(AutoEnum):
ACTIVE = auto()
INACTIVE = auto()
PENDING = auto()
class Task(Typed, Registry):
title: str
status: Status = Status.PENDING
priority: int = 1
@classmethod
def pre_validate(cls, data: Dict) -> NoReturn:
# Normalize title
if 'title' in data:
data['title'] = data['title'].strip()
if not data['title']:
raise ValueError("Title cannot be empty")
# Clamp priority to valid range
if 'priority' in data:
priority = int(data['priority'])
data['priority'] = max(1, min(10, priority)) # Clamp to 1-10
# Auto-assign status based on priority
if 'status' not in data:
priority = int(data.get('priority', 1))
if priority >= 8:
data['status'] = Status.ACTIVE
else:
data['status'] = Status.PENDING
# Usage with Registry factory
task = Task.of(title=" Important Task ", priority=15)
assert task.title == "Important Task"
assert task.priority == 10 # Clamped from 15
assert task.status == Status.ACTIVE # Auto-assigned
Error Handling Best Practices
- Raise descriptive ValueError messages with context about what failed
- Include the problematic field name and value in error messages
- Use early returns or guard clauses for optional field validation
- Validate field dependencies and relationships
- Consider using helper methods for complex validation logic
Performance Considerations
- This method is called for every model instantiation
- Avoid expensive operations like network calls or file I/O
- Cache validation results or patterns when possible
- Use lazy evaluation for optional validations
Thread Safety
- This method operates on the input data dictionary, not the class
- Avoid modifying class-level attributes or shared state
- Each validation call receives its own data dictionary copy
See Also
pre_initialize(): For setting up derived fields before validationpost_validate(): For post-validation validationpre_set_validate_inputs(): To customize the execution order@field_validator: Field-level validation for specific fields
Source code in src/morphic/typed.py
2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 | |
post_initialize() -> NoReturn
¶
Post-initialization hook for side effects after validation.
This instance method is called after Pydantic validation is complete and before post_validate. It's designed for performing side effects that don't modify the instance (e.g., logging, external system integration).
Execution Order:
1. _set_default_values() - Apply default values for missing fields
2. pre_initialize() - Initialize derived fields
3. pre_validate() - Validate and normalize input data
4. Pydantic field validation - Type conversion and constraint validation
5. post_initialize() - Post-validation initialization (this method)
6. post_validate() - Post-validation validation
Key Features: - Post-Validation Hook: Called after all field validation and type conversion - Instance Access: Can access validated field values (read-only) - Side Effects: Perfect for logging, external system integration, or notifications - Error Handling: Can handle initialization errors gracefully - Frozen Instance: Cannot modify instance attributes (instance is frozen) - Automatic Inheritance: Parent class hooks are called automatically
Differences from pre_initialize:
- Timing: pre_initialize() runs before validation, post_initialize() runs after
- Data Access: pre_initialize() works on raw input dict, post_initialize() works on validated instance
- Purpose: pre_initialize() for setting derived fields, post_initialize() for side effects
- Mutability: pre_initialize() can modify data dict, post_initialize() cannot modify frozen instance
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
None
|
This method takes no parameters. Access validated fields via |
required |
Returns:
| Name | Type | Description |
|---|---|---|
NoReturn |
NoReturn
|
This method should not return anything. Since the instance is frozen, this method is primarily for side effects rather than modifying attributes. |
Raises:
| Type | Description |
|---|---|
Any exception
|
Exceptions raised during initialization will be caught and wrapped by Typed's error handling system, similar to validation errors. |
Note
Parent class post_initialize methods are called automatically in MRO order
(base to derived), so subclasses don't need to call super().post_initialize().
Override post_set_validate_inputs if you need custom ordering.
Examples:
Side Effects and Logging:
class User(Typed):
name: str
email: str
display_name: Optional[str] = None
email_domain: Optional[str] = None
@classmethod
def pre_validate(cls, data: dict) -> None:
# Set computed fields during validation
if 'name' in data:
data['display_name'] = data['name'].title()
if 'email' in data:
data['email_domain'] = data['email'].split("@")[1]
def post_initialize(self) -> None:
# Perform side effects after validation
print(f"User created: {self.display_name} ({self.email_domain})")
# Could also integrate with external systems, logging, etc.
user = User(name="john doe", email="john@example.com")
assert user.display_name == "John Doe"
assert user.email_domain == "example.com"
External System Integration:
from datetime import datetime
class Product(Typed):
name: str
price: float
total_with_tax: Optional[float] = None
metadata: Optional[dict] = None
@classmethod
def pre_validate(cls, data: dict) -> None:
# Compute derived values during validation
if 'price' in data:
data['total_with_tax'] = data['price'] * 1.1
data['metadata'] = {
"created_at": datetime.now().isoformat(),
"price_category": "expensive" if data['price'] > 100 else "affordable"
}
def post_initialize(self) -> None:
# Integrate with external systems after validation
# e.g., send to analytics, update cache, etc.
print(f"Product {self.name} registered in system")
product = Product(name="Laptop", price=999.99)
assert product.total_with_tax == 1099.989
assert product.metadata["price_category"] == "expensive"
Conditional Side Effects:
class Task(Typed):
title: str
priority: int = 1
processing_time: Optional[int] = None
error_message: Optional[str] = None
@classmethod
def pre_validate(cls, data: dict) -> None:
# Set processing time and pre_validate during validation
if 'priority' in data:
data['processing_time'] = data['priority'] * 100
if data['priority'] > 10:
data['error_message'] = "Priority too high"
def post_initialize(self) -> None:
# Perform conditional side effects
if self.priority > 5:
print(f"High priority task created: {self.title}")
if self.error_message:
print(f"Warning: {self.error_message}")
task = Task(title="Important Task", priority=5)
assert task.processing_time == 500
assert task.error_message is None
External Dependencies:
class CacheableModel(Typed):
id: str
data: str
cache_key: Optional[str] = None
hash_value: Optional[int] = None
@classmethod
def pre_validate(cls, data: dict) -> None:
# Generate cache key during validation
if 'id' in data and 'data' in data:
data['cache_key'] = f"cache_{data['id']}_{hash(data['data'])}"
data['hash_value'] = hash(data['data'])
def post_initialize(self) -> None:
# Interact with external systems after validation
# e.g., register with cache service, send to analytics, etc.
print(f"Model {self.id} registered with cache service")
model = CacheableModel(id="user123", data="important data")
assert model.cache_key.startswith("cache_user123_")
assert model.hash_value is not None
Error Handling:
class RobustModel(Typed):
value: int
processed_value: Optional[int] = None
error: Optional[str] = None
@classmethod
def pre_validate(cls, data: dict) -> None:
# Handle processing during validation
if 'value' in data:
try:
if data['value'] < 0:
raise ValueError("Value cannot be negative")
data['processed_value'] = data['value'] * 2
except Exception as e:
data['error'] = str(e)
def post_initialize(self) -> None:
# Handle side effects after validation
if self.error:
print(f"Error during processing: {self.error}")
else:
print(f"Successfully processed value: {self.processed_value}")
# Successful initialization
model1 = RobustModel(value=10)
assert model1.processed_value == 20
assert model1.error is None
# Initialization with error
model2 = RobustModel(value=-5)
assert model2.processed_value is None
assert model2.error == "Value cannot be negative"
Nested Object Side Effects:
class Address(Typed):
street: str
city: str
full_address: Optional[str] = None
@classmethod
def pre_validate(cls, data: dict) -> None:
if 'street' in data and 'city' in data:
data['full_address'] = f"{data['street']}, {data['city']}"
def post_initialize(self) -> None:
print(f"Address created: {self.full_address}")
class Person(Typed):
name: str
address: Address
contact_info: Optional[str] = None
@classmethod
def pre_validate(cls, data: dict) -> None:
if 'name' in data and 'address' in data:
# Create address to get full_address
address = Address(**data['address'])
data['contact_info'] = f"{data['name']} at {address.full_address}"
def post_initialize(self) -> None:
print(f"Person created: {self.contact_info}")
person = Person(
name="John Doe",
address={"street": "123 Main St", "city": "Anytown"}
)
assert person.address.full_address == "123 Main St, Anytown"
assert person.contact_info == "John Doe at 123 Main St, Anytown"
Advanced Patterns
Inheritance and Super Calls:
class BaseModel(Typed):
name: str
base_info: Optional[str] = None
@classmethod
def pre_validate(cls, data: dict) -> None:
if 'name' in data:
data['base_info'] = f"Base: {data['name']}"
def post_initialize(self) -> None:
print(f"Base model initialized: {self.base_info}")
class ExtendedModel(BaseModel):
age: int
extended_info: Optional[str] = None
@classmethod
def pre_validate(cls, data: dict) -> None:
# Call parent validation
super().pre_validate(data)
# Add extended validation
if 'name' in data and 'age' in data:
data['extended_info'] = f"Extended: {data['name']} is {data['age']} years old"
def post_initialize(self) -> None:
# Call parent initialization
super().post_initialize()
# Add extended initialization
print(f"Extended model initialized: {self.extended_info}")
model = ExtendedModel(name="John", age=30)
assert model.base_info == "Base: John"
assert model.extended_info == "Extended: John is 30 years old"
Factory Method Integration:
class FactoryModel(Typed):
name: str
factory_info: Optional[str] = None
@classmethod
def pre_validate(cls, data: dict) -> None:
if 'name' in data:
data['factory_info'] = f"Created via factory: {data['name']}"
def post_initialize(self) -> None:
print(f"Factory model initialized: {self.factory_info}")
# Works with of() factory method
model = FactoryModel.of(name="FactoryTest")
assert model.factory_info == "Created via factory: FactoryTest"
Inheritance Example:
class Parent(Typed):
name: str
def post_initialize(self) -> None:
print(f"Parent initialized: {self.name}")
class Child(Parent):
age: int
def post_initialize(self) -> None:
# Parent's hook is called automatically before this
print(f"Child initialized: {self.name}, age {self.age}")
# Both hooks run automatically in order
model = Child(name="john", age=30)
# Output:
# Parent initialized: john
# Child initialized: john, age 30
Multi-Level Inheritance Example:
class Level1(Typed):
field1: str
def post_initialize(self) -> None:
print(f"Level1: {self.field1}")
class Level2(Level1):
field2: str
def post_initialize(self) -> None:
print(f"Level2: {self.field2}")
class Level3(Level2):
field3: str
def post_initialize(self) -> None:
print(f"Level3: {self.field3}")
# All three hooks run in order: Level1 -> Level2 -> Level3
model = Level3(field1="a", field2="b", field3="c")
# Output:
# Level1: a
# Level2: b
# Level3: c
Performance Considerations
- This method is called for every model instantiation
- Avoid expensive operations like network calls or file I/O
- Cache expensive computations when possible
- Use lazy evaluation for optional initializations
Thread Safety
- This method operates on the model instance, not shared state
- Avoid modifying class-level attributes
- Each initialization call receives its own model instance
Best Practices
- Use for side effects like logging, external system integration, or notifications
- Handle errors gracefully with try-catch blocks
- Keep initialization logic simple and fast
- Document any side effects or external dependencies
- Use
pre_validate()for input transformation and computed fields instead
Working with Nested Typed Objects
Like in pre_initialize, nested Typed objects are already instantiated (not dicts).
By the time post_initialize runs, all nested objects are fully validated and their
hooks have completed.
class Item(Typed):
name: str
price: float
def post_initialize(self) -> NoReturn:
print(f"Item {self.name} created")
class Order(Typed):
items: List[Item]
total: float
def post_initialize(self) -> NoReturn:
# All items are fully validated Item instances
for item in self.items:
assert isinstance(item, Item)
print(f" - {item.name}: ${item.price}")
# Output when creating:
# Item Widget created
# Item Gadget created
# - Widget: $10.0
# - Gadget: $20.0
order = Order(
items=[{"name": "Widget", "price": 10.0}, {"name": "Gadget", "price": 20.0}],
total=30.0
)
Note: Nested objects are converted before any hooks run, so they're available as objects in both pre-hooks and post-hooks.
See Also
pre_initialize(): For setting up derived fields before validationpost_validate(): For post-validation validationpost_set_validate_inputs(): To customize the execution order@model_validator(mode="after"): Pydantic's post-creation validation hook
Source code in src/morphic/typed.py
2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 | |
post_validate() -> NoReturn
¶
Post-validation hook for validating the model instance after initialization.
This instance method is called after post_initialize. It's designed for performing validation on the fully constructed and initialized model instance.
Execution Order:
1. _set_default_values() - Apply default values for missing fields
2. pre_initialize() - Initialize derived fields
3. pre_validate() - Validate and normalize input data
4. Pydantic field validation - Type conversion and constraint validation
5. post_initialize() - Post-validation initialization
6. post_validate() - Post-validation validation (this method)
Key Features: - Post-Validation Hook: Called after initialization is complete - Instance Access: Can access all validated and initialized fields (read-only) - Cross-Field Validation: Perfect for validating relationships between fields - Frozen Instance: Cannot modify instance attributes (instance is frozen) - Automatic Inheritance: Parent class hooks are called automatically
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
None
|
This method takes no parameters. Access validated fields via |
required |
Returns:
| Name | Type | Description |
|---|---|---|
NoReturn |
NoReturn
|
This method should not return anything. It's primarily for validation that raises exceptions if the instance is invalid. |
Raises:
| Type | Description |
|---|---|
ValueError
|
Should raise ValueError (or subclasses) for validation failures. |
Any other exception
|
Will be caught and wrapped by Typed's error handling system. |
Note
Parent class post_validate methods are called automatically in MRO order
(base to derived), so subclasses don't need to call super().post_validate().
Override post_set_validate_inputs if you need custom ordering.
Examples:
Cross-Field Validation:
class DateRange(Typed):
start_date: str
end_date: str
def post_validate(self) -> NoReturn:
from datetime import datetime
start = datetime.fromisoformat(self.start_date)
end = datetime.fromisoformat(self.end_date)
if start >= end:
raise ValueError("start_date must be before end_date")
# Valid range
date_range = DateRange(start_date="2024-01-01", end_date="2024-01-10")
# Invalid range raises error
try:
DateRange(start_date="2024-01-10", end_date="2024-01-01")
except ValueError as e:
print(e) # "start_date must be before end_date"
Business Logic Validation:
class Order(Typed):
items: List[str]
subtotal: float
discount: float = 0.0
total: float
def post_validate(self) -> NoReturn:
# Validate discount
if self.discount < 0 or self.discount > self.subtotal:
raise ValueError("Invalid discount amount")
# Validate total calculation
expected_total = self.subtotal - self.discount
if abs(self.total - expected_total) > 0.01:
raise ValueError(f"Total mismatch: expected {expected_total}, got {self.total}")
# Validate items
if not self.items:
raise ValueError("Order must have at least one item")
See Also
pre_validate(): For input validation before model creationpost_initialize(): For side effects after validationpost_set_validate_inputs(): To customize the execution order
Source code in src/morphic/typed.py
3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 | |
MutableTyped
¶
Bases: Typed
A mutable variant of Typed that allows field modification after instantiation.
Unlike the base Typed class which is frozen (immutable), MutableTyped instances can have their fields modified after creation. This is useful when you need to update model instances during runtime, especially in tight loops or with frequent modifications where validation overhead should be minimized.
Key Features: - Mutable: Fields can be modified after instantiation - Performance Optimized: No validation on assignment by default for speed - Type Safe at Creation: Full validation during instantiation - Pydantic Compatible: Built on Pydantic's validation system - Optional Validation: Can enable assignment validation if needed
Configuration:
- frozen=False: Allows field modification
- validate_assignment=False: Disabled by default for performance (can be enabled)
- validate_private_assignment=False: Private attrs not validated (inherited default)
Basic Usage
class User(MutableTyped):
name: str
age: int
active: bool = True
user = User(name="John", age=30)
user.name = "Jane" # This works with MutableTyped
user.age = 25 # This also works
print(user.name) # "Jane"
# Compare with regular Typed (frozen):
class FrozenUser(Typed):
name: str
age: int
frozen_user = FrozenUser(name="John", age=30)
frozen_user.name = "Jane" # This would raise ValidationError
No Validation on Assignment (Default): By default, assignments are NOT validated for performance:
```python
user = User(name="John", age=30)
user.age = "not_a_number" # Allowed! No validation on assignment
user.name = 123 # Also allowed for performance
# This is intentional for high-performance scenarios like tight loops
for i in range(1000000):
user.age = i # Fast - no validation overhead
```
Enabling Validation on Assignment (Optional): If you need validation on assignment, enable it explicitly:
```python
from pydantic import ConfigDict
class ValidatedUser(MutableTyped):
model_config = ConfigDict(
frozen=False,
validate_assignment=True, # Enable validation
)
name: str
age: int
user = ValidatedUser(name="John", age=30)
try:
user.age = "not_a_number" # Now raises ValidationError
except ValidationError:
print("Validation enforced!")
```
Hooks and Derived Fields
Important: Use pre-hooks for derived fields, not post-hooks. Post-hooks should only perform side effects (logging, notifications, etc.).
class UserWithScore(MutableTyped):
name: str
age: int
score: Optional[int] = None
@classmethod
def pre_initialize(cls, data: Dict) -> None:
# ✅ CORRECT: Set derived fields in pre_initialize
if 'age' in data:
data['score'] = data['age'] * 10
def post_initialize(self) -> None:
# ✅ CORRECT: Use post hooks for side effects only
print(f"User {self.name} created with score {self.score}")
# ❌ WRONG: Don't modify instance here
# self.score = self.age * 10 # Would cause issues
user = UserWithScore(name="John", age=30)
print(user.score) # 300 (set by pre_initialize)
# Modifying age triggers validation including pre_initialize again
user.age = 25
print(user.score) # 250 (recomputed by pre_initialize!)
Performance Considerations
By default, MutableTyped prioritizes performance over validation:
class Counter(MutableTyped):
count: int = 0
label: str = "counter"
counter = Counter()
# Fast - no validation overhead
for i in range(1000000):
counter.count = i # Direct assignment, no validation
# Validation only happens at creation time
counter2 = Counter(count="invalid") # Raises ValidationError
When to Enable validate_assignment=True: - When data integrity is critical and performance is not - When assignments come from untrusted sources - When you need to catch type errors during development - When assignment frequency is low
When to Keep validate_assignment=False (default): - High-performance scenarios (tight loops, frequent updates) - Internal state management where types are controlled - When you trust the assignment sources - When you want minimal overhead
See Also
Typed: The base frozen (immutable) classpre_validate(): For function parameter validationpre_initialize(): For setting up derived fieldspost_initialize(): For side effects after creation- Pydantic's
ConfigDict: For advanced configuration options
Source code in src/morphic/typed.py
3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 | |
validate(*args, **kwargs)
¶
Function decorator for automatic parameter validation using Pydantic.
This decorator validates function parameters against their type annotations using Pydantic's validation system. It provides automatic type conversion, validation, and helpful error messages for function arguments, making it easy to add runtime type checking to any function.
Features
- Automatic Type Conversion: Converts compatible types (e.g., string to int)
- Type Validation: Validates all parameters against their type annotations
- Default Value Validation: Validates default parameter values at call time
- Detailed Error Messages: Provides clear validation error messages
- Arbitrary Types: Supports custom types and Typed models as parameters
- Return Value Validation: Optional validation of return values
Configuration
The decorator is pre-configured with the following Pydantic settings:
populate_by_name=True: Allows both original names and aliases for fieldsarbitrary_types_allowed=True: Supports custom types beyond built-in typesvalidate_default=True: Validates default parameter values when used
Basic Usage
from morphic.typed import validate
@validate
def create_user(name: str, age: int, active: bool = True) -> str:
return f"User {name}, age {age}, active: {active}"
# Automatic type conversion
result = create_user("John", "30", "false")
print(result) # "User John, age 30, active: False"
# Validation errors for invalid types
try:
create_user("John", "invalid_age")
except ValidationError as e:
print(e) # Clear error message about invalid integer
Advanced Usage
from typing import List, Optional
from morphic.typed import validate, Typed
class User(Typed):
name: str
age: int
@validate
def process_users(
users: List[User],
active_only: bool = True,
max_age: Optional[int] = None
) -> List[str]:
# users automatically converted from list of dicts to list of User objects
filtered = [u for u in users if not active_only or u.age <= (max_age or 100)]
return [u.name for u in filtered]
# Dict to Typed conversion happens automatically
result = process_users([
{"name": "Alice", "age": "25"}, # Dict converted to User
{"name": "Bob", "age": "30"},
], max_age="35") # String converted to int
print(result) # ["Alice", "Bob"]
Return Value Validation
@validate(validate_return=True)
def get_user_name(user_id: int) -> str:
if user_id > 0:
return f"user_{user_id}"
else:
return None # This will raise ValidationError
name = get_user_name(5) # "user_5"
try:
get_user_name(-1) # ValidationError: return value not a string
except ValidationError as e:
print(e)
Type Conversion Examples
The decorator handles many common type conversions automatically:
@validate
def example_conversions(
number: int, # "123" -> 123
decimal: float, # "3.14" -> 3.14
flag: bool, # "true" -> True, "false" -> False
items: List[int], # ["1", "2", "3"] -> [1, 2, 3]
mapping: Dict[str, int], # {"a": "1"} -> {"a": 1}
user: User, # {"name": "John", "age": 30} -> User instance
):
pass
Error Handling
Integration with Typed Models
class Config(Typed):
host: str = "localhost"
port: int = 8080
debug: bool = False
@validate
def start_server(config: Config) -> str:
return f"Starting server on {config.host}:{config.port}"
# Dict automatically converted to Config instance
result = start_server({
"host": "example.com",
"port": "9000", # String converted to int
"debug": "true" # String converted to bool
})
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
validate_return
|
bool
|
Whether to validate the return value against the function's return type annotation. Defaults to False. |
required |
config
|
dict
|
Additional Pydantic configuration options to override the default settings. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Callable |
The decorated function with automatic parameter validation. |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If parameter validation fails or if return value validation is enabled and the return value doesn't match the annotation. |
Note
This is a pre-configured version of Pydantic's validate_call decorator with
sensible defaults for use with morphic types and patterns.
See Also
pydantic.validate_call: The underlying Pydantic decoratormorphic.typed.Typed: For creating validated data modelsmorphic.autoenum.AutoEnum: For creating validated enumerations
Source code in src/morphic/typed.py
3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 | |