Loading a YAML configuration

As YAML syntax contains JSON syntax, the previous examples can be loaded with YAML as well as JSON. Here's a version of the nested dictionary-of-dictionaries technique from the JSON file:

# Complete Simulation Settings
table: !!python/object:Chapter_14.simulation_model.Table
dealer: !!python/object:Chapter_14.simulation_model.Hit17 {}
decks: 6
limit: 50
payout: !!python/tuple [3, 2]
split: !!python/object:Chapter_14.simulation_model.NoReSplitAces {}
player: !!python/object:Chapter_14.simulation_model.Player
betting: !!python/object:Chapter_14.simulation_model.Flat {}
init_stake: 50
max_rounds: 100
play: !!python/object:Chapter_14.simulation_model.SomeStrategy {}
rounds: 0
stake: 63.0
samples: 100
outputfile: data/ch14_simulation4c.dat

This is often easier for people to edit than pure JSON. For applications where the configuration is dominated by strings and integers, this has a number of advantages. The process to load this file is the same as the process to load the JSON file:

import yaml 
config = yaml.load("config.yaml") 

This has the same limitations as the nested dictionaries. We don't have an easy way to handle default values unless we flatten out the names.

When we move beyond simple strings and integers, however, we can try to leverage YAML's ability to encode class names and create instances of our customized classes. Here's a YAML file that will directly build the configuration objects that we need for our simulation:

# Complete Simulation Settings 
table: !!python/object:__main__.Table 
  dealer: !!python/object:__main__.Hit17 {} 
  decks: 6 
  limit: 50 
  payout: !!python/tuple [3, 2] 
  split: !!python/object:__main__.NoReSplitAces {} 
player: !!python/object:__main__.Player 
  betting:  !!python/object:__main__.Flat {} 
  init_stake: 50 
  max_rounds: 100 
  play: !!python/object:__main__.SomeStrategy {} 
  rounds: 0 
  stake: 63.0 
samples: 100 
outputfile: data/ch14_simulation4c.dat

We have encoded class names and instance construction in YAML, allowing us to define the complete initialization for Table and Player. We can use this initialization file as follows:

import yaml

if __name__ == "__main__":

config = yaml.load(yaml1_file)
print(config)

simulate(
config["table"],
config["player"],
Path(config["outputfile"]),
config["samples"]
)

This shows us that a YAML configuration file can be used for human editing. YAML provides us with the same capabilities as Python but with a different syntax. For this type of example, a Python configuration script might be better than YAML.

Another format available for configuration parameters is called the properties file. We'll examine the structure and parsing of properties files, and learn how to use them in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset