Skip to content

Instantly share code, notes, and snippets.

@Hultner
Created May 19, 2020 19:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Hultner/41b57326797291bcbd5ab2541daed2ec to your computer and use it in GitHub Desktop.
Save Hultner/41b57326797291bcbd5ab2541daed2ec to your computer and use it in GitHub Desktop.
Generate python data models using hy, input is eventually thought to be database introspection based.
(import [pydantic [BaseModel]])
(defn create-attribute [type name]
`(^~type ~name))
(defn create-attributes [attributes]
(map (fn [x] (create-attribute (unpack-iterable x)))
attributes))
(defn create-imports [deps]
nil)
;; TODO: Convert snake_case to TitleCase
(defn create-model [name attributes]
`(
;; Not sure how to handle multiple statments so I can include the imports
;[(import [pydantic [BaseModel]])
;; Can I reference the actual class here? ~BaseModel doesn't work
defclass ~name [BaseModel]
;~attributes
~(unpack-iterable
(create-attributes attributes))
;]
#_ /))
(defn generate-python-source [code] (print (disassemble code True)))
(setv test-model [
;; This will more likely be a string that needs to be converted somehow
'TestModel
[
;; I'd like to pass the type directly and the name as a string
;; (int "id") (str "name")…
(, 'int 'id)
(, 'str 'name)]])
(generate-python-source
(create-model
(unpack-iterable test-model)))
@Hultner
Copy link
Author

Hultner commented May 19, 2020

Far from perfect but a quick PoC, imports doesn't quite work, name is reference name from hy not a new named indentifier/symbol. The BaseModel should actually reference the previously imported base-model but unquoting via ~BaseModel didn't do it.

Current output from running the script

$ hy model_generator_poc.hy
from hy.core.language import name


class TestModel(BaseModel):
    id: int
    name: str

Would truly appreciate feedback and recommendations from someone more experienced in hy-lisp, this is my first ever hy program.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment