The ability to define how operators behave on structures and classes is one of the cooler features available in modern programming languages. It's one of those things that everyone knows how to do but no one has actually done. Aside, of course, from writing that String class back in CS-215: C++ Programming.

But some are not content with having only overloaded operators in college. These programmers work to use it whenever possible under the guise of "simplifying" things for them self. Take, for example, Tim O's predecessor, who insisted on this creation instead of os.path.join() which was used four or five times throughout the application ...

class path(object):
    '''Utility class for handling paths with less typing.

    str(path("project", "super")) -> "project/super"

    # note the trailing ()
    path("project", "super")() -> "project/super"
    path("project")["s-u-p-e-r"]() -> "project/s-u-p-e-r"
    path("project")a.b.c.super() -> "project/a/b/c/super"
    path("/")() -> "/"
    path("project", ".", "super")() -> "project/super"
    path("project").super[".."]() -> "project"

    The basic idea is: given a starting path object, you can use
    item or attribute access to contruct longer paths.

    The actual path is accessible by converting the object to 
    a string or just calling to object.

    def __init__(self, *args):
        """Set base path"""
        self.base = str(os.path.normpath(os.path.join(*args)))

    def __str__(self):
        """return self as a string """
        return self.str()

    def __call__(self):
        """return self as a string """
        return self.str()

    def str(self):
        """return self as a string """
        return self.base

    def __add__(self, segment):
        """Append a new path from self + component"""
        return path(self.base, str(segment))

    def __getattr__(self, attribute):
        """Append a new path from self + attribute
        It is handy for path.smith = "path/smith"
        return self + attribute

    __getitem__ = __getattr__

    def __cmp__(self, other_object):
        """Compare self to string or other path"""
        other = str(other_object)
        return cmp(self.base, other)

    def __repr__(self):
        """Return representation"""
        return '' % self.base + '- %s' % hash(self.base)

    def __hash__(self):
        """Return a hash of path"""
        return hash(self.base)

[Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!