Curieux.JY
  • Post
  • Note
  • Jung Yeon Lee

On this page

  • Config Class
  • Class to Dict
  • Dict to Yaml
  • Yaml to Dict
  • Dict to Class

👩‍💻class ⟷ dict ⟷ yaml

config
yaml
code
여러 파라미터들을 기록하기 위한 config 관리
Published

December 26, 2022

Config Class

기준이 되는 부모 class AConfig

  • 자식 class가 같은 하위 class에 override 할 때는 이름을 바꾸지 않음

  • 부모 class에 없었던 하위 class를 만들 경우 자식Class의 이름(e.g. B, C) 활용

  • 대문자는 Config 객체의 ID

  • 소문자는 한개의 Config 클래스 객체 내에서의 하위 class 순서

class AConfig():
    class A_a_Config:
        element01 = "element01"
        element02 = True
    class A_b_Config:
        element03 = 0
        element04 = [2,4,6]

BConfig는

  • AConfig의 A_a_Config를 override

  • AConfig의 A_b_Config를 override 하지 않음

  • B_a_Config 추가

class BConfig(AConfig):
    class A_a_Config:
        element02 = False
    # class A_b_Config:
    #     pass
    class B_a_Config:
        element05 = {"key":"value"}

CConfig는

  • AConfig의 A_a_Config를 override

  • AConfig의 A_b_Config를 pass로 override

  • C_a_Config 추가

class CConfig(AConfig):
    class A_a_Config:
        element02 = False
    class A_b_Config:
        pass
    class C_a_Config:
        element05 = {"key":"value"}

DConfig는

  • AConfig의 A_a_Config를 인자로 받아 override

  • AConfig의 A_b_Config를 인자로 받아 override

class DConfig(AConfig):
    class A_a_Config(AConfig.A_a_Config):
        element02 = False
    class A_b_Config(AConfig.A_b_Config):
        pass

EConfig는

  • __init__(super)로 Aconfig 상속
class EConfig(AConfig):
    def __init__(super): pass
    class E_a_Config:
        element06 = (1,3,5)

Class to Dict

class 객체를 dictionary로 만들기

def class_to_dict(obj) -> dict:
    if not hasattr(obj, "__dict__"):                # __dict__ : 클래스 객체의 속성 정보를 확인하기 위해 사용. 객체가 가진 여러가지 속성들을 딕셔너리 형태로 편하게 확인
        return obj
    result = {}                                     # 빈 dict 객체 만들기
    for key in dir(obj):                            # dir(): 어떤 객체를 인자로 넣어주면 해당 객체가 어떤 변수와 메소드(method)를 가지고 있는지 나열
        if key.startswith("_"):                     # startswith: str.startswith(str or tuple) 형식으로 사용하면 되고, 반환 값으로는 True, False를 반환
            continue
        element = []                                # 리스트 요소에 대비
        val = getattr(obj, key)                     # getattr: object에 존재하는 속성의 값을 가져옴
        if isinstance(val, list):                   # isinstance로 list 객체인지 확인 e.g.) isinstance(object, type)
            for item in val:
                element.append(class_to_dict(item))
        else:                                       # 리스트가 아닌 모든 요소들 처리
            element = class_to_dict(val)
        result[key] = element                       # 결과 dict에 저장
    return result
AConfigDict = class_to_dict(AConfig)
AConfigDict
{'A_a_Config': {'element01': 'element01', 'element02': True},
 'A_b_Config': {'element03': 0, 'element04': [2, 4, 6]}}
BConfigDict = class_to_dict(BConfig)
BConfigDict
{'A_a_Config': {'element02': False},
 'A_b_Config': {'element03': 0, 'element04': [2, 4, 6]},
 'B_a_Config': {'element05': {'key': 'value'}}}
CConfigDict = class_to_dict(CConfig)
CConfigDict
{'A_a_Config': {'element02': False},
 'A_b_Config': {},
 'C_a_Config': {'element05': {'key': 'value'}}}
DConfigDict = class_to_dict(DConfig)
DConfigDict
{'A_a_Config': {'element01': 'element01', 'element02': False},
 'A_b_Config': {'element03': 0, 'element04': [2, 4, 6]}}
EConfigDict = class_to_dict(EConfig)
EConfigDict
{'A_a_Config': {'element01': 'element01', 'element02': True},
 'A_b_Config': {'element03': 0, 'element04': [2, 4, 6]},
 'E_a_Config': {'element06': (1, 3, 5)}}

Dict to Yaml

import yaml
from pprint import pprint
AConfigDictYaml = yaml.dump(AConfigDict)
print(AConfigDictYaml)
print(type(AConfigDictYaml))
A_a_Config:
  element01: element01
  element02: true
A_b_Config:
  element03: 0
  element04:
  - 2
  - 4
  - 6

<class 'str'>

Yaml to Dict

AYamlDict = yaml.safe_load(AConfigDictYaml)
pprint(AYamlDict)
{'A_a_Config': {'element01': 'element01', 'element02': True},
 'A_b_Config': {'element03': 0, 'element04': [2, 4, 6]}}

Dict to Class

  • 속성값으로 만들어주는 것이기 때문에 내부 메소드나 내부 클래스가 아닌, 내부 변수와 같음
class Dict2Class(object):
    def __init__(self, input_dict):
        for key in input_dict:
            print("Set arribute: ", key)
            setattr(self, key, input_dict[key]) # object에 존재하는 속성의 값을 바꾸거나, 새로운 속성을 생성하여 값을 부여
AYamlDictClass = Dict2Class(AYamlDict)
Set arribute:  A_a_Config
Set arribute:  A_b_Config
AYamlDictClass.A_a_Config
{'element01': 'element01', 'element02': True}
AYamlDictClass.A_b_Config
{'element03': 0, 'element04': [2, 4, 6]}

Copyright 2024, Jung Yeon Lee