Select to view content in your preferred language

Add support for pathlib.Path objects to arcpy

5005
16
04-09-2020 09:20 AM
ScottDavis
Frequent Contributor

pathlib seems to be the preferred method for working with system paths in Python 3. We've started using it in place of `os.path` in our office recently and really like it. However, we've run into problems with using it with arcpy. For example:

workspace = pathlib.Path('C:\some path') \ 'anotherfolder' \ 'connection.sde'
with arcpy.EnvManager(workspace=workspace):
    pass‍‍‍‍‍‍

Throws this error: "RuntimeError: Object: Error in accessing environment <workspace>"

To work around this, we end up wrapping all of our Path object with str(). For example:

workspace = str(pathlib.Path('C:\some path') \ 'anotherfolder' \ 'connection.sde')
with arcpy.EnvManager(workspace=workspace):
    pass‍‍‍‍‍‍‍‍‍

It would be great if arcpy (Pro version) handled these Path objects natively!

Tags (2)
16 Comments
KoryKramer

👍Thanks, Shaun!

BlakeTerhune

Thank you for the consideration @ShaunWalbridge😊

EthanSchaefer

It seems to me that one (partial?) solution would be to wrap each function/method so that any passed object with a __fspath__ method is converted to the result of calling that method. This is essentially the same logic behind os.fspath(), which returns arbitrary strings unchanged, even if they couldn't possibly represent a path. Of course, it sequences of paths must also be covered, that could be accommodated, too. But if there are more complicated scenarios that I haven't anticipated, they may be harder to support.

Incidentally, the basic approach I outlined is how I deal with this problem (at an abstract level) when generating scripts on the fly and passing them via propy.bat.

philnagel

Is there any progress on this? It's quite annoying to be stuck with legacy path handling from Python 2, or always having to manually convert paths to strings, just because arcpy still does not support pathlib almost 3 years after this idea was posted.

OliviaHughes

I'd really like to upvote this as well. I want to use pathlib Path objects in my scripts as we use that as standard procedure for other file handling scripts. Having to break this pattern due to the arcpy library is really inconvenient. 

subora_iastate

I agree with Olivia, any progress incorporating pathlib would be greatly appreciated. Maybe I am mistaken, but I think just being able to pass pathlib.Path types into parameter fields would be sufficient.