YAML 解析为对象 (PyYAML Python3)
YAML parsing to Objects (PyYAML Python3)
我有以下代码:
class Settings:
def __init__(self, annual_volatility_target):
self.annual_volatility_target = annual_volatility_target
self.daily = annual_volatility_target/np.sqrt(252)
def yaml_load(name):
with open('yaml/' + str(name) + '.yaml', 'r') as ymlfile:
return yaml.load(ymlfile)
settings = yaml_load("settings")
使用以下 YAML:
!!python/object:v.Settings
annual_volatility_target: 0.25
问题是,当我加载 settings
时,settings.daily
没有设置。 settings.annual_volatility_target
是,无论我在 __init__
中是否这么说。
如果我手动实例化一个 Settings
对象(即不使用 PyYAML),它工作正常。
我做错了什么?
一种可能是为Settings
写一个constructor:
import yaml
import numpy as np
class Settings:
def __init__(self, annual_volatility_target):
self.annual_volatility_target = annual_volatility_target
self.daily = annual_volatility_target/np.sqrt(252)
def yaml_load(name):
with open(str(name) + '.yaml', 'r') as ymlfile:
return yaml.load(ymlfile)
def settings_constructor(loader, node):
fields = loader.construct_mapping(node)
return Settings(fields['annual_volatility_target'])
yaml.add_constructor('!v.Settings', settings_constructor)
settings = yaml_load("settings")
print(settings.annual_volatility_target)
print(settings.daily)
我必须使用修改后的 yaml
文件(我无法使用注释 !!python/object:v.Settings
):
!v.Settings
annual_volatility_target: 0.25
Python PyYAML 中的对象分两步构建。首先调用 __new__
(在 Constructor.make_python_instance()
中),然后设置属性(在 Constructor.set_python_instance_state()
中)。这两个步骤是必需的,因为 YAML 支持对对象的引用,如果该对象是(间接)自引用的,则不能一次性构建它,因为它所依赖的参数(包括自身)尚不可用。
您可以通过两种方式解决这个问题。您可以为 Settings
定义 __setstate__()
,这将用 dict
调用,也可以从 __init__()
调用:
import yaml
yaml_str = """\
!!python/object:try.Settings
annual_volatility_target: 0.25
"""
class Settings:
def __init__(self, annual_volatility_target):
self.__setstate__({annual_volatility_target: annual_volatility_target})
def __setstate__(self, kw):
self.annual_volatility_target = kw.get('annual_volatility_target')
self.daily = self.annual_volatility_target/np.sqrt(252)
def __repr__(self):
return "Setting({}, {})".format(self.annual_volatility_target, self.daily)
settings = yaml.load(yaml_str)
print(settings)
另一个更通用的(非 PyYAML)解决方案是在首次访问时创建 daily
值:
class Settings:
def __init__(self, annual_volatility_target):
self.annual_volatility_target = annual_volatility_target
@property:
def daily(self):
return annual_volatility_target/np.sqrt(252)
如果您经常访问 daily
,那么您应该将其缓存在例如self._daily
第一次计算值:
class Settings:
def __init__(self, annual_volatility_target):
self.annual_volatility_target = annual_volatility_target
self._daily = None
@property:
def daily(self):
if self._daily is None:
self._daily = annual_volatility_target/np.sqrt(252)
return self._daily
我有以下代码:
class Settings:
def __init__(self, annual_volatility_target):
self.annual_volatility_target = annual_volatility_target
self.daily = annual_volatility_target/np.sqrt(252)
def yaml_load(name):
with open('yaml/' + str(name) + '.yaml', 'r') as ymlfile:
return yaml.load(ymlfile)
settings = yaml_load("settings")
使用以下 YAML:
!!python/object:v.Settings
annual_volatility_target: 0.25
问题是,当我加载 settings
时,settings.daily
没有设置。 settings.annual_volatility_target
是,无论我在 __init__
中是否这么说。
如果我手动实例化一个 Settings
对象(即不使用 PyYAML),它工作正常。
我做错了什么?
一种可能是为Settings
写一个constructor:
import yaml
import numpy as np
class Settings:
def __init__(self, annual_volatility_target):
self.annual_volatility_target = annual_volatility_target
self.daily = annual_volatility_target/np.sqrt(252)
def yaml_load(name):
with open(str(name) + '.yaml', 'r') as ymlfile:
return yaml.load(ymlfile)
def settings_constructor(loader, node):
fields = loader.construct_mapping(node)
return Settings(fields['annual_volatility_target'])
yaml.add_constructor('!v.Settings', settings_constructor)
settings = yaml_load("settings")
print(settings.annual_volatility_target)
print(settings.daily)
我必须使用修改后的 yaml
文件(我无法使用注释 !!python/object:v.Settings
):
!v.Settings
annual_volatility_target: 0.25
Python PyYAML 中的对象分两步构建。首先调用 __new__
(在 Constructor.make_python_instance()
中),然后设置属性(在 Constructor.set_python_instance_state()
中)。这两个步骤是必需的,因为 YAML 支持对对象的引用,如果该对象是(间接)自引用的,则不能一次性构建它,因为它所依赖的参数(包括自身)尚不可用。
您可以通过两种方式解决这个问题。您可以为 Settings
定义 __setstate__()
,这将用 dict
调用,也可以从 __init__()
调用:
import yaml
yaml_str = """\
!!python/object:try.Settings
annual_volatility_target: 0.25
"""
class Settings:
def __init__(self, annual_volatility_target):
self.__setstate__({annual_volatility_target: annual_volatility_target})
def __setstate__(self, kw):
self.annual_volatility_target = kw.get('annual_volatility_target')
self.daily = self.annual_volatility_target/np.sqrt(252)
def __repr__(self):
return "Setting({}, {})".format(self.annual_volatility_target, self.daily)
settings = yaml.load(yaml_str)
print(settings)
另一个更通用的(非 PyYAML)解决方案是在首次访问时创建 daily
值:
class Settings:
def __init__(self, annual_volatility_target):
self.annual_volatility_target = annual_volatility_target
@property:
def daily(self):
return annual_volatility_target/np.sqrt(252)
如果您经常访问 daily
,那么您应该将其缓存在例如self._daily
第一次计算值:
class Settings:
def __init__(self, annual_volatility_target):
self.annual_volatility_target = annual_volatility_target
self._daily = None
@property:
def daily(self):
if self._daily is None:
self._daily = annual_volatility_target/np.sqrt(252)
return self._daily