PEP 355 – Path - Object oriented filesystem paths | peps.python.org
PEP 355 – Path - Object oriented filesystem paths PEP 355 – Path - Object oriented filesystem paths Author : Björn Lindqvist <bjourne at gmail.com> Status : Rejected Type : Standards Track Created : 24-Jan-2006 Python-Version : 2.5 Post-History : Table of Contents Rejection Notice Abstract Background Motivation Rationale Specification Replacing older functions with the Path class Deprecations Closed Issues Open Issues Reference Implementation Examples References and Footnotes Copyright Rejection Notice This PEP has been rejected (in this form).
The proposed path class is the ultimate kitchen sink; but the notion that it’s better to implement all functionality that uses a path as a method on a single class is an anti-pattern. (E.g. why not open() ? Or execfile() ?) Subclassing from str is a particularly bad idea; many string operations make no sense when applied to a path. This PEP has lingered, and while the discussion flares up from time to time, it’s time to put this PEP out of its misery.
A less far-fetched proposal might be more palatable. Abstract This PEP describes a new class, Path , to be added to the os module, for handling paths in an object oriented fashion. The “weak” deprecation of various related functions is also discussed and recommended. Background The ideas expressed in this PEP are not recent, but have been debated in the Python community for many years. Many have felt that the API for manipulating file paths as offered in the os.path module is inadequate.
The first proposal for a Path object was raised by Just van Rossum on python-dev in 2001 [2] . In 2003, Jason Orendorff released version 1.0 of the “path module” which was the first public implementation that used objects to represent paths [3] . The path module quickly became very popular and numerous attempts were made to get the path module included in the Python standard library; [4] , [5] , [6] , [7] . This PEP summarizes the ideas and suggestions people have expressed about the path module and proposes that a modified version should be included in the standard library.
Motivation Dealing with filesystem paths is a common task in any programming language, and very common in a high-level language like Python. Good support for this task is needed, because: Almost every program uses paths to access files. It makes sense that a task, that is so often performed, should be as intuitive and as easy to perform as possible. It makes Python an even better replacement language for over-complicated shell scripts.
Currently, Python has a large number of different functions scattered over half a dozen modules for handling paths. This makes it hard for newbies and experienced developers to choose the right method. The Path class provides the following enhancements over the current common practice: One “unified” object provides all functionality from previous functions. Subclassability - the Path object can be extended to support paths other than filesystem paths.
The programmer does not need to learn a new API, but can reuse their knowledge of Path to deal with the extended class. With all related functionality in one place, the right approach is easier to learn as one does not have to hunt through many different modules for the right functions. Python is an object oriented language. Just like files, datetimes and sockets are objects so are paths, they are not merely strings to be passed to functions.
Path objects is inherently a pythonic idea. Path takes advantage of properties. Properties make for more readable code: if imgpath . ext == 'jpg' : jpegdecode ( imgpath ) Is better than: if os . path . splitexit ( imgpath )[ 1 ] == 'jpg' : jpegdecode ( imgpath ) Rationale The following points summarize the design: Path extends from string, therefore all code which expects string pathnames need not be modified and no existing code will break.
A Path object can be created either by using the classmethod Path.cwd , by instantiating the class with a string representing a path or by using the default constructor which is equivalent to Path(".") . Path provides common pathname manipulation, pattern expansion, pattern matching and other high-level file operations including copying. Basically Path provides everything path-related except the manipulation of file contents, for which file objects are better suited.
Platform incompatibilities are dealt with by not instantiating system specific methods. Specification This class defines the following public interface (docstrings have been extracted from the reference implementation, and shortened for brevity; see the reference implementation for more detail): class Path ( str ): # Special Python methods: def __new__ ( cls , * args ) => Path """ Creates a new path object concatenating the *args. *args may only contain Path objects or strings.
If *args is empty, Path(os.curdir) is created. """ def __repr__ ( self ): ... def __add__ ( self , more ): ... def __radd__ ( self , other ): ... # Alternative constructor. def cwd ( cls ): ... # Operations on path strings: def abspath ( self ) => Path """Returns the absolute path of self as a new Path object.""" def normcase ( self ): ... def normpath ( self ): ... def realpath ( self ): ... def expanduser ( self ): ... def expandvars ( self ): ... def basename ( self ): ... def expand ( self ): ... def splitpath ( self ) => ( Path , str ) """p.splitpath() -> Return (p.parent, p.name).""" def stripext ( self ) => Path """p.stripext() -> Remove one file extension from the path.""" def splitunc ( self ): ... # See footnote [1] def splitall ( self ): ... def relpath ( self ): ... def relpathto ( self , dest ): ... # Properties about the path: parent => Path """This Path's parent directory as a new path object.""" name => str """The name of this file or directory without the full path.""" ext => str """ The file extension or an empty string if Path refers to a file without an extension or a directory.
""" drive => str """ The drive specifier. Always empty on systems that don't use drive specifiers. """ namebase => str """ The same as path.name, but with one file extension stripped off. """ uncshare [ 1 ] # Operations that return lists of paths: def listdir ( self , pattern = None ): ... def dirs ( self , pattern = None ): ... def files ( self , pattern = None ): ... def walk ( self , pattern = None ): ... def walkdirs ( self , pattern = None ): ... def walkfiles ( self , pattern = None ): ... def match ( self , pattern ) => bool """Returns True if self.name matches the given pattern.""" def matchcase ( self , pattern ) => bool """ Like match() but is guaranteed to be case sensitive even on platforms with case insensitive filesystems.
""" def glob ( self , pattern ): # Methods for retrieving information about the filesystem # path: def exists ( self ): ... def isabs ( self ): ... def isdir ( self ): ... def isfile ( self ): ... def islink ( self ): ... def ismount ( self ): ... def samefile ( self , other ): ... # See footnote [1] def atime ( self ): ... """Last access time of the file.""" def mtime ( self ): ... """Last-modified time of the file.""" def ctime ( self ): ...
""" Return the system's ctime which, on some systems (like Unix) is the time of the last change, and, on others (like Windows), is the creation time for path. """ def size ( self ): ... def access ( self , mode ): ... # See footnote [1] def stat ( self ): ... def lstat ( self ): ... def statvfs ( self ): ... # See footnote [1] def pathconf ( self , name ): ... # See footnote [1] # Methods for manipulating information about the filesystem # path. def utime ( self , times ) => None def chmod ( self , mode ) => None def chown ( self , uid , gid ) => None # See footnote [1] def rename ( self , new ) => None def renames ( self , new ) => None # Create/delete operations on directories def mkdir ( self , mode = 0777 ): ... def makedirs ( self , mode = 0777 ): ... def rmdir ( self ): ... def removedirs ( self ): ... # Modifying operations
The rest of this page is on the live site.