0

A while back I came across this code on Stack Overflow for locking a directory:

import os
import fcntl
import time

class LockDirectory(object):
    def __init__(self, directory):
        assert os.path.exists(directory)
        self.directory = directory

    def __enter__(self):
        self.dir_fd = os.open(self.directory, os.O_RDONLY)
        try:
            fcntl.flock(self.dir_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except IOError as ex:             
            raise Exception('Somebody else is locking %r - quitting.' % self.directory)
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        # fcntl.flock(self.dir_fd,fcntl.LOCK_UN)
        os.close(self.dir_fd)

def main():
    with LockDirectory("test") as lock:
        newfd = os.dup(lock.dir_fd)
    with LockDirectory("test") as lock2:
        pass

if __name__ == '__main__':
    main()

I use OOP often with Python, however I rarely use dunder methods with the exception of the occasional __str__ method. How is it possible that the self.dir_fd doesn't have to be declared in the initializer and how are __exit__ and __enter__ called in this example?

  • "How is it possible that the self.dir_fd doesn't have to be declared in the initializer?" Python does not require you to declare anything in `__init__`. You can add attributes to an object at any time. – Mateen Ulhaq May 11 '20 at 04:58
  • Well it's too late as the question was closed, but I guess I had meant that typically Pycharm will warn that the initializer doesn't have the variable declared. But in this case Pycharm also doesn't issue the warning. –  May 11 '20 at 14:26

0 Answers0