繁体   English   中英

导入的模块不能使用宏(不再)

[英]Imported modules not working with macros (anymore)

使用以下pytest文件:

(import pytest [mark])
(import pathlib [Path])
(require oreo [with-cwd])
(defn [mark.with-cwd] test-with-cwd [cookies]
      (let [ cwd (.cwd Path) ]
           (with-cwd cookies (assert (= (.cwd Path) cookies)))
           (assert (= (.cwd Path) cwd))))

我收到以下错误:

Traceback (most recent call last):
  File "/home/shadowrylander/shadowrylander/sylveon/syvlorg/oreo/tests/test-with-cwd.hy", line 7, in test_with_cwd
    (with-cwd cookies (assert (= (.cwd Path) cookies)))
NameError: name 'os' is not defined

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/shadowrylander/shadowrylander/sylveon/syvlorg/oreo/tests/test-with-cwd.hy", line 7, in test_with_cwd
    (with-cwd cookies (assert (= (.cwd Path) cookies)))
NameError: name 'os' is not defined

cookies夹具如下:

@pytest.fixture()
def cookies(request):
    from pathlib import Path
    return Path(request.config.rootdir).expanduser().resolve(strict = True) / "cookies"

最后, oreo模块中的with-cwd基本上是:

(eval-and-compile (import os hy))
(defmacro with-cwd [dir #* body]
          (setv cwd (hy.gensym))
          `(let [ ~cwd (.cwd Path) ]
                (try (.chdir os ~dir)
                     ~@body
                     (finally (.chdir os ~cwd)))))

我正在使用hy版本0.25.0 如果我在测试文件本身中导入os ,则测试有效。


更新

这个新的似乎也不起作用,给我同样的错误:

(defmacro with-cwd [dir #* body]
          (setv cwd (hy.gensym)
                os (hy.gensym))
          `(let [ ~cwd (.cwd Path) ]
                (import os :as ~os)
                (try ((. ~os chdir) ~dir)
                     ~@body
                     (finally ((. ~os chdir) ~cwd)))))

听起来你几乎完全回答了你自己的问题,但还没有完全联系起来。 像往常一样,在一个最小的例子中更容易看出发生了什么:

(defmacro m []
  (import os)
  `(os.getcwd))

(print (m))

这会引发NameError: name 'os' is not defined因为os确实在运行时未在m扩展的 scope 中定义。 代码相当于简单

(print (os.getcwd))

因此,要么os必须已经在宏扩展的 scope 中,要么必须在扩展中包含导入,如下所示:

(defmacro m []
  (setv os (hy.gensym))
  `(do
    (import os :as ~os)
    ((. ~os getcwd))))

(print (m))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM