This article is the first in a series that studies the design of a module import system. Although this work is situated in the Python context it can stay on its own to a large extent and ideas may be transferred to other systems and languages. We will provide as much integration with Python as necessary but keep the structure as general as possible. The article series will roughly cover following topics:
- Path objects – module paths and their representation
- ModuleNode objects – loading and caching modules using Path objects
- Import system – binding ModuleNode objects to import statements
- Implementation – putting it all together in an EasyExtend langlet as a reference implementation
In this article we will discuss `Path` objects. This topic is foundational and a bit dry but I hope the reader will be compensated by the elegance of some its constructions. `Path` objects are used to establish a relationship between internally used name spaces and external path structures in physical or logical “media” like file-systems, zip-files or the web. Those path structures can also be fully abstract and represented by special data-structures only. We’ll provide several examples.
First some terminology is introduced. Many of the notions given here a rather abstract but they mostly capture what people know about Python modules, packages and file system paths anyway. They provide a conceptual background for specifications given later.
TerminologyA module name is an ordinary Python name: a finite sequence of alphanumeric characters and underscores starting with an alphabetic character or underscore. A module path is a dot-separated sequence of module names. It is possible for a module path to be preceded by dots. In that case a module path is called a relative path. `A.B.C` and `..A.B.C` are both module paths but only the latter one is relative. The names of a module path are also called its components. So `A`, `B`, `C` are the components of the module path `A.B.C`.
Besides module paths we consider external paths. The intuitive meaning of an external path is that of a pointer to a location of a module in some medium. Most commonly file system paths are used as external paths: modules are represented as files and the dot separators are mapped onto file-system separators. Throughout this article we use a slash “/” as an external path separator. So `A.B.C` is a module path and `A/B/C` is an external path. A proper external path definition is given below using a `Path` abstract base class.
A module can be loaded from an external path which yields an interpreter level <`module`> object. Each <`module`> object shall have a unique module name. If `M` is a known module name we write <`M`>. It is also possible to load <`module`> objects from builtins or even create fresh <`module`> objects on the fly. In any case we still consider a <`module`> being loaded from a path. If no such path is available we associate the <`module`> with the empty path.
A module path `A.B.C…` is valid if an external path `…/A/B/C/…` exists and `` can be loaded from `…/A`, `` can be loaded from `…A/B` etc.
We call a module `P` a package if there is a module `M` and if `P1.M` and `P2.M` are valid module paths then `P1 = P2 = P`. So each module has at most one package. If a module has no package we call it an unpackaged or a free module. For any module the chain of packages `P1.P2….M` containing M shall be finite. This implies that each of such chains has a maximum length. If `P0.P1.P2…M` is a a module path of maximal chain of packages we call `P0` a top level module and the module path a full path. Each unpackaged module is by definition also a top level module.
Notice that the concept of a namespace is a little more general than the ones we have defined. Each <`module`> has an associated namespace. This is usually a `__dict__` for user defined modules. This namespace can contain other modules as well and might be changed dynamically. We rather intend to have a close reference of the module path concept with the way it is used in an import statement.
With `PYTHONPATH` we denote a set of external paths from which modules can be found. Those paths can represent file-system paths, zip-files or other entities. The `PYTHONPATH` may contain external paths that are paths of some package. In this case the modules we can reach from the `PYTHONPATH` are not all top-level modules. In this situation the top-level module `P0` of a full path `P0.P1…..M` may not be reachable from `PYTHONPATH`. We call such a full path a finger.
The intuitive idea of an external path as a file path is actually a bit too simplistic. In practice there might be various files that might correspond to a module. For example `A.py`, `A.pyc`, `A.pyd` are all files that correspond to a Python module `A`. An external path is a class of file paths and they are equivalent in the sense that they all describe a single module entity. In this sense a set of file suffixes is an equivalence class of file paths.
Path objectsPath objects are defined as abstract base classes. Concrete subclasses of `Path` are `FSPath` which uses file system operations to implement `Path`methods, `ZipPath` which combines file system path operations with those provided by the <`zipfile`> module. We have also defined a silly `Path` subclass called `TuplePath`. All of those `Path` objects are used to represent external paths or path-like objects.
from abc import * class Path: __metaclass__ = ABCMeta def __init__(self, pathobj): self.path = pathobj @abstractmethod def fullpath(self): ''' Derives full module path from given path. ''' def find(self, modulepath): ''' Interprets the modulepath as a sequence of parent / joinpath operations. ''' P = self components = modulepath.split(".") if components[-1] == '': components.pop() for component in components: if component is "": P = P.parent() else: P = P.joinpath(component) if not P.exists(): raise ValueError("invalid path object: '%s'"%P.path) return P @abstractmethod def ispackage(self): ''' Returns true if path belongs to a package and false otherwise. ''' @abstractmethod def ismodule(self): ''' Returns True if path corresponds with a Python module and False otherwise. ''' @abstractmethod def isempty(self): ''' Returns True if this path object is empty and False otherwise. ''' @abstractmethod def exists(self): ''' Returns True if the path object is valid and False otherwise. ''' return self.path in self.files @abstractmethod def parent(self): ''' If path is .../A/B/C a new path object initialized by .../A/B will be created and returned. ''' @abstractmethod def children(self): ''' All valid one element extensions of path. If there are no such children return None. ''' @abstractmethod def joinpath(self, *args): ''' Joins the current path object with those provided by args in the sequence of occurrence in args. So if this path is ../A/B then self.joinpath('C/D', 'E') will return ../A/B/C/D/E. ''' @abstractmethod def base(self): ''' Returns the rightmost element of a path. If ../A/B/C is a path it C will be returned. ''' @abstractmethod def split(self): ''' Returns a tuple containing path components. ''' @abstractmethod def splitbase(self): ''' Returns the tuple (parent, base) for a given path. ''' def __repr__(self): return "<%s : %s>"%(self.__class__.__name__, self.path)
The methods `find` and `fullpath` establish the relationship between `Path` objects and module paths. The `fullpath` method is intended to return the module path that corresponds to the `Path` object. The concrete `find` method is a representation of a module path in terms of the `parent` and `joinpath` methods which are also defined in the `Path` class. So each module path has a an unambiguous interpretation as a sequence of operations on a `Path` object.
FSPath objectsNow we start looking at concrete examples. The first and most important example is that of the `FSPath` class which relies on file system operations defined in `os.path`. The `FSPath` object enables configurable file suffixes. In Python file-suffix data are hardcoded. They can be accessed using the
import os import imp class SuffixInfo(object): def __init__(self, suffix_data): self.suffix = suffix_data self.read_mode = suffix_data self.priority = suffix_data class FSPath(Path): modulesuffixes = set() def __init__(self, pathobj): self.path = pathobj @classmethod def add_suffix(cls, suffixinfo): cls.modulesuffixes.add(suffixinfo) def fullpath(self): if self.ismodule(): module = self.base() name, ext = os.path.splitext(module) P = self.parent().fullpath() return P+"."+name if P else name elif self.ispackage(): directory, name = self.splitbase() P = directory.fullpath() return P+"."+name if P else name else: return "" def ispackage(self): if os.path.isdir(self.path): if os.path.isfile(self.path+os.sep+"__init__.py"): return True return False def isempty(self): return self.path == "" def exists(self): return self.ispackage() or self.ismodule() def ismodule(self): suffixes = [""]+[suffix.suffix for suffix in self.modulesuffixes] for suffix in suffixes: if os.path.isfile(self.path+suffix): return True return False def parent(self): return self.__class__(os.path.dirname(self.path)) def children(self): if os.path.isdir(self.path): return [self.__class__(self.path.join(f)) for f in os.path.listdir(self.path)] def joinpath(self, *args): return self.__class__(os.sep.join([self.path]+list(args))) def base(self): return os.path.basename(self.path) def split(self): return self.path.split(os.sep) def splitbase(self): return self.parent(), self.base()
The next two path objects have separate listings.