Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading