[Edu-sig] a local peak (as in mountain top)

kirby urner kirby.urner at gmail.com
Thu Feb 11 19:57:08 EST 2016


In calculus we encounter "local maxima" in our manifold, i.e. mountain
peaks, from where the view is grand (other mountains stretch across the
horizon).

One such peak in Python is:  seeing a decorator turn a generator into a
context manager.

Getting this construct down may take more than one pass and certainly more
than one code sample.  The beauty is in so many concepts meshing together.
Epiphanies are possible, even likely.

In the code below, I'm building up "context manager" as a concept.  Our
theme at <guild /> is games, as in board games, even more than computer
games.

What would your job look like, if gamified i.e. turned into a board game?
Imagine inventing a board game to help a complete noobie learn the ropes.
What would be the rules, on the back of the box.  Now code it? The goal is
more something grammatically correct, than heavy duty.  It's a doodle, a
runnable poem.

The exercise of coding something one is familiar with, such as an
institution and its workflows, is about killing two virtual birds:
 learning the grammar of a new computer language; tackling programming as
an exercise in simulating, where the knowledge domain is one the student
already knows (e.g. working in a restaurant).

We see people tackling widgets in inventory, students in classrooms,
computing GPAs, but what about modeling the school more completely, or the
factory?  Invent some more classes e.g. FacultyMeeting.

I'll post one more example today, of what I consider intermediate
orange-to-green belt Python code i.e. ascending through keywords:

yield try: except: finally: with (with cm() as obj)

with added decorator syntax.

We already know about instances, class and static methods by this point.

We'll spiral back to yield later, to take on 'yield from' at a higher level.

Sticking to core Python with a cherry pick approach to modules, standard
library and 3rd party, is how I'm playing it.

The goal of the black belt is to not be stopped by any unknown keywords at
least, i.e. a reading knowledge of Python involves not remaining in the
dark about any of the core locutions / constructs.

But then each new level is also a chance to harness related, now more
within reach concepts.

Like when we get to yield (and the builtins: next send iter), that's the
time to stress "iterator" as an "interface" (in the sense of API) involving
__next__ and __iter__.

That discussion paves the way for the "interface" of a context manager
(__enter__ and __exit__), or a descriptor.

Also, each new level is a place to introduce more special names (or
__ribs__ as I sometimes call them).  We don't get to them all at once.

The special names are like Kanji (Chinese characters).  Add a few, get to
know them, add a few more, and so on.

Kirby


# -*- coding: utf-8 -*-
"""
Created on Thu Feb 11 10:16:34 2016

@author: Kirby Urner
"""

from collections import namedtuple
from random import randint

Survivor = namedtuple("Survivor", "name nick") # name, nickname

survivors = [Survivor("Joe","Dr. J."),
             Survivor("Sheila","Miss S."),
             Survivor("Eric","Monty"),
             Survivor("Prince","Prince"),
             Survivor("Thelma", "Da Queen"),
             Survivor("Peter", "the Spamster")]

class Game_Island:
    """
    VERY unconventional to not use 'self' as the instance placeholder
    but we're learning the grammar and therefore bend the rules
    """
    def __init__(island, survivors):  # context manager setup
        island.survivors = survivors

    def __enter__(island):
        return island # named Island within the context scope below

    def draw_straws(island):
        return island.survivors.pop(randint(0, len(island.survivors)-1))

    def __exit__(island, *exception_data):
        # maybe this isn't about exceptions, just crowning the winner
        print("The Last Survivor is...{winner.name} aka '{winner.nick}'".\
                format(winner=island.survivors[0]))
        if exception_data[0]:
            # uh oh....
            return False  # re-raise!  Something unexpected...
        return True


with Game_Island(survivors) as Island:  # Gilligan's?
    while len(Island.survivors) > 1:
        loser = Island.draw_straws()  # Island knows who they are
        print(("{loser.name} aka '{loser.nick}'" + \
        " is off the island").format(loser = loser))
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/edu-sig/attachments/20160211/16ec7e2c/attachment-0001.html>


More information about the Edu-sig mailing list