@@ -33,7 +33,10 @@ module Python.Internal.Eval
3333 , Namespace (.. )
3434 , Main (.. )
3535 , Temp (.. )
36- , PtrNamespace (.. )
36+ , Dict (.. )
37+ , DictPtr (.. )
38+ , Module (.. )
39+ , ModulePtr (.. )
3740 , unsafeWithCode
3841 , eval
3942 , exec
@@ -687,9 +690,7 @@ class Namespace a where
687690-- | Namespace for the top level code execution.
688691data Main = Main
689692
690-
691693instance Namespace Main where
692- -- NOTE: almost dupe of basicMainDict
693694 basicNamespaceDict _ =
694695 throwOnNULL =<< Py [CU. block | PyObject* {
695696 PyObject* main_module = PyImport_AddModule("__main__");
@@ -700,20 +701,49 @@ instance Namespace Main where
700701 return dict;
701702 }|]
702703
704+
703705-- | Temporary namespace which get destroyed after execution
704706data Temp = Temp
705707
706708instance Namespace Temp where
707709 basicNamespaceDict _ = basicNewDict
708710
711+
712+ -- | Newtype wrapper for bare python object. It's assumed to be a
713+ -- dictionary. This is not checked.
714+ newtype DictPtr = DictPtr (Ptr PyObject )
715+
716+ instance Namespace DictPtr where
717+ basicNamespaceDict (DictPtr p) = p <$ incref p
718+
719+
709720-- | Newtype wrapper for bare python object. It's assumed to be a
710721-- dictionary. This is not checked.
711- newtype PtrNamespace = PtrNamespace (Ptr PyObject )
722+ newtype Dict = Dict PyObject
723+
724+ instance Namespace Dict where
725+ basicNamespaceDict (Dict d)
726+ -- NOTE: We're incrementing counter inside bracket so we're safe.
727+ = unsafeWithPyObject d (basicNamespaceDict . DictPtr )
728+
729+ -- | Newtype wrapper over module object.
730+ newtype ModulePtr = ModulePtr (Ptr PyObject )
731+
732+ instance Namespace ModulePtr where
733+ basicNamespaceDict (ModulePtr p) = do
734+ throwOnNULL =<< Py [CU. block | PyObject* {
735+ PyObject* dict = PyModule_GetDict($(PyObject* p));
736+ Py_XINCREF(dict);
737+ return dict;
738+ }|]
739+
740+ -- | Newtype wrapper over module object.
741+ newtype Module = Module PyObject
712742
713- instance Namespace PtrNamespace where
714- basicNamespaceDict (PtrNamespace p) = do
715- Py [ CU. block | void { Py_XINCREF($(PyObject* p)); } |]
716- return p
743+ instance Namespace Module where
744+ basicNamespaceDict (Module d)
745+ -- NOTE: We're incrementing counter inside bracket so we're safe.
746+ = unsafeWithPyObject d (basicNamespaceDict . ModulePtr )
717747
718748
719749-- | Evaluate python expression
0 commit comments