0

This is new question because this question.

I want to extend set to make custom set of file names in a folder:

class FilesSet(set):

    def __init__(self, in_dir = None):
        set.__init__(self, ())

        self.in_dir = ''
        self.files = set()        

        if in_dir:        
            self.in_dir = in_dir        
            self.files = set(map(os.path.basename, 
                             glob.glob(self.in_dir + "/*.txt")))


    def __contains__(self, item):
        return item in self.files

    def __len__(self):
        return len(self.files)

    def __iter__(self):
        return iter(self.files)     

When I try it:

f1 = FilesSet(in_dir = inDir1)
f2 = FilesSet(in_dir = inDir2)

c1 = f1 | f2
c2 = f1 & f2

print(c1, c2)

c1 and c2 are empty. Why? Should I overwrite other methods from set? From link i think i only need to define contains, len and iter. Other methods like or(), sub(), xor() are for performance only, I understand.

Community
  • 1
  • 1
user3654650
  • 5,283
  • 10
  • 27
  • 28
  • 3
    If you want `|` and `&` to operate on your `files` attribute instead of the object itself, then yes, you need to override them. There isn't much point in inheriting from `set` if you're going to create *another* set as an attribute and store all the data there. Either make your own type that defines the operations you need, or inherit from `set` and store the data by directly manipulating `self`. – BrenBarn Jun 09 '14 at 04:54
  • If all you want is input validation, then just extend `set` and wrap the `__init__()` function and other mutation functions like `add()` and `update()` to do the validation. – Addison Jun 09 '14 at 06:02

0 Answers0