[Baypiggies] puzzle: binding invocation context for a function call during a class declaration

Bill Janssen janssen at parc.com
Fri Dec 31 21:09:55 CET 2010

I'm puzzling out how one would ape a declarative language in Python.
For instance, take a language that has declarations like

  concept Foo {
    is-a A;
    is-a B;
    part-of X;

    public int counter;
    public analogue bar;

  expression Bletch {

    expresses Foo;

    counter = 3;

where "concept", "public", "is-a", "part-of", "int", "analogue",
"expression", and "expresses" are all keywords.

Since it's largely declarative, I'd naturally express it in Python as a
set of class declarations:

  from mylang import is_a, part_of, Concept, Expression, attribute, public, analogue, expresses

  class Foo (Concept):


    counter = attribute(public, int)
    bar = attribute(public, analogue)

  class Bletch (Expression):

    counter = 3

Now, my question is, how can I capture the invocation context of a
function, so that I can know that "is_a(A)" is being called as part of
the definition of class "Foo"?  Do functions called during the
evaluation of a class leave their return result somewhere, for instance,
so that I could define a metaclass to do something with that result?

Right now, I'm using the fragile workaround of

  _relationships = []
  def _store_relationship (x, rel):
      primary = inspect.stack()[2][0].f_code.co_name
      _relationships.append((primary, rel, x))
  is_a = lambda x: _store_relationship(x, "is-a")

If I was willing to use Python 3, I could use class decorators instead,
I suppose.  But I'd like to nest these declarations inside the class
definition if I can.

Any ideas would be appreciated.


More information about the Baypiggies mailing list