Skip to content

Commit

Permalink
Fix bug with unset __name__ of one-line functions
Browse files Browse the repository at this point in the history
The bug was a regression that I introduced in #1228.

I've created a new special form named `fn*` that works like the old `fn` (that is, it always creates a `FunctionDef`). Since this is intended only for internal use, like `with*`, I haven't documented it.
  • Loading branch information
Kodiologist authored and tuturto committed Apr 13, 2017
1 parent 491b474 commit 7c203ab
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 3 deletions.
8 changes: 6 additions & 2 deletions hy/compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -2297,9 +2297,13 @@ def compile_set(self, expression):
return ret

@builds("fn")
@builds("fn*")
# The starred version is for internal use (particularly, in the
# definition of `defn`). It ensures that a FunctionDef is
# produced rather than a Lambda.
@checkargs(min=1)
def compile_function_def(self, expression):
expression.pop(0)
force_functiondef = expression.pop(0) == "fn*"

arglist = expression.pop(0)
if not isinstance(arglist, HyList):
Expand Down Expand Up @@ -2376,7 +2380,7 @@ def compile_function_def(self, expression):
defaults=defaults)

body = self._compile_branch(expression)
if not body.stmts:
if not force_functiondef and not body.stmts:
ret += ast.Lambda(
lineno=expression.start_line,
col_offset=expression.start_column,
Expand Down
2 changes: 1 addition & 1 deletion hy/core/bootstrap.hy
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
(macro-error name "defn takes a name as first argument"))
(if (not (isinstance lambda-list hy.HyList))
(macro-error name "defn takes a parameter list as second argument"))
`(setv ~name (fn ~lambda-list ~@body)))
`(setv ~name (fn* ~lambda-list ~@body)))

(defmacro if-python2 [python2-form python3-form]
"If running on python2, execute python2-form, else, execute python3-form"
Expand Down
13 changes: 13 additions & 0 deletions tests/native_tests/language.hy
Original file line number Diff line number Diff line change
Expand Up @@ -900,6 +900,19 @@
(assert (= 43 (my-fun 42))))


(defn test-defn-dunder-name []
"NATIVE: test that defn preserves __name__"

(defn phooey [x]
(+ x 1))
(assert (= phooey.__name__ "phooey"))

(defn mooey [x]
(+= x 1)
x)
(assert (= mooey.__name__ "mooey")))


(defn test-mangles []
"NATIVE: test mangles"
(assert (= 2 ((fn [] (+ 1 1))))))
Expand Down

0 comments on commit 7c203ab

Please sign in to comment.