Duck Typing and Python

I recently learned about the term duck typing, as it pertains to Python (and, I gather, to some other programming languages as well). If you’re not familiar, the idea is to evaluate an object’s suitability for use by the methods it exposes rather than by its type. The name comes from the adage (paraphrased): if it quacks like a duck, walks like a duck, and swims like a duck, it’s a duck.

When you write a function or method in Python, the convention is that you should use duck typing. Rather than calling type(x) to validate a parameter, you should test the functionality of the object. Obviously, duck typing is for complex classes, not for Python’s built-in types. If, for example, you need a string, checking to see whether a parameter is a string is still the right call in most cases.

But, enough talk, time for examples. Take a look at the following two classes:

class Human:
    def __init__(self, nationality):
        self.__nationality = nationality

    def speak(self):
        if self.__nationality == 'English':
        elif self.__nationality == 'American':
        elif self.__nationality == 'French':
            print('The {} person doesn\'t seem to understand you.'.format(self.__nationality))

class Dog:
    def speak(self):

Both of these classes have a method called speak. The Human class defines a pseudo-constructor that takes a nationality, while no pseudo-constructor is defined for the Dog class. Note that the signatures of the speak methods of the two classes are identical.

Here are two functions that take an object as their only parameter:

def talk_to(human):
    if type(human) != Human:
        raise TypeError


def flex_talk_to(entity):
    except AttributeError:
        raise TypeError

The first function, talk_to uses traditional static type checking. It will only work with an object of type Human.

The second function, flex_talk_to does not use a static type check. Instead, it tries the speak method of the object passed to it, and raises a type error if the object doesn’t have such a method. Note that AttributeError is the exception that Python raises whenever you try to access an attribute that an object doesn’t have (a reminder that a method is really just an attribute that happens to be a function). In this example, we catch the attribute error and raise a type error, because the catch is serving the purpose of a type check.

Now let’s define some variables to show how these functions react.

jacques = Human('French')
hildy = Human('German')
spot = Dog()
pi = 3.14159

The simplest case is pi. Either function will raise a type error, because an integer is not type Human, and it does not have a speak method.

Both jacques and hildy will work fine with either function. And spot will work with flex_talk_to, but will result in a type error is passed to talk_to.

As you’ve no doubt worked out, the flex_talk_to function is using duck typing. As long as the object that you pass to it has a speak method, it behaves as though the object is the type that we wanted.

Now imagine that you have an object with a speak method that does something other than print out a message. You can no doubt see that duck typing can potentially cause problems. Of course, how likely are those problems to arise? If you’re documenting your functions properly, it should be clear what the requirements for them are—you should never be passing objects to functions on faith alone. In any case, I’m not here to discuss the relative merits of static type checking versus duck type checking. That’s a philosophical issue you’ll have to come to terms with on your own.

Duck typing seems to be in keeping with Python’s philosophies and quirks to me. Rather than questioning the practice, I want to say a few words about how duck typing exemplifies Python’s take on some common programming concepts. Duck typing is the dynamic type checking solution to the problem that is solved by interfaces (or protocols, depending on what language you’re using) in statically-typed languages. An interface is the signature of an object’s functionality that ensures that the object can interact with other objects that consume and rely on that same functionality. An interface is a formal way of saying that you don’t care what object you’re dealing with, or how it does things under the covers, as long as it interacts with other objects in predictable ways. Duck typing is far less formal, perhaps frighteningly so.

A lot of Python’s philosophy seems at first to me like a leap of faith. As a language, it doesn’t clutter up its syntax with formalities. It relies instead on the notion that programmers are going to act in good faith and use their own code properly most of the time. For someone like me, who was trained in an older school of programming, the lack of formality and static definition can cause some intellectual vertigo: the language feels chaotic and unfixed. But I think that my uneasiness is largely unfounded. Not only are most of the potentially vague or ambiguous bits of Python’s syntax typically clear in practice, that vagary may encourage programmers to clarify with helpful comments, which are more concise and human-readable than interface definitions and the like. Also, no amount of formal definition will ever substitute for complete documentation and description of your functions and objects. The preference for duck typing is just another way that Python seems to trust reality over formality. It encourages you not to try to ward yourself against every improbable pitfall, but to write flexible, readable code with proper documentation. And that’s a good thing in my book.

