Wednesday, 1 May 2019

Check if package is imported from within the source tree

Users should install our python package via pip or it can be cloned from a github repo and installed from source. Users should not be running import Foo from within the source tree directory for a number of reasons, e.g. C extensions are missing (numpy has the same issue: read here). So, we want to check if the user is running import Foo from within the source tree, but how to do this cleanly, efficiently, and robustly with support for Python 3 and 2?

We considered the following:

  • Check Foo/__init__.py for the __file__ variable. This displays a relative path when imported from source and an absolute path otherwise, but only on Python 2.
  • Check for setup.py, or other file like PKG-INFO, which should only be present in the source. It’s not that elegant and checking for the presence of a file is not very cheap, given this check will happen every time someone import Foo. Also there is nothing to stop someone from putting a setup.py outside to the source tree in their lib/python3.X/site-packages/ directory or similar.
  • Parsing the contents of setup.py for the package name, but it also adds overhead and is not that clean to parse.
  • Create a dummy flag file that is only present in the source tree.
  • Some clever, but likely overcomplicated and error-prone, ideas like modifying Foo/__init__.py during installation to note that we are now outside of the source tree.


from Check if package is imported from within the source tree

No comments:

Post a Comment