Skip to content

Commit ab457d8

Browse files
cmccandlessBethanyG
authored andcommitted
handle positional arguments in custom dataclass init
1 parent 442c142 commit ab457d8

1 file changed

Lines changed: 23 additions & 5 deletions

File tree

bin/data.py

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,34 @@
11
from enum import Enum
22
from dataclasses import dataclass, asdict, fields
3+
import dataclasses
34
from itertools import chain
45
import json
56
from pathlib import Path
67
import toml
7-
from typing import List, Any, Dict
8-
9-
10-
def _custom_dataclass_init(self, **kwargs):
11-
names = set([f.name for f in fields(self)])
8+
from typing import List, Any, Dict, Type
9+
10+
11+
def _custom_dataclass_init(self, *args, **kwargs):
12+
# print(self.__class__.__name__, "__init__")
13+
positional_count = len([
14+
f.name
15+
for f in fields(self)
16+
if isinstance(f.default, dataclasses._MISSING_TYPE)
17+
])
18+
names = [f.name for f in fields(self)]
19+
for i, v in enumerate(args):
20+
k = names[i]
21+
# print(f'setting {k}={v}')
22+
setattr(self, k, v)
23+
if i < positional_count - 1:
24+
raise TypeError(f"__init__() missing {positional_count - i - 1} required positional argument")
25+
elif i >= len(names):
26+
raise TypeError(f"__init__() too many positional arguments given")
1227
for k, v in kwargs.items():
1328
if k in names:
29+
if hasattr(self, k):
30+
raise TypeError(f"__init__() got multiple values for argument '{k}'")
31+
# print(f'setting {k}={v}')
1432
setattr(self, k, v)
1533
else:
1634
raise TypeError(

0 commit comments

Comments
 (0)