[英]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.