[Python-ideas] __dir__ in which folder is this py file

Eric Snow ericsnowcurrently at gmail.com
Mon May 7 10:42:20 EDT 2018


On Mon, May 7, 2018 at 7:14 AM, Serhiy Storchaka <storchaka at gmail.com> wrote:
> * Additional burden on maintainers of import machinery. It is already too
> complex, and __file__ is set in multiple places. Don't forgot about
> third-party implementations.
>
> See also issue33277: "Deprecate __loader__, __package__, __file__, and
> __cached__ on modules" (https://bugs.python.org/issue33277).

Thanks for mentioning all this, Serhiy. :)

That said, it *may* be worth considering a method on ModuleSpec (aka
"dir()['__spec__']").  One (rough) possibility:

    def dirname(self):
        """Return the absolute path to the directory the module is in.

        This will return None for modules that do not have __file__ or
        where "directory" does not make sense (e.g. extension modules).
        """
        if self.origin is None:  # XXX ...or self.origin isn't a filename.
            return None
        import os.path  # This "lazy" import is necessary in this case.
        filename = os.path.abspath(self.origin)
        return os.path.dirname(filename)

Putting this on the module spec has several advantages:

1. __spec__ is a single source of truth (though tied to how a module
was "found" rather than to anything that happened when "loaded")
2. encourages folks to rely on __spec__ (where we'd like to head, as
demonstrated by the issue Serhiy referenced above)
3. does not add any overhead to import performance (i.e. cost only
incurred when needed)
4. does not add complexity to any other part of the import machinery

I'm not necessarily saying we should add ModuleSpec.dirname(), but it
(or something like it) is what I'd advocate for *if* we were to add a
convenient shortcut to the directory a module is in.  FWIW, I'd
probably use it.

-eric


More information about the Python-ideas mailing list