Search code examples
pythonpython-class

Pass class type as argument to class constructor


Say I have a Directory class which accepts a list of other sub-directories as an argument:

class File:
    pass

class Directory:
    def __init__(self, directories: List[Directory], files: List[File]):
                                         ^^^^^^^^^
        self.directories = directories
        self.files = files

I am getting an error saying "Directory" is not defined. This code works just fine if I don't pass the types, but how do you handle this use-case in python?


Solution

  • What you need is a recursive typing definition. This can be achieved in Python by providing a string with the name of the type, rather than the type itself.

    class File:
       pass
    
    class Directory:
       def __init__(self, directories: List['Directory'], files: List[File]):
          self.directories = directories
          self.files = files