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

Ethan Furman ethan at stoneleaf.us
Sun Apr 10 17:31:15 EDT 2016

On 04/10/2016 02:24 PM, Nikolaus Rath wrote:
> On Apr 09 2016, Nick Coghlan wrote:

>> The equivalent motivating use case here is "allow pathlib objects to
>> be used with the open() builtin, os module functions, and os.path
>> module functions".
> Why isn't this use case perfectly solved by:
> def open(obj, *a):
>     # If pathlib isn't imported, we can't possibly receive
>     # a Path object.
>     pathlib = sys.modules.get('pathlib', None):
>     if pathlib is not None and isinstance(obj, pathlib.Path):
>         obj = str(obj)
>     return real_open(obj, *a)

pathlib is the primary motivator, but there's no reason to shut everyone 
else out.

By having a well-defined protocol and helper function we not only make 
our own lives easier but we also make the lives of third-party libraries 
and experimenters easier.


More information about the Python-ideas mailing list