0

I have a class like this:

from __future__ import annotations

import os
from dataclasses import dataclass


@dataclass(frozen=True)
class Config:
    name: str
    age: str

    @staticmethod
    def init() -> Config:
        return Config(
            name=...
            age=...
        )

I would like to ensure that the init method always returns the same instance of Config.

I could achieve this by doing something like this:

@dataclass(frozen=True)
class Config:
    name: str
    age: str

    @staticmethod
    def init() -> Config:
        if not _private_instance:
            global _private_instance = Config(
                name=...
                age=...
            )
        return _private_instance

_private_instance: Optional[Config] = None

But I am wondering if there is a more Pythonic way of doing this.  Thanks
sixtyfootersdude
  • 23,394
  • 39
  • 132
  • 200
  • Does this answer your question? [Creating a singleton in Python](https://stackoverflow.com/questions/6760685/creating-a-singleton-in-python) – quamrana May 11 '21 at 19:54
  • There's nothing wrong with your approach. I would say, the singleton pattern like this is not without it's detractors... and it's not something that is very common in Python – juanpa.arrivillaga May 11 '21 at 20:09
  • @quamrana - Thanks for the link. I read through that answer before posting. That question doesn't really work for my question. I am primarily interested in how to do this while using a `@dataclass`. – sixtyfootersdude May 11 '21 at 20:55

0 Answers0