Skip to content

Instantly share code, notes, and snippets.

@mscuthbert
Created September 7, 2018 20:14
Show Gist options
  • Save mscuthbert/c7b87138b905f16140c596498401f2cd to your computer and use it in GitHub Desktop.
Save mscuthbert/c7b87138b905f16140c596498401f2cd to your computer and use it in GitHub Desktop.
Get likely Python module name
import pathlib
def likely_python_module(filename):
'''
Given a filename or Path, return the "likely" python module name. That is, iterate the
parent directories until it doesn't contain an __init__.py file.
Python 3.4+ only (uses pathlib), but then again, it's only Python 3 where
no relative imports causes this problem!
'''
p = pathlib.Path(filename).resolve()
paths = []
if p.name != '__init__.py':
paths.append(p.stem)
while True:
p = p.parent
if not p:
break
if not p.is_dir():
break
inits = [f for f in p.iterdir() if f.name == '__init__.py']
if not inits:
break
paths.append(p.stem)
return '.'.join(reversed(paths))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment