[Python-ideas] Working with Path objects: p-strings?
Paul Moore
p.f.moore at gmail.com
Wed Mar 30 06:45:24 EDT 2016
On 30 March 2016 at 10:58, Sven R. Kunze <srkunze at mail.de> wrote:
>> That's fine, but I also don't want to have the worry of latent bugs lurking
>> in code either due to implicit type compatibility and so that clashes in
>> this instance.
>
> Could you give an example here?
def fix_path(p):
# Old code, possibly in a module.
# Quite possibly it does a lot more than
# simply calling abspath, so it might not
# be easy to review
return os.path.abspath(p)
# Elsewhere
p = Path(sys.argv[1])
if not p.is_absolute():
p = fix_path(p)
# Now a relative p is no longer a Path object. Later in your code,
possibly somewhere
# miles away if you rely heavily on paths being interchangeable with
strings, you get
# an AttributeError when you try to use a Path method on p.
Obviously the issue here is trivial to spot. But in real code, it
could be a mess of complex logic, with a single os.path call somewhere
in an obscure conditional branch. Possibly fix_path has even been
updated to work with pathlib, but that one os.path call was
accidentally missed and there's no test covering it.
Before you say so, of course this is a made up scenario, and of course
it'll likely be rare. The question isn't whether such things are
common, so much as whether the cost of requiring explicit conversion
to string is worth the benefit of avoiding situations like this. And
that's a hard judgement call. For casual scripters, and people doing
research, the answer is "clearly not". For teaching new users,
probably not (new users won't make this sort of mistake, but equally
having to teach what a string subclass is relatively early is maybe an
issue). For people writing mission critical software, very definitely
yes (as a pip developer, I'd hate to switch pip over to a str-subclass
path object, whereas switching to a non-subclass one is much more
conceivable[1]).
Paul
[1] Backward compatibility, not wanting another dependency (on the
pathlib backport) and the fact that it's change for no actual benefit
mean we'd probably not bother anyway, but that's a different decision.
More information about the Python-ideas
mailing list