os.path and Path

Eric Snow ericsnowcurrently at gmail.com
Thu Jun 16 13:21:05 EDT 2011


On Thu, Jun 16, 2011 at 10:41 AM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
>
> On a Linux or OS X box, you could have a file e inside a directory c:d
> inside b inside a. It can't be treated as platform independent, because
> c:d is not a legal path component under classic Mac or Windows.
>
> On a classic Mac (does anyone still use them?), you could have a file e
> inside a directory c/d inside b inside a. Likewise c/d isn't legal under
> POSIX or Windows.
>
> So there are paths that are legal under one file system, but not others,
> and hence there is no single normalization that can represent all legal
> paths under arbitrary file systems.
>

Perhaps one solution is to have the Path class accept registrations of
valid path formats:

    class PathFormat:
        @abstractmethod
        def map_path(self, pathstring):
            """Map the pathstring to the canonical path.

            This could take the form of some regex or an even a more
            explicit conversion.

            If there is no match, return None.

            """

        @abstractmethod
        def unmap_path(self, pathstring):
            """Map the pathstring from a canonical path to this format.

            If there is no match, return None.

            """

    class Path:
        ...
        _formats = []
        @classmethod
        def register_format(cls, format):
            cls._formats.append(format)

        def map_path(self, pathstring):
            for format in self._formats:
                result = format.map_path(pathstring)
                if result is None:
                    continue
                # remember which format matched?
                return result
            raise TypeError("No formatters could map the pathstring.")

        def unmap_path(self, pathstring):
            ...

With something like that, you have a PathFormat class for each
platform that matters.  Anyone would be able to add more, as they
like, through register_format.  This module could also include a few
lines to register a particular PathFormat depending on the platform
determined through sys.platform or whatever.

This way your path class doesn't have to try to worry about the
conversion to and from the canonical path format.

-eric

>
> --
> Steven
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list