osdir.com

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Import module from file path


On Wed, 5 Dec 2018 at 07:57, Peter Otten <__peter__ at web.de> wrote:
>
> Oscar Benjamin wrote:
> >
> > I'm looking to import a module given a string representing the path to
> > the .py file defining the module.
>
> I am not aware of a clean way. I have used
>
> def guess_modulename(filename):
>     """Infer module name from filename.
>
>     >>> guess_modulename("/foo/bar/baz.py")
>     'baz'
>     >>> guess_modulename("/usr/lib/python3.4/logging/handlers.py")
>     'logging.handlers'
>     """
>     if not filename.endswith(".py"):
>         raise ValueError("expecting .py file, but got %r" % filename)
>     filename = filename[:-3]
>     folder, name = os.path.split(filename)
>     names = [name]
>     while os.path.isfile(os.path.join(folder, "__init__.py")):
>         folder, name = os.path.split(folder)
>         names.append(name)
>     return ".".join(reversed(names))
>
>
> which unfortunately does not work with namespace packages.

Thanks Peter. I don't need to worry about namespace packages thankfully.

Thinking about this some more I can see that although the mapping from
module names to file paths needs to be well defined for normal imports
to work the reverse mapping will not always be well defined. For one
there are namespace packages. For another there maybe multiple routes
from sys.path to a particular .py file so that it might be possible to
import a.b.c.stuff as c.stuff if a/b is also in sys.path. Maybe that's
why a ready made solution doesn't seem to exist: the problem itself
isn't well-posed.

--
Oscar