1

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
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Blueynuey
  • 23
  • 2
  • Do the answers to this [question](https://stackoverflow.com/questions/11351032/named-tuple-and-default-values-for-optional-keyword-arguments) help at all? – quamrana Jan 24 '23 at 11:21
  • 3
    Have you considered using a [`dataclass`](https://docs.python.org/3/library/dataclasses.html) instead? Then set `frozen=True` to prevent assignment. See [Is there an alias or name parameter for dataclass arguments?](https://stackoverflow.com/q/72170886/2745495) – Gino Mempin Jan 24 '23 at 13:44
  • 1
    What exactly do you mean by "alias"? Do you want that you can access `metadata.init_version` and get `metadata.project_version`? – mkrieger1 Jan 24 '23 at 13:53
  • And if so, why do you think that's preferable to having a single name for this particular attribute of your data structure? – chepner Jan 24 '23 at 13:54
  • 1
    This is part of a much larger codebase, essentially I want to deprecate `project_version` by renaming it with `init_version` but still want it to be backwards compatible. I can't change it directly as this would be a breaking change and not backwards compatible. I want to treat `project_version` and `init_version` as being the same. – Blueynuey Jan 24 '23 at 14:41

1 Answers1

1

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
mkrieger1
  • 19,194
  • 5
  • 54
  • 65