I want to use importlib.resources.files to access a file from a module.
According to the docs,
If the anchor is omitted, the caller’s module is used.
So I would assume something like
import importlib.resources
importlib.resources.files() # (+ some further calls afterwards to access the actual file)
should refer to the callers module. Instead, I get an error:
Traceback (most recent call last):
[...]
importlib.resources.files()
~~~~~~~~~~~~~~~~~~~~~~~~~^^
File "/usr/lib/python3.13/importlib/resources/_common.py", line 45, in wrapper
return func()
File "/usr/lib/python3.13/importlib/resources/_common.py", line 56, in files
return from_package(resolve(anchor))
File "/usr/lib/python3.13/importlib/resources/_common.py", line 116, in from_package
reader = spec.loader.get_resource_reader(spec.name)
^^^^^^^^^
File "/usr/lib/python3.13/importlib/resources/_adapters.py", line 17, in __getattr__
return getattr(self.spec, name)
AttributeError: 'NoneType' object has no attribute 'name'
This does only happen when calling this from a file.
Creating an __init__.py in the same directory does not help.
Using the same code from the python shell gives me
PosixPath('/usr/lib/python3.13/_pyrepl')
which sounds about right (but is not very helpful for actual use).
What is happening here? How is this intended to be used?
EDIT:
There is also a similar question that wants to achieve the same thing. The accepted solution using __package__ does not work for me, as __package__ seems to be None too.