yuce / pyswip

PySwip is a Python-Prolog interface that enables querying SWI-Prolog in your Python programs.
https://pyswip.org
MIT License
482 stars 98 forks source link

Prolog.consult method updates #177

Closed yuce closed 1 month ago

yuce commented 1 month ago

This PR contains several enhancements to the Prolog.consult method.

Tilde character in paths are expanded to the user home directory

Prolog.consult("~/my_files/hanoi.pl")
# consults file /home/me/my_files/hanoi.pl

Both strings and pathlib.Path objects are allowed as paths

from pathlib import Path
Prolog.consult(Path("myfile.pl"))
# equivalent to:
Prolog.consult("myfile.pl")

Added relative_to keyword argument

relative_to keyword argument makes it easier to construct the consult path. This keyword is no-op, if the consult path is absolute.

If the given relative_to path is a file, then the consult path is updated to become a sibling of that path. Assume you have the /home/me/project/facts.pl that you want to consult from the run.py file which exists in the same directory /home/me/project. Using the built-in __file__ constant which contains the path of the current Python file , it becomes very easy to do that:

# in run.py
Prolog.consult("facts.pl", relative_to=__file__)

If the given relative_path is a directory, then the consult path is updated to become a child of that path.

project_dir = "~/projects"
Prolog.consult("facts1.pl", relative_to=project_dir)
Prolog.consult("facts2.pl", relative_to=project_dir)

Symbolic links are not yet supported yet.