Search code examples
hy

How to declare 'main' in a hy program


As per the official docs, I should be able to to use

def main [ &rest _ ]

I tried the example in a let block :

(import argparse) 
(require [hy.contrib.walk [let]]) 
(def main [&rest _]
   (let [parser (argparse.ArgumentParser)]
     (.add-argument parser "STRING"
       :help "string to replicate")
     (.add-argument parser "-n" :type int :default 3
       :help "number of copies")
     (setv args (parser.parse_args))
     (print (* args.STRING args.n))
     ))

But I see the following error :

... trace
NameError: name 'hyx_def' is not defined

Oddly enough, the codeblock which prints the string 'n' times, works fine. The error appears at the end however.

As per this link : https://github.com/hylang/hy/pull/1483 , def has been completely removed.

So what should I use to declare a main function ?


Solution

  • defmain
    

    is the correct form. The below works :

    (import argparse) 
    (require [hy.contrib.walk [let]]) 
    (defmain [&rest _]
       (let [parser (argparse.ArgumentParser)]
         (.add-argument parser "STRING"
           :help "string to replicate")
         (.add-argument parser "-n" :type int :default 3
           :help "number of copies")
         (setv args (parser.parse_args))
         (print (* args.STRING args.n))
         ))