pythonwindows

Why does module.__file__ return None?


I've added a local directory to my system path. When I import it, it's fine but when I do

import local_repo 
print(local_repo.__file__) 

it returns None.

How do I get it to return the path...

P.S. When I try this with other modules works fine - returns the path - for example

import pathlib 
print(pathlib.__file__)

>>>> "C:\Python38\lib\pathlib.py"

Solution

  • __file__ is None because there is no file for your package. You've made a namespace package, and those aren't even supposed to correspond to a specific directory, let alone a file - they're designed for a very specialized use case that doesn't match what you're doing.

    If you want a regular package, with a non-None __file__ and all, you should give it an __init__.py file. __file__ will then be the path to the package's __init__.py.