Search code examples
hy

Defn async with decorators and types


I saw from Hy docs

(defn :async [decorator1 decorator2] :tp [T1 T2] #^ annotation name [params] …)

This is working without the :tp (async, decorators, return type are working fine).

  (defn :async [(.get app "directions/{direction_name}")] 
    #^ str get-direction [direction-name]
    (print "---------------"  directon-name)
    "response")

How to add the :tp also? I tried this and many others and didn't work.

(defn :async [(.get app "directions/{direction_name}")] 
    :tp [#^ str : T]
    #^ str get-direction [direction-name : T]
    (print "---------------"  directon-name)
    "response")
Traceback (most recent call last):
  File "/home/white/.local/bin/hy2py", line 8, in <module>
    sys.exit(hy2py_main())
  File "index.hy", line 76
    :tp [#^ str : T]
    ^
hy.errors.HySyntaxError: parse error for pattern macro 'defn': got unexpected token: hy.models.List([
  hy.models.Expression([
    hy.models.Expression([
      hy.models.Symbol('.'),
      hy.models.Symbol('None'),
      hy.models.Symbol('get')]),
    hy.models.Symbol('app'),
    hy.models.String('directions/{direction_name}')])]), expected: Symbol

Minimal example
I want to know how give the types of the arguments, i guess i have wrong syntax because i am getting error.

(defn  :tp [#^ int T] test [i : T]
  i)

(test 10)

Traceback (most recent call last):
  File "/usr/lib/python3.10/runpy.py", line 288, in run_path
    code, fname = _get_code_from_file(run_name, path_name)
  File "/home/white/visual-studio/fastapi/index.hy", line 59
    (defn  :tp [#^ int T] test [i : T]
               ^
hy.errors.HySyntaxError: parse error for pattern macro 'defn': got unexpected token: :, expected: end of macro call: hy.models.List([
  hy.models.Expression([
    hy.models.Symbol('annotate'),
    hy.models.Symbol('T'),
    hy.models.Symbol('int')])]), expected: end of macro call
    

Solution (based on accepted answer, if anyone stucks in future)

(defn :async [(.get app "directions/{direction_name}")] 
    #^ str get-direction [#^ str direction-name]
    "response")

With hy2py it generates

@app.get('directions/{direction_name}')
async def get_direction(direction_name: str) -> str:
    return 'response'

Solution

  • The lambda list [i : T] is nonsensical. If you want a parameter named i annotated to have the type T, which would be written i : T in Python, that's #^ T i or (annotate i T) in Hy.