1

I can get the path of 'os.py' like this:

import os
os.__file__

But how can I get it without importing it? I found this relevant question, but none of these work for Python3.11 , although they work for Python<=3.10 .

It seems that the newly introduced Python3.11 optimizations (doc) broke these solutions.

tamuhey
  • 2,904
  • 3
  • 21
  • 50

1 Answers1

1

This works for me (though it seems that resolve_name actually imports the module):

>>> osp = pkgutil.resolve_name("os")
>>> osp.__file__
'/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/os.py'

or

>>> from importlib.util import find_spec
>>> spec = find_spec('os')
>>> spec.loader_state.filename
'/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/os.py'
Yevhen Kuzmovych
  • 10,940
  • 7
  • 28
  • 48