streambricks 0.2.13__tar.gz → 0.2.15__tar.gz

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.
Files changed (33) hide show
  1. {streambricks-0.2.13 → streambricks-0.2.15}/PKG-INFO +1 -1
  2. {streambricks-0.2.13 → streambricks-0.2.15}/src/streambricks/__init__.py +1 -1
  3. {streambricks-0.2.13 → streambricks-0.2.15}/src/streambricks/widgets/model_widget/main.py +249 -79
  4. streambricks-0.2.15/src/streambricks/widgets/type_helpers.py +392 -0
  5. streambricks-0.2.13/src/streambricks/widgets/type_helpers.py +0 -242
  6. {streambricks-0.2.13 → streambricks-0.2.15}/.copier-answers.yml +0 -0
  7. {streambricks-0.2.13 → streambricks-0.2.15}/.github/FUNDING.yml +0 -0
  8. {streambricks-0.2.13 → streambricks-0.2.15}/.github/copilot-instructions.md +0 -0
  9. {streambricks-0.2.13 → streambricks-0.2.15}/.github/dependabot.yml +0 -0
  10. {streambricks-0.2.13 → streambricks-0.2.15}/.github/workflows/build.yml +0 -0
  11. {streambricks-0.2.13 → streambricks-0.2.15}/.github/workflows/documentation.yml +0 -0
  12. {streambricks-0.2.13 → streambricks-0.2.15}/.gitignore +0 -0
  13. {streambricks-0.2.13 → streambricks-0.2.15}/.pre-commit-config.yaml +0 -0
  14. {streambricks-0.2.13 → streambricks-0.2.15}/LICENSE +0 -0
  15. {streambricks-0.2.13 → streambricks-0.2.15}/README.md +0 -0
  16. {streambricks-0.2.13 → streambricks-0.2.15}/docs/.empty +0 -0
  17. {streambricks-0.2.13 → streambricks-0.2.15}/duties.py +0 -0
  18. {streambricks-0.2.13 → streambricks-0.2.15}/mkdocs.yml +0 -0
  19. {streambricks-0.2.13 → streambricks-0.2.15}/overrides/_dummy.txt +0 -0
  20. {streambricks-0.2.13 → streambricks-0.2.15}/pyproject.toml +0 -0
  21. {streambricks-0.2.13 → streambricks-0.2.15}/src/streambricks/helpers.py +0 -0
  22. {streambricks-0.2.13 → streambricks-0.2.15}/src/streambricks/py.typed +0 -0
  23. {streambricks-0.2.13 → streambricks-0.2.15}/src/streambricks/state.py +0 -0
  24. {streambricks-0.2.13 → streambricks-0.2.15}/src/streambricks/widgets/__init__.py +0 -0
  25. {streambricks-0.2.13 → streambricks-0.2.15}/src/streambricks/widgets/bind_kwargs.py +0 -0
  26. {streambricks-0.2.13 → streambricks-0.2.15}/src/streambricks/widgets/model_selector.py +0 -0
  27. {streambricks-0.2.13 → streambricks-0.2.15}/src/streambricks/widgets/model_widget/__init__.py +0 -0
  28. {streambricks-0.2.13 → streambricks-0.2.15}/src/streambricks/widgets/model_widget/field_metadata_renderers.py +0 -0
  29. {streambricks-0.2.13 → streambricks-0.2.15}/src/streambricks/widgets/model_widget/type_renderers.py +0 -0
  30. {streambricks-0.2.13 → streambricks-0.2.15}/src/streambricks/widgets/multi_select.py +0 -0
  31. {streambricks-0.2.13 → streambricks-0.2.15}/tests/__init__.py +0 -0
  32. {streambricks-0.2.13 → streambricks-0.2.15}/tests/conftest.py +0 -0
  33. {streambricks-0.2.13 → streambricks-0.2.15}/tests/test_widgets.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: streambricks
3
- Version: 0.2.13
3
+ Version: 0.2.15
4
4
  Summary: Streamlit widgets and helpers
5
5
  Project-URL: Documentation, https://phil65.github.io/streambricks/
6
6
  Project-URL: Source, https://github.com/phil65/streambricks
@@ -1,4 +1,4 @@
1
- __version__ = "0.2.13"
1
+ __version__ = "0.2.15"
2
2
 
3
3
 
