2

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
5
  • Do the answers to this question help at all? Commented Jan 24, 2023 at 11:21
  • 3
    Have you considered using a dataclass instead? Then set frozen=True to prevent assignment. See Is there an alias or name parameter for dataclass arguments? Commented Jan 24, 2023 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? Commented Jan 24, 2023 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? Commented Jan 24, 2023 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. Commented Jan 24, 2023 at 14:41

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.