Home > Mobile >  Define a Class in Python that has a property of it's own Class (recursion)
Define a Class in Python that has a property of it's own Class (recursion)

Time:12-08

I'm trying to model a file-system structure in Python. My file-system has two types of objects:

  • File: always has a containing_folder
  • Folder: optionally has a containing_folder

I have the following code now:

class Folder:
    def __init__(self, name: str, containing_folder: Folder):
        self.name = name
        self.containing_folder = containing_folder

class File:
    def __init__(self, name: str, size: int, containing_folder: Folder):
        self.name = name
        self.containing_folder = containing_folder

I get the following error on def __init__() when defining Class Folder:

NameError: name 'Folder' is not defined

I understand why I get the error, but I don't know how to fix it. I can omit the type from the parameter containing_folder but I'd rather be explicit about it.

Questions

  • Any ideas on how to define this recursive structure?
  • Any ideas on how to make the containing_folder optional for the Class Folder?

CodePudding user response:

When using type hint of a class inside itself, you need to surround it with quotes (or double quotes).

class Folder:
    def __init__(self, name: str, containing_folder: 'Folder'):
        self.name = name
        self.containing_folder = containing_folder

CodePudding user response:

You should import annotations from __futures__ and it will work as expected. To make containing_folder optional, just add a default value like None and add typing information about optional value:

from __future__ import annotations
from typing import Optional


class Folder:
    def __init__(self, name: str, containing_folder: Optional[Folder] = None):
        self.name = name
        self.containing_folder = containing_folder


class File:
    def __init__(self, name: str, size: int, containing_folder: Folder):
        self.name = name
        self.containing_folder = containing_folder

Note: Optional[Folder] == Folder | None for python >= 3.10 or Optional[Folder] == Union[Folder, None] for all python 3 versions.

  • Related