Using a properties file

We have two choices for how we use a properties file. We could follow the design pattern of configparser and parse multiple files to create a single mapping from the union of the various values. Alternatively, we could follow the ChainMap pattern and create a sequence of property mappings for each configuration file.

The ChainMap processing is reasonably simple and provides us with all the required features:

pp = PropertyParser()

candidate_list = [prop_file]
config = ChainMap(
*[dict(pp.read_file(file))
for file in reversed(candidate_list)
]
)

We've taken the list in reverse order: the most specific settings will be first in the internal list, while the most general settings will be the last. Once ChainMap has been loaded, we can use the properties to initialize and build our Player, Table, and Simulate instances.

This seems simpler than updating a single mapping from several sources. Additionally, this follows the pattern used to process JSON or YAML configuration files.

We can use a method like this to exploit ChainMap. This is very similar to the main_cm() function mentioned previously. We'll only show you the first part, which builds the Table instance:

import ast

def main_cm_prop(config):
dealer_nm = config.get("table.dealer", "Hit17")
dealer_rule = {"Hit17": Hit17(), "Stand17": Stand17()}.get(dealer_nm, Hit17())
split_nm = config.get("table.split", "ReSplit")
split_rule = {
"ReSplit": ReSplit(), "NoReSplit": NoReSplit(), "NoReSplitAces": NoReSplitAces()
}.get(
split_nm, ReSplit()
)
decks = int(config.get("table.decks", 6))
limit = int(config.get("table.limit", 100))
payout = ast.literal_eval(config.get("table.payout", "(3,2)"))
table = Table(
decks=decks, limit=limit, dealer=dealer_rule, split=split_rule, payout=payout
)

The difference between this version and the main_cm() function is the handling of the payout tuple. In the previous version, JSON (and YAML) could parse the tuple. When using the properties files, all values are simple strings. We must use eval() or ast.literal_eval() to evaluate the given value. The other portions of this main_cm_str() function are identical to main_cm().

Using the properties file format is one way to persist configuration data. In the next section, we'll look at using XML syntax to represent configuration parameters.

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

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