[Python-Dev] Add os.path.resolve to simplify the use of os.readlink

Phil Vandry vandry at TZoNE.ORG
Thu Jun 21 15:46:12 CEST 2012


On 2012-06-21 06:23, Armin Ronacher wrote:
> Due to an user error on my part I was not using os.readlink correctly.
> Since links can be relative to their location I think it would make sense
> to provide an os.path.resolve helper that automatically returns the
> absolute path:
>
>      def resolve(filename):
>          try:
>              target = os.readlink(filename)
>          except OSError as e:
>              if e.errno == errno.EINVAL:
>                  return abspath(filename)
>              raise
>          return normpath(join(dirname(filename), target))
>
> The above implementation also does not fail if an entity exists but is not
> a link and just returns the absolute path of the given filename in that
> case.

It's expensive (not to mention racy) to do this correctly, when any 
component of the pathname (not just the component after the last slash) 
might be a symlink. For example:

mkdir -p foo1/foo2
touch bar
ln -s ../../bar foo1/foo2/symlink
ln -s foo1/foo2 foo

Now try to resolve "foo/symlink" using your function. It produces 
"../bar", which doesn't exist.

Why not just work with the pathname you're given and let the kernel 
worry about resolving it?

-Phil


More information about the Python-Dev mailing list