1

Suppose you have the following dataclass

@dataclass
class Task:
    subTasks: Optional[List[Task]]

This is not possible, since Task is not declared yet.

I am using Python 3.6 w/ dacite + dataclasses to parse a large dictionary into a dataclass.

Currently I've been doing it like this:

from dataclasses import dataclass
from dacite import from_dict

@dataclass
class Task:
    subTasks: Optional[List]

    def process_sub_tasks(self) -> None:
        cls = type(self)
        if self.subTasks:
            self.subTasks = [from_dict(data_class=cls, data=d) for d in self.subTasks]
            for subtask in self.subTasks:
                subtask.process_sub_tasks()

I was wondering if there's a way to type subTasks somehow to make it know that it is also a List[Task] object, rather than a generic List

NinjaKitty
  • 638
  • 7
  • 17
  • Incidentally, it's a lot cleaner to have `subTasks` be an empty list instead of `None` for a task with no subtasks. – user2357112 Jun 13 '19 at 00:59
  • Maybe. However, I am writing this to mostly be identical to the product I'm testing, so that the typing listed on the API Documentation for the product is identical to what's written here. It helps in maintaining future changes, since the product is still changing a lot.. I do agree with you though, that subTasks should ideally always be a List. – NinjaKitty Jun 13 '19 at 01:06
  • I also noticed with the duplicated question, that it would require that I pass forward references to every call to `from_dict` in `dacite` using `Config(forward_references={"Y": Y})` (which is inconvenient :/) otherwise subTasks elements won't have that type, which I assume would only be solved via 3.7's annotation. – NinjaKitty Jun 13 '19 at 01:11
  • If anyone else is reading, this doesn't work with `pydantic` in python 3.6 because of [Issue 463](https://github.com/samuelcolvin/pydantic/issues/463) – NinjaKitty Jun 13 '19 at 18:01

0 Answers0