Some thoughts about Python

I have been cultivating a real appreciation for Python over the last year or so, and am trying to immerse myself more deeply in the hopes of more consistently using it as part of my paid work. This is my first post about it, so I thought I’d give an overview of my impressions so far.

One of the most common contexts in which I hear Python lauded is as a language that’s friendly to newcomers. Often cited is its emphasis on prioritizing readability. I’ve been skeptical about this kind of assertion from the start, but couldn’t really articulate why until recently.

Certainly Python has many of the hallmarks of a good introductory language:

  • It uses English-like operators pretty much wherever possible.
  • It enforces indentation and other formatting that make it readable.
  • It doesn’t bog down code with lots of strange characters.
  • It makes command-line input and output very simple.

(And many more!)

But it also has characteristics that can be really complicating for the beginner or casual programmer, for example:

  • It supports modular, object-oriented, and functional programming models indiscriminately and interchangeably. This can make it really confusing to navigate.

  • It supports some syntactically complicated things like method chaining and multiple assignment that make code hard to follow if you aren’t already used to that paradigm.

    I would argue, for example, that this code:

    mystr = '    This is a string THAT I wrote!  '
    thatloc = mystr.strip().lower().find('that')

    Is infinitely harder to follow for a new programmer than:

    mystr = '    This is a string THAT I wrote!  '
    mystr = mystr.strip()
    mystr = mystr.lower()
    thatloc = mystr.find('that')

    Even though the former is unquestionably more efficient to write, and easy enough for an experienced Python programmer to understand.

  • It has strongly typed variables that are not explicit, making type problems non-intuitive for the student. Here it occupies a middle ground between an explicitly-typed language like C and a much looser language like VB  and that middle ground is kind of weird (more on this weirdness later).

  • While a very high-level language, it has pockets of low-level usage scattered throughout. For example, it uses zero-based indexes for lists and tuples.

The more I use Python and get used to its quirks, the more I get the feeling that it occupies a very strange space: at its core, it presents a simple syntax that is uncomplicated enough for the most unseasoned beginner, but it packs a tremendous amount of power into the core language, and much more with even just the standard library of modules. While the core functionality makes it seem like a language intended for learning, like old-school BASIC, it also has the features to do almost anything. There’s a strange mix of simplicity and functionality that can be disorientating for the student of the language. There are times when it feels like a high-level language for people who like the concepts of a much lower-level language, like C. In fact, even though there are other implementations, the most common Python is written in C and has libraries written in C.

The standard library shows its roots in places. If you want to get at command line arguments for your script, you can use sys.argv, which is very much analogous to the argv used in C. You can also use the getopt module, which has the stated purpose of being similar to a C function (getopt()). The difference, of course, is that Python now has a much more fully-featured module, argparse, that makes support for complicated command-line arguments relatively simple to implement. And this is, I think, the source of the strange feeling I have about Python: many of its features began as analogues for C implementations, but over time the library has expanded to provide higher-level versions of the same functionality. Which is to say that, as much as Van Rossum and co. made Python with simplicity and friendliness toward newcomers in mind, it often feels in practice like a high-level language for experienced programmers. Not that I’m complaining it’s precisely that feeling of powerful simplicity that has me hooked on the language. But it does make me wonder about Python as an introductory language. Here I have a hard time, because there’s always a part of me that thinks C is a great learning language that starting with a language that doesn’t hide much under the covers will teach the student about how programs fundamentally work and will pay dividends for their whole programming life. There are times when the only way I can get my head around why Python does something the way it does is my background knowledge about C and about how computers work.

