Collections and delegating format specifications
When formatting a complex object that includes a collection, we have two formatting issues: how to format the overall object and how to format the items in the collection. When we look at Hand
, for example, we see that we have a collection of individual Cards
class. We'd like to have Hand
delegate some formatting details to the individual Card
instances in the Hand
collection.
The following is a __format__()
method that applies to Hand
:
def __format__( self, format_specification ): if format_specification == "": return str(self) return ", ".join( "{0:{fs}}".format(c, fs=format_specification) for c in self.cards )
The format_specification
parameter will be used for each individual Card
instance within the Hand
collection. The format specification of "{0:{fs}}"
uses the nested format specification technique to push the format_specification
string to create a format that applies to each Card
instance. Given this method, we can format a Hand
object, player_hand
, as follows:
"Player: {hand:%r%s}".format(hand=player_hand)
This will apply the %r%s
format specification to each Card
instance of the Hand
object.