p2a 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
p2a/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .model import *
2
+
3
+ __version__ = "0.1.0"
p2a/model.py ADDED
@@ -0,0 +1,527 @@
1
+ import sys
2
+ from argparse import ArgumentParser
3
+ from enum import Enum
4
+ from pathlib import Path
5
+ from typing import Dict, List, Literal, Optional, Type, Union, get_args, get_origin
6
+
7
+ from pkn.logging import getSimpleLogger
8
+
9
+ try:
10
+ from pydantic import BaseModel, TypeAdapter, ValidationError
11
+ from pydantic_core import PydanticUndefined
12
+ except ImportError:
13
+ raise ImportError("pydantic is required to use p2a")
14
+
15
+ __all__ = (
16
+ "create_model_parser",
17
+ "parse_extra_args_model",
18
+ )
19
+
20
+ _log = None
21
+
22
+
23
+ def _initlog(level: str = "WARNING"):
24
+ global _log
25
+ _log = getSimpleLogger("p2a")
26
+ _log.setLevel(level)
27
+
28
+
29
+ _initlog()
30
+
31
+
32
+ def _add_argument(parser: ArgumentParser, name: str, arg_type: type, default_value, **kwargs):
33
+ _log.debug(f"Adding argument: {name:<75} - {str(arg_type):<10} - {str(default_value):<10}")
34
+ if "action" in kwargs:
35
+ parser.add_argument(name, default=default_value, action=kwargs["action"])
36
+ else:
37
+ parser.add_argument(name, type=arg_type, default=default_value, **kwargs)
38
+
39
+
40
+ def parse_extra_args(subparser: Optional[ArgumentParser] = None, argv: List[str] = None) -> List[str]:
41
+ if subparser is None:
42
+ subparser = ArgumentParser(prog="p2a", allow_abbrev=False)
43
+
44
+ kwargs, extras = subparser.parse_known_args(argv or sys.argv)
45
+ return vars(kwargs), extras
46
+
47
+
48
+ def _is_supported_type(field_type: type) -> bool:
49
+ if get_origin(field_type) is Optional:
50
+ field_type = get_args(field_type)[0]
51
+ elif get_origin(field_type) is Union:
52
+ non_none_types = [t for t in get_args(field_type) if t is not type(None)]
53
+ if all(_is_supported_type(t) for t in non_none_types):
54
+ return True
55
+ if len(non_none_types) == 1:
56
+ field_type = non_none_types[0]
57
+ elif get_origin(field_type) is Literal:
58
+ return all(isinstance(arg, (str, int, float, bool, Enum)) for arg in get_args(field_type))
59
+ if not isinstance(field_type, type):
60
+ return False
61
+ return field_type in (str, int, float, bool) or issubclass(field_type, Enum)
62
+
63
+
64
+ def _recurse_add_fields(parser: ArgumentParser, model: Union["BaseModel", Type["BaseModel"]], prefix: str = ""):
65
+ # Model is required
66
+ if model is None:
67
+ raise ValueError("Model instance cannot be None") # coverage: ignore
68
+
69
+ # Extract the fields from a model instance or class
70
+ if isinstance(model, type):
71
+ model_fields = model.model_fields
72
+ else:
73
+ model_fields = model.__class__.model_fields
74
+
75
+ # For each available field, add an argument to the parser
76
+ for field_name, field in model_fields.items():
77
+ # Grab the annotation to map to type
78
+ field_type = field.annotation
79
+ # Build the argument name converting underscores to dashes
80
+ arg_name = f"--{prefix.replace('_', '-')}{field_name.replace('_', '-')}"
81
+
82
+ # If theres an instance, use that so we have concrete values
83
+ model_instance = model if not isinstance(model, type) else None
84
+
85
+ # If we have an instance, grab the field value
86
+ field_instance = getattr(model_instance, field_name, None) if model_instance else None
87
+
88
+ # MARK: Wrappers:
89
+ # - Optional[T]
90
+ # - Union[T, None]
91
+ if get_origin(field_type) is Optional:
92
+ field_type = get_args(field_type)[0]
93
+ elif get_origin(field_type) is Union:
94
+ non_none_types = [t for t in get_args(field_type) if t is not type(None)]
95
+ if len(non_none_types) == 1:
96
+ field_type = non_none_types[0]
97
+ else:
98
+ _log.warning(f"Unsupported Union type for argument '{field_name}': {field_type}")
99
+ continue
100
+
101
+ # Default value, promote PydanticUndefined to None
102
+ if field.default is PydanticUndefined:
103
+ default_value = None
104
+ elif field_instance:
105
+ default_value = field_instance
106
+ else:
107
+ default_value = field.default
108
+
109
+ # Handled types
110
+ # - bool, str, int, float
111
+ # - Enum
112
+ # - Path
113
+ # - Nested BaseModel
114
+ # - Literal
115
+ # - List[T]
116
+ # - where T is bool, str, int, float, Enum
117
+ # - List[BaseModel] where we have an instance to recurse into
118
+ # - Dict[K, V]
119
+ # - where K is bool, str, int, float, Enum
120
+ # - where V is bool, str, int, float, Enum, BaseModel
121
+ # - Dict[K, BaseModel] where we have an instance to recurse into
122
+ if field_type is bool:
123
+ #############
124
+ # MARK: bool
125
+ _add_argument(
126
+ parser=parser, name=arg_name, arg_type=bool, default_value=default_value, action="store_true" if not default_value else "store_false"
127
+ )
128
+ elif field_type in (str, int, float):
129
+ ########################
130
+ # MARK: str, int, float
131
+ try:
132
+ _add_argument(parser=parser, name=arg_name, arg_type=field_type, default_value=default_value)
133
+ except TypeError:
134
+ # TODO: handle more complex types if needed
135
+ _add_argument(parser=parser, name=arg_name, arg_type=str, default_value=default_value)
136
+ elif isinstance(field_type, type) and issubclass(field_type, Enum):
137
+ #############
138
+ # MARK: Enum
139
+ enum_choices = [e.value for e in field_type]
140
+ _add_argument(parser=parser, name=arg_name, arg_type=type(enum_choices[0]), default_value=default_value, choices=enum_choices)
141
+ elif isinstance(field_type, type) and issubclass(field_type, Path):
142
+ #############
143
+ # MARK: Path
144
+ # Promote to/from string
145
+ _add_argument(parser=parser, name=arg_name, arg_type=str, default_value=str(default_value) if isinstance(default_value, Path) else None)
146
+ elif isinstance(field_instance, BaseModel):
147
+ ############################
148
+ # MARK: instance(BaseModel)
149
+ # Nested model, add its fields with a prefix
150
+ _recurse_add_fields(parser, field_instance, prefix=f"{field_name}.")
151
+ elif isinstance(field_type, Type) and issubclass(field_type, BaseModel):
152
+ ########################
153
+ # MARK: type(BaseModel)
154
+ # Nested model class, add its fields with a prefix
155
+ _recurse_add_fields(parser, field_type, prefix=f"{field_name}.")
156
+ elif get_origin(field_type) is Literal:
157
+ ################
158
+ # MARK: Literal
159
+ literal_args = get_args(field_type)
160
+ if not all(isinstance(arg, (str, int, float, bool, Enum)) for arg in literal_args):
161
+ # Only support simple literal types for now
162
+ _log.warning(f"Only Literal types of str, int, float, or bool are supported - field `{field_name}` got {literal_args}")
163
+ continue
164
+ ####################################
165
+ # MARK: Literal[str|int|float|bool]
166
+ _add_argument(parser=parser, name=arg_name, arg_type=type(literal_args[0]), default_value=default_value)
167
+ elif get_origin(field_type) in (list, List):
168
+ ################
169
+ # MARK: List[T]
170
+ if get_args(field_type) and not _is_supported_type(get_args(field_type)[0]):
171
+ # If theres already something here, we can procede by adding the command with a positional indicator
172
+ if field_instance:
173
+ for i, value in enumerate(field_instance):
174
+ if isinstance(value, BaseModel):
175
+ ########################
176
+ # MARK: List[BaseModel]
177
+ _recurse_add_fields(parser, value, prefix=f"{field_name}.{i}.")
178
+ continue
179
+ else:
180
+ ########################
181
+ # MARK: List[str|int|float|bool]
182
+ _add_argument(
183
+ parser=parser,
184
+ name=f"{arg_name}.{i}",
185
+ arg_type=type(value),
186
+ default_value=value,
187
+ )
188
+ continue
189
+ # If there's nothing here, we don't know how to address them
190
+ # TODO: we could just prefill e.g. --field.0, --field.1 up to some limit
191
+ _log.warning(f"Only lists of str, int, float, or bool are supported - field `{field_name}` got {get_args(field_type)[0]}")
192
+ continue
193
+ if field_instance:
194
+ for i, value in enumerate(field_instance):
195
+ ########################
196
+ # MARK: List[str|int|float|bool]
197
+ _add_argument(
198
+ parser=parser,
199
+ name=f"{arg_name}.{i}",
200
+ arg_type=type(value),
201
+ default_value=value,
202
+ )
203
+ #################################
204
+ # MARK: List[str|int|float|bool]
205
+ _add_argument(
206
+ parser=parser, name=arg_name, arg_type=str, default_value=",".join(map(str, default_value)) if isinstance(field, str) else None
207
+ )
208
+ elif get_origin(field_type) in (dict, Dict):
209
+ ######################
210
+ # MARK: Dict[str, T]
211
+ key_type, value_type = get_args(field_type)
212
+
213
+ if not _is_supported_type(key_type):
214
+ # Check Key type, must be str, int, float, bool, enum
215
+ _log.warning(f"Only dicts with str, int, float, bool, or enum keys are supported - field `{field_name}` got key type {key_type}")
216
+ continue
217
+
218
+ if isinstance(key_type, type) and issubclass(key_type, Enum):
219
+ # If key is enum, we can fully enumerate
220
+
221
+ if not _is_supported_type(value_type) and not (isinstance(value_type, type) and issubclass(value_type, BaseModel)):
222
+ # Unsupported value type
223
+ _log.warning(
224
+ f"Only dicts with str, int, float, bool, enum, or BaseModel values are supported - field `{field_name}` got value type {value_type}"
225
+ )
226
+ continue
227
+
228
+ if isinstance(value_type, type) and issubclass(value_type, BaseModel):
229
+ # Add each submodel recursively, if it exists on the instance
230
+ #############################
231
+ # MARK: Dict[Enum, BaseModel]
232
+ for enum_key in key_type:
233
+ if not field_instance or enum_key not in field_instance:
234
+ continue
235
+ _recurse_add_fields(parser, (field_instance or {}).get(enum_key, value_type), prefix=f"{field_name}.{enum_key.name}.")
236
+ _recurse_add_fields(parser, (field_instance or {}).get(enum_key, value_type), prefix=f"{field_name}.{enum_key.value}.")
237
+
238
+ elif _is_supported_type(value_type):
239
+ # Add directly
240
+ ###################
241
+ # MARK: Dict[Enum, str|int|float|bool]
242
+
243
+ for enum_key in key_type:
244
+ value = (field_instance or {}).get(enum_key, default_value.get(enum_key) if default_value else None)
245
+ _add_argument(
246
+ parser=parser,
247
+ name=f"{arg_name}.{enum_key.name}",
248
+ arg_type=value_type,
249
+ default_value=value,
250
+ )
251
+ _add_argument(
252
+ parser=parser,
253
+ name=f"{arg_name}.{enum_key.value}",
254
+ arg_type=value_type,
255
+ default_value=value,
256
+ )
257
+
258
+ if not _is_supported_type(value_type) and not field_instance:
259
+ # Check Value type, must be str, int, float, bool if an instance isnt provided
260
+ _log.warning(
261
+ f"Only dicts with str, int, float, bool, or enum values are supported - field `{field_name}` got value type {value_type}"
262
+ )
263
+ continue
264
+
265
+ # If theres already something here, we can procede by adding the command by keyword
266
+ if field_instance:
267
+ if all(isinstance(v, BaseModel) for v in field_instance.values()):
268
+ #############################
269
+ # MARK: Dict[str, BaseModel]
270
+ for key, value in field_instance.items():
271
+ if isinstance(key, Enum):
272
+ # Already handled above
273
+ continue
274
+ _recurse_add_fields(parser, value, prefix=f"{field_name}.{key}.")
275
+ continue
276
+
277
+ # If we have mixed, we don't support
278
+ elif any(isinstance(v, BaseModel) for v in field_instance.values()):
279
+ _log.warning(f"Mixed dict value types are not supported - field `{field_name}` has mixed BaseModel and non-BaseModel values")
280
+ continue
281
+
282
+ # If we have non BaseModel values, we can still add a parser by route
283
+ if all(isinstance(v, (str, int, float, bool, Enum)) for v in field_instance.values()):
284
+ # We can set "known" values here
285
+ for key, value in field_instance.items():
286
+ if isinstance(key, Enum):
287
+ # Already handled above
288
+ continue
289
+ if isinstance(value, Enum):
290
+ value = value.name
291
+ ##########################################
292
+ # MARK: Dict[str, str|int|float|bool]
293
+ _add_argument(
294
+ parser=parser,
295
+ name=f"{arg_name}.{key}",
296
+ arg_type=type(value),
297
+ default_value=value,
298
+ )
299
+ # NOTE: don't continue to allow adding the full setter below
300
+
301
+ # Finally add the full setter for unknown values
302
+ ##########################################
303
+ # MARK: Dict[str, str|int|float|bool|str|Enum]
304
+ defaults = []
305
+ for k, v in (default_value or {}).items():
306
+ if isinstance(k, Enum):
307
+ defaults.append(f"{k.name}={v}")
308
+ defaults.append(f"{k.value}={v}")
309
+ else:
310
+ defaults.append(f"{k}={v}")
311
+ _add_argument(parser=parser, name=arg_name, arg_type=str, default_value=",".join(defaults) if defaults else None)
312
+ else:
313
+ _log.warning(f"Unsupported field type for argument '{field_name}': {field_type}")
314
+ return parser
315
+
316
+
317
+ def create_model_parser(model: "BaseModel") -> ArgumentParser:
318
+ # Recursively parse fields from a pydantic model and its sub-models
319
+ # and create an argument parser to parse extra args
320
+ parser = ArgumentParser(prog="hatch-build-extras-model", allow_abbrev=False)
321
+ parser = _recurse_add_fields(parser, model)
322
+ return parser
323
+
324
+
325
+ def parse_extra_args_model(model: "BaseModel"):
326
+ # Parse the extra args and update the model
327
+ args, kwargs = parse_extra_args(create_model_parser(model))
328
+
329
+ for key, value in args.items():
330
+ # Handle nested fields
331
+ if "." in key:
332
+ # We're going to walk down the model tree to get to the right sub-model
333
+ parts = key.split(".")
334
+
335
+ # Accounting
336
+ sub_model = model
337
+ parent_model = None
338
+
339
+ for i, part in enumerate(parts[:-1]):
340
+ if part.isdigit() and isinstance(sub_model, list):
341
+ # List index
342
+ index = int(part)
343
+
344
+ # Should never be out of bounds, but check to be sure
345
+ if index >= len(sub_model):
346
+ raise IndexError(
347
+ f"Index {index} out of range for field '{parts[i - 1]}' on model '{parent_model.__class__.__name__}'"
348
+ ) # coverage: ignore
349
+
350
+ # Grab the model instance from the list
351
+ model_to_set = sub_model[index]
352
+ elif isinstance(sub_model, dict):
353
+ # Dict key
354
+
355
+ # If its an enum, we may need to match by name or value
356
+ for k in sub_model.keys():
357
+ if isinstance(k, Enum):
358
+ if k.name == part or k.value == part:
359
+ part = k
360
+ break
361
+
362
+ # Should always exist, but check to be sure
363
+ if part not in sub_model:
364
+ raise KeyError(
365
+ f"Key '{part}' not found for field '{parts[i - 1]}' on model '{parent_model.__class__.__name__}'"
366
+ ) # coverage: ignore
367
+
368
+ # Grab the model instance from the dict
369
+ model_to_set = sub_model[part]
370
+ else:
371
+ model_to_set = getattr(sub_model, part)
372
+
373
+ if model_to_set is None:
374
+ # Create a new instance of model
375
+ field = sub_model.__class__.model_fields[part]
376
+
377
+ # if field annotation is an optional or union with none, extract type
378
+ if get_origin(field.annotation) is Optional:
379
+ model_to_instance = get_args(field.annotation)[0]
380
+ elif get_origin(field.annotation) is Union:
381
+ non_none_types = [t for t in get_args(field.annotation) if t is not type(None)]
382
+ if len(non_none_types) == 1:
383
+ model_to_instance = non_none_types[0]
384
+
385
+ else:
386
+ model_to_instance = field.annotation
387
+ if not isinstance(model_to_instance, type) or not issubclass(model_to_instance, BaseModel):
388
+ raise ValueError(
389
+ f"Cannot create sub-model for field '{part}' on model '{sub_model.__class__.__name__}': - type is {model_to_instance}"
390
+ )
391
+ model_to_set = model_to_instance()
392
+ setattr(sub_model, part, model_to_set)
393
+
394
+ parent_model = sub_model
395
+ sub_model = model_to_set
396
+
397
+ key = parts[-1]
398
+ else:
399
+ # Accounting
400
+ sub_model = model
401
+ parent_model = model
402
+ model_to_set = model
403
+
404
+ if not isinstance(model_to_set, BaseModel):
405
+ if isinstance(model_to_set, dict):
406
+ if value is None:
407
+ continue
408
+
409
+ # We allow setting dict values directly
410
+ # Grab the dict from the parent model, set the value, and continue
411
+ if key in model_to_set:
412
+ model_to_set[key] = value
413
+ elif key.replace("_", "-") in model_to_set:
414
+ # Argparse converts dashes back to underscores, so undo
415
+ model_to_set[key.replace("_", "-")] = value
416
+ elif key in [k.name for k in model_to_set.keys() if isinstance(k, Enum)]:
417
+ enum_key = [k for k in model_to_set.keys() if isinstance(k, Enum) and k.name == key][0]
418
+ model_to_set[enum_key] = value
419
+ elif key in [k.value for k in model_to_set.keys() if isinstance(k, Enum)]:
420
+ enum_key = [k for k in model_to_set.keys() if isinstance(k, Enum) and k.value == key][0]
421
+ model_to_set[enum_key] = value
422
+ elif (
423
+ get_args(parent_model.__class__.model_fields[part].annotation)
424
+ and isinstance(get_args(parent_model.__class__.model_fields[part].annotation)[0], type)
425
+ and issubclass(get_args(parent_model.__class__.model_fields[part].annotation)[0], Enum)
426
+ ):
427
+ enum_type = get_args(parent_model.__class__.model_fields[part].annotation)[0]
428
+ for enum_key in enum_type:
429
+ if enum_key.name == key or enum_key.value == key:
430
+ key = enum_key
431
+ break
432
+ else:
433
+ raise KeyError(f"Key '{key}' not found for dict field on model '{parent_model.__class__.__name__}'") # coverage: ignore
434
+ model_to_set[key] = value
435
+ else:
436
+ raise KeyError(f"Key '{key}' not found for dict field on model '{parent_model.__class__.__name__}'") # coverage: ignore
437
+
438
+ _log.debug(f"Set dict key '{key}' on parent model '{parent_model.__class__.__name__}' with value '{value}'")
439
+
440
+ # Now adjust our variable accounting to set the whole dict back on the parent model,
441
+ # allowing us to trigger any validation
442
+ key = part
443
+ value = model_to_set
444
+ model_to_set = parent_model
445
+ elif isinstance(model_to_set, list):
446
+ if value is None:
447
+ continue
448
+
449
+ # We allow setting list values directly
450
+ # Grab the list from the parent model, set the value, and continue
451
+ model_to_set[int(key)] = value
452
+
453
+ _log.debug(f"Set list index '{key}' on parent model '{parent_model.__class__.__name__}' with value '{value}'")
454
+
455
+ # Now adjust our variable accounting to set the whole dict back on the parent model,
456
+ # allowing us to trigger any validation
457
+ key = part
458
+ value = model_to_set
459
+ model_to_set = parent_model
460
+ else:
461
+ _log.warning(f"Cannot set field '{key}' on non-BaseModel instance of type '{type(model_to_set).__name__}'. value: `{value}`")
462
+ continue
463
+
464
+ # Grab the field from the model class and make a type adapter
465
+ field = model_to_set.__class__.model_fields[key]
466
+ adapter = TypeAdapter(field.annotation)
467
+
468
+ if value is not None:
469
+ _log.debug(f"Setting field '{key}' on model '{model_to_set.__class__.__name__}' with raw value '{value}'")
470
+
471
+ # Convert the value using the type adapter
472
+ if get_origin(field.annotation) in (list, List):
473
+ if isinstance(value, list):
474
+ # Already a list, use as is
475
+ pass
476
+ elif isinstance(value, str):
477
+ # Convert from comma-separated values
478
+ value = value.split(",")
479
+ else:
480
+ # Unknown, raise
481
+ raise ValueError(f"Cannot convert value '{value}' to list for field '{key}'")
482
+ elif get_origin(field.annotation) in (dict, Dict):
483
+ if isinstance(value, dict):
484
+ # Already a dict, use as is
485
+ pass
486
+ elif isinstance(value, str):
487
+ # Convert from comma-separated key=value pairs
488
+ dict_items = value.split(",")
489
+ dict_value = {}
490
+ for item in dict_items:
491
+ if item:
492
+ k, v = item.split("=", 1)
493
+ # If the key type is an enum, convert
494
+ dict_value[k] = v
495
+
496
+ # Grab any previously existing dict to preserve other keys
497
+ existing_dict = getattr(model_to_set, key, {}) or {}
498
+ _log.debug(f"Existing dict for field '{key}': {existing_dict}")
499
+ _log.debug(f"New dict items for field '{key}': {dict_value}")
500
+ dict_value.update(existing_dict)
501
+ value = dict_value
502
+ else:
503
+ # Unknown, raise
504
+ raise ValueError(f"Cannot convert value '{value}' to dict for field '{key}'")
505
+ try:
506
+ # Post process and convert keys if needed
507
+ # pydantic shouldve done this automatically, but alas
508
+ if isinstance(value, dict) and get_args(field.annotation):
509
+ key_type = get_args(field.annotation)[0]
510
+ if isinstance(key_type, type) and issubclass(key_type, Enum):
511
+ for enum_key in key_type:
512
+ if enum_key.name in value:
513
+ v = value.pop(enum_key.name)
514
+ if value.get(enum_key) is None:
515
+ value[enum_key] = v
516
+
517
+ value = adapter.validate_python(value)
518
+
519
+ # Set the value on the model
520
+ setattr(model_to_set, key, value)
521
+ except ValidationError:
522
+ _log.warning(f"Failed to validate field '{key}' with value '{value}' for model '{model_to_set.__class__.__name__}'")
523
+ continue
524
+ else:
525
+ _log.debug(f"Skipping setting field '{key}' on model '{model_to_set.__class__.__name__}' with None value")
526
+
527
+ return model, kwargs
@@ -0,0 +1,189 @@
1
+ import sys
2
+ from enum import Enum
3
+ from io import StringIO
4
+ from pathlib import Path
5
+ from typing import Dict, List, Literal, Optional, Union
6
+ from unittest.mock import patch
7
+
8
+ from pydantic import BaseModel
9
+
10
+ from p2a import parse_extra_args_model
11
+ from p2a.model import _initlog
12
+
13
+
14
+ class MyEnum(Enum):
15
+ OPTION_A = "option_a"
16
+ OPTION_B = "option_b"
17
+ OPTION_C = "option_c"
18
+
19
+
20
+ class SubModel(BaseModel, validate_assignment=True):
21
+ sub_arg: int = 42
22
+ sub_arg_with_value: str = "sub_default"
23
+ sub_arg_enum: MyEnum = MyEnum.OPTION_A
24
+ sub_arg_literal: Literal["x", "y", "z"] = "x"
25
+
26
+
27
+ class MyTopLevelModel(BaseModel, validate_assignment=True):
28
+ extra_arg: bool = False
29
+ extra_arg_with_value: str = "default"
30
+ extra_arg_with_value_equals: Optional[str] = "default_equals"
31
+ extra_arg_literal: Literal["a", "b", "c"] = "a"
32
+
33
+ enum_arg: MyEnum = MyEnum.OPTION_A
34
+ list_arg: List[int] = [1, 2, 3]
35
+ dict_arg: Dict[str, str] = {}
36
+ dict_arg_default_values: Dict[str, str] = {"existing-key": "existing-value"}
37
+ path_arg: Path = Path(".")
38
+
39
+ list_literal: List[Literal["a", "b", "c"]] = ["a"]
40
+ dict_literal_key: Dict[Literal["a", "b", "c"], str] = {"a": "first"}
41
+ dict_literal_value: Dict[str, Literal["a", "b", "c"]] = {"first": "a"}
42
+
43
+ list_enum: List[MyEnum] = [MyEnum.OPTION_A]
44
+ dict_enum: Dict[str, MyEnum] = {"first": MyEnum.OPTION_A}
45
+ dict_enum_key: Dict[MyEnum, str] = {MyEnum.OPTION_A: "first"}
46
+ dict_enum_key_model_value: Dict[MyEnum, SubModel] = {MyEnum.OPTION_A: SubModel()}
47
+
48
+ submodel: SubModel
49
+ submodel2: SubModel = SubModel(sub_args=84, sub_arg_with_value="predefined", sub_arg_enum=MyEnum.OPTION_B, sub_arg_literal="z")
50
+ submodel3: Optional[SubModel] = None
51
+
52
+ submodel_list_instanced: List[SubModel] = [SubModel()]
53
+ submodel_dict_instanced: Dict[str, SubModel] = {"a": SubModel()}
54
+
55
+ unsupported_literal: Literal[b"test"] = b"test"
56
+ unsupported_dict: Dict[SubModel, str] = {}
57
+ unsupported_dict_mixed_types: Dict[str, Union[str, SubModel]] = {}
58
+ unsupported_random_type: Optional[set] = None
59
+
60
+ unsupported_submodel_list: List[SubModel] = []
61
+ unsupported_submodel_dict: Dict[str, SubModel] = {}
62
+
63
+
64
+ class TestCLIMdel:
65
+ def test_get_arg_from_model(self):
66
+ with (
67
+ patch.object(
68
+ sys,
69
+ "argv",
70
+ [
71
+ "--extra-arg",
72
+ "--extra-arg-with-value",
73
+ "value",
74
+ "--extra-arg-with-value-equals=value2",
75
+ "--extra-arg-not-in-parser",
76
+ "--extra-arg-literal",
77
+ "b",
78
+ "--enum-arg",
79
+ "option_b",
80
+ "--list-arg",
81
+ "1,2,3",
82
+ "--dict-arg",
83
+ "key1=value1,key2=value2",
84
+ "--dict-arg-default-values.existing-key",
85
+ "new-value",
86
+ "--path-arg",
87
+ "/some/path",
88
+ "--list-literal",
89
+ "a,b",
90
+ "--dict-literal-key.a",
91
+ "first",
92
+ "--dict-literal-value.first",
93
+ "a",
94
+ "--list-enum",
95
+ "option_a,option_b",
96
+ "--dict-enum.first",
97
+ "option_b",
98
+ "--dict-enum-key.option_b",
99
+ "second",
100
+ "--dict-enum-key.OPTION_C",
101
+ "third",
102
+ "--dict-enum-key-model-value.option-a.sub-arg",
103
+ "600",
104
+ "--submodel.sub-arg",
105
+ "100",
106
+ "--submodel.sub-arg-with-value",
107
+ "sub_value",
108
+ "--submodel.sub-arg-enum",
109
+ "option_a",
110
+ "--submodel.sub-arg-literal",
111
+ "y",
112
+ "--submodel2.sub-arg",
113
+ "200",
114
+ "--submodel2.sub-arg-with-value",
115
+ "sub_value2",
116
+ "--submodel3.sub-arg",
117
+ "300",
118
+ "--submodel-list-instanced.0.sub-arg",
119
+ "400",
120
+ "--submodel-list-instanced.0.sub-arg-with-value",
121
+ "list_value",
122
+ "--submodel-list-instanced.0.sub-arg-enum",
123
+ "option_b",
124
+ "--submodel-list-instanced.0.sub-arg-literal",
125
+ "z",
126
+ "--submodel-dict-instanced.a.sub-arg",
127
+ "500",
128
+ ],
129
+ ),
130
+ patch("sys.stderr", new_callable=StringIO) as mock_stderr,
131
+ ):
132
+ _initlog("DEBUG")
133
+ model, extras = parse_extra_args_model(MyTopLevelModel(submodel=SubModel()))
134
+
135
+ assert len(extras) == 1
136
+ assert "--extra-arg-not-in-parser" in extras
137
+
138
+ assert model.extra_arg is True
139
+ assert model.extra_arg_with_value == "value"
140
+ assert model.extra_arg_with_value_equals == "value2"
141
+ assert model.extra_arg_literal == "b"
142
+
143
+ assert model.enum_arg == MyEnum.OPTION_B
144
+ assert model.list_arg == [1, 2, 3]
145
+ assert model.dict_arg == {"key1": "value1", "key2": "value2"}
146
+ assert model.dict_arg_default_values == {"existing-key": "new-value"}
147
+ assert model.path_arg == Path("/some/path")
148
+
149
+ assert model.list_literal == ["a", "b"]
150
+ assert model.dict_literal_key == {"a": "first"}
151
+ assert model.dict_literal_value == {"first": "a"}
152
+
153
+ assert model.list_enum == [MyEnum.OPTION_A, MyEnum.OPTION_B]
154
+ assert model.dict_enum == {"first": MyEnum.OPTION_B}
155
+ assert model.dict_enum_key == {MyEnum.OPTION_A: "first", MyEnum.OPTION_B: "second", MyEnum.OPTION_C: "third"}
156
+ assert model.dict_enum_key_model_value[MyEnum.OPTION_A].sub_arg == 600
157
+
158
+ assert model.submodel.sub_arg == 100
159
+ assert model.submodel.sub_arg_with_value == "sub_value"
160
+ assert model.submodel.sub_arg_enum == MyEnum.OPTION_A
161
+ assert model.submodel.sub_arg_literal == "y"
162
+ assert model.submodel2.sub_arg == 200
163
+ assert model.submodel2.sub_arg_with_value == "sub_value2"
164
+ assert model.submodel2.sub_arg_enum == MyEnum.OPTION_B
165
+ assert model.submodel2.sub_arg_literal == "z"
166
+
167
+ assert model.submodel3.sub_arg == 300
168
+ assert model.submodel_list_instanced[0].sub_arg == 400
169
+ assert model.submodel_list_instanced[0].sub_arg_with_value == "list_value"
170
+ assert model.submodel_list_instanced[0].sub_arg_enum == MyEnum.OPTION_B
171
+ assert model.submodel_list_instanced[0].sub_arg_literal == "z"
172
+ assert model.submodel_dict_instanced["a"].sub_arg == 500
173
+
174
+ stderr = mock_stderr.getvalue()
175
+ for text in (
176
+ "[p2a][WARNING]: Only lists of str, int, float, or bool are supported - field `unsupported_submodel_list` got <class 'test_model.SubModel'>",
177
+ "[p2a][WARNING]: Only dicts with str, int, float, bool, or enum values are supported - field `unsupported_submodel_dict` got value type <class 'test_model.SubModel'>",
178
+ "[p2a][WARNING]: Only Literal types of str, int, float, or bool are supported - field `unsupported_literal` got (b'test',)",
179
+ "[p2a][WARNING]: Only dicts with str, int, float, bool, or enum keys are supported - field `unsupported_dict` got key type <class 'test_model.SubModel'>",
180
+ "[p2a][WARNING]: Only dicts with str, int, float, bool, or enum values are supported - field `unsupported_dict_mixed_types` got value type typing.Union[str, test_model.SubModel]",
181
+ "[p2a][WARNING]: Unsupported field type for argument 'unsupported_random_type': <class 'set'>",
182
+ ):
183
+ assert text in stderr
184
+ stderr = stderr.replace(text, "")
185
+ if "[p2a][WARNING]" in stderr.strip():
186
+ for line in stderr.strip().splitlines():
187
+ if "[p2a][WARNING]" in line:
188
+ print("UNEXPECTED WARNING:", line)
189
+ assert False
@@ -0,0 +1,51 @@
1
+ Metadata-Version: 2.4
2
+ Name: p2a
3
+ Version: 0.1.0
4
+ Summary: pydantic models to argparse CLIs
5
+ Project-URL: Repository, https://github.com/1kbgz/p2a
6
+ Project-URL: Homepage, https://github.com/1kbgz/p2a
7
+ Author-email: the p2a authors <dev@1kbgz.com>
8
+ License: Apache-2.0
9
+ License-File: LICENSE
10
+ Keywords: argparse,cli,command-line,models,pydantic,validation
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Programming Language :: Python
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Programming Language :: Python :: Implementation :: CPython
20
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
21
+ Requires-Python: >=3.10
22
+ Requires-Dist: pkn<0.4,>=0.3
23
+ Provides-Extra: develop
24
+ Requires-Dist: build; extra == 'develop'
25
+ Requires-Dist: bump-my-version; extra == 'develop'
26
+ Requires-Dist: check-manifest; extra == 'develop'
27
+ Requires-Dist: codespell<2.5,>=2.4; extra == 'develop'
28
+ Requires-Dist: hatchling; extra == 'develop'
29
+ Requires-Dist: mdformat-tables>=1; extra == 'develop'
30
+ Requires-Dist: mdformat<1.1,>=0.7.22; extra == 'develop'
31
+ Requires-Dist: pytest; extra == 'develop'
32
+ Requires-Dist: pytest-cov; extra == 'develop'
33
+ Requires-Dist: ruff<0.15,>=0.9; extra == 'develop'
34
+ Requires-Dist: twine; extra == 'develop'
35
+ Requires-Dist: uv; extra == 'develop'
36
+ Requires-Dist: wheel; extra == 'develop'
37
+ Description-Content-Type: text/markdown
38
+
39
+ # p2a
40
+
41
+ pydantic models to argparse CLIs
42
+
43
+ [![Build Status](https://github.com/1kbgz/p2a/actions/workflows/build.yaml/badge.svg?branch=main&event=push)](https://github.com/1kbgz/p2a/actions/workflows/build.yaml)
44
+ [![codecov](https://codecov.io/gh/1kbgz/p2a/branch/main/graph/badge.svg)](https://codecov.io/gh/1kbgz/p2a)
45
+ [![License](https://img.shields.io/github/license/1kbgz/p2a)](https://github.com/1kbgz/p2a)
46
+ [![PyPI](https://img.shields.io/pypi/v/p2a.svg)](https://pypi.python.org/pypi/p2a)
47
+
48
+ ## Overview
49
+
50
+ > [!NOTE]
51
+ > This library was generated using [copier](https://copier.readthedocs.io/en/stable/) from the [Base Python Project Template repository](https://github.com/python-project-templates/base).
@@ -0,0 +1,7 @@
1
+ p2a/__init__.py,sha256=Kb2nTSWltXbkvfawx7upoVZ3jNoAsZUODr66rGTugPs,44
2
+ p2a/model.py,sha256=ccvFAsuWQJdaOd_0S26HUKlD2xIRWwzN4leiwzrH3tA,25314
3
+ p2a/tests/test_model.py,sha256=QLwmPaEEmKSeDqRLohFrR5dLcLae3snaqsUSb2vX05o,8103
4
+ p2a-0.1.0.dist-info/METADATA,sha256=okGLOybHRpPskZkgyeQ5JmMNPoZJRva85a6dx88LY3o,2311
5
+ p2a-0.1.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
6
+ p2a-0.1.0.dist-info/licenses/LICENSE,sha256=BMaxAInGUDRuCHdrrtfkh4FemQFYkYRqxnhOhRYaliA,11345
7
+ p2a-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2025 the p2a authors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.