Question Details

No question body available.

Tags

python string object path pathlib

Answers (1)

May 23, 2026 Score: 2 Rep: 166,209 Quality: Medium Completeness: 60%

In modern Python, in code under my control, I convert to a pathlib.Path as soon as I can and always pass that around. This addresses the naming ambiguity you describe, gives you a richer API, and makes it immediately clear in type annotations what the value is.

def replacestringinfile(file: Path, original: str, replacement: str) -> None:
  ...

If it's unavoidable, or if it will clarify things, you can have the variable name end in "path". For example, in a FastAPI route (where variable names become HTTP query parameters) you might say

UPLOADDIR: Path = ...

@app.get("/something") def something(path: Annotated[str, Query()]) -> None: if "/" in path: raise ValueError("invalid path") uploadpath = UPLOADDIR / path ...

I don't personally like an ambiguous str | Path parameter, in part because I often enough want to write code that can operate on a file content. So, is the "string" form "foo.csv", or "col1,col2\n1,2,3\n"? You'll also inevitably wind up immediately normalizing it to either a string or a Path immediately so you don't have duplicated code paths, and it'd be better to name the specific type you need up front.