5 Calling Prolog from Python
All Application Manual Name SummaryHelp

  • Documentation
    • Reference manual
    • Packages
      • SWI-Prolog Python interface
        • Calling Prolog from Python
          • Janus iterator query
          • Janus iterator apply
          • Janus access to Python locals and globals
          • Janus and Prolog truth
          • Janus class Term
          • Janus class PrologError

5.3 Janus access to Python locals and globals

Python provides access to dictionaries holding the local variables of a function using locals() as well as the global variables stored as attributes to the module to which the function belongs as globals(). The Python C API provides PyEval_GetLocals() and PyEval_GetGlobals(), but these return the scope of the Janus API function rather than user code, i.e., the global variables of the janus module and the local variables of the running Janus interface function.

Python code that wishes Prolog to access its scope must pass the necessary scope elements (local and global variables) explicitly to the Prolog code. It is possible to pass the entire local and or global scope by the output of locals() and/or globals(). Note however that a dict passed to Prolog is translated to its Prolog representation. This representation may be prohibitively large and does not allow Prolog to modify variables in the scope. Note that Prolog can access the global scope of a module as attributes of this module, e.g.

increment :-
    py_call(demo:counter, V0),
    V is V0+1,
    py_setattr(demo, counter, V).