Skip to content

Commit 4ed8547

Browse files
committed
Add pycode quasiquoter and tests
1 parent 63bce0f commit 4ed8547

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

src/Python/Inline/QQ.hs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ module Python.Inline.QQ
3434
, py_
3535
, pye
3636
, pyf
37+
, pycode
3738
) where
3839

3940
import Language.Haskell.TH.Quote
@@ -91,3 +92,15 @@ pyf = QuasiQuoter
9192
, quoteType = error "quoteType"
9293
, quoteDec = error "quoteDec"
9394
}
95+
96+
-- | Create quote of python code suitable for use with
97+
-- 'Python.Inline.Eval.exec'
98+
--
99+
-- It creates value of type @PyQuote@
100+
pycode :: QuasiQuoter
101+
pycode = QuasiQuoter
102+
{ quoteExp = \txt -> expQQ Exec txt
103+
, quotePat = error "quotePat"
104+
, quoteType = error "quoteType"
105+
, quoteDec = error "quoteDec"
106+
}

test/TST/Run.hs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,12 @@ import Control.Concurrent
66
import Control.Exception
77
import Control.Monad
88
import Control.Monad.IO.Class
9+
import Data.Map.Strict qualified as Map
910
import Test.Tasty
1011
import Test.Tasty.HUnit
1112
import Python.Inline
1213
import Python.Inline.QQ
14+
import Python.Inline.Eval
1315
import TST.Util
1416

1517
tests :: TestTree
@@ -137,6 +139,31 @@ tests = testGroup "Run python"
137139
xs = [i*x_hs for i in [1, 200, 40000]]
138140
return sum(xs)
139141
|]
142+
, testCase "exec with Dict" $ runPy $ do
143+
dct <- [pye| {} |]
144+
exec Main (Dict dct) [pycode|
145+
a = 12
146+
b = 13
147+
|]
148+
throwsPy $ exec Main (Module dct) [pycode| |]
149+
d <- fromPy dct
150+
liftIO $ assertEqual "dict" (Just (Map.fromList [("a",12::Int),("b",13)])) d
151+
, testCase "exec with Module" $ runPy $ do
152+
m <- [pyf|
153+
import importlib.util
154+
spec = importlib.util.spec_from_loader("dyn", loader=None)
155+
return importlib.util.module_from_spec(spec)
156+
|]
157+
exec Main (Module m) [pycode|
158+
a = 12
159+
b = 'asd'
160+
|]
161+
[py_|
162+
import types
163+
isinstance(m_hs, types.ModuleType)
164+
assert m_hs.a == 12
165+
assert m_hs.b == 'asd'
166+
|]
140167
]
141168

142169
data Stop = Stop

0 commit comments

Comments
 (0)