How to alias class attributes when creating NamedTuple?

272 views Asked by At

I want to alias project_version with init_version, but since NamedTuple is a factory method I'm having difficulty in doing this.

from typing import NamedTuple

class ProjectMetadata(NamedTuple):
    """Structure holding project metadata derived from `pyproject.toml`"""

    config_file: Path
    package_name: str
    project_name: str
    project_path: Path
    project_version: str
    source_dir: Path

I've tried the basic alias technique but met with undefined init_version errors.

from typing import NamedTuple

class ProjectMetadata(NamedTuple):
    """Structure holding project metadata derived from `pyproject.toml`"""

    config_file: Path
    package_name: str
    project_name: str
    project_path: Path
    project_version: str = init_version
    source_dir: Path
1

There are 1 answers

0
mkrieger1 On

You can simply add a property named init_version to the class which returns the project_version attribute:

class ProjectMetadata(NamedTuple):
    # ...
    project_version: str

    @property
    def init_version(self) -> str:
        return self.project_version