FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

fix handling of positional arguments and keyword arguments · ioload/python@4e2aa32 · GitHub

Repository navigation

Commit 4e2aa32

Browse files
authored andcommitted
fix handling of positional arguments and keyword arguments
1 parent ab457d8 commit 4e2aa32

1 file changed

Lines changed: 29 additions & 13 deletions

File tree

‎bin/data.py‎

Lines changed: 29 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -10,32 +10,48 @@
1010

1111
def _custom_dataclass_init(self, *args, **kwargs):
1212
# 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-
])
1813
names = [f.name for f in fields(self)]
19-
for i, v in enumerate(args):
20-
k = names[i]
14+
used_names = set()
15+
16+
# Handle positional arguments
17+
for v in args:
18+
try:
19+
k = names.pop(0)
20+
except IndexError:
21+
raise TypeError(f"__init__() given too many positional arguments")
2122
# print(f'setting {k}={v}')
2223
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")
24+
used_names.add(k)
25+
26+
# Handle keyword arguments
2727
for k, v in kwargs.items():
2828
if k in names:
29-
if hasattr(self, k):
30-
raise TypeError(f"__init__() got multiple values for argument '{k}'")
3129
# print(f'setting {k}={v}')
3230
setattr(self, k, v)
31+
used_names.add(k)
32+
elif k in used_names:
33+
raise TypeError(f"__init__() got multiple values for argument '{k}'")
3334
else:
3435
raise TypeError(
3536
f"Unrecognized field '{k}' for dataclass {self.__class__.__name__}."
3637
"\nIf this field is valid, please add it to the dataclass in data.py."
3738
"\nIf adding an object-type field, please create a new dataclass for it."
3839
)
40+
41+
# Check for missing positional arguments
42+
missing = [
43+
f"'{f.name}'" for f in fields(self)
44+
if isinstance(f.default, dataclasses._MISSING_TYPE) and f.name not in used_names
45+
]
46+
if len(missing) == 1:
47+
raise TypeError(f"__init__() missing 1 required positional argument: {missing[0]}")
48+
elif len(missing) == 2:
49+
raise TypeError(f"__init__() missing 2 required positional arguments: {' and '.join(missing)}")
50+
elif len(missing) != 0:
51+
missing[-1] = f"and {missing[-1]}"
52+
raise TypeError(f"__init__() missing {len(missing)} required positional arguments: {', '.join(missing)}")
53+
54+
# Run post init if available
3955
if hasattr(self, "__post_init__"):
4056
self.__post_init__()
4157

0 commit comments

Comments
 (0)

Back | FazBrowse Home | New Git URL