I’ll acknowledge these things, and let others decide the right language to be their first:

  • Python’s popularity exists for a reason. It makes me remember the fun of programming.
  • There’s not much you can’t do with it. It’s not a toy language by a long shot.

Solvable Games, Themes, Mechanics, & Player Expectations

People often talk about “breaking” games. Most of the time, I think what they mean is that they have arrived at a process by which they can win against their particular playgroup (or groups). My board gaming is challenged by the fact that my family will play games with me as a way of spending time together, but none of them are particularly into games. This tends to suit my preference for playing new games regularly (which frustrates them, I’m afraid) because I don’t gain expertise in the games and thereby surpass them in an un-fun way.

But some games see a lot of play, and some of those I don’t seem able to lose. 7 Wonders is one of these. No matter what I do, I seem to do well compared to my family in this game. Last night I played a game of it with my brother, Todd, and Jenifer. I thought I would try monopolizing the gray resources early in the game and thereby get an income from the other two as they tried to stop me from getting a crushing monopoly on science (green) cards. Well, they didn’t try to stop me, so I ended up with an insane collection of science (three full sets of three, plus a couple more).

In our brief debrief, I asked why they didn’t stop me from getting all those easily chained cards. The answer was a little surprising to me. That level of competition is less interesting to them than to thinking positively about their own civilizations. It is more fun for them to more or less ignore my winning tableau and focus on making a satisfying tableau of their own. I feel like this is a case of a mismatch between theme and mechanics. The theme is about building up a civilization, but the game is all about drafting the best pick of limited resources while keeping a shrewd eye on what the other players are doing. It’s not a huge mismatch, but the ways in which a civilization are built are not modeled in the game one for one. Both of my opponents value constructive play over competitive play and destructive play. But in the thematic approach of the game’s designers, civilization isn’t about inward-facing constructive urges so much as it is about competition. So when I say a mismatch of theme and mechanics, it’s really a mismatch between player expectations for this particular group and the experience that is produced by the mechanics in play.

Like any well-conceived game, 7 Wonders models a certain experience of play to reinforce a position on its theme. I don’t know if the designers thought about it like this, but in order to play well, you have to play in a certain way (competitive play with attention paid to restricting limited resources from others). Following through on that way necessarily paints a picture of the rise of ancient civilizations where competition is highlighted.

Compare with the focus of Race for the Galaxy (also about civilization building, albeit far future) and you will see a huge difference in the play experience. RftG is all about the efficient use of internal resources, and finding the best way forward given random opportunities. Both games involve making the right choices from a limited set of tempting options, but in RftG competition is sidelined to a timer mechanism–you have to watch the others to adjust the pace of your development and to try to use their needs (read: action card selection) to your advantage. Playing RftG tells you that you never know what the universe is going to hand you, and that the most important thing is to be aware and make the best use of this things it does.

For a third look a the broad category of civilization games, take a peek at Smallworld (or its predecessor, Vinci). Smallworld has a completely different take on civilizations: each has its moments of glory and then a slow burn to decline, and the most successful players can time things right. One of the things that I most like about Smallworld is that protracted, direct competition is almost always detrimental to the aggressor. So choosing to go to war means reducing your short-term potential for scoring. Yet the game is rife with conflict.  It reinforces a view that conflict is unavoidable, but that you should choose your battles with great care.

The more I think about games, the more I come back to core experiences. What does the game push you to do? It is all well to think about games in terms of mechanics. But the presence of a particular mechanic or procedure tells you very little about the core experience of the game. And a good experience is like a good literary theme, it makes a stand about something, leaving you to ponder it. Just as with literature (and other arts as well) some themes are not to the liking of some people. Consumer beware.


[Monthly Monsterhearts] First Session

This is the second installment of my actual play log of a monthly Monsterhearts game that I’m playing with Jamie Fristrom, Sev Trooskin-Zoller, and Erin Sara Beach-Garcia. You can find the first installment, which contains basic information about the characters in the story, here.

Session 1

