Class: Synthra::Export::Python
- Defined in:
- lib/synthra/export/python.rb
Overview
Exports schema as Python with Pydantic models or dataclasses
Constant Summary collapse
- TYPE_MAPPINGS =
Type mappings from DSL types to Python types
{ # Strings "uuid" => "UUID", "ulid" => "str", "email" => "EmailStr", "url" => "HttpUrl", "ip" => "IPvAnyAddress", "ipv6" => "IPvAnyAddress", "date" => "date", "past_date" => "date", "future_date" => "date", "timestamp" => "datetime", "text" => "str", "name" => "str", "full_name" => "str", "first_name" => "str", "last_name" => "str", "phone" => "str", "city" => "str", "country" => "str", "country_code" => "str", "postal_code" => "str", "state" => "str", "street" => "str", "address" => "str", "username" => "str", "social_handle" => "str", "domain" => "str", "user_agent" => "str", "mac_address" => "str", "iban" => "str", "credit_card" => "str", "currency" => "str", "currency_code" => "str", "paragraph" => "str", "sentence" => "str", "word" => "str", "message_text" => "str", "hashtag_text" => "str", "snowflake_id" => "str", "numeric_string_id" => "str", # Numbers (integers) "number" => "int", "integer" => "int", "age" => "int", "airport_elevation" => "int", "discount" => "int", "formula" => "int", "row_number" => "int", "sequence" => "int", "id_sequence" => "int", # Numbers (floats) "float" => "float", "money" => "Decimal", "latitude" => "float", "longitude" => "float", "airport_latitude" => "float", "airport_longitude" => "float", "product_price" => "float", "tax_rate" => "float", "transaction_amount" => "float", # Boolean "boolean" => "bool", # Date (generate Date objects) "date_between" => "date", "mobile_device_release_date" => "date", "now" => "date", # Date/Time "datetime" => "datetime", # Objects "object" => "Dict[str, Any]", "map_by_field" => "Dict[str, Any]", # Arrays "array" => "List[Any]", "empty_array" => "List[Any]", "json_array" => "List[Any]", "indices_pair" => "Tuple[int, int]" }.freeze
- PYDANTIC_IMPORTS =
Pydantic imports needed based on types used
{ "UUID" => "from uuid import UUID", "EmailStr" => "from pydantic import EmailStr", "HttpUrl" => "from pydantic import HttpUrl", "IPvAnyAddress" => "from pydantic import IPvAnyAddress", "date" => "from datetime import date", "datetime" => "from datetime import datetime", "Decimal" => "from decimal import Decimal" }.freeze
Class Method Summary collapse
-
.export_all(registry, **options) ⇒ String
Export all schemas in a registry.
Instance Method Summary collapse
- #build_array_type(args) ⇒ Object private
- #build_const_type(args) ⇒ Object private
- #build_dataclass(target_schema) ⇒ Object private
- #build_enum_type(args) ⇒ Object private
- #build_imports(types_used, style) ⇒ Object private
- #build_model(target_schema, style) ⇒ Object
- #build_pydantic_field(field) ⇒ Object private
- #build_pydantic_model(target_schema) ⇒ Object private
- #build_typed_dict(target_schema) ⇒ Object private
- #build_union_type(args) ⇒ Object private
- #collect_field_schemas(field, schemas) ⇒ Object private
- #collect_referenced_schemas ⇒ Object private
- #collect_types_used ⇒ Object private
- #export ⇒ Object
- #export_dataclass ⇒ Object private
- #export_pydantic ⇒ Object private
- #export_typed_dict ⇒ Object private
- #field_to_python(field) ⇒ Object private
- #get_field_default(field) ⇒ Object private
- #to_snake_case(str) ⇒ Object private
Constructor Details
This class inherits a constructor from Synthra::Export::Base
Class Method Details
.export_all(registry, **options) ⇒ String
Export all schemas in a registry
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 |
# File 'lib/synthra/export/python.rb', line 136 def self.export_all(registry, **) style = [:style] || :pydantic lines = [] lines << "# Generated from Synthra schemas" lines << "# Schemas: #{registry.names.join(', ')}" lines << "" # Collect all types used all_types = Set.new registry.schemas.each do |name, schema| schema.fields.each { |f| all_types << TYPE_MAPPINGS[f.type_name] } end # Add imports - use first schema to create instance for build_imports first_schema = registry.schemas.values.first if first_schema exporter = new(first_schema, registry: registry, **) lines << exporter.send(:build_imports, all_types, style) lines << "" end registry.schemas.each do |name, schema| exporter = new(schema, registry: registry, **) lines << exporter.build_model(schema, style) lines << "" end lines.join("\n") end |
Instance Method Details
#build_array_type(args) ⇒ Object (private)
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 |
# File 'lib/synthra/export/python.rb', line 510 def build_array_type(args) element = args[:element] if element if schema_reference?(element.to_s) "List[#{element}]" elsif TYPE_MAPPINGS[element.to_s] "List[#{TYPE_MAPPINGS[element.to_s]}]" else # Unknown element types are string-producing types (e.g. array(string)). "List[str]" end else "List[Any]" end end |
#build_const_type(args) ⇒ Object (private)
496 497 498 499 500 501 502 503 504 505 506 507 508 |
# File 'lib/synthra/export/python.rb', line 496 def build_const_type(args) value = args[:value] case value when String "Literal[\"#{value}\"]" when TrueClass, FalseClass "Literal[#{value}]" when Numeric "Literal[#{value}]" else "Literal[\"#{value}\"]" end end |
#build_dataclass(target_schema) ⇒ Object (private)
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 |
# File 'lib/synthra/export/python.rb', line 309 def build_dataclass(target_schema) lines = [] lines << "@dataclass" lines << "class #{target_schema.name}:" # Required fields first, then optional required_fields = target_schema.fields.reject { |f| f.optional? || f.nullable? } optional_fields = target_schema.fields.select { |f| f.optional? || f.nullable? } if target_schema.fields.empty? lines << " pass" else required_fields.each do |field| py_type = field_to_python(field) lines << " #{to_snake_case(field.name)}: #{py_type}" end optional_fields.each do |field| py_type = field_to_python(field) lines << " #{to_snake_case(field.name)}: Optional[#{py_type}] = None" end end lines.join("\n") end |
#build_enum_type(args) ⇒ Object (private)
491 492 493 494 |
# File 'lib/synthra/export/python.rb', line 491 def build_enum_type(args) values = args[:values]&.map { |v| v.respond_to?(:value) ? v.value : v } || [] "Literal[#{values.map { |v| "\"#{v}\"" }.join(', ')}]" end |
#build_imports(types_used, style) ⇒ Object (private)
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 |
# File 'lib/synthra/export/python.rb', line 383 def build_imports(types_used, style) lines = [] case style when :pydantic lines << "from typing import Optional, List, Dict, Any, Tuple" lines << "from pydantic import BaseModel, Field" # Add specific imports PYDANTIC_IMPORTS.each do |type, import_stmt| lines << import_stmt if types_used.include?(type) end # Add Literal for enums if types_used.include?("Literal") lines << "from typing import Literal" end when :dataclass lines << "from dataclasses import dataclass, field" lines << "from typing import Optional, List, Dict, Any, Tuple" PYDANTIC_IMPORTS.each do |type, import_stmt| next if %w[EmailStr HttpUrl IPvAnyAddress].include?(type) lines << import_stmt if types_used.include?(type) end when :typed_dict lines << "from typing import TypedDict, Optional, List, Dict, Any, Tuple" PYDANTIC_IMPORTS.each do |type, import_stmt| next if %w[EmailStr HttpUrl IPvAnyAddress].include?(type) lines << import_stmt if types_used.include?(type) end end lines.uniq.join("\n") end |
#build_model(target_schema, style) ⇒ Object
167 168 169 170 171 172 173 174 175 176 177 178 |
# File 'lib/synthra/export/python.rb', line 167 def build_model(target_schema, style) case style when :pydantic build_pydantic_model(target_schema) when :dataclass build_dataclass(target_schema) when :typed_dict build_typed_dict(target_schema) else build_pydantic_model(target_schema) end end |
#build_pydantic_field(field) ⇒ Object (private)
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 |
# File 'lib/synthra/export/python.rb', line 291 def build_pydantic_field(field) py_type = field_to_python(field) field_name = to_snake_case(field.name) if field.optional? "#{field_name}: Optional[#{py_type}] = None" elsif field.nullable? "#{field_name}: Optional[#{py_type}]" else default = get_field_default(field) if default "#{field_name}: #{py_type} = #{default}" else "#{field_name}: #{py_type}" end end end |
#build_pydantic_model(target_schema) ⇒ Object (private)
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 |
# File 'lib/synthra/export/python.rb', line 259 def build_pydantic_model(target_schema) lines = [] if target_schema.deprecated? lines << "# DEPRECATED: #{target_schema. || 'This model is deprecated'}" end lines << "class #{target_schema.name}(BaseModel):" if target_schema.version lines << " \"\"\"#{target_schema.name} model (v#{target_schema.version})\"\"\"" end if target_schema.fields.empty? lines << " pass" else target_schema.fields.each do |field| lines << " #{build_pydantic_field(field)}" end # Add Config if needed if [:orm_mode] || [:validate_assignment] lines << "" lines << " class Config:" lines << " orm_mode = True" if [:orm_mode] lines << " validate_assignment = True" if [:validate_assignment] end end lines.join("\n") end |
#build_typed_dict(target_schema) ⇒ Object (private)
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 |
# File 'lib/synthra/export/python.rb', line 336 def build_typed_dict(target_schema) lines = [] # Check if we need total=False for optional fields has_optional = target_schema.fields.any? { |f| f.optional? } if has_optional # Create two TypedDicts - required and optional required_fields = target_schema.fields.reject(&:optional?) optional_fields = target_schema.fields.select(&:optional?) lines << "class #{target_schema.name}Required(TypedDict):" if required_fields.empty? lines << " pass" else required_fields.each do |field| py_type = field_to_python(field) lines << " #{to_snake_case(field.name)}: #{py_type}" end end lines << "" lines << "class #{target_schema.name}(#{target_schema.name}Required, total=False):" if optional_fields.empty? lines << " pass" else optional_fields.each do |field| py_type = field_to_python(field) lines << " #{to_snake_case(field.name)}: #{py_type}" end end else lines << "class #{target_schema.name}(TypedDict):" if target_schema.fields.empty? lines << " pass" else target_schema.fields.each do |field| py_type = field_to_python(field) nullable = " | None" if field.nullable? lines << " #{to_snake_case(field.name)}: #{py_type}#{nullable}" end end end lines.join("\n") end |
#build_union_type(args) ⇒ Object (private)
526 527 528 529 530 531 532 533 |
# File 'lib/synthra/export/python.rb', line 526 def build_union_type(args) schemas = args[:schemas] || [] types = schemas.map do |s| schema_name = s.is_a?(Hash) ? (s[:schema] || s["schema"]) : s.to_s schema_reference?(schema_name) ? schema_name : "Any" end "Union[#{types.join(', ')}]" end |
#collect_field_schemas(field, schemas) ⇒ Object (private)
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 |
# File 'lib/synthra/export/python.rb', line 440 def collect_field_schemas(field, schemas) type_name = field.type_name if schema_reference?(type_name) ref_schema = get_schema(type_name) if ref_schema && !schemas.any? { |s| s.name == ref_schema.name } schemas << ref_schema ref_schema.fields.each { |f| collect_field_schemas(f, schemas) } end end if type_name == "array" element = field.type_args[:element] if element && schema_reference?(element.to_s) ref_schema = get_schema(element.to_s) if ref_schema && !schemas.any? { |s| s.name == ref_schema.name } schemas << ref_schema ref_schema.fields.each { |f| collect_field_schemas(f, schemas) } end end end end |
#collect_referenced_schemas ⇒ Object (private)
432 433 434 435 436 437 438 |
# File 'lib/synthra/export/python.rb', line 432 def collect_referenced_schemas schemas = [] schema.fields.each do |field| collect_field_schemas(field, schemas) end schemas.uniq(&:name) end |
#collect_types_used ⇒ Object (private)
422 423 424 425 426 427 428 429 430 |
# File 'lib/synthra/export/python.rb', line 422 def collect_types_used types = Set.new schema.fields.each do |field| py_type = TYPE_MAPPINGS[field.type_name] types << py_type if py_type types << "Literal" if field.type_name == "enum" end types end |
#export ⇒ Object
115 116 117 118 119 120 121 122 123 124 125 126 127 128 |
# File 'lib/synthra/export/python.rb', line 115 def export style = [:style] || :pydantic case style when :pydantic export_pydantic when :dataclass export_dataclass when :typed_dict export_typed_dict else export_pydantic # fallback end end |
#export_dataclass ⇒ Object (private)
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 |
# File 'lib/synthra/export/python.rb', line 213 def export_dataclass lines = [] lines << '"""' lines << "Generated from Synthra schema: #{schema.name}" lines << '"""' lines << "" types_used = collect_types_used lines << build_imports(types_used, :dataclass) lines << "" exported = Set.new collect_referenced_schemas.each do |ref_schema| lines << build_dataclass(ref_schema) lines << "" exported << ref_schema.name end lines << build_dataclass(schema) unless exported.include?(schema.name) lines.join("\n") end |
#export_pydantic ⇒ Object (private)
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 |
# File 'lib/synthra/export/python.rb', line 182 def export_pydantic lines = [] # Header lines << '"""' lines << "Generated from Synthra schema: #{schema.name}" lines << "Version: #{schema.version}" if schema.version lines << '"""' lines << "" # Collect types used types_used = collect_types_used # Imports lines << build_imports(types_used, :pydantic) lines << "" # Export referenced schemas first exported = Set.new collect_referenced_schemas.each do |ref_schema| lines << build_pydantic_model(ref_schema) lines << "" exported << ref_schema.name end # Export main schema lines << build_pydantic_model(schema) unless exported.include?(schema.name) lines.join("\n") end |
#export_typed_dict ⇒ Object (private)
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 |
# File 'lib/synthra/export/python.rb', line 236 def export_typed_dict lines = [] lines << '"""' lines << "Generated from Synthra schema: #{schema.name}" lines << '"""' lines << "" types_used = collect_types_used lines << build_imports(types_used, :typed_dict) lines << "" exported = Set.new collect_referenced_schemas.each do |ref_schema| lines << build_typed_dict(ref_schema) lines << "" exported << ref_schema.name end lines << build_typed_dict(schema) unless exported.include?(schema.name) lines.join("\n") end |
#field_to_python(field) ⇒ Object (private)
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 |
# File 'lib/synthra/export/python.rb', line 463 def field_to_python(field) type_name = field.type_name type_args = field.type_args case type_name when "enum" build_enum_type(type_args) when "const" build_const_type(type_args) when "array" build_array_type(type_args) when "one_of" build_union_type(type_args) when "map_by_field" "Dict[str, Any]" else if TYPE_MAPPINGS[type_name] TYPE_MAPPINGS[type_name] elsif schema_reference?(type_name) type_name else # Most Synthra types generate strings, so an unmapped, non-structural # type is a string rather than Any. "str" end end end |
#get_field_default(field) ⇒ Object (private)
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 |
# File 'lib/synthra/export/python.rb', line 535 def get_field_default(field) type_name = field.type_name case type_name when "enum" values = field.type_args[:values] || [] first = values.first first ? "\"#{first.respond_to?(:value) ? first.value : first}\"" : nil when "const" value = field.type_args[:value] value.is_a?(String) ? "\"#{value}\"" : value.to_s else nil end end |
#to_snake_case(str) ⇒ Object (private)
551 552 553 554 555 |
# File 'lib/synthra/export/python.rb', line 551 def to_snake_case(str) str.gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2') .gsub(/([a-z\d])([A-Z])/, '\1_\2') .downcase end |