Search code examples
macroshy

macro inside of macro creates a list of None


I have defined two macros:

(defmacro property [name type]
  `(setv ^(of Optional ~type) ~name None))

(defmacro data-type [vname &rest propertys]
  `(with-decorator dataclass
    (defclass ~vname []
      ~propertys)))

When called as:

(data-type my-test-type
    (property name str)
    (property unitprice float)
    (property qty_on_hand int)
    (property test int))

and expanded and translated into python it produces the following:

@dataclass
class my_test_type:
    name: Optional[str] = None
    unitprice: Optional[float] = None
    qty_on_hand: Optional[int] = None
    test: Optional[int] = None
    [None, None, None, None]

Writing it without the nested macros still yeilds a list of one None:

(data-type my-test-type
    (setv ^(of Optional str) name None
          ^(of Optional float) unitprice None
          ^(of Optional int) qty_on_hand None
          ^(of Optional int) test None))
@dataclass
class my_test_type:
    name: Optional[str] = None
    unitprice: Optional[float] = None
    qty_on_hand: Optional[int] = None
    test: Optional[int] = None
    [None]

Where is this list of [None, None, None, None] coming from? While the list of none won't break anything it's still a little jarring and I wish I knew what would be a better way to write this macro to avoid the list of None.


Solution

  • It looks like you wrote ~propertys but meant ~@propertys. You want to splice each of the property declarations into the defclass, instead of combining them into a list. Making this change removes the trailing list of Nones.