4
4
  from streambricks.widgets.model_widget import (
@@ -31,7 +31,9 @@ from streambricks.widgets.type_helpers import (
31
31
  add_new_item,
32
32
  create_default_instance,
33
33
  get_description,
34
+ get_field,
34
35
  get_inner_type,
36
+ get_union_type_options,
35
37
  get_with_default,
36
38
  is_dataclass_like,
37
39
  is_literal_type,
@@ -67,7 +69,7 @@ PRIMITIVE_RENDERERS = {
67
69
  }
68
70
 
69
71
 
70
- def render_union_field( # noqa: PLR0911
72
+ def render_union_field(
71
73
  *,
72
74
  key: str,
73
75
  value: Any = None,
@@ -78,24 +80,144 @@ def render_union_field( # noqa: PLR0911
78
80
  ) -> Any:
79
81
  """Render a field that can accept multiple types."""
80
82
  annotation = field_info.get("type") or field_info.get("annotation")
81
- possible_types = get_args(annotation)
82
- type_key = f"{key}_type"
83
- type_names = [
84
- t.__name__ if hasattr(t, "__name__") else str(t) for t in possible_types
85
- ]
86
- selected_type_name = st.selectbox(
87
- f"Type for {label or key}",
88
- options=type_names,
89
- key=type_key,
90
- disabled=disabled,
91
- help=help,
92
- )
93
83
 
94
- selected_type_index = type_names.index(selected_type_name)
95
- selected_type = possible_types[selected_type_index]
84
+ type_options = get_union_type_options(annotation) # list of (type, description)
85
+
86
+ # Check if None is one of the options
87
+ none_type_index = None
88
+ for i, (t, _) in enumerate(type_options):
89
+ if t is type(None):
90
+ none_type_index = i
91
+ break
92
+
93
+ # Handle optional fields (union with None)
94
+ if none_type_index is not None:
95
+ # Remove None from type options
96
+ type_options.pop(none_type_index)
97
+
98
+ # Add checkbox to toggle between None and non-None
99
+ enable_key = f"{key}_not_none"
100
+
101
+ # Initialize the session state for this checkbox if it doesn't exist
102
+ if enable_key not in st.session_state:
103
+ st.session_state[enable_key] = value is not None
104
+
105
+ # Render checkbox using session state
106
+ is_enabled = st.checkbox(
107
+ f"Enable {label or key}",
108
+ key=enable_key,
109
+ disabled=disabled,
110
+ help=help,
111
+ )
112
+
113
+ if not is_enabled:
114
+ # If checkbox is unchecked, return None
115
+ st.text("None")
116
+ return None
117
+
118
+ # Continue with the regular union handling for non-None types
119
+ # If there's only one non-None type left, we can skip the type selector
120
+ if len(type_options) == 1:
121
+ selected_type, selected_type_name = type_options[0]
122
+ field_key = f"{key}_value"
123
+
124
+ # Special case for literal types
125
+ if is_literal_type(selected_type):
126
+ literal_values = get_args(selected_type)
127
+ value_index = 0
128
+ if value in literal_values:
129
+ value_index = literal_values.index(value)
130
+
131
+ return st.selectbox(
132
+ label or key,
133
+ options=literal_values,
134
+ index=value_index,
135
+ key=field_key,
136
+ disabled=disabled,
137
+ help=None, # Help already shown with checkbox
138
+ )
139
+
140
+ # For regular type, use standard field renderer
141
+ modified_field_info = field_info.copy()
142
+ modified_field_info["type"] = selected_type
143
+
144
+ typed_val: Any = None
145
+ if value is not None:
146
+ try:
147
+ if selected_type is int and isinstance(value, int | float):
148
+ typed_val = int(value)
149
+ elif selected_type is float and isinstance(value, int | float):
150
+ typed_val = float(value)
151
+ elif selected_type is str:
152
+ typed_val = str(value)
153
+ elif selected_type is bool:
154
+ typed_val = bool(value)
155
+ elif isinstance(value, selected_type):
156
+ typed_val = value
157
+ except (ValueError, TypeError):
158
+ # If conversion fails, start with a blank/default value
159
+ pass
160
+
161
+ renderer = get_field_renderer(modified_field_info)
162
+ result = renderer(
163
+ key=field_key,
164
+ value=typed_val,
165
+ label=label or key,
166
+ disabled=disabled,
167
+ help=None, # Help already shown with checkbox
168
+ **modified_field_info,
169
+ )
170
+
171
+ return convert_result_type(result, selected_type)
172
+
173
+ # Original code for handling standard unions (no None or None already handled)
174
+ default_index = 0
175
+ if value is not None:
176
+ for i, (t, _) in enumerate(type_options):
177
+ if (is_literal_type(t) and value in get_args(t)) or isinstance(value, t):
178
+ default_index = i
179
+ break
180
+
181
+ type_descriptions = [desc for _, desc in type_options]
182
+
183
+ # Skip type selector if there's only one option left
184
+ if len(type_options) == 1:
185
+ selected_type, selected_type_name = type_options[0]
186
+ else:
187
+ type_key = f"{key}_type"
188
+ selected_type_name = st.selectbox(
189
+ f"Type for {label or key}",
190
+ options=type_descriptions,
191
+ index=default_index,
192
+ key=type_key,
193
+ disabled=disabled,
194
+ help=help,
195
+ )
196
+ selected_type_index = type_descriptions.index(selected_type_name)
197
+ selected_type, selected_type_name = type_options[selected_type_index]
198
+
96
199
  field_key = f"{key}_value"
200
+
201
+ # Special case for literal types
202
+ if is_literal_type(selected_type):
203
+ literal_values = get_args(selected_type)
204
+ value_index = 0
205
+ if value in literal_values:
206
+ value_index = literal_values.index(value)
207
+
208
+ return st.selectbox(
209
+ f"Value ({selected_type_name if len(type_options) > 1 else label or key})",
210
+ options=literal_values,
211
+ index=value_index,
212
+ key=field_key,
213
+ disabled=disabled,
214
+ help=help if len(type_options) == 1 else None,
215
+ )
216
+
217
+ # For other types, use standard field renderer
97
218
  modified_field_info = field_info.copy()
98
219
  modified_field_info["type"] = selected_type
220
+
99
221
  typed_value: Any = None
100
222
  if value is not None:
101
223
  try:
@@ -117,31 +239,36 @@ def render_union_field( # noqa: PLR0911
117
239
  result = renderer(
118
240
  key=field_key,
119
241
  value=typed_value,
120
- label=f"Value ({selected_type_name})",
242
+ label=f"Value ({selected_type_name})" if len(type_options) > 1 else label or key,
121
243
  disabled=disabled,
122
- help=help,
244
+ help=help if len(type_options) == 1 else None,
123
245
  **modified_field_info,
124
246
  )
125
247
 
248
+ return convert_result_type(result, selected_type)
249
+
250
+
251
+ def convert_result_type(result: Any, target_type: Any) -> Any: # noqa: PLR0911
252
+ """Convert result to the target type, with error handling."""
126
253
  try:
127
- if selected_type is int and not isinstance(result, int):
254
+ if target_type is int and not isinstance(result, int):
128
255
  return int(result)
129
- if selected_type is float and not isinstance(result, float):
256
+ if target_type is float and not isinstance(result, float):
130
257
  return float(result)
131
- if selected_type is str and not isinstance(result, str):
258
+ if target_type is str and not isinstance(result, str):
132
259
  return str(result)
133
- if selected_type is bool and not isinstance(result, bool):
260
+ if target_type is bool and not isinstance(result, bool):
134
261
  return bool(result)
135
262
  except (ValueError, TypeError) as e:
136
- error_msg = f"Cannot convert {result} to {selected_type.__name__}: {e!s}"
263
+ error_msg = f"Cannot convert {result} to {target_type.__name__}: {e!s}"
137
264
  st.error(error_msg)
138
- if selected_type is int:
265
+ if target_type is int:
139
266
  return 0
140
- if selected_type is float:
267
+ if target_type is float:
141
268
  return 0.0
142
- if selected_type is str:
269
+ if target_type is str:
143
270
  return ""
144
- if selected_type is bool:
271
+ if target_type is bool:
145
272
  return False
146
273
  return None
147
274
  else:
@@ -460,7 +587,7 @@ def wrap_as_optional_field(renderer: WidgetFunc) -> WidgetFunc:
460
587
  return optional_wrapper
461
588
 
462
589
 
463
- def render_model_instance_field(
590
+ def render_model_instance_field( # noqa: PLR0911
464
591
  *,
465
592
  key: str,
466
593
  value: Any = None,
@@ -474,52 +601,57 @@ def render_model_instance_field(
474
601
  if model_class is None:
475
602
  error_msg = f"Model class not provided for field {key}"
476
603
  raise ValueError(error_msg)
477
-
478
- # Handle Union types (including Python 3.10+ pipe syntax)
479
- if is_union_type(model_class) or hasattr(model_class, "__or__"):
480
- model_type_name = getattr(
481
- model_class,
482
- "__name__",
483
- "Union[" + ", ".join(str(t) for t in get_args(model_class)) + "]",
484
- )
485
-
486
- # Initialize value if none
604
+ if is_union_type(model_class):
487
605
  if value is None:
488
- # For Union types, try to create an instance of the first model type
606
+ # For Union types, try each possible model type
489
607
  possible_types = get_args(model_class)
490
608
  for possible_type in possible_types:
491
609
  if is_dataclass_like(possible_type):
492
610
  try:
493
- value = try_create_default_instance(possible_type)
494
- if value is not None:
495
- break
496
- except Exception: # noqa: BLE001
611
+ # Try to create a minimal valid instance
612
+ value = create_default_instance(possible_type)
613
+ break
614
+ except Exception as e: # noqa: BLE001
615
+ st.warning(f"Could not create {possible_type.__name__}: {e}")
497
616
  continue
498
617
 
499
618
  if value is None:
500
- st.error(f"Could not create instance of any type in {model_type_name}")
619
+ for possible_type in possible_types:
620
+ if not is_dataclass_like(possible_type):
621
+ if possible_type is type(None):
622
+ return None
623
+ if is_literal_type(possible_type):
624
+ return get_args(possible_type)[
625
+ 0
626
+ ] # Return first literal value
627
+
628
+ st.error(
629
+ f"Could not create instance of any type in {model_class.__name__}"
630
+ )
501
631
  return None
502
632
  # Initialize value if none for non-union types
503
633
  elif value is None:
504
- value = try_create_default_instance(model_class)
505
- if value is None: # If creation failed
506
- try:
507
- value = model_class()
508
- except Exception as e: # noqa: BLE001
509
- error_msg = f"Failed to create instance of {model_class.__name__}: {e!s}"
510
- st.error(error_msg)
511
- return None
634
+ try:
635
+ # Try to create a minimal valid instance
636
+ value = create_default_instance(model_class)
637
+ except Exception as e: # noqa: BLE001
638
+ st.error(f"Failed to create {model_class.__name__}: {e}")
639
+ return None
512
640
 
513
641
  st.markdown(f"**{label or key}**")
514
642
  if help:
515
643
  st.caption(help)
516
644
 
517
645
  with st.expander("Edit", expanded=True):
646
+ if value is None:
647
+ st.error("Cannot render model: creation failed")
648
+ return None
649
+
518
650
  updated_value = {}
519
651
  try:
520
652
  # Use the actual class of the value instance, not the field type
521
653
  actual_class = value.__class__
522
- for field in fieldz.fields(actual_class):
654
+ for field in fieldz.fields(actual_class, parse_annotated=True):
523
655
  field_name = field.name
524
656
  field_value = get_with_default(value, field_name, field)
525
657
  field_help = get_description(field)
@@ -615,7 +747,7 @@ def render_model_readonly[T](
615
747
 
616
748
  with st.container():
617
749
  # Get all fields from the model
618
- for field in fieldz.fields(model_class):
750
+ for field in fieldz.fields(model_class, parse_annotated=True):
619
751
  field_name = field.name
620
752
  if field_name in excluded_fields:
621
753
  continue
@@ -703,7 +835,7 @@ def display_model_readonly(value, key=None):
703
835
  for field in fieldz.fields(model_class):
704
836
  field_name = field.name
705
837
  field_value = getattr(value, field_name, None)
706
- if field_value == "MISSING":
838
+ if field_value == fieldz.Field.MISSING:
707
839
  field_value = get_with_default(value, field_name, field)
708
840
  sub_key = f"{key}_{field_name}" if key else field_name
709
841
  cols = st.columns([0.3, 0.7])
@@ -715,10 +847,7 @@ def display_model_readonly(value, key=None):
715
847
 
716
848
  def render_model_field(model_class, field_name, value=None, container=st):
717
849
  """Render a field from a model using a compact layout."""
718
- field = next((f for f in fieldz.fields(model_class) if f.name == field_name), None)
719
- if field is None:
720
- error_msg = f"Field {field_name} not found in {model_class.__name__}"
721
- raise ValueError(error_msg)
850
+ field = get_field(model_class, field_name)
722
851
  field_info = {"name": field.name, "type": field.type, "default": field.default}
723
852
  if hasattr(field.native_field, "json_schema_extra"):
724
853
  dct = field.native_field.json_schema_extra or {} # type: ignore
@@ -772,7 +901,6 @@ def render_model_form(
772
901
  result = {}
773
902
  field_groups: dict[str, Any] = {}
774
903
  for field in fieldz.fields(model_class):
775
- # Check if field has a category defined
776
904
  category = "General"
777
905
  if "category" in field.metadata:
778
906
  category = field.metadata["category"]
@@ -789,34 +917,61 @@ def render_model_form(
789
917
  for i, (_group_name, fields) in enumerate(field_groups.items()):
790
918
  with tabs[i]:
791
919
  for field in fields:
792
- field_name = field.name
793
- if field_name in excluded_fields:
920
+ if field.name in excluded_fields:
794
921
  continue
795
- current_value = get_with_default(instance, field_name, field)
796
- result[field_name] = render_model_field(
797
- model_class, field_name, current_value
922
+ current_value = get_with_default(instance, field.name, field)
923
+ result[field.name] = render_model_field(
924
+ model_class, field.name, current_value
798
925
  )
799
926
  else:
800
927
  # Single category, render fields directly
801
- for field in fieldz.fields(model_class):
802
- field_name = field.name
803
- if field_name in excluded_fields:
928
+ for field in fieldz.fields(model_class, parse_annotated=True):
929
+ if field.name in excluded_fields:
804
930
  continue
805
- current_value = get_with_default(instance, field_name, field)
806
- result[field_name] = render_model_field(
807
- model_class, field_name, current_value
931
+ current_value = get_with_default(instance, field.name, field)
932
+ result[field.name] = render_model_field(
933
+ model_class, field.name, current_value
808
934
  )
809
935
 
810
936
  return fieldz.replace(instance, **result)
811
937
 
812
938
 
813
939
  if __name__ == "__main__":
814
- from typing import Literal
940
+ from typing import Annotated, Literal
815
941
 
816
- from pydantic import BaseModel, Field
942
+ import pydantic
817
943
 
818
944
  from streambricks.helpers import run
819
945
 
946
+ # Example models to simulate chunker configs
947
+ class LlamaIndexChunkerConfig(BaseModel):
948
+ """LlamaIndex chunker configuration."""
949
+
950
+ type: Literal["llamaindex"] = "llamaindex"
951
+ chunk_size: int = 1024
952
+ chunk_overlap: int = 20
953
+
954
+ class MarkdownChunkerConfig(BaseModel):
955
+ """Markdown chunker configuration."""
956
+
957
+ type: Literal["markdown"] = "markdown"
958
+ split_level: int = 1
959
+
960
+ class AiChunkerConfig(BaseModel):
961
+ """AI-based chunker configuration."""
962
+
963
+ type: Literal["ai"] = "ai"
964
+ max_chunk_size: int = 2000
965
+
966
+ # Create an Annotated union type similar to ChunkerConfig
967
+ ChunkerConfig = Annotated[
968
+ LlamaIndexChunkerConfig | MarkdownChunkerConfig | AiChunkerConfig,
969
+ pydantic.Field(discriminator="type"),
970
+ ]
971
+
972
+ # Create a literal type similar to ChunkerShorthand
973
+ ChunkerShorthand = Literal["markdown", "llamaindex", "ai"]
974
+
820
975
  class SubModel(BaseModel):
821
976
  """Test submodel."""
822
977
 
@@ -825,36 +980,51 @@ if __name__ == "__main__":
825
980
  active: bool = True
826
981
 
827
982
  class TestModel(BaseModel):
828
- """Test model."""
983
+ """Test model with complex union types."""
984
+
985
+ # This field simulates the problematic chunker field
986
+ chunker: ChunkerConfig | ChunkerShorthand | None = None
987
+ """Optional chunker configuration. If None, processes entire document at once."""
829
988
 
830
989
  status: int | str | bool = 2
831
990
  """A field that can be either int, str, or bool."""
991
+
832
992
  boolean: bool = True
833
993
  """Optional text field."""
834
- long_text: str | None = "test " * 40
994
+
995
+ long_text: str = "test " * 40
835
996
  """Long text."""
836
997
 
837
998
  optional_int: int | None = None
838
999
  """An optional integer that can be None."""
1000
+
839
1001
  optional_string: str | None = None
840
1002
  """An optional string that can be None."""
1003
+
841
1004
  optional_model: SubModel | None = None
842
1005
  """An optional nested model that can be None."""
843
1006
 
844
- tags: list[str] = Field(default_factory=list)
1007
+ tags: list[str] = pydantic.Field(default_factory=list)
845
1008
  """A list of string tags."""
846
- numbers: list[int | float] = Field(default_factory=list)
1009
+
1010
+ numbers: list[int | float] = pydantic.Field(default_factory=list)
847
1011
  """A list of numbers (int or float)"""
848
- settings: list[SubModel] = Field(default_factory=list)
1012
+
1013
+ settings: list[SubModel] = pydantic.Field(default_factory=list)
849
1014
  """A list of nested models"""
850
- priorities: list[Literal["Low", "Medium", "High"]] = Field(default_factory=list)
1015
+
1016
+ priorities: list[Literal["Low", "Medium", "High"]] = pydantic.Field(
1017
+ default_factory=list
1018
+ )
851
1019
  """A list of priority levels."""
852
1020
 
853
1021
  def demo():
854
1022
  st.title("Pydantic Form Demo")
855
1023
  if "model" not in st.session_state:
856
1024
  st.session_state.model = TestModel(status=2)
857
- st.session_state.model = render_model_form(TestModel)
1025
+
1026
+ st.session_state.model = render_model_form(st.session_state.model)
1027
+
858
1028
  with st.expander("Current Model State", expanded=True):
859
1029
  st.json(st.session_state.model.model_dump_json(indent=2))
860
1030
 
@@ -0,0 +1,392 @@
1
+ """Primitive type handlers for Pydantic form fields."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Sequence
6
+ from typing import Annotated, Any, Literal, get_args, get_origin
7
+
8
+ import fieldz
9
+
10
+
11
+ # For reference, these are the fieldz classes:
12
+ #
13
+ # @dataclasses.dataclass(**DC_KWARGS)
14
+ # class Constraints:
15
+ # gt: int | float | None = None
16
+ # ge: int | float | None = None
17
+ # lt: int | float | None = None
18
+ # le: int | float | None = None
19
+ # multiple_of: int | float | None = None
20
+ # min_length: int | None = None # for str
21
+ # max_length: int | None = None # for str
22
+ # max_digits: int | None = None # for decimal
23
+ # decimal_places: int | None = None # for decimal
24
+ # pattern: str | None = None
25
+ # deprecated: bool | None = None
26
+ # tz: bool | None = None
27
+ # predicate: Callable[[Any], bool] | None = None
28
+ # # enum: list[Any] | None = None
29
+ # # const: Any | None = None
30
+ #
31
+ # def __rich_repr__(self) -> Iterable[tuple[str, Any]]:
32
+ # for name, val in dataclasses.asdict(self).items():
33
+ # if val is not None:
34
+ # yield name, val
35
+ #
36
+ #
37
+ # @dataclasses.dataclass(**DC_KWARGS)
38
+ # class Field(Generic[_T]):
39
+ # MISSING: ClassVar[Literal[_MISSING_TYPE.MISSING]] = _MISSING_TYPE.MISSING
40
+ #
41
+ # name: str,
42
+ # type
43
+ # description: str | None = None
44
+ # title: str | None = None
45
+ # default: _T | Literal[_MISSING_TYPE.MISSING] = MISSING
46
+ # default_factory: Callable[[], _T] | Literal[_MISSING_TYPE.MISSING] = MISSING
47
+ # repr: bool = True
48
+ # hash: bool | None = None
49
+ # init: bool = True
50
+ # compare: bool = True
51
+ # metadata: Mapping[Any, Any] = dataclasses.field(default_factory=dict)
52
+ # kw_only: bool = False
53
+ # # extra
54
+ # frozen: bool = False
55
+ # native_field: Any | None = dataclasses.field(
56
+ # default=None, compare=False, repr=False
57
+ # )
58
+ # constraints: Constraints | None = None
59
+
60
+ # # populated during parse_annotated
61
+ # annotated_type: builtins.type[_T] | None = dataclasses.field(
62
+ # default=None, repr=False, compare=False
63
+ # )
64
+
65
+
66
+ def unpack_annotated(annotation: Any) -> Any:
67
+ """Unpack an Annotated type annotation to its base type."""
68
+ if get_origin(annotation) is Annotated and (args := get_args(annotation)):
69
+ return args[0]
70
+ return annotation
71
+
72
+
73
+ def is_literal_type(annotation: Any) -> bool:
74
+ """Check if a type annotation is a Literal type."""
75
+ # Check directly against the origin or special attribute
76
+ return (
77
+ get_origin(annotation) is Literal
78
+ or getattr(annotation, "__origin__", None) is Literal
79
+ )
80
+
81
+
82
+ def is_union_type(annotation: Any) -> bool:
83
+ import typing
84
+
85
+ origin = get_origin(annotation)
86
+ # Direct identity check for typing.Union
87
+ if origin is typing.Union:
88
+ return True
89
+
90
+ # Check for Python 3.10+ pipe syntax union
91
+ if hasattr(annotation, "__class__") and annotation.__class__.__name__ == "UnionType":
92
+ return True
93
+
94
+ # For Python 3.10+ unions detected via get_origin
95
+ return bool(
96
+ origin is not None
97
+ and hasattr(origin, "__class__")
98
+ and origin.__class__.__name__ == "UnionType"
99
+ )
100
+
101
+
102
+ def is_optional_type(annotation: Any) -> bool:
103
+ """Check if a type annotation is an Optional type (T | None)."""
104
+ if not is_union_type(annotation):
105
+ return False
106
+
107
+ args = get_args(annotation)
108
+ return type(None) in args
109
+
110
+
111
+ def is_set_type(annotation: Any) -> bool:
112
+ """Check if the annotation represents a set type."""
113
+ if annotation is set:
114
+ return True
115
+ origin = get_origin(annotation)
116
+ return origin is set
117
+
118
+
119
+ def is_sequence_type(annotation: Any) -> bool:
120
+ """Check if an annotation represents a sequence type (except sets)."""
121
+ origin = get_origin(annotation)
122
+ if origin in (list, tuple, Sequence):
123
+ return True
124
+
125
+ return annotation in (list, tuple, Sequence)
126
+
127
+
128
+ def get_with_default(obj: Any, field_name: str, field_info: fieldz.Field) -> Any: # noqa: PLR0911
129
+ """Get field value with appropriate default if it's missing."""
130
+ # Get the raw value
131
+ value = getattr(obj, field_name, None)
132
+
133
+ # If value isn't MISSING, return it as is
134
+ if value != fieldz.Field.MISSING:
135
+ return value
136
+
137
+ # If we don't have field info, get it
138
+ if field_info is None:
139
+ for field in fieldz.fields(obj.__class__):
140
+ if field.name == field_name:
141
+ field_info = field
142
+ break
143
+
144
+ # If we have field info, use it to determine appropriate default
145
+ if field_info is not None:
146
+ field_type = field_info.type
147
+
148
+ # Handle Union types
149
+ if is_union_type(field_type):
150
+ types = [t for t in get_args(field_type) if t is not type(None)]
151
+ if int in types:
152
+ return 0
153
+ if float in types:
154
+ return 0.0
155
+ if str in types:
156
+ return ""
157
+ if bool in types:
158
+ return False
159
+ if types and isinstance(types[0], type):
160
+ if issubclass(types[0], int):
161
+ return 0
162
+ if issubclass(types[0], float):
163
+ return 0.0
164
+ if issubclass(types[0], str):
165
+ return ""
166
+ if issubclass(types[0], bool):
167
+ return False
168
+
169
+ # Handle basic types
170
+ if isinstance(field_type, type):
171
+ if issubclass(field_type, int):
172
+ return 0
173
+ if issubclass(field_type, float):
174
+ return 0.0
175
+ if issubclass(field_type, str):
176
+ return ""
177
+ if issubclass(field_type, bool):
178
+ return False
179
+ if (
180
+ issubclass(field_type, list)
181
+ or issubclass(field_type, set)
182
+ or issubclass(field_type, tuple)
183
+ ):
184
+ return []
185
+
186
+ # Default fallback for unknown types
187
+ return None
188
+
189
+
190
+ def is_dataclass_like(annotation: Any) -> bool:
191
+ """Check if a type is a dataclass-like object (Pydantic model, attrs, etc.)."""
192
+ if not isinstance(annotation, type):
193
+ return False
194
+ try:
195
+ fields = fieldz.fields(annotation)
196
+ # If we get fields, it's a dataclass-like object
197
+ return len(fields) > 0
198
+ except Exception: # noqa: BLE001
199
+ # If fieldz can't handle it, it's not a dataclass-like object
200
+ return False
201
+
202
+
203
+ def create_default_instance(model_class: type) -> Any:
204
+ """Create a default instance of a model with default values for required fields."""
205
+ # Create an empty dict to collect required values
206
+ default_values = {}
207
+
208
+ # Get all fields
209
+ for field in fieldz.fields(model_class):
210
+ field_name = field.name
211
+
212
+ # Check if the field already has a default value
213
+ has_default = False
214
+ if field.default != fieldz.Field.MISSING:
215
+ default_values[field_name] = field.default
216
+ has_default = True
217
+ elif field.default_factory != fieldz.Field.MISSING:
218
+ try:
219
+ default_values[field_name] = field.default_factory() # pyright: ignore
220
+ has_default = True
221
+ except Exception: # noqa: BLE001
222
+ # If default_factory fails, fall back to type-based defaults
223
+ pass
224
+
225
+ if not has_default:
226
+ default_values[field_name] = get_default_value(field.type)
227
+
228
+ return model_class(**default_values)
229
+
230
+
231
+ def get_default_value(field_type: Any): # noqa: PLR0911
232
+ if is_union_type(field_type):
233
+ types = [t for t in get_args(field_type) if t is not type(None)]
234
+ if int in types:
235
+ return 0
236
+ if float in types:
237
+ return 0.0
238
+ if str in types:
239
+ return ""
240
+ if bool in types:
241
+ return False
242
+ if isinstance(field_type, type):
243
+ if issubclass(field_type, str):
244
+ return ""
245
+ if issubclass(field_type, int):
246
+ return 0
247
+ if issubclass(field_type, float):
248
+ return 0.0
249
+ if issubclass(field_type, bool):
250
+ return False
251
+ if is_dataclass_like(field_type):
252
+ return create_default_instance(field_type)
253
+ return None # or field_type()?
254
+
255
+
256
+ def get_description(field: fieldz.Field) -> str | None:
257
+ if "description" in field.metadata:
258
+ return field.metadata["description"]
259
+ if hasattr(field.native_field, "description"):
260
+ return field.native_field.description # type: ignore
261
+ return None
262
+
263
+
264
+ def add_new_item(items_list: list, item_type: Any) -> None:
265
+ """Add a new item to a list based on its type."""
266
+ if is_dataclass_like(item_type):
267
+ new_item = create_default_instance(item_type)
268
+ if new_item is not None:
269
+ items_list.append(new_item)
270
+ # For basic types, add appropriate default values
271
+ elif item_type is str:
272
+ items_list.append("")
273
+ elif item_type is int:
274
+ items_list.append(0)
275
+ elif item_type is float:
276
+ items_list.append(0.0)
277
+ elif item_type is bool:
278
+ items_list.append(False)
279
+ elif is_union_type(item_type):
280
+ # For union types, use the first non-None type
281
+ types = [t for t in get_args(item_type) if t is not type(None)]
282
+ if int in types:
283
+ items_list.append(0)
284
+ elif float in types:
285
+ items_list.append(0.0)
286
+ elif str in types:
287
+ items_list.append("")
288
+ elif bool in types:
289
+ items_list.append(False)
290
+ else:
291
+ items_list.append(None)
292
+ else:
293
+ # For unknown types, add None
294
+ items_list.append(None)
295
+
296
+
297
+ def get_inner_type(field_info: Any) -> Any:
298
+ annotation = field_info.get("type") or field_info.get("annotation")
299
+ try:
300
+ return get_args(annotation)[0] # Get type of set items
301
+ except (IndexError, TypeError):
302
+ return Any
303
+
304
+
305
+ def get_field(model_class, field_name: str) -> fieldz.Field:
306
+ field = next(
307
+ (f for f in fieldz.fields(model_class) if f.name == field_name),
308
+ None,
309
+ )
310
+ if field is None:
311
+ error_msg = f"Field {field_name} not found in {model_class.__name__}"
312
+ raise ValueError(error_msg)
313
+ return field
314
+
315
+
316
+ def get_union_type_options(annotation: Any) -> list[tuple[Any, str]]:
317
+ """Analyze a union type and extract individual types with their descriptions.
318
+
319
+ Args:
320
+ annotation: Type annotation to analyze
321
+
322
+ Returns:
323
+ List of tuples containing (resolved_type, type_description)
324
+ """
325
+ type_options = []
326
+
327
+ # Process each union member
328
+ for arg in get_args(annotation):
329
+ # Handle Annotated type that contains a union
330
+ if get_origin(arg) is Annotated:
331
+ annotated_args = get_args(arg)
332
+ if not annotated_args:
333
+ continue
334
+
335
+ # Get the inner type (first arg of Annotated)
336
+ inner = annotated_args[0]
337
+
338
+ # Handle pipe-syntax union (Python 3.10+)
339
+ if inner.__class__.__name__ == "UnionType":
340
+ # Extract each union member - use __args__ attribute for pipe unions
341
+ for union_member in inner.__args__:
342
+ description = (
343
+ union_member.__name__
344
+ if hasattr(union_member, "__name__")
345
+ else str(union_member)
346
+ )
347
+ type_options.append((union_member, description))
348
+ elif is_union_type(inner):
349
+ # Handle traditional Union types
350
+ for union_member in get_args(inner):
351
+ description = (
352
+ union_member.__name__
353
+ if hasattr(union_member, "__name__")
354
+ else str(union_member)
355
+ )
356
+ type_options.append((union_member, description))
357
+ else:
358
+ # Single type in Annotated
359
+ description = inner.__name__ if hasattr(inner, "__name__") else str(inner)
360
+ type_options.append((inner, description))
361
+
362
+ # Handle Literal types
363
+ elif is_literal_type(arg):
364
+ values = ", ".join(
365
+ f'"{v}"' if isinstance(v, str) else str(v) for v in get_args(arg)
366
+ )
367
+ description = f"Literal[{values}]"
368
+ type_options.append((arg, description))
369
+
370
+ # Handle None type
371
+ elif arg is type(None):
372
+ type_options.append((arg, "None"))
373
+
374
+ # Handle regular types
375
+ else:
376
+ description = arg.__name__ if hasattr(arg, "__name__") else str(arg)
377
+ type_options.append((arg, description))
378
+
379
+ return type_options
380
+
381
+
382
+ if __name__ == "__main__":
383
+ from pydantic import BaseModel
384
+
385
+ class SubModel(BaseModel):
386
+ """Test submodel."""
387
+
388
+ name: str
389
+ value: int | float
390
+ active: bool = True
391
+
392
+ print(create_default_instance(SubModel))
@@ -1,242 +0,0 @@
1
- """Primitive type handlers for Pydantic form fields."""
2
-
3
- from __future__ import annotations
4
-
5
- from collections.abc import Sequence
6
- from typing import Annotated, Any, Literal, get_args, get_origin
7
-
8
- import fieldz
9
-
10
-
11
- def unpack_annotated(annotation: Any) -> Any:
12
- """Unpack an Annotated type annotation to its base type."""
13
- if get_origin(annotation) is Annotated and (args := get_args(annotation)):
14
- return args[0]
15
- return annotation
16
-
17
-
18
- def is_literal_type(annotation: Any) -> bool:
19
- """Check if a type annotation is a Literal type."""
20
- # Check directly against the origin or special attribute
21
- return (
22
- get_origin(annotation) is Literal
23
- or getattr(annotation, "__origin__", None) is Literal
24
- )
25
-
26
-
27
- def is_union_type(annotation: Any) -> bool:
28
- """Check if a type annotation is a Union type."""
29
- origin = get_origin(annotation)
30
- # Check if it's Union or Optional (which is Union[T, None])
31
- return origin is not None and (
32
- origin.__name__ == "Union" if hasattr(origin, "__name__") else False
33
- )
34
-
35
-
36
- def is_optional_type(annotation: Any) -> bool:
37
- """Check if a type annotation is an Optional type (T | None)."""
38
- if not is_union_type(annotation):
39
- return False
40
-
41
- args = get_args(annotation)
42
- return type(None) in args
43
-
44
-
45
- def is_set_type(annotation: Any) -> bool:
46
- """Check if the annotation represents a set type."""
47
- if annotation is set:
48
- return True
49
- origin = get_origin(annotation)
50
- return origin is set
51
-
52
-
53
- def is_sequence_type(annotation: Any) -> bool:
54
- """Check if an annotation represents a sequence type (except sets)."""
55
- origin = get_origin(annotation)
56
- if origin in (list, tuple, Sequence):
57
- return True
58
-
59
- return annotation in (list, tuple, Sequence)
60
-
61
-
62
- def get_with_default(obj: Any, field_name: str, field_info: Any = None) -> Any: # noqa: PLR0911
63
- """Get field value with appropriate default if it's missing."""
64
- # Get the raw value
65
- value = getattr(obj, field_name, None)
66
-
67
- # If value isn't MISSING, return it as is
68
- if value != "MISSING":
69
- return value
70
-
71
- # If we don't have field info, get it
72
- if field_info is None:
73
- for field in fieldz.fields(obj.__class__):
74
- if field.name == field_name:
75
- field_info = field
76
- break
77
-
78
- # If we have field info, use it to determine appropriate default
79
- if field_info is not None:
80
- field_type = field_info.type
81
-
82
- # Handle Union types
83
- if is_union_type(field_type):
84
- types = [t for t in get_args(field_type) if t is not type(None)]
85
- if int in types:
86
- return 0
87
- if float in types:
88
- return 0.0
89
- if str in types:
90
- return ""
91
- if bool in types:
92
- return False
93
- if types and isinstance(types[0], type):
94
- if issubclass(types[0], int):
95
- return 0
96
- if issubclass(types[0], float):
97
- return 0.0
98
- if issubclass(types[0], str):
99
- return ""
100
- if issubclass(types[0], bool):
101
- return False
102
-
103
- # Handle basic types
104
- if isinstance(field_type, type):
105
- if issubclass(field_type, int):
106
- return 0
107
- if issubclass(field_type, float):
108
- return 0.0
109
- if issubclass(field_type, str):
110
- return ""
111
- if issubclass(field_type, bool):
112
- return False
113
- if (
114
- issubclass(field_type, list)
115
- or issubclass(field_type, set)
116
- or issubclass(field_type, tuple)
117
- ):
118
- return []
119
-
120
- # Default fallback for unknown types
121
- return None
122
-
123
-
124
- def is_dataclass_like(annotation: Any) -> bool:
125
- """Check if a type is a dataclass-like object (Pydantic model, attrs, etc.)."""
126
- if not isinstance(annotation, type):
127
- return False
128
- try:
129
- fields = fieldz.fields(annotation)
130
- # If we get fields, it's a dataclass-like object
131
- return len(fields) > 0
132
- except Exception: # noqa: BLE001
133
- # If fieldz can't handle it, it's not a dataclass-like object
134
- return False
135
-
136
-
137
- def create_default_instance(model_class: type) -> Any:
138
- """Create a default instance of a model with default values for required fields."""
139
- # Create an empty dict to collect required values
140
- default_values = {}
141
-
142
- # Get all fields
143
- for field in fieldz.fields(model_class):
144
- field_name = field.name
145
-
146
- # Check if the field already has a default value
147
- has_default = False
148
- if hasattr(field, "default") and field.default != "MISSING":
149
- # Use the field's default value
150
- default_values[field_name] = field.default
151
- has_default = True
152
- elif hasattr(field, "default_factory") and field.default_factory != "MISSING":
153
- try:
154
- # Use the field's default factory
155
- default_values[field_name] = field.default_factory() # pyright: ignore
156
- has_default = True
157
- except Exception: # noqa: BLE001
158
- # If default_factory fails, fall back to type-based defaults
159
- pass
160
-
161
- # If the field doesn't have a default, create one based on type
162
- if not has_default:
163
- field_type = field.type
164
-
165
- # Handle union types
166
- if is_union_type(field_type):
167
- types = [t for t in get_args(field_type) if t is not type(None)]
168
- if int in types:
169
- default_values[field_name] = 0
170
- elif float in types:
171
- default_values[field_name] = 0.0
172
- elif str in types:
173
- default_values[field_name] = ""
174
- elif bool in types:
175
- default_values[field_name] = False
176
- continue
177
-
178
- # Set type-appropriate default values based on Python type
179
- if isinstance(field_type, type):
180
- if issubclass(field_type, str):
181
- default_values[field_name] = ""
182
- elif issubclass(field_type, int):
183
- default_values[field_name] = 0
184
- elif issubclass(field_type, float):
185
- default_values[field_name] = 0.0
186
- elif issubclass(field_type, bool):
187
- default_values[field_name] = False
188
- elif is_dataclass_like(field_type):
189
- # For nested models, recursively create default instances
190
- default_values[field_name] = create_default_instance(field_type)
191
-
192
- return model_class(**default_values)
193
-
194
-
195
- def get_description(field: fieldz.Field) -> str | None:
196
- if "description" in field.metadata:
197
- return field.metadata["description"]
198
- if hasattr(field.native_field, "description"):
199
- return field.native_field.description # type: ignore
200
- return None
201
-
202
-
203
- def add_new_item(items_list: list, item_type: Any) -> None:
204
- """Add a new item to a list based on its type."""
205
- if is_dataclass_like(item_type):
206
- # For dataclass-like types, create a default instance
207
- new_item = create_default_instance(item_type)
208
- if new_item is not None:
209
- items_list.append(new_item)
210
- # For basic types, add appropriate default values
211
- elif item_type is str:
212
- items_list.append("")
213
- elif item_type is int:
214
- items_list.append(0)
215
- elif item_type is float:
216
- items_list.append(0.0)
217
- elif item_type is bool:
218
- items_list.append(False)
219
- elif is_union_type(item_type):
220
- # For union types, use the first non-None type
221
- types = [t for t in get_args(item_type) if t is not type(None)]
222
- if int in types:
223
- items_list.append(0)
224
- elif float in types:
225
- items_list.append(0.0)
226
- elif str in types:
227
- items_list.append("")
228
- elif bool in types:
229
- items_list.append(False)
230
- else:
231
- items_list.append(None)
232
- else:
233
- # For unknown types, add None
234
- items_list.append(None)
235
-
236
-
237
- def get_inner_type(field_info: Any) -> Any:
238
- annotation = field_info.get("type") or field_info.get("annotation")
239
- try:
240
- return get_args(annotation)[0] # Get type of set items
241
- except (IndexError, TypeError):
242
- return Any
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes