@@ -108,6 +108,52 @@ An alternative build directory can be specified using the
108108:option: `build-dir ` config setting.
109109
110110
111+ Data files
112+ ---------- 
113+ 
114+ It is relatively common to install data files needed at runtime
115+ alongside the package's Python code or extension modules. For a Python
116+ package named ``package `` this would look like this:
117+ 
118+ ..  TODO the :force: option should be removed once the pygments meson lexer is
119+    updated to fix https://github.com/pygments/pygments/issues/2918 
120+ 
121+  .. literalinclude :: ../../tests/packages/install-data/meson.build 
122+    :language:  meson
123+    :force: 
124+    :lines:  5-
125+ 
126+ In most circumstances, these files can be accessed deriving their
127+ filesystem path from the filesystem path of the Python module next to
128+ them via the ``__file__ `` special variable. For example, within the
129+ package ``__init__.py ``:
130+ 
131+ .. code-block :: python 
132+ 
133+    import  pathlib 
134+ 
135+    data =  pathlib.Path(__file__ ).parent.joinpath(' data.txt'  ).read_text() 
136+    uuid =  pathlib.Path(__file__ ).parent.joinpath(' uuid.txt'  ).read_text()  #  WRONG! 
137+ 
138+  However, this does not work when modules are not loaded from a package
139+ installed in the Python library path in the filesystem but with a
140+ special module loader, as used to implement editable installs in
141+ ``meson-python ``. In the example above, the second read would fail
142+ when the package is installed in editable mode.  For this reason, data
143+ files need to be accessed using :mod: `importlib.resources `. The code
144+ above should be replaced with:
145+ 
146+ .. literalinclude :: ../../tests/packages/install-data/__init__.py 
147+    :lines:  5,7-
148+ 
149+ :mod: `importlib.resources ` implements a virtual filesystem that allows
150+ to access individual files as if they were in their install location.
151+ However, there is no way to expose this file structure outside of the
152+ python runtime. In the example above, it is not possible to make the
153+ ``data.txt `` and ``uuid.txt `` files appear in the same fileystem
154+ directory.
155+ 
156+ 
111157.. _how-to-guides-editable-installs-verbose :
112158
113159Verbose mode
0 commit comments