Repository: hylang/hy

Issue:
`lfor` can't see an imported name in `hy -c`
This one is deeply bizarre.

```
$ CODE='(import math) (print (lfor j [1] (math.sqrt 5)))' 
$ hy -c "$CODE"
Traceback (most recent call last):
  File "/usr/local/bin/hy", line 8, in <module>
    sys.exit(hy_main())
  File "<string>", line 1, in <module>
  File "<string>", line 1, in <listcomp>
NameError: name 'math' is not defined
$ echo "$CODE" | hy           
hy 0.18.0 using CPython(default) 3.7.5 on Linux
=> [2.23606797749979]
=> 
now exiting HyREPL...
$ echo "$CODE" > /tmp/foo.hy && hy /tmp/foo.hy 
[2.23606797749979]
```

Discussion:

Patch:
diff --git a/NEWS.rst b/NEWS.rst
index 220b9f76..8c97e0f1 100644
--- a/NEWS.rst
+++ b/NEWS.rst
@@ -19,6 +19,7 @@ Bug Fixes
 * Quoted f-strings are no longer evaluated prematurely.
 * Fixed a regression in the production of error messages for empty
   expressions.
+* Fixed a scoping bug for code executed with `hy -c`.
 
 0.18.0
 ==============================
diff --git a/hy/cmdline.py b/hy/cmdline.py
index b9ffcdb5..6277d3d7 100644
--- a/hy/cmdline.py
+++ b/hy/cmdline.py
@@ -429,7 +429,7 @@ def run_command(source, filename=None):
         return 1
 
     with filtered_hy_exceptions():
-        hy_eval(tree, None, __main__, filename=filename, source=source)
+        hy_eval(tree, __main__.__dict__, __main__, filename=filename, source=source)
     return 0
 
 


Test patch:
diff --git a/tests/test_bin.py b/tests/test_bin.py
index 6c8e51c7..9bb63c8f 100644
--- a/tests/test_bin.py
+++ b/tests/test_bin.py
@@ -266,6 +266,10 @@ def test_bin_hy_cmd():
     _, err = run_cmd("hy -c \"(koan\"", expect=1)
     assert "Premature end of input" in err
 
+    # https://github.com/hylang/hy/issues/1879
+    output, _ = run_cmd(
+        """hy -c '(setv x "bing") (defn f [] (+ "fiz" x)) (print (f))'""")
+    assert 'fizbing' in output
 
 def test_bin_hy_icmd():
     output, _ = run_cmd("hy -i \"(koan)\"", "(ideas)")