Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to annotate a dataclass' attribute as another dataclass' object?

I have two dataclasses like:

from dataclasses import dataclass
from pathlib import Path

@dataclass
class InnerDataClass:
    host: str

@dataclass
class OuterDataClass:
    directory: Path
    host: InnerDataClass

When I call OuterDataClass(...), Python returns the error NameError: name 'InnerDataClass' is not defined on the last line. Why does it do this and how can I resolve it?

like image 537
A1122 Avatar asked Jan 19 '26 21:01

A1122


1 Answers

Your example actually works, you probably had the order of classes the other way round in your actual code. Python code files get executed line by line, so when the first classe's class body is executed, the second class needs to exist already. You have to declare classes in the order that matches their internal hierarchy from bottom to top if you want things to work.


But if all you're doing is annotating and not actual instance creation, you can also do this:

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path


@dataclass
class OuterDataClass:
    directory: Path
    host: InnerDataClass

@dataclass
class InnerDataClass:
    host: str

Running from __future__ import annotations as the first line of your code file will make annotations work, no matter the order classes were defined in. It was introduced as PEP 563 to help, among other things, with circular dependencies.

like image 177
Arne Avatar answered Jan 21 '26 11:01

Arne