Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python pathlib operator '/' - how does it do it?

Tags:

I found the pathlib syntax - or is it the python syntax - surprising. I'd like to know how this makes the forward slash '/' act as a joiner of windowspaths etc. Does it override/overload '/' ? It seems to be in a magical context, the slash is between a WindowsPath type object and a string. If I try between 2 strings it fails to join the 2 strings (i.e. "123" / "123" -> fails)

p=pathlib.Path(".")  p Out[66]: WindowsPath('.')  p.cwd() Out[67]: WindowsPath('C:/Users/user1')  p.cwd() / "mydir" Out[68]: WindowsPath('C:/Users/user1/mydir') 
like image 759
JoePythonKing Avatar asked Oct 31 '18 13:10

JoePythonKing


People also ask

How does Pathlib work in Python?

Since Python 3.4, pathlib has been available in the standard library. With pathlib , file paths can be represented by proper Path objects instead of plain strings as before. These objects make code dealing with file paths: Easier to read, especially because / is used to join paths together.

What does import Pathlib do in Python?

Pathlib module in Python provides various classes representing file system paths with semantics appropriate for different operating systems. This module comes under Python's standard utility modules. Path classes in Pathlib module are divided into pure paths and concrete paths.

Does Python come with Pathlib?

The pathlib library is included in all versions of python >= 3.4.


1 Answers

The Path class has a __truediv__ method that returns another Path. You can do the same with your own classes:

>>> class WeirdThing(object):         def __truediv__(self, other):             return 'Division!'  >>> WeirdThing() / WeirdThing() 'Division!' 
like image 111
AbyxDev Avatar answered Oct 27 '22 11:10

AbyxDev