### Testing Package Installation and Execution Source: https://github.com/hylang/hy/wiki/Release-instructions Set up a virtual environment, install the source distribution, and test Hy execution. ```bash virtualenv tenv -p python3 && cd tenv && source ./bin/activate && pip install [source distribution file] && deactivate && source ./bin/activate && echo `type hy` && echo '(+ 1 1)' | hy -i ``` -------------------------------- ### Hy Range and Slice Syntax Source: https://github.com/hylang/hy/blob/master/tests/resources/hy_repr_str_tests.txt Examples of creating ranges and slices in Hy, with variations in start, stop, and step parameters. ```hy (range 5) (slice 5) (range 2 5) (slice 2 5) (range 5 2) (slice 5 2) (range 0 5 2) (slice 0 5 2) (range 0 5 -2) (slice 0 5 -2) ``` ```hy (slice [1 2 3] #(4 6) "hello") ``` -------------------------------- ### Hy do-while loop execution example Source: https://github.com/hylang/hy/blob/master/docs/whyhy.rst Example usage of the `do-while` macro. Initializes a variable `x` and prints a message once. ```hy (setv x 0) (do-while x (print "This line is executed once.")) ``` -------------------------------- ### Python with statement example Source: https://github.com/hylang/hy/blob/master/docs/whyhy.rst Illustrates Python's `with` statement for resource management, showing how it executes a set of statements. ```python with open("foo") as o: f1 = o.read() with open("bar") as o: f2 = o.read() print(len(f1) + len(f2)) ``` -------------------------------- ### REPL Startup File Configuration Source: https://github.com/hylang/hy/blob/master/docs/repl.rst Details on configuring the Hy REPL startup file, including special variables and example configurations. ```APIDOC ## REPL Startup Files ### Description The REPL startup file allows for customization of the REPL environment, including importing modules, defining macros, and setting special variables that control REPL behavior. ### Method N/A ### Endpoint N/A ### Parameters #### Special Variables in Startup File - **`repl-spy`** (boolean) - If true, prints equivalent Python code before executing each piece of Hy code. - **`repl-output-fn`** (callable) - The :ref:`output function `, as a unary callable object. - **`repl-ps1`** (string) - String to use as the primary prompt string (`sys.ps1`). - **`repl-ps2`** (string) - String to use as the secondary prompt string (`sys.ps2`). ### Request Body N/A ### Response N/A ### Example Startup File Configuration ```hy ;; Wrapping in an `eval-and-compile` ensures these Python packages ;; are available in macros defined in this file as well. (eval-and-compile (import sys os) (sys.path.append "~/")) (import re json pathlib [Path] hy.pyops * hyrule [pp pformat]) (require hyrule [unless]) (setv repl-spy True repl-output-fn pformat ;; Make the REPL prompt `=>` green. repl-ps1 "\x01\x1b[0;32m\x02=> \x01\x1b[0m\x02" ;; Make the REPL prompt `...` red. repl-ps2 "\x01\x1b[0;31m\x02... \x01\x1b[0m\x02") (defn slurp [path] (setv path (Path path)) (when (path.exists) (path.read-text))) (defmacro greet [person] `(print ~person)) ``` ``` -------------------------------- ### Allow installation without Git in Hy Source: https://github.com/hylang/hy/blob/master/NEWS.rst Enables Hy to be installed even when the Git version control system is not available. ```hy Allow installation without Git ``` -------------------------------- ### Hy Function Hoisting Example Source: https://github.com/hylang/hy/blob/master/NEWS.rst Illustrates function hoisting in Hy, allowing for inline invocation of anonymous functions. ```hy ((fn [] (print "hi!"))) ``` -------------------------------- ### Hy Quasiquoting Examples Source: https://github.com/hylang/hy/blob/master/tests/resources/hy_repr_str_tests.txt Demonstrates quasiquoting and unquoting in Hy for constructing code or data structures programmatically. ```hy '[1 `[2 3] 4] '[1 `[~foo ~@bar] 4] '[1 `[~(+ 1 2) ~@(+ [1] [2])] 4] '[1 `[~(do (print x 'y) 1)] 4] ``` ```hy '(quasiquote 1 2 3) ``` ```hy '[1 `[2 (unquote foo bar)]] ``` ```hy '[a ~@b] '[a ~ @b] ``` -------------------------------- ### Configure Hy REPL Startup File Source: https://github.com/hylang/hy/blob/master/docs/repl.rst This example demonstrates how to configure the Hy REPL startup file. It includes importing modules, setting special variables like repl-spy and repl-output-fn, and customizing prompt strings. ```hy ;; Wrapping in an `eval-and-compile` ensures these Python packages ;; are available in macros defined in this file as well. (eval-and-compile (import sys os) (sys.path.append "~/")) (import re json pathlib [Path] hy.pyops * hyrule [pp pformat]) (require hyrule [unless]) (setv repl-spy True repl-output-fn pformat ;; Make the REPL prompt `=>` green. repl-ps1 "\x01\x1b[0;32m\x02=> \x01\x1b[0m\x02" ;; Make the REPL prompt `...` red. repl-ps2 "\x01\x1b[0;31m\x02... \x01\x1b[0m\x02") (defn slurp [path] (setv path (Path path)) (when (path.exists) (path.read-text))) (defmacro greet [person] `(print ~person)) ``` -------------------------------- ### Hy Yield-From Example Source: https://github.com/hylang/hy/blob/master/docs/api.rst Illustrates the 'yield :from' construct for delegating to a subgenerator. It requires two arguments: the keyword ':from' and the subgenerator itself. ```hy (defn myrange [] (setv r (range 10)) (while True (yield :from r))) ``` ```hy (list (zip "abc" (myrange))) ``` -------------------------------- ### Python Traceback Example Source: https://github.com/hylang/hy/blob/master/docs/semantics.rst Illustrates a typical Python traceback, showing line and column numbers to pinpoint the source of an error. ```text Traceback (most recent call last): File "cinco.py", line 4, in find() File "cinco.py", line 2, in find print(chippy) ^^^^^^^ NameError: name 'chippy' is not defined ``` -------------------------------- ### Hy Context Managers with with Source: https://context7.com/hylang/hy/llms.txt Manage resources like files using the 'with' statement for automatic setup and teardown. Supports multiple context managers and asynchronous operations. ```hy ; File handling with context manager (with [f (open "example.txt" "w")] (.write f "Hello, Hy!")) (print (with [f (open "example.txt" "r")] (.read f))) ; => Hello, Hy! ``` ```hy ; Multiple context managers (import tempfile [NamedTemporaryFile]) (with [f1 (NamedTemporaryFile :mode "w" :delete False) f2 (NamedTemporaryFile :mode "w" :delete False)] (.write f1 "File 1") (.write f2 "File 2") (print f1.name f2.name)) ``` ```hy ; Anonymous context manager (using _ as placeholder) (import contextlib [suppress]) (with [_ (suppress FileNotFoundError)] (import os) (os.remove "nonexistent.txt")) ; No error raised ``` ```hy ; Async context manager (import asyncio) (import aiofiles) ; External library (asyncio.run ((fn :async [] (with [:async f (aiofiles.open "data.txt" :mode "r")] (print (await (.read f))))))) ``` -------------------------------- ### Hy Yield Example for Generators Source: https://github.com/hylang/hy/blob/master/docs/api.rst Demonstrates the 'yield' macro for creating generators. A single argument yields that value, while omitting the argument yields None. This example shows yielding 'nope' indefinitely. ```hy (defn naysayer [] (while True (yield "nope"))) ``` ```hy (list (zip "abc" (naysayer))) ``` -------------------------------- ### Hy `lfor` list comprehension Source: https://github.com/hylang/hy/blob/master/docs/api.rst A simple `lfor` example creating a list comprehension by doubling elements from a range. ```hy (lfor x (range 5) (* 2 x)) ``` -------------------------------- ### Define a Simple Macro with Model Patterns Source: https://github.com/hylang/hy/blob/master/docs/model_patterns.rst This example shows how to write a simple macro 'pairs' using model patterns to parse and transform arguments. It expects pairs of symbols and forms, converting them into a list of tuples. Ensure 'funcparserlib' and 'hy.model-patterns' are imported. ```hy (defmacro pairs [#* args] (import funcparserlib.parser [many] hy.model-patterns [whole SYM FORM]) (setv [args] (.parse (whole [(many (+ SYM FORM))]) args)) `[~@(gfor [a1 a2] args #((str a1) a2))]) ``` ```hy (print (hy.repr (pairs a 1 b 2 c 3))) ``` -------------------------------- ### Hy with Macro for Context Managers (Return Value) Source: https://github.com/hylang/hy/blob/master/docs/api.rst This example shows how the `with` macro returns the value of its last form, similar to how Python's `with` statement works. ```hy (print (with [o (open "file.txt" "rt")] (.read o))) ``` -------------------------------- ### Launch Interactive Hy REPL Source: https://context7.com/hylang/hy/llms.txt Start an interactive Hy Read-Eval-Print Loop (REPL) from Python using `hy.REPL().run()`. You can also provide custom local variables to the REPL environment. ```python import hy # Basic REPL launch hy.REPL().run() # REPL with custom locals my_vars = {"x": 42, "data": [1, 2, 3]} hy.REPL(locals={**globals(), **my_vars}).run() ``` -------------------------------- ### Hy gfor with with statement Source: https://github.com/hylang/hy/blob/master/docs/whyhy.rst A concise example using Hy's `gfor` and `with` to process multiple files and sum their lengths. Requires `sum` and `gfor`. ```hy (print (sum (gfor filename ["foo" "bar"] (len (with [o (open filename)] (.read o)))))) ``` -------------------------------- ### Run Hy Interpreter and REPL Source: https://context7.com/hylang/hy/llms.txt Use the `hy` command-line tool to start an interactive REPL, run Hy scripts, execute code directly, or preview Python output. ```bash # Start interactive REPL $ hy Hy 1.2.0 using CPython 3.11.0 => (print "Hello!") Hello! => (+ 1 2 3) 6 ``` ```bash # Run a Hy script $ hy myprogram.hy arg1 arg2 ``` ```bash # Run a module $ hy -m mypackage.mymodule ``` ```bash # Execute code directly $ hy -c "(print (* 6 7))" 42 ``` ```bash # REPL with Python code preview $ hy --spy => (defn square [x] (* x x)) def square(x): return x * x ------------------------------ => (square 5) square(5) ------------------------------ 25 ``` ```bash # Run script then drop into REPL $ hy -i myscript.hy ``` -------------------------------- ### Hy dfor Macro Example Source: https://github.com/hylang/hy/blob/master/docs/api.rst The `dfor` macro creates a dictionary comprehension. It takes a key-producing form and a value-producing form. ```hy (dfor x (range 5) x (* x 10)) ; => {0 0 1 10 2 20 3 30 4 40} ``` -------------------------------- ### Hy match Macro Complex Example with Guards and OR Patterns Source: https://github.com/hylang/hy/blob/master/docs/api.rst Demonstrates advanced pattern matching with `match`, including OR patterns `(|)`, AS patterns `(:as NAME)`, guards `(:if FORM)`, and wildcards `_`. ```hy (match #(100 200) [100 300] "Case 1" [100 200] :if flag "Case 2" [900 y] f"Case 3, y: {y}" [100 (| 100 200) :as y] f"Case 4, y: {y}" _ "Case 5, I match anything!") ``` -------------------------------- ### Hy Macro Definition Example Source: https://github.com/hylang/hy/blob/master/NEWS.rst Demonstrates the removal of tag macros and the recommended use of reader macros instead. Shows the old tag macro syntax and the new `defreader` equivalent. ```hy (defmacro "#foo" [arg] ...) (defreader foo (setv arg (.parse-one-form &reader)) ...) ``` -------------------------------- ### Hy Expression Syntax Source: https://github.com/hylang/hy/blob/master/tests/resources/hy_repr_str_tests.txt Examples of Hy expressions, including function calls, attribute access, and dotted attribute access. ```hy '(+ 1 2) '(f a b) '(f #* args #** kwargs) '(.real 3) '(.a.b.c foo) '(math.sqrt 25) '(. a) '(. None) '(. 1 2) ``` ```hy '(.. 1 2) '(.. a b) ``` ```hy [1 [2 3] #(4 #('mysymbol :mykeyword)) {"a" b"hello"} '(f #* a #** b)] ``` ```hy '(quote) ``` -------------------------------- ### Logical operations with `(setv …)` Source: https://github.com/hylang/hy/blob/master/NEWS.rst Fixed a bug where logical operations starting with a `(setv …)` expression failed to compile. ```hy (setv …) ``` -------------------------------- ### Replacing removed functions with alternatives Source: https://github.com/hylang/hy/blob/master/NEWS.rst Use `(help (get-macro foo))` or `(help (get-macro :reader foo))` instead of `doc`. Use `(eval-when-compile (del (get _hy_macros (hy.mangle "foo"))))` instead of `delmacro`. ```hy (help (get-macro foo)) ``` ```hy (help (get-macro :reader foo)) ``` ```hy (eval-when-compile (del (get _hy_macros (hy.mangle "foo")))) ``` -------------------------------- ### Define and Use Global Macro in Hy Source: https://github.com/hylang/hy/blob/master/docs/macros.rst Demonstrates defining a global macro, checking its existence, getting help, executing it, deleting it, and observing the NameError after deletion. Also shows defining a new macro using `setv` and `hy.mangle`. ```hy (defmacro m [] "This is a docstring." '(print "Hello, world.")) (print (in "m" _hy_macros)) ; => True (help (get-macro m)) (m) ; => "Hello, world." (eval-and-compile (del (get _hy_macros "m"))) (m) ; => NameError (eval-and-compile (setv (get _hy_macros (hy.mangle "new-mac")) (fn [] '(print "Goodbye, world.")))) (new-mac) ; => "Goodbye, world." ``` -------------------------------- ### Hy with Macro for Context Managers (Single Manager) Source: https://github.com/hylang/hy/blob/master/docs/api.rst The `with` macro compiles to Python's `with` statement for managing resources. This example shows opening a file and reading its content. ```hy (with [o (open "file.txt" "rt")]) (.read o)) ``` -------------------------------- ### Hy with statement returning values Source: https://github.com/hylang/hy/blob/master/docs/whyhy.rst Shows how Hy's `with` form can return values, allowing it to be used like a function call. This example reads from files and sums their lengths. ```hy (print (+ (len (with [o (open "foo")] (.read o))) (len (with [o (open "bar")] (.read o)))))) ``` -------------------------------- ### Hy `lfor` with multiple clauses and `:if` Source: https://github.com/hylang/hy/blob/master/docs/api.rst A complex `lfor` example demonstrating multiple iteration clauses, an `:if` condition, and `:setv` to build a list of lists. ```hy (lfor x (range 3) y (range 3) :if (!= x y) :setv total (+ x y) [x y total]) ``` -------------------------------- ### Hy `car` and `cdr` Source: https://github.com/hylang/hy/blob/master/NEWS.rst Introduces `car` (or `first`) to get the head of a list and `cdr` (or `rest`) to get the tail. ```hy (car '(1 2 3)) ``` ```hy (first '(1 2 3)) ``` ```hy (cdr '(1 2 3)) ``` ```hy (rest '(1 2 3)) ``` -------------------------------- ### Hy Early Return Example Source: https://github.com/hylang/hy/blob/master/docs/api.rst Illustrates the use of the 'return' macro in Hy to exit a function early. The 'return' macro compiles to a Python 'return' statement. If no argument is provided, it returns None. ```hy (defn f [x] (for [n (range 10)] (when (> n x) (return n)))) ``` ```hy (f 3.9) ``` -------------------------------- ### Use Toolz Library for Partitioning Source: https://github.com/hylang/hy/blob/master/docs/tutorial.rst Shows how to use the `partition` function from the `toolz` library to group elements of a list. ```hy (import toolz [partition]) (list (partition 2 [1 2 3 4 5 6])) ; => [#(1 2) #(3 4) #(5 6)] ``` -------------------------------- ### Hy Sequence Accessors Source: https://github.com/hylang/hy/blob/master/NEWS.rst Provides `car` (or `first`) to get the first element and `cdr` (or `rest`) to get the rest of a sequence. ```hy (car sequence) ``` ```hy (first sequence) ``` ```hy (cdr sequence) ``` ```hy (rest sequence) ``` -------------------------------- ### Context Managers with with Source: https://context7.com/hylang/hy/llms.txt Illustrates the use of the `with` macro for managing resources via context managers. ```APIDOC ### with - Context Managers Use `with` to work with context managers for resource management. ### Request Example ```hy ; File handling with context manager (with [f (open "example.txt" "w")] (.write f "Hello, Hy!")) (print (with [f (open "example.txt" "r")] (.read f))) ; => Hello, Hy! ; Multiple context managers (import tempfile [NamedTemporaryFile]) (with [f1 (NamedTemporaryFile :mode "w" :delete False) f2 (NamedTemporaryFile :mode "w" :delete False)] (.write f1 "File 1") (.write f2 "File 2") (print f1.name f2.name)) ; Anonymous context manager (using _ as placeholder) (import contextlib [suppress]) (with [_ (suppress FileNotFoundError)] (import os) (os.remove "nonexistent.txt")) ; No error raised ; Async context manager (import asyncio) (import aiofiles) ; External library (asyncio.run ((fn :async [] (with [:async f (aiofiles.open "data.txt" :mode "r")] (print (await (.read f))))))) ``` ``` -------------------------------- ### Parse a Try Form with Model Patterns Source: https://github.com/hylang/hy/blob/master/docs/model_patterns.rst This example demonstrates parsing a complex 'try' form using Hy's model patterns. It shows how to define a parser for nested structures including 'except', 'else', and 'finally' clauses. The result can be conveniently destructured into variables. ```hy (import funcparserlib.parser [maybe many] hy.model-patterns *) (setv parser (whole [ (sym "try") (many (notpexpr "except" "else" "finally")) (many (pexpr (sym "except") (| (brackets) (brackets FORM) (brackets SYM FORM)) (many FORM))) (maybe (dolike "else")) (maybe (dolike "finally"))])) ``` -------------------------------- ### Access List Elements with `get` in Hy Source: https://github.com/hylang/hy/blob/master/docs/tutorial.rst Use `get` to access elements of a list by index. It also supports modifying elements in place. ```hy (setv fruit ["apple" "banana" "cantaloupe"]) (print (get fruit 0)) ; => apple (setv (get fruit 1) "durian") (print (get fruit 1)) ; => durian ``` -------------------------------- ### Constructing Hy Models for Macros Source: https://github.com/hylang/hy/blob/master/docs/macros.rst Demonstrates the explicit way to construct Hy models for macro expansion, useful for understanding the underlying structure. ```hy (defmacro addition [] (hy.models.Expression [ (hy.models.Symbol "+") (hy.models.Integer 1) (hy.models.Integer 1)])) ``` -------------------------------- ### Hy match Macro Basic Example Source: https://github.com/hylang/hy/blob/master/docs/api.rst The `match` macro compiles to Python 3.10+'s `match` statement for pattern matching. This example matches an arithmetic result. ```hy (match (+ 1 1) 1 "one" 2 "two" 3 "three") ; => "two" ``` -------------------------------- ### Tagging a New Version Source: https://github.com/hylang/hy/wiki/Release-instructions Use this command to create a Git tag for a new release version. ```bash git tag x.y.z -m 'Version x.y.z' ``` -------------------------------- ### Exception Handling with `raise` and `try` Source: https://github.com/hylang/hy/blob/master/docs/api.rst Demonstrates how to raise and catch exceptions using Hy's `raise` and `try` macros, including various syntaxes for exception specification. ```APIDOC ## `raise` Macro ### Description Raises an exception. If called with no arguments, it reraises the current exception. If called with one argument (an exception), that exception is raised. ### Syntax - `(raise)` - `(raise EXCEPTION)` - `(raise EXCEPTION_1 :from EXCEPTION_2)` ### Example ```hy (try (raise KeyError) (except [KeyError] (print "gottem"))) ``` ## `try` Macro ### Description Compiles to a Python `try` statement, allowing for exception catching and cleanup actions. It supports multiple `except` clauses, an `else` clause, and a `finally` clause. ### Syntax `(try body* (except [exception_list] body*)? (else body*)? (finally body*)?)` `exception_list` can be: - `[]`: Catches any subtype of `Exception`. - `[ETYPE]`: Catches only the single type `ETYPE`. - `[[ETYPE1 ETYPE2 ...]]`: Catches any of the named types. - `[VAR ETYPE]`: Catches `ETYPE` and binds it to `VAR`. - `[VAR [ETYPE1 ETYPE2 ...]]`: Catches any of the named types and binds it to `VAR`. - `[[]]` or `[VAR []]`: Catches no exceptions. ### Example ```hy (try (error-prone-function) (except [ZeroDivisionError] (print "Division by zero")) (except [[IndexError KeyboardInterrupt]] (print "Index error or Ctrl-C")) (except [e ValueError] (print "ValueError:" (repr e))) (else (print "No errors")) (finally (print "All done"))) ``` ``` -------------------------------- ### Multiple Assignments with setv in Hy Source: https://github.com/hylang/hy/blob/master/docs/api.rst Shows how `setv` can handle multiple assignment pairs, executing them sequentially. ```hy (setv x 1 y x x 2) (print x y) ``` -------------------------------- ### Launch Hy REPL from Python Source: https://github.com/hylang/hy/blob/master/docs/interop.rst Initiate the Hy REPL session directly from a Python environment. Ensure local and global variables are passed to the REPL. ```python hy.REPL(locals = {**globals(), **locals()}).run() ``` -------------------------------- ### Context Manager Macro: with Source: https://github.com/hylang/hy/blob/master/docs/api.rst Documentation for the `with` macro, which compiles to Python's `with` or `async with` statements. ```APIDOC ## (with [MANAGERS #* BODY]) ### Description Wraps a code block with one or more context managers, compiling to Python's `with` or `async with` statement. ### Method Macro ### Endpoint N/A ### Parameters - **MANAGERS** (list) - Required - A list of context managers. Can be a single manager, a variable-manager pair, or multiple pairs. The symbol `_` can be used to indicate no variable binding. - **BODY** (#* forms) - Required - The forms to execute within the context. ### Request Example ```hy (with [o (open "file.txt" "rt")] (print (.read o))) (with [x (range 5)] (print x)) (with [:async v1 e1] ...) ``` ### Response Returns the value of the last form in the body, or `None` if an exception was suppressed. ### Response Example ```hy (print (with [o (open "file.txt" "rt")] (.read o))) ``` ``` -------------------------------- ### Define a Reader Macro for Decimal Source: https://github.com/hylang/hy/blob/master/docs/tutorial.rst Example of defining a reader macro `d` to create Decimal objects from Hy source. ```hy (defreader d (.slurp-space &reader) `(hy.I.decimal.Decimal ~(.read-ident &reader))) (print (repr #d .1)) ; => Decimal('0.1') (import fractions [Fraction]) (print (Fraction #d .1)) ; => 1/10 ;; Contrast with the normal floating-point .1: (print (Fraction .1)) ; => 3602879701896397/36028797018963968 ``` -------------------------------- ### Hy Symbols and Keywords Source: https://github.com/hylang/hy/blob/master/tests/resources/hy_repr_str_tests.txt Shows examples of symbols and keywords in Hy, including those with special characters and single quotes. ```hy 'mysymbol 'my♥symbol? '. '.. '... '.... :mykeyword :my♥keyword? : '':mykeyword ``` -------------------------------- ### Get Current Hy Nickname Source: https://github.com/hylang/hy/blob/master/docs/versioning.rst Retrieve the current nickname of the Hy version as a string. Returns `None` for unreleased commits. ```python hy.nickname ``` -------------------------------- ### Hy REPL Replacement Source: https://github.com/hylang/hy/blob/master/NEWS.rst `hy.cmdline.run_repl` has been replaced with `hy.cmdline.HyREPL.run`. ```python hy.cmdline.run_repl ``` ```python hy.cmdline.HyREPL.run ``` -------------------------------- ### Hy with Macro for Context Managers (Multiple Managers) Source: https://github.com/hylang/hy/blob/master/docs/api.rst This demonstrates the `with` macro with multiple context managers, compiling to Python's `with ... as ..., ... as ...:` syntax. ```hy (with [v1 e1 v2 e2 v3 e3] ...) ``` -------------------------------- ### Unquote Splice Example in Hy Source: https://github.com/hylang/hy/blob/master/docs/api.rst Demonstrates the use of `~@` for splicing iterables into sequences. False values are treated as empty lists. ```hy (setv X [1 2 3]) (hy.repr `[a b ~X c d ~@X e f]) ``` -------------------------------- ### Function Definition with `defn` Source: https://github.com/hylang/hy/blob/master/docs/api.rst Explains how to define functions using the `defn` macro, including parameter list syntax, docstrings, async functions, decorators, and type annotations. ```APIDOC ## `defn` Macro ### Description Compiles to a Python function definition or an assignment of a lambda expression. It returns `None`. ### Syntax `(defn [name #* args])` Can include optional arguments before the name: - `:async`: Creates an asynchronous function. - `[decorator1 decorator2]`: Applies decorators. - `:tp [T1 T2]`: Specifies type parameters. - `#^ annotation`: Specifies the return type annotation. `(defn [:async] [decorators] [:tp [type_params]] [#^ annotation] name [params] bodyform1 bodyform2…)` ### Parameters - `name` (symbol): The name of the function. - `params` (list): A list of symbols representing function parameters. Supports Python's parameter list features including positional-only, keyword-only, default values, `*args`, and `**kwargs`. - `[pname value]`: Parameter with a default value. - `/`: Indicates preceding parameters are positional-only. - `*`: Indicates subsequent parameters are keyword-only. ### Body - The first body form, if a string literal, becomes the function's docstring. - The last body form is implicitly returned, unless it's an asynchronous generator. - An empty body implies `(return None)`. ### Example ```hy (defn greet [name] (print "Hello, " name)) (defn add [a b] (+ a b)) (defn calculate [x y #^ float] "Calculates the result of x divided by y." (/ x y)) (defn :async fetch-data [url] (let [response (http/get url)] (response.text))) ``` ``` -------------------------------- ### Looping Macros: dfor, gfor, sfor Source: https://github.com/hylang/hy/blob/master/docs/api.rst Documentation for macros that create loops and comprehensions. ```APIDOC ## (dfor [KEY VALUE] COLLECTION BODY) ### Description Creates a dictionary from a collection, where KEY and VALUE are forms that produce the key and value for each element. ### Method Macro ### Endpoint N/A ### Parameters - **KEY** (form) - Required - Form to produce the key for each dictionary element. - **VALUE** (form) - Required - Form to produce the value for each dictionary element. - **COLLECTION** (form) - Required - The collection to iterate over. ### Request Example ```hy (dfor x (range 5) x (* x 10)) ``` ### Response Returns a dictionary. ### Response Example ```hy {0 0 1 10 2 20 3 30 4 40} ``` ## (gfor [VAR] COLLECTION BODY) ### Description Creates a generator expression that yields values one at a time. ### Method Macro ### Endpoint N/A ### Parameters - **VAR** (symbol) - Required - Variable to bind each element to. - **COLLECTION** (form) - Required - The collection to iterate over. - **BODY** (form) - Required - The expression to evaluate for each element. ### Request Example ```hy (gfor x (count) :do (.append accum x) x) ``` ### Response Returns an iterator. ### Response Example ```hy [0 1 2 3 4] ``` ## (sfor [CLAUSES VALUE]) ### Description Creates a set comprehension, equivalent to `(set (lfor CLAUSES VALUE))`. ### Method Macro ### Endpoint N/A ### Parameters - **CLAUSES** (list) - Required - Clauses for the comprehension. - **VALUE** (form) - Required - The expression to evaluate for each element. ### Request Example ```hy (sfor x (range 5) x) ``` ### Response Returns a set. ### Response Example ```hy {0 1 2 3 4} ``` ``` -------------------------------- ### Use new standard macros `do-n`, `list-n`, `cfor` Source: https://github.com/hylang/hy/blob/master/NEWS.rst New standard macros `do-n`, `list-n`, and `cfor` are available for common operations. ```hy (do-n ...) ``` ```hy (list-n ...) ``` ```hy (cfor ...) ``` -------------------------------- ### Uploading to PyPI Source: https://github.com/hylang/hy/wiki/Release-instructions Upload the built distribution files to the Python Package Index (PyPI). ```bash twine upload dist/* ``` -------------------------------- ### Hy If Statement Hoisting Example Source: https://github.com/hylang/hy/blob/master/NEWS.rst Demonstrates if hoisting in Hy, where the return value of an `if` statement can be directly used, such as within a `print` call. ```hy (print (if true true true)) ``` -------------------------------- ### Lexical Scoping with let Source: https://context7.com/hylang/hy/llms.txt Explains how to create lexically scoped local variables using the `let` macro. ```APIDOC ### let - Lexical Scoping Create lexically scoped local variables with `let`. ### Request Example ```hy ; Basic let binding (let [x 10 y 20] (print (+ x y))) ; => 30 ; x and y are not visible here ; Nested let with shadowing (setv x 1) (let [x 100] (print x) ; => 100 (let [x 1000] (print x)) ; => 1000 (print x)) ; => 100 (print x) ; => 1 ; Sequential binding (like let*) (let [a 1 b (+ a 1) c (+ a b)] (print a b c)) ; => 1 2 3 ; Destructuring in let (let [[head #* tail] [1 2 3 4 5]] (print head tail)) ; => 1 [2, 3, 4, 5] ``` ``` -------------------------------- ### Define Anonymous Functions with `fn` in Hy Source: https://github.com/hylang/hy/blob/master/docs/tutorial.rst Use `fn` to define anonymous functions. This example uses `fn` with `filter` and `range`. ```hy (print (list (filter (fn [x] (% x 2)) (range 10)))) ; => [1, 3, 5, 7, 9] ``` -------------------------------- ### Define Named Functions with `defn` in Hy Source: https://github.com/hylang/hy/blob/master/docs/tutorial.rst Use `defn` to define named functions. This example shows a recursive Fibonacci function. ```hy (defn fib [n] (if (< n 2) n (+ (fib (- n 1)) (fib (- n 2))))) (print (fib 8)) ; => 21 ``` -------------------------------- ### Building Source Distribution Source: https://github.com/hylang/hy/wiki/Release-instructions Create a source distribution (sdist) of the Hy package. ```bash python3 setup.py sdist ``` -------------------------------- ### Hy comment example Source: https://github.com/hylang/hy/blob/master/docs/tutorial.rst Demonstrates how to add comments in Hy using a semicolon, which extends to the end of the line. Comments are treated as whitespace. ```hy (setv password "susan") ; My daughter's name ``` -------------------------------- ### Use Hyrule Library Functions Source: https://github.com/hylang/hy/blob/master/docs/tutorial.rst Demonstrates importing and using functions like `inc` and `case` from the Hyrule utility library. ```hy (import hyrule [inc]) (list (map inc [1 2 3])) ; => [2 3 4] (require hyrule [case]) (setv x 2) (case x 1 "a" 2 "b" 3 "c") ; => "b" ``` -------------------------------- ### Customizing Hy REPL prompts Source: https://github.com/hylang/hy/blob/master/NEWS.rst Set `repl-ps1` and `repl-ps2` in your `HYSTARTUP` file to customize `sys.ps1` and `sys.ps2` for the Hy REPL. ```hy You can now set `repl-ps1` and `repl-ps2` in your `HYSTARTUP` to customize `sys.ps1` and `sys.ps2` for the Hy REPL. ``` -------------------------------- ### Import modules with import Source: https://github.com/hylang/hy/blob/master/NEWS.rst The `import` syntax has been simplified; use `(import foo)` instead of `(import [foo])`. ```hy (import foo) ``` -------------------------------- ### Discard Prefix Example in Hy Source: https://github.com/hylang/hy/blob/master/docs/syntax.rst The `#_` prefix in Hy discards the following form, similar to a structure-aware comment. Reader macros are still executed. ```hy [dilly #_ and krunk] ``` ```hy [dilly ; and krunk] ``` -------------------------------- ### Define Classes with `defclass` in Hy Source: https://github.com/hylang/hy/blob/master/docs/tutorial.rst Use `defclass` to define classes. This example defines a simple class `FooBar` with an initializer and a getter method. ```hy (defclass FooBar [] (defn __init__ [self x] (setv self.x x)) (defn get-x [self] self.x)) ``` -------------------------------- ### Hy shebang line Source: https://github.com/hylang/hy/blob/master/docs/tutorial.rst Example of a shebang line at the beginning of a Hy script. Hy ignores this line, allowing the script to be made executable. ```hy #!/usr/bin/env hy (print "Make me executable, and run me!") ``` -------------------------------- ### Attribute Access and Method Calls in Hy Source: https://github.com/hylang/hy/blob/master/NEWS.rst The attribute access macro `.` in Hy now supports method calls. For example, `(. x (f a))` is equivalent to `(x.f a)`. ```hy (. x (f a)) ``` ```hy (x.f a) ``` -------------------------------- ### Define Reader Macro in Hy Source: https://github.com/hylang/hy/blob/master/NEWS.rst Use `defreader` to define user-defined reader macros. This example shows how to rewrite a tag macro using `defreader`. ```hy (defmacro "#foo" [arg] …) (defreader foo (setv arg (.parse-one-form &reader)) …) ``` -------------------------------- ### Symbol Examples in Hy Source: https://github.com/hylang/hy/blob/master/docs/syntax.rst Symbols are the general category of identifiers in Hy, often compiled to Python variable names. They can include a wide range of characters. ```hy hello ``` ```hy +++ ``` ```hy 3fiddy ``` ```hy $40 ``` ```hy just✈wrong ``` ```hy 🦑 ``` -------------------------------- ### Pattern Matching with match Source: https://context7.com/hylang/hy/llms.txt Shows how to use the `match` macro for structural pattern matching, available in Python 3.10+. ```APIDOC ### match - Pattern Matching (Python 3.10+) Use structural pattern matching with the `match` macro. ### Request Example ```hy ; Basic pattern matching (defn describe [value] (match value 0 "zero" 1 "one" 2 "two" _ "other")) (print (describe 1)) ; => one (print (describe 99)) ; => other ; Sequence patterns (defn analyze-list [lst] (match lst [] "empty" [x] f"single: {x}" [x y] f"pair: {x}, {y}" [x #* rest] f"head: {x}, tail has {(len rest)} items")) (print (analyze-list [])) ; => empty (print (analyze-list [1])) ; => single: 1 (print (analyze-list [1 2])) ; => pair: 1, 2 (print (analyze-list [1 2 3 4])) ; => head: 1, tail has 3 items ; Pattern with guards (defn classify-point [point] (match point #(0 0) "origin" #(x 0) :if (> x 0) f"positive x-axis at {x}" #(0 y) :if (> y 0) f"positive y-axis at {y}" #(x y) :if (= x y) f"diagonal at {x}" #(x y) f"point at ({x}, {y})")) (print (classify-point #(0 0))) ; => origin (print (classify-point #(5 0))) ; => positive x-axis at 5 (print (classify-point #(3 3))) ; => diagonal at 3 ``` ``` -------------------------------- ### Hy raise Macro Example Source: https://github.com/hylang/hy/blob/master/docs/api.rst The `raise` macro compiles to Python's `raise` statement for throwing exceptions. It supports the optional `:from` clause for exception chaining. ```hy (raise [exception :from other]) ``` -------------------------------- ### Call keyword objects with a default value Source: https://github.com/hylang/hy/blob/master/NEWS.rst Keyword objects can be called directly, accepting a default value as the second argument. This is shorthand for `(get obj :key default_value)`. ```hy (:key obj default_value) ``` -------------------------------- ### Unpacking Assignment in Hy Source: https://github.com/hylang/hy/blob/master/docs/api.rst Illustrates unpacking assignment with `setv` and iterable unpacking syntax. ```hy (setv [letter1 letter2 #* others] "abcdefg") (print letter1 letter2 (hy.repr others)) ``` -------------------------------- ### Hy F-string Example Source: https://github.com/hylang/hy/blob/master/docs/syntax.rst Demonstrates the usage of Hy f-strings, similar to Python's, for embedding expressions within strings. The embedded code is evaluated and inserted into the string. ```hy (print f"The sum is {(+ 1 1)}.") ; => The sum is 2. ``` -------------------------------- ### Addition operation in Hy Source: https://github.com/hylang/hy/blob/master/docs/tutorial.rst Demonstrates the prefix syntax for the addition operator in Hy, equivalent to '1 + 3' in Python. Supports multiple arguments. ```hy (+ 1 3) ``` ```hy (+ 1 2 3) ``` -------------------------------- ### Hy String and Byte String Literals Source: https://github.com/hylang/hy/blob/master/tests/resources/hy_repr_str_tests.txt Examples of string and byte string literals in Hy, including empty strings, strings with special characters, and bracketed strings. ```hy "" b"" (bytearray b"") ``` ```hy "apple bloom" b"apple bloom" (bytearray b"apple bloom") "⚘" ``` ```hy "single ' quotes" b"single ' quotes" "\"double \" quotes\"" b"\"double \" quotes\"" ``` ```hy '#[[bracketed string]] '#[delim[bracketed string]delim] '#[delim[brack'eted string]delim] ``` -------------------------------- ### Expression Evaluation: Method Calls Source: https://github.com/hylang/hy/blob/master/docs/syntax.rst Expressions starting with `(. None ...)` are used to construct method calls. The element after `None` is the object, and the subsequent elements are arguments to the method. ```hy (.add my-set 5) ``` ```hy ((. my-set add) 5) ``` -------------------------------- ### Hy with Macro for Asynchronous Context Managers Source: https://github.com/hylang/hy/blob/master/docs/api.rst Shows how to use the `:async` keyword with the `with` macro to handle asynchronous context managers. ```hy (with [:async v1 e1] ...) ``` -------------------------------- ### Help function stability Source: https://github.com/hylang/hy/blob/master/NEWS.rst `help` should no longer crash when objects are missing docstrings. ```python help ``` -------------------------------- ### Hy REPL Class and Methods Source: https://github.com/hylang/hy/blob/master/docs/repl.rst Information about the `hy.REPL` class and its `run` method for programmatic REPL execution. ```APIDOC ## `hy.REPL` Class ### Description Implements the Hy Read-Eval-Print Loop (REPL). ### Method - **run()**: Starts the REPL interactively or programmatically. ### Endpoint N/A (Programmatic Interface) ### Parameters N/A ### Request Body N/A ### Response N/A ### Error Handling N/A ``` -------------------------------- ### Keyword object calls perform string lookup Source: https://github.com/hylang/hy/blob/master/NEWS.rst Calling a keyword object now performs a string lookup. `(:key obj)` is equivalent to `(get obj (mangle (. :key name)))`. ```hy (get obj (mangle (. :key name))) ``` -------------------------------- ### Raw String Literal Example Source: https://github.com/hylang/hy/blob/master/docs/syntax.rst Use the `r` prefix to create a raw string literal that interprets backslashes literally. Unrecognized escape sequences will result in a syntax error. ```hy r"slash\not" ``` -------------------------------- ### Anaphoric Macro Example with `ap-if` Source: https://github.com/hylang/hy/blob/master/docs/macros.rst Demonstrates the use of an anaphoric macro `ap-if` from Hyrule, which assigns a test form's result to a variable named `it` for use in subsequent forms. ```hy (import os) (ap-if (.get os.environ "PYTHONPATH") (print "Your PYTHONPATH is" it)) ``` -------------------------------- ### Using Quasiquotation for Macro Arguments Source: https://github.com/hylang/hy/blob/master/docs/macros.rst Illustrates how quasiquotation (`` ` ``) and unquote (`` ~ ``) can be used to construct macro expansions with dynamic components, such as variable names. ```hy (defmacro set-to-2 [variable] `(setv ~variable 2)) (set-to-2 foobar) (print foobar) ``` -------------------------------- ### Block Scoping with let in Hy Source: https://github.com/hylang/hy/blob/master/docs/api.rst Demonstrates `let` for simulating block scoping with lexical variables. Nested `let` forms can shadow names. ```hy (let [x 5 y 6] (print x y) (let [x 7] (print x y)) (print x y)) ``` -------------------------------- ### Hy Readline Import Optimization Source: https://github.com/hylang/hy/blob/master/NEWS.rst Readline is now imported only when necessary, reducing startup time and avoiding potential issues. ```python Readline ``` -------------------------------- ### Expression Evaluation: Macro Expansion Source: https://github.com/hylang/hy/blob/master/docs/syntax.rst Expressions starting with a symbol that is a macro name are evaluated by calling the macro. An exception occurs if the symbol is also a function in `hy.pyops` and an argument is an `unpack-iterable` form. ```hy (+ #* summands) ``` -------------------------------- ### Use `hy.as-model` to promote values Source: https://github.com/hylang/hy/blob/master/NEWS.rst To compare Hy model objects with ordinary Python values, use `hy.as-model` to promote the Python values to Hy models before comparison. ```hy (hy.as-model 1) ``` -------------------------------- ### Return value of `--init--` in Hy Source: https://github.com/hylang/hy/blob/master/NEWS.rst Specifies that `None` is returned instead of the last form in `--init--`. ```hy None is returned instead of the last form in --init-- ``` -------------------------------- ### REPL Output Functions Source: https://github.com/hylang/hy/blob/master/docs/repl.rst Details on how to customize the output function for the REPL, including the default behavior and command-line arguments. ```APIDOC ## REPL Output Functions ### Description By default, the return value of each REPL input is printed using `hy.repr`. This behavior can be customized using the `--repl-output-fn` command-line argument or by setting the `repl-output-fn` variable in the startup file. ### Method N/A ### Endpoint N/A ### Parameters #### Command-line Argument - **--repl-output-fn** (callable) - Specifies a unary callable object to use as the REPL output function. #### Startup File Variable - **repl-output-fn** (callable) - The :ref:`output function `, as a unary callable object. ### Request Body N/A ### Response N/A ### Error Handling N/A ``` -------------------------------- ### Define macros with optional arguments using defmacro! Source: https://github.com/hylang/hy/blob/master/NEWS.rst The `defmacro!` macro now supports optional arguments. ```hy (defmacro! my-macro [arg1 &optional arg2] `(+ ~arg1 ~arg2)) ``` -------------------------------- ### Reader Macro Definition and Usage in Hy Source: https://github.com/hylang/hy/blob/master/docs/macros.rst Example showing the definition of a reader macro `up` and its subsequent use. Note that reader macros cannot be used in the same top-level form that defines them due to parse-time evaluation. ```hy (do (defreader up (.slurp-space &reader) (.upper (.read-one-form &reader))) (print #up "hello?")) ``` -------------------------------- ### Macro Pitfall: Name Shadowing with Assignment Source: https://github.com/hylang/hy/blob/master/docs/macros.rst This example demonstrates a common macro pitfall where a local variable assignment within the macro modifies a variable in the outer scope, leading to unexpected results. ```hy (defmacro upper-twice [arg] `(do (setv x (.upper ~arg)) (+ x x))) (setv x "Okay guys, ") (setv salutation (upper-twice "bye")) (print (+ x salutation)) ```