Skip to content

path

Utility path/pathlib functions.

Functions

try_joinpath

try_joinpath(
    path: Path, *others: str | Path
) -> Path | None

Test and return joined path if it exists.

This function is especially useful when used with walrus operator (:=).

Example:

if p := try_joinpath(some_dir, "subdir", "file.txt"):
    with open(p, "r") as f:
        ...

Parameters:

  • path

    (Path) –

    path to test

  • others

    (str | Path, default: () ) –

    other paths to join

Returns:

  • Path | None

    full joined path if it exists or None

Source code in ipsl_common/path.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
def try_joinpath(path: Path, *others: str | Path) -> Path | None:
    """Test and return joined path if it exists.

    This function is especially useful when used with walrus operator (:=).

    Example:

        if p := try_joinpath(some_dir, "subdir", "file.txt"):
            with open(p, "r") as f:
                ...

    Args:
        path: path to test
        others: other paths to join

    Returns:
        full joined path if it exists or None
    """
    new_path = path.joinpath(*others)
    return new_path if new_path.exists() else None

try_path

try_path(path: Path) -> Path | None

Test and return path if it exists.

This function is especially useful when used with walrus operator (:=).

Example:

if p := try_path(some_file):
    with open(p, "r") as f:
        ...

Parameters:

  • path

    (Path) –

    path to test

Returns:

  • Path | None

    path if it exists or None

Source code in ipsl_common/path.py
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def try_path(path: Path) -> Path | None:
    """Test and return path if it exists.

    This function is especially useful when used with walrus operator (:=).

    Example:

        if p := try_path(some_file):
            with open(p, "r") as f:
                ...

    Args:
        path: path to test

    Returns:
        path if it exists or None
    """
    return path if path.exists() else None