[Python-ideas] Dunder method to make object str-like

Random832 random832 at fastmail.com
Thu Apr 7 14:43:40 EDT 2016

On Thu, Apr 7, 2016, at 13:30, Ethan Furman wrote:
> The protocol is "the how" of supporting pathlib, and, interestingly 
> enough, the easiest way to do so (avoids circular imports, etc., etc,.).

If the problem is importing pathlib, what about a "pathlib lite" that
can check if an object is a path without importing pathlib? This could
be a recipe, a separate module, or part of os.

def is_Path(x):
    return 'pathlib' in sys.modules and isinstance(x,

def path_str(x):
    if isinstance(x, str): return x
    if isPath(x): return x.path
    raise TypeError

# convenience methods for modules that want to support returning a Path
but don't import it
def to_Path(x):
    import pathlib
    return pathlib.Path(x)

# most common case, return a path iff an input argument is a path.
def to_Path_maybe(value, *args):
   if any(is_Path(arg) for arg in args):
      return to_Path(value)
      return value

All this other stuff seems to have an ambition of making these things
fully general, such that some other library can be dropped in instead of
pathlib without subclassing either str or Path, and I'm not sure what
the use case for that is. Pathlib is the battery that's included.

More information about the Python-ideas mailing list