4

The first method found by auto-complete on a pathlib.Path is absolute().

It seems to just prepend Path.cwd() at the start:

>>> from pathlib import Path
>>> path = Path('./relative/path') / '../with/some/../relative/parts'
Path('relative/path/../with/some/../relative/parts')
# calling absolute...
>>> absolute_path = path.absolute()
Path('/[current_dir]/relative/path/../with/some/../relative/parts')
# does the same as prepending cwd at the start
>>> Path.cwd() / path
Path('/[current_dir]/relative/path/../with/some/../relative/parts')

However, Path.absolute() is not listed in the pathlib documentation.

Compare this to Path.resolve(), which does the opposite (replace relative parts but don't prepend cwd) and is documented.

Can I use absolute() or should I avoid it?

florisla
  • 12,668
  • 6
  • 40
  • 47

1 Answers1

4

No.

At least up until Python version 3.8, you should avoid using Path.absolute().

According to the discussion in the bug report about the missing documentation, absolute() is not tested, and therefore not officially advertised. In fact, it might even be removed in a future release of Python.

So it's safer to just use Path.cwd() instead.

>>> # make path absolute if it isn't already
>>> path = Path.cwd() / path
Path('/[current_dir]/relative/path/../with/some/../relative/parts')

It's not necessary to check beforehand using Path.is_absolute() since cwd() / path will not change a path that's already absolute.

florisla
  • 12,668
  • 6
  • 40
  • 47