[Python-ideas] Context helper for new os.*at functions

Christian Heimes lists at cheimes.de
Sun Jun 17 02:13:49 CEST 2012


Python 3.3 has got new wrappers for the 'at' variants of low level
functions, for example os.openat(). The 'at' variants work like their
brothers and sisters with one exception. The first argument must be a
file descriptor of a directory. The fd is used to calculate the absolute
path instead of the current working directory.

File descriptors are harder to manage than files because a fd isnt't
automatically closed when it gets out of scope. I've written a small
wrapper that takes care of the details. It also ensures that only
directories are opened.


with atcontext("/etc") as at:
    # functools.partial(<built-in function openat>, 3)
    f = at.open("fstab", os.O_RDONLY)
    print(os.read(f, 50))


The code calculates the name and creates dynamic wrapper with
functool.partial. This may not be desired if the wrapper is added to the
os module. I could add explicit methods and generate the doc strings
from the methods' doc strings.

def docfix(func):
    name = func.__name__
    nameat = name + "at"
    doc = getattr(os, nameat).__doc__
    func.__doc__ = doc.replace("{}(dirfd, ".format(nameat),
    return func

class atcontext:

    def open(self, *args):
        return self.openat(self.dirf, *args)

How do you like my proposal?


More information about the Python-ideas mailing list