As this was our first session, we spent some time talking through our setting (modern day, in a fictionalized Concrete, WA) and doing the homeroom seating chart. I have to say, as an opinionated aside, that I really enjoy the seating charts. Beyond setting up some interesting NPCs for the game, I feel that it really gets a lot of work done setting expectations and normalizing genre for everyone assembled. The results of that work are the characters summarized in my first post.

Scene 1

Miss Mayberry, the home room/English/Social Studies teacher set the class up for some unstructured study time. Tucker, the captain of the wrestling team and our resident asshat, was languidly lobbing spit balls at the back of Logan’s head from two rows back. Logan contacted the Emissary on his smart phone to determine what it would take to cause Tucker to choke on one of the projectiles. The cost, telling Tess (the girl sitting between the two) a secret about himself, was too high, and Logan kept things low-key. Meanwhile, Brooke made a show of going up to the teacher’s desk to ask a question as cover for passing a note to Anita (“This school needs a party. Stat!”). She followed this up with a note to Peter (through the hands of smitten and disgruntled Tom) stating that there would be a party in the woods that night. To Brooke’s chagrin, Peter passed the note on to Tucker.

Scene 2

P.E. for the boys. “Coach” Bartlett was yet again making the class play football, and every fumble and error resulted in running laps. We see Peter making his way slowly around the track, smoking a cigarette. Bartlett tells Preston, his favorite, to stop Peter. Preston throws the ball at Peter, who catches it and tries, ineffectually, to throw it back hard at his head. The “coach” tells Peter he has to come to “football practice” after school.

Scene 3

Meanwhile, in art class, Brooke makes a point of getting an easel next to Amber and asks her to the party. Amber is suspicious of social sabotage of some sort, but eventually promises to come.

Scene 4

Cut to the party that night. It’s out in the woods down by the river. This is the only place for kids to hang out in the area, so it’s well-used. Between Brooke and friends, enough alcohol has been gathered to sate the crowd. Bea is on hand providing weed—it isn’t clear whether she’s selling or giving it away. Brooke is trying to be nice to Amber. She invites her over to where the cooler kids have been hanging out by the inevitable fire and gives her a wine cooler (or more up-to-date girly drink). Tess and Anita aren’t quite convinced that they should be hanging out with Amber, and accuse Brooke of taking her on as a “charity case.” Brooke pulls them aside and tries to get them to stop being bitchy, but they resist and go their separate ways. Brooke is accused of sympathizing with a slut and of being obvious.

Meanwhile, Peter is shotgunning beers with Tucker and they are both a little wasted. Shelly is pissed that Tucker is getting drunk with his buddies instead of her and starts exchanging innuendoes with the more sober Peter. They are both momentarily turned on, but Peter’s conscience gets the better of him, preventing him from going off in the woods with his friend’s girlfriend. Shelly, not in the mood to feel rejected, sees that Tucker isn’t even paying attention and therefor can’t get jealous, and stalks off.

Concurrent with the beginning of the party, Logan dons his ski-mask and prowls the streets “on patrol.” He eventually finds Jeff’s parents behind a bar in mid-drunken-altercation. He tries to cow the dad with his super-heroic presence, but fails and inadvertently insults the mom, who punches him in the face. Undeterred, Logan lays out Jeff’s dad cold. This causes Jeff’s mom, Lacy, to start yelling for help. The bartender-cum-bouncer comes out of the bar with a baseball bat. After a brief exchange, Logan tries to punch the guy, who fends him off easily and takes his ski-mask. After a little more posturing and flailing, Logan leaves.

Back at the party, Peter drunkenly tries to look into the abyss, but fails. He is dazed and woozy from the experience, and in that state he runs into Bea. He convinces her to sit and smoke a joint with him, and turns her on in the process. They go off to Peter’s truck to have sex.

Brooke apologizes to Amber about her bitchy friends and takes her out to lay on the big rock in the middle of the river and look at the stars. They talk for a little while, but Amber continues to be uncomfortable, both socially and physically (it’s cold out on the river late at night). Brooke convinces Amber to go play video games together at Amber’s place (Amber is into video games). Amber still suspects social sabotage, but Brooke walks through the party to the parking lock arm-in-arm with her to reassure her that everything’s okay.

Logan, discouraged and unmasked, decides to go to the party (where better to find trouble, after all?) He arrives to find Tucker smacking Shelly around. With significant help from The Emissary, Logan steps up and give Tucker a little of his own medicine. Tucker leaves, and Logan tries to take advantage of the situation to arouse an already receptive Shelly. After failing that, he joins the party proper and tries to be cool. A group of freshmen seem impressed, particularly Marshall, who seems to admire him. After a short conversation, Logan manages to out himself as a geek.

Logan walks to the parking lot and sees Peter, post-coital, leaning out of the truck, chest-hair bristling and coolly smoking a cigarette. Logan is a bit turned on. They talk a little and Logan realizes that Peter wants to be friends like the old days, but wants Logan to be more cool (or at least less nerdy). Logan tries to be cool by talking about how he punched Tucker, with limited success. He notices that there’s a girl in the truck at some point.

“Who’s that in the truck?” Logan asks.

“I don’t know.” Peter pauses for a beat, then, “Just fucking with you, it’s Bea.”

Peter drives both Bea and Logan home. He drops Bea off first and smacks her ass on the way out of the truck. She’s pissed at him.

Scene 5

While the second half of the party is going on, Brooke and Amber are at Amber’s house playing video games. Brooke isn’t very good at them, but laughs good naturedly whenever Amber shoots her in the head. After a while of letting things unwind on their own, Brooke starts to offer some physical reassurance—a hand on a shoulder, for instance. Soon they are making out on the couch. It’s obvious that Amber is craving affection. It doesn’t go any farther than that. As she leaves, Brooke gets Amber to promise that she’ll try to stand up for herself more, at least when she has Brooke to back her up.

[Monthly Monsterhearts] Who’s Who

This is the first account of the Monsterhearts game that I’m playing once a month with Jamie Fristrom, Sev Trooskin-Zoller, and Erin Sara Beach-Garcia. It’s mostly a record for us to remember what the heck is going on between widely-spaced sessions, but it might be interesting to others (though, probably not—play reports are kind of like describing the details of your marathon run to someone who wasn’t there).

Dramatis Personae

Sev graciously volunteered to MC for us, leaving three player characters. We’re all juniors in a fictionalized version of Concrete, WA (it’s a real place, look it up). Heading up toward the mountains in the middle of nowhere, with lots of trees and whatnot around. Our school is a commuter high school for the small towns in the surrounding area.

Logan, The Infernal (Jamie)

Logan is a nerd who discovered a “secret equation” on his computer that, it turns out, is something bad called the Emissary. Logan is a lonely kid, mostly ignored, not too much picked on. This one time, at the end of last year, Logan’s mom made him go to a school dance so he could “meet people”. He was miserable and alone, and Brooke danced with him. Since then, he’s been watching her, a little. He and Peter used to be besties when they were little, but Logan retreated into his nerdy pursuits at some point and they drifted apart.

Logan may or may not be bisexual. Or, rather, he probably is, but he hasn’t worked it all out yet.

Peter, The Werewolf (Erin Sara)

Peter is a tough kid who manages a level of popularity while still being a little removed from the popular kids. He hangs out with Tucker, the captain of the wrestling team (which is where the jocks are in absence of a football team) but isn’t on the team and seems to have some influence over him that we haven’t really figured out yet.

Last year, Peter was at an epic party out in the woods where everyone was wasted. He got bitten by a werewolf, but the memories weren’t all that clear. He’s slowly learning the extent of his abilities (or, if you prefer, curse). Peter and Logan were tight when they were kids, but they drifted apart as Logan began to withdraw into his nerdiness. Peter has been watching him, hoping that there was a way to get back what they once had. Recently, he drove Logan into “the city” (Bellingham) to get some computer parts or something, and Logan kind of owes him one for it.

Brooke, The Fae (Jay)

Brooke was born into a family that lived out in the middle of nowhere, even by the standards of concrete. Her parents were always at each other’s throats. When she was 10 she ran away into the woods and was “never found”. The parents soon split up and moved away. She was actually found by a full-blooded Fae who had chosen to live among mortals for reasons as yet unknown. Her adopted mother bestowed the gifts of the fae on her and they moved to Concrete together.

Brooke is on the volleyball team and is reasonably popular. There was that time last year when she danced with Logan at the Spring Fling to make the other girls stop laughing at him.


In no particular order.


Tom is into Brooke and sits right behind her in home room. She’s been nice to him, partly because she’s “nice to everybody,” and partly because he’s a good photographer, and is helping her get the school newspaper off the ground.


Apart from Logan, Jeff is the smartest kid in class. He’s well-rounded in his academics and is relatively cheerful. He is, at least in part, motivated to do well because he fears his abusive parents.


Bea’s dad is the go to pot dealer in town. She likes the money and what they can do with it, but tries not to think too hard about where it comes from. Very recently, she was walking on the train trestle with Tess and Mary. She was stoned and fooling around, and caused Mary to get caught and hit by a train.


Used to be friends with Bea, but blames her (rightly, it would seem) for Mary’s death. At least nominally friends with Brooke.


He’s a geek, but isn’t comfortable in the role. He’s nearsighted, but won’t wear his glasses, because he doesn’t want to look like a nerd.


Captain of the wrestling team. A douchebag.


Held back a year because last year she got pregnant and had an abortion. She likes to play video games.

Miss Mayberry

Home room teacher. She was the prom queen at school a decade or more ago, and tries to continue in that mode. Plays favorites.


Brooke’s best friend. She’s into theater and, perhaps, “drama”.


Tucker’s #1 crony. Sheldon’s cousin. He’s not comfortable with how much control Peter has over his friends, and wants to be top dog himself.

“Coach” Bartlett

Would be the football coach if there was a team. Uses P.E. as an excuse to indulge his gridiron fantasies. Trying to get Peter to be one the non-existent team, for which he holds practices and everything.


“Coach” Bartlett’s favorite suck-up.


The queen bee of the junior class. Dating Tucker. Not a nice person.


Jeff’s mom. Abused., but not all sunshine herself.

RPGs vs. Story Games



A year ago, I would have told you that I didn’t like the term “story games”. It seemed to me to be a slightly elitist term for roleplaying games used by slightly elitist gamers who wanted to put some distance between themselves and the dysfunction and baggage of “traditional” games like Dungeons & Dragons. I still can’t confidently tell people the difference beyond the mind-numbingly simple (“a story game is a game where you make a story”). However, I have come a long way in that year, partly because I have had a chance to put in a lot more play time on games that can’t be confused with D&D at all–games like Fiasco and A Penny for My Thoughts.

Most importantly, I’ve internalized a lot about the kind of play that happens at the Story Games Seattle Meetup group. Those gatherings demand that a whole and complete story be played out in 3-4 hours, (usually) without a centralized authority, and with zero prep. To make that work, you need games that create and support dynamic situations quickly. You need games that often feel very different from the traditional model to play. In short, you need story games. And my designer’s mind has really embraced the idea.

In my mind, I’ve started calling them story-making games. That is, games where the story is made by playing the game instead of ahead of time. I’ve found this so much more satisfying than traditional play that I find myself looking for ways to eliminate the game master from games that have them by default.

So, yeah, I’m okay with “story games” as a thing now. Which is not to diminish the fun that many people still have with traditional RPGs. It’s better for both activities to differentiate.

Fiasco Night was not a Fiasco!

I facilitated an evening of Fiasco for five tables of four players each last night at the Center for Serious Play at UWB. It was a blast! I was kind of bummed to not be playing, but it was hilarious to run from table to table and overhear a variety of crazy scenes in progress.

I don’t know yet if I have any new converts to Story Games, but everyone seemed to heave a great time.