Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Yaml on dumping giving different result #783

Open
sorreu99 opened this issue Feb 7, 2024 · 0 comments
Open

Yaml on dumping giving different result #783

sorreu99 opened this issue Feb 7, 2024 · 0 comments

Comments

@sorreu99
Copy link

sorreu99 commented Feb 7, 2024

I have a class EnhancedString which basically inherits from str used for a enum created lets say Pets such that Pets.DOG will give me str representation directy 'dog' but when passing it as in dictionary as a key against a value and on dumping it is giving different output since it is understanding it as the object of EnhancedString not str but I want to dump it as if it is a str only.

class EnumDirectValueMeta(EnumMeta):
"""Metaclass to fetch the value of the enum directly."""

def __getattribute__(self, name):
    value = super().__getattribute__(name)
    if isinstance(value, self):
        value = value.value
    return value

class EnhancedString(str):
def new(cls, seq, display_name=None, is_deprecated=False):
instance = super().new(cls, seq)
instance.__display_name = display_name or seq.replace('_', ' ').title()
instance.__is_deprecated = is_deprecated
return instance

@property
def display_name(self):
    return self.__display_name

@property
def is_deprecated(self):
    return self.__is_deprecated

class EnhancedEnum(Enum, metaclass=EnumDirectValueMeta):
"""Class to facilitate the Enum creation with metaclass EnumDirectValuesMeta.
"""
pass

class StringifiedEnum(EnhancedEnum):
def new(cls, value, name=None):
instance = EnhancedString(value, display_name=name)
return instance

class Pets(StringifiedEnum):
DOG = ('Fido', 'Hey Fido!')
CAT = ('Kitty', 'Hey Kitty!')
TIGER = ('Tiger')

my_dict = {Pets.DOG : 'hey fido', 'home': 'India', 'travelled_place': ['usa','Australia']}
import yaml

isinstance(Pets.DOG , str)

True

type(Pets.DOG)
<class 'main.EnhancedString'>

output = yaml.dump(my_dict)

print(output)

_? !!python/object/new:main.EnhancedString
args:

  • Fido
    state:
    _EnhancedString__display_name: Hey Fido!
    _EnhancedString__is_deprecated: false
    _EnhancedString__seq: Fido
    objclass: !!python/name:main.Pets ''
    name: DOG
    value: !!python/tuple
    • Fido
    • Hey Fido!
      : hey fido
      home: India
      travelled_place:
  • usa
  • Australia_
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant