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

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


Hello,

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.

Example:

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

Code:
http://pastebin.com/J4SLjB6k

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),
                               "{}(".format(name))
    return func

class atcontext:
    ...

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


How do you like my proposal?

Christian




More information about the Python-ideas